/*!
 * jQuery JavaScript Library v1.11.3
 * http://jquery.com/
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 *
 * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2015-04-28T16:19Z
 */

(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 inherently posses a window with a document
		// (such as Node.js), expose a jQuery-making 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 ) {

// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//

var deletedIds = [];

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.11.3",

	// 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.
	// (You can seed the arguments with an array of args, but this is
	// only used internally.)
	each: function( callback, args ) {
		return jQuery.each( this, callback, args );
	},

	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(null);
	},

	// 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)
		return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 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.ownLast ) {
			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;
	},

	// Evaluates a script in a global context
	// 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 );
			} )( 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();
	},

	// args is for internal usage only
	each: function( obj, callback, args ) {
		var value,
			i = 0,
			length = obj.length,
			isArray = isArraylike( obj );

		if ( args ) {
			if ( isArray ) {
				for ( ; i < length; i++ ) {
					value = callback.apply( obj[ i ], args );

					if ( value === false ) {
						break;
					}
				}
			} else {
				for ( i in obj ) {
					value = callback.apply( obj[ i ], args );

					if ( value === false ) {
						break;
					}
				}
			}

		// A special, fast, case for the most common use of each
		} else {
			if ( isArray ) {
				for ( ; i < length; i++ ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

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

					if ( value === 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 value,
			i = 0,
			length = elems.length,
			isArray = isArraylike( elems ),
			ret = [];

		// Go through the array, translating each of the items to their new values
		if ( isArray ) {
			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
});

// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".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 = "length" in obj && obj.length,
		type = jQuery.type( obj );

	if ( type === "function" || jQuery.isWindow( obj ) ) {
		return false;
	}

	if ( obj.nodeType === 1 && length ) {
		return true;
	}

	return type === "array" || length === 0 ||
		typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
 * Sizzle CSS Selector Engine v2.2.0-pre
 * http://sizzlejs.com/
 *
 * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2014-12-16
 */
(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

	// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
	whitespace = "[\\x20\\t\\r\\n\\f]",
	// http://www.w3.org/TR/css3-syntax/#characters
	characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",

	// Loosely modeled on CSS identifier characters
	// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
	// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
	identifier = characterEncoding.replace( "w", "w#" ),

	// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
	attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
		// Operator (capture 2)
		"*([*^$|!~]?=)" + whitespace +
		// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
		"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
		"*\\]",

	pseudos = ":(" + characterEncoding + ")(?:\\((" +
		// 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( "^#(" + characterEncoding + ")" ),
		"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
		"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
		"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 match, elem, m, nodeType,
		// QSA vars
		i, groups, old, nid, newContext, newSelector;

	if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
		setDocument( context );
	}

	context = context || document;
	results = results || [];
	nodeType = context.nodeType;

	if ( typeof selector !== "string" || !selector ||
		nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {

		return results;
	}

	if ( !seed && documentIsHTML ) {

		// Try to shortcut find operations when possible (e.g., not under DocumentFragment)
		if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
			// Speed-up: Sizzle("#ID")
			if ( (m = match[1]) ) {
				if ( nodeType === 9 ) {
					elem = context.getElementById( m );
					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document (jQuery #6963)
					if ( elem && elem.parentNode ) {
						// Handle the case where IE, Opera, and Webkit return items
						// by name instead of ID
						if ( elem.id === m ) {
							results.push( elem );
							return results;
						}
					} else {
						return results;
					}
				} else {
					// Context is not a document
					if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
						contains( context, elem ) && elem.id === m ) {
						results.push( elem );
						return results;
					}
				}

			// Speed-up: Sizzle("TAG")
			} else if ( match[2] ) {
				push.apply( results, context.getElementsByTagName( selector ) );
				return results;

			// Speed-up: Sizzle(".CLASS")
			} else if ( (m = match[3]) && support.getElementsByClassName ) {
				push.apply( results, context.getElementsByClassName( m ) );
				return results;
			}
		}

		// QSA path
		if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
			nid = old = expando;
			newContext = context;
			newSelector = nodeType !== 1 && selector;

			// qSA works strangely on Element-rooted queries
			// We can work around this by specifying an extra ID on the root
			// and working up from there (Thanks to Andrew Dupont for the technique)
			// IE 8 doesn't work on object elements
			if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
				groups = tokenize( selector );

				if ( (old = context.getAttribute("id")) ) {
					nid = old.replace( rescape, "\\$&" );
				} else {
					context.setAttribute( "id", nid );
				}
				nid = "[id='" + nid + "'] ";

				i = groups.length;
				while ( i-- ) {
					groups[i] = nid + toSelector( groups[i] );
				}
				newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
				newSelector = groups.join(",");
			}

			if ( newSelector ) {
				try {
					push.apply( results,
						newContext.querySelectorAll( newSelector )
					);
					return results;
				} catch(qsaError) {
				} finally {
					if ( !old ) {
						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 = attrs.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;

	// If no document and documentElement is available, return
	if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
		return document;
	}

	// Set our document
	document = doc;
	docElem = doc.documentElement;
	parent = doc.defaultView;

	// Support: IE>8
	// If iframe document is assigned to "document" variable and if iframe has been reloaded,
	// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
	// IE6-8 do not support the defaultView property so parent will be undefined
	if ( parent && parent !== parent.top ) {
		// IE11 does not have attachEvent, so all must suffer
		if ( parent.addEventListener ) {
			parent.addEventListener( "unload", unloadHandler, false );
		} else if ( parent.attachEvent ) {
			parent.attachEvent( "onunload", unloadHandler );
		}
	}

	/* Support tests
	---------------------------------------------------------------------- */
	documentIsHTML = !isXML( doc );

	/* 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( doc.createComment("") );
		return !div.getElementsByTagName("*").length;
	});

	// Support: IE<9
	support.getElementsByClassName = rnative.test( doc.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 !doc.getElementsByName || !doc.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 );
				// Check parentNode to catch when Blackberry 4.6 returns
				// nodes that are no longer in the document #6963
				return m && m.parentNode ? [ 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 ( 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( doc.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 + "-\f]' 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.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+
			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 = doc.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 does not implement inclusive descendent
	// 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 === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
				return -1;
			}
			if ( b === doc || 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 === doc ? -1 :
				b === doc ? 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 doc;
};

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 &&
		( !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, outerCache, node, diff, nodeIndex, start,
						dir = simple !== forward ? "nextSibling" : "previousSibling",
						parent = elem.parentNode,
						name = ofType && elem.nodeName.toLowerCase(),
						useCache = !xml && !ofType;

					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
							outerCache = parent[ expando ] || (parent[ expando ] = {});
							cache = outerCache[ type ] || [];
							nodeIndex = cache[0] === dirruns && cache[1];
							diff = cache[0] === dirruns && 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 ) {
									outerCache[ type ] = [ dirruns, nodeIndex, diff ];
									break;
								}
							}

						// Use previously-cached element index if available
						} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
							diff = cache[1];

						// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
						} else {
							// 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 ) {
										(node[ expando ] || (node[ expando ] = {}))[ 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, outerCache,
				newCache = [ dirruns, doneName ];

			// We can't set arbitrary data on XML nodes, so they don't benefit from dir 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 ] = {});
						if ( (oldCache = outerCache[ 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
							outerCache[ 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;
			}

			// Add elements passing elementMatchers directly to results
			// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
			// 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;
					while ( (matcher = elementMatchers[j++]) ) {
						if ( matcher( elem, context, 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 );
					}
				}
			}

			// Apply set filters to unmatched elements
			matchedCount += i;
			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 no seed and only one group
	if ( match.length === 1 ) {

		// Take a shortcut and set the context if the root 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,
		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.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;



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 ) >= 0 ) !== 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,

	// Use the correct document accordingly with window argument (sandbox)
	document = window.document,

	// 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 ) {
		var match, elem;

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

		// 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 || rootjQuery ).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 rootjQuery.ready !== "undefined" ?
				rootjQuery.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.extend({
	dir: function( elem, dir, until ) {
		var matched = [],
			cur = elem[ dir ];

		while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
			if ( cur.nodeType === 1 ) {
				matched.push( cur );
			}
			cur = cur[dir];
		}
		return matched;
	},

	sibling: function( n, elem ) {
		var r = [];

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

		return r;
	}
});

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.unique( 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.unique(
				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 jQuery.dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return sibling( elem, "nextSibling" );
	},
	prev: function( elem ) {
		return sibling( elem, "previousSibling" );
	},
	nextAll: function( elem ) {
		return jQuery.dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return jQuery.dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
	},
	children: function( elem ) {
		return jQuery.sibling( 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.unique( ret );
			}

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

		return this.pushStack( ret );
	};
});
var rnotwhite = (/\S+/g);



// String to Object options format cache
var optionsCache = {};

// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
	var object = optionsCache[ options ] = {};
	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" ?
		( optionsCache[ options ] || 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,
		// End of the loop when firing
		firingLength,
		// Index of currently firing callback (modified by remove if needed)
		firingIndex,
		// First callback to fire (used internally by add and fireWith)
		firingStart,
		// Actual callback list
		list = [],
		// Stack of fire calls for repeatable lists
		stack = !options.once && [],
		// Fire callbacks
		fire = function( data ) {
			memory = options.memory && data;
			fired = true;
			firingIndex = firingStart || 0;
			firingStart = 0;
			firingLength = list.length;
			firing = true;
			for ( ; list && firingIndex < firingLength; firingIndex++ ) {
				if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
					memory = false; // To prevent further calls using add
					break;
				}
			}
			firing = false;
			if ( list ) {
				if ( stack ) {
					if ( stack.length ) {
						fire( stack.shift() );
					}
				} else if ( memory ) {
					list = [];
				} else {
					self.disable();
				}
			}
		},
		// Actual Callbacks object
		self = {
			// Add a callback or a collection of callbacks to the list
			add: function() {
				if ( list ) {
					// First, we save the current length
					var start = list.length;
					(function add( args ) {
						jQuery.each( args, function( _, arg ) {
							var type = jQuery.type( arg );
							if ( type === "function" ) {
								if ( !options.unique || !self.has( arg ) ) {
									list.push( arg );
								}
							} else if ( arg && arg.length && type !== "string" ) {
								// Inspect recursively
								add( arg );
							}
						});
					})( arguments );
					// Do we need to add the callbacks to the
					// current firing batch?
					if ( firing ) {
						firingLength = list.length;
					// With memory, if we're not firing then
					// we should call right away
					} else if ( memory ) {
						firingStart = start;
						fire( memory );
					}
				}
				return this;
			},
			// Remove a callback from the list
			remove: function() {
				if ( list ) {
					jQuery.each( arguments, function( _, arg ) {
						var index;
						while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
							list.splice( index, 1 );
							// Handle firing indexes
							if ( firing ) {
								if ( index <= firingLength ) {
									firingLength--;
								}
								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 && list.length );
			},
			// Remove all callbacks from the list
			empty: function() {
				list = [];
				firingLength = 0;
				return this;
			},
			// Have the list do nothing anymore
			disable: function() {
				list = stack = memory = undefined;
				return this;
			},
			// Is it disabled?
			disabled: function() {
				return !list;
			},
			// Lock the list in its current state
			lock: function() {
				stack = undefined;
				if ( !memory ) {
					self.disable();
				}
				return this;
			},
			// Is it locked?
			locked: function() {
				return !stack;
			},
			// Call all callbacks with the given context and arguments
			fireWith: function( context, args ) {
				if ( list && ( !fired || stack ) ) {
					args = args || [];
					args = [ context, args.slice ? args.slice() : args ];
					if ( firing ) {
						stack.push( args );
					} else {
						fire( args );
					}
				}
				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()
										.done( newDefer.resolve )
										.fail( newDefer.reject )
										.progress( newDefer.notify );
								} else {
									newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
								}
							});
						});
						fns = null;
					}).promise();
				},
				// 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()
						.done( updateFunc( i, resolveContexts, resolveValues ) )
						.fail( deferred.reject )
						.progress( updateFunc( i, progressContexts, progressValues ) );
				} 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;
		}

		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
		if ( !document.body ) {
			return setTimeout( jQuery.ready );
		}

		// 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, false );
		window.removeEventListener( "load", completed, false );

	} 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 || 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.
		// we once tried to use readyState "interactive" here, but it caused issues like the one
		// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
		if ( document.readyState === "complete" ) {
			// Handle it asynchronously to allow scripts the opportunity to delay ready
			setTimeout( jQuery.ready );

		// Standards-based browsers support DOMContentLoaded
		} else if ( document.addEventListener ) {
			// Use the handy event callback
			document.addEventListener( "DOMContentLoaded", completed, false );

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

		// 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 setTimeout( doScrollCheck, 50 );
						}

						// detach all dom ready events
						detach();

						// and execute any waiting functions
						jQuery.ready();
					}
				})();
			}
		}
	}
	return readyList.promise( obj );
};


var strundefined = typeof undefined;



// Support: IE<9
// Iteration over object's inherited properties before its own
var i;
for ( i in jQuery( support ) ) {
	break;
}
support.ownLast = 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 !== strundefined ) {
		// 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" );

	// Execute the test only if not already executed in another module.
	if (support.deleteExpando == null) {
		// Support: IE<9
		support.deleteExpando = true;
		try {
			delete div.test;
		} catch( e ) {
			support.deleteExpando = false;
		}
	}

	// Null elements to avoid leaks in IE.
	div = null;
})();


/**
 * Determines whether an object can have data
 */
jQuery.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 ( !jQuery.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 ( !jQuery.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, null
	} else {
		cache[ id ] = null;
	}
}

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 );
	}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;

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 );
	};



// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.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 ) {
			jQuery.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);



(function() {
	// Minified: var a,b,c
	var input = document.createElement( "input" ),
		div = document.createElement( "div" ),
		fragment = document.createDocumentFragment();

	// 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 );
	div.innerHTML = "<input type='radio' checked='checked' name='t'/>";

	// 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
	// Opera does not clone events (and typeof div.attachEvent === undefined).
	// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
	support.noCloneEvent = true;
	if ( div.attachEvent ) {
		div.attachEvent( "onclick", function() {
			support.noCloneEvent = false;
		});

		div.cloneNode( true ).click();
	}

	// Execute the test only if not already executed in another module.
	if (support.deleteExpando == null) {
		// Support: IE<9
		support.deleteExpando = true;
		try {
			delete div.test;
		} catch( e ) {
			support.deleteExpando = false;
		}
	}
})();


(function() {
	var i, eventName,
		div = document.createElement( "div" );

	// Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event)
	for ( i in { submit: true, change: true, focusin: true }) {
		eventName = "on" + i;

		if ( !(support[ i + "Bubbles" ] = eventName in window) ) {
			// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
			div.setAttribute( eventName, "t" );
			support[ i + "Bubbles" ] = 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)|click/,
	rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
	rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;

function returnTrue() {
	return true;
}

function returnFalse() {
	return false;
}

function safeActiveElement() {
	try {
		return document.activeElement;
	} catch ( err ) { }
}

/*
 * 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 !== strundefined && (!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(".") >= 0 ) {
			// 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.namespace_re = 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 && jQuery.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) &&
				jQuery.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, ret, handleObj, matched, j,
			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.namespace_re || event.namespace_re.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 sel, handleObj, matches, i,
			handlerQueue = [],
			delegateCount = handlers.delegateCount,
			cur = event.target;

		// Find delegate handlers
		// Black-hole SVG <use> instance trees (#13180)
		// Avoid non-left-click bubbling in Firefox (#3861)
		if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {

			/* 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 ) >= 0 :
								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: Chrome 23+, Safari?
		// 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 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;
				}
			}
		}
	},

	simulate: function( type, elem, event, bubble ) {
		// Piggyback on a donor event to simulate a different one.
		// Fake originalEvent to avoid donor's stopPropagation, but if the
		// simulated event prevents default then we do the same on the donor.
		var e = jQuery.extend(
			new jQuery.Event(),
			event,
			{
				type: type,
				isSimulated: true,
				originalEvent: {}
			}
		);
		if ( bubble ) {
			jQuery.event.trigger( e, null, elem );
		} else {
			jQuery.event.dispatch.call( elem, e );
		}
		if ( e.isDefaultPrevented() ) {
			event.preventDefault();
		}
	}
};

jQuery.removeEvent = document.removeEventListener ?
	function( elem, type, handle ) {
		if ( elem.removeEventListener ) {
			elem.removeEventListener( type, handle, false );
		}
	} :
	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 ] === strundefined ) {
				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 = {
	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 ) {
			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
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 mousenter/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.submitBubbles ) {

	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" ) ? elem.form : undefined;
				if ( form && !jQuery._data( form, "submitBubbles" ) ) {
					jQuery.event.add( form, "submit._submit", function( event ) {
						event._submit_bubble = true;
					});
					jQuery._data( form, "submitBubbles", 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._submit_bubble ) {
				delete event._submit_bubble;
				if ( this.parentNode && !event.isTrigger ) {
					jQuery.event.simulate( "submit", this.parentNode, event, true );
				}
			}
		},

		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.changeBubbles ) {

	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._just_changed = true;
						}
					});
					jQuery.event.add( this, "click._change", function( event ) {
						if ( this._just_changed && !event.isTrigger ) {
							this._just_changed = false;
						}
						// Allow triggered, simulated change events (#11500)
						jQuery.event.simulate( "change", this, event, true );
					});
				}
				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, "changeBubbles" ) ) {
					jQuery.event.add( elem, "change._change", function( event ) {
						if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
							jQuery.event.simulate( "change", this.parentNode, event, true );
						}
					});
					jQuery._data( elem, "changeBubbles", 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 );
		}
	};
}

// Create "bubbling" focus and blur events
if ( !support.focusinBubbles ) {
	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 ), true );
			};

		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, /*INTERNAL*/ one ) {
		var type, origFn;

		// 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 ) {
				this.on( type, selector, data, types[ type ], one );
			}
			return this;
		}

		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 this;
		}

		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 this.each( function() {
			jQuery.event.add( this, types, fn, data, selector );
		});
	},
	one: function( types, selector, data, fn ) {
		return this.on( 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 );
		}
	}
});


function createSafeFragment( document ) {
	var list = nodeNames.split( "|" ),
		safeFrag = document.createDocumentFragment();

	if ( safeFrag.createElement ) {
		while ( list.length ) {
			safeFrag.createElement(
				list.pop()
			);
		}
	}
	return safeFrag;
}

var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
		"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
	rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
	rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
	rleadingWhitespace = /^\s+/,
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
	rtagName = /<([\w:]+)/,
	rtbody = /<tbody/i,
	rhtml = /<|&#?\w+;/,
	rnoInnerhtml = /<(?:script|style|link)/i,
	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	rscriptType = /^$|\/(?:java|ecma)script/i,
	rscriptTypeMasked = /^true\/(.*)/,
	rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,

	// We have to close these tags to support XHTML (#13200)
	wrapMap = {
		option: [ 1, "<select multiple='multiple'>", "</select>" ],
		legend: [ 1, "<fieldset>", "</fieldset>" ],
		area: [ 1, "<map>", "</map>" ],
		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>"  ]
	},
	safeFragment = createSafeFragment( document ),
	fragmentDiv = safeFragment.appendChild( document.createElement("div") );

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 !== strundefined ? context.getElementsByTagName( tag || "*" ) :
			typeof context.querySelectorAll !== strundefined ? 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;
}

// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
	if ( rcheckableType.test( elem.type ) ) {
		elem.defaultChecked = elem.checked;
	}
}

// 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;
}

// 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" ) );
	}
}

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;
	}
}

jQuery.extend({
	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;
	},

	buildFragment: function( elems, context, scripts, selection ) {
		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] + elem.replace( rxhtmlTag, "<$1></$2>" ) + 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++ ]) ) {

			// #4087 - If origin and destination elements are the same, and this is
			// that element, do not do anything
			if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
				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;
	},

	cleanData: function( elems, /* internal */ acceptData ) {
		var elem, type, id, data,
			i = 0,
			internalKey = jQuery.expando,
			cache = jQuery.cache,
			deleteExpando = support.deleteExpando,
			special = jQuery.event.special;

		for ( ; (elem = elems[i]) != null; i++ ) {
			if ( acceptData || jQuery.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 ];

						// IE does not allow us to delete expando properties from nodes,
						// nor does it have a removeAttribute function on Document nodes;
						// we must handle all of these cases
						if ( deleteExpando ) {
							delete elem[ internalKey ];

						} else if ( typeof elem.removeAttribute !== strundefined ) {
							elem.removeAttribute( internalKey );

						} else {
							elem[ internalKey ] = null;
						}

						deletedIds.push( id );
					}
				}
			}
		}
	}
});

jQuery.fn.extend({
	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 this.domManip( arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.appendChild( elem );
			}
		});
	},

	prepend: function() {
		return this.domManip( 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 this.domManip( arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this );
			}
		});
	},

	after: function() {
		return this.domManip( arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			}
		});
	},

	remove: function( selector, keepData /* Internal Use Only */ ) {
		var elem,
			elems = selector ? jQuery.filter( selector, this ) : this,
			i = 0;

		for ( ; (elem = elems[i]) != null; i++ ) {

			if ( !keepData && elem.nodeType === 1 ) {
				jQuery.cleanData( getAll( elem ) );
			}

			if ( elem.parentNode ) {
				if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
					setGlobalEval( getAll( elem, "script" ) );
				}
				elem.parentNode.removeChild( elem );
			}
		}

		return this;
	},

	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 = value.replace( rxhtmlTag, "<$1></$2>" );

				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 arg = arguments[ 0 ];

		// Make the changes, replacing each context element with the new content
		this.domManip( arguments, function( elem ) {
			arg = this.parentNode;

			jQuery.cleanData( getAll( this ) );

			if ( arg ) {
				arg.replaceChild( elem, this );
			}
		});

		// Force removal if there was no new content (e.g., from empty arguments)
		return arg && (arg.length || arg.nodeType) ? this : this.remove();
	},

	detach: function( selector ) {
		return this.remove( selector, true );
	},

	domManip: function( args, callback ) {

		// Flatten any nested arrays
		args = concat.apply( [], args );

		var first, node, hasScripts,
			scripts, doc, fragment,
			i = 0,
			l = this.length,
			set = this,
			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 this.each(function( index ) {
				var self = set.eq( index );
				if ( isFunction ) {
					args[0] = value.call( this, index, self.html() );
				}
				self.domManip( args, callback );
			});
		}

		if ( l ) {
			fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
			first = fragment.firstChild;

			if ( fragment.childNodes.length === 1 ) {
				fragment = first;
			}

			if ( first ) {
				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 ) {
							jQuery.merge( scripts, getAll( node, "script" ) );
						}
					}

					callback.call( this[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 this;
	}
});

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 = {};

/**
 * 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 style,
		elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),

		// getDefaultComputedStyle might be reliably used only on attached element
		display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?

			// Use of this method is a temporary fix (more like optmization) until something better comes along,
			// since it was removed from specification and supported only in FF
			style.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;
}


(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 !== strundefined ) {
			// 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 rmargin = (/^margin/);

var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );



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"
		if ( elem.ownerDocument.defaultView.opener ) {
			return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
		}

		return window.getComputedStyle( elem, null );
	};

	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;

		if ( computed ) {

			if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
				ret = jQuery.style( elem, name );
			}

			// 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 ( 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 ( document.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() {
			var condition = conditionFn();

			if ( condition == null ) {
				// The test was not ready at this point; screw the hook this time
				// but check again when needed next time.
				return;
			}

			if ( condition ) {
				// Hook not needed (or it's not possible to use it due to missing dependency),
				// remove it.
				// Since there are no other hooks for marginRight, remove the whole object.
				delete this.get;
				return;
			}

			// Hook needed; redefine it so that the support test is not executed again.

			return (this.get = hookFn).apply( this, arguments );
		}
	};
}


(function() {
	// Minified: var b,c,d,e,f,g, h,i
	var div, style, a, pixelPositionVal, boxSizingReliableVal,
		reliableHiddenOffsetsVal, reliableMarginRightVal;

	// Setup
	div = document.createElement( "div" );
	div.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
	a = div.getElementsByTagName( "a" )[ 0 ];
	style = a && a.style;

	// Finish early in limited (non-browser) environments
	if ( !style ) {
		return;
	}

	style.cssText = "float:left;opacity:.5";

	// Support: IE<9
	// Make sure that element opacity exists (as opposed to filter)
	support.opacity = style.opacity === "0.5";

	// Verify style float existence
	// (IE uses styleFloat instead of cssFloat)
	support.cssFloat = !!style.cssFloat;

	div.style.backgroundClip = "content-box";
	div.cloneNode( true ).style.backgroundClip = "";
	support.clearCloneStyle = div.style.backgroundClip === "content-box";

	// Support: Firefox<29, Android 2.3
	// Vendor-prefix box-sizing
	support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" ||
		style.WebkitBoxSizing === "";

	jQuery.extend(support, {
		reliableHiddenOffsets: function() {
			if ( reliableHiddenOffsetsVal == null ) {
				computeStyleTests();
			}
			return reliableHiddenOffsetsVal;
		},

		boxSizingReliable: function() {
			if ( boxSizingReliableVal == null ) {
				computeStyleTests();
			}
			return boxSizingReliableVal;
		},

		pixelPosition: function() {
			if ( pixelPositionVal == null ) {
				computeStyleTests();
			}
			return pixelPositionVal;
		},

		// Support: Android 2.3
		reliableMarginRight: function() {
			if ( reliableMarginRightVal == null ) {
				computeStyleTests();
			}
			return reliableMarginRightVal;
		}
	});

	function computeStyleTests() {
		// Minified: var b,c,d,j
		var div, body, container, contents;

		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 );

		div.style.cssText =
			// Support: Firefox<29, Android 2.3
			// Vendor-prefix box-sizing
			"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
			"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
			"border:1px;padding:1px;width:4px;position:absolute";

		// Support: IE<9
		// Assume reasonable values in the absence of getComputedStyle
		pixelPositionVal = boxSizingReliableVal = false;
		reliableMarginRightVal = true;

		// Check for getComputedStyle so that this code is not run in IE<9.
		if ( window.getComputedStyle ) {
			pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
			boxSizingReliableVal =
				( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";

			// Support: Android 2.3
			// 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: 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:0";
			contents.style.marginRight = contents.style.width = "0";
			div.style.width = "1px";

			reliableMarginRightVal =
				!parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight );

			div.removeChild( contents );
		}

		// Support: IE8
		// 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.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
		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;
		}

		body.removeChild( container );
	}

})();


// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.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
		ralpha = /alpha\([^)]*\)/i,
	ropacity = /opacity\s*=\s*([^)]*)/,

	// 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" ),
	rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),

	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssNormalTransform = {
		letterSpacing: "0",
		fontWeight: "400"
	},

	cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];


// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {

	// shortcut for names that are not vendor prefixed
	if ( name in style ) {
		return name;
	}

	// check for vendor prefixed names
	var capName = name.charAt(0).toUpperCase() + name.slice(1),
		origName = name,
		i = cssPrefixes.length;

	while ( i-- ) {
		name = cssPrefixes[ i ] + capName;
		if ( name in style ) {
			return name;
		}
	}

	return origName;
}

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: {
		"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( style, 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 relative number strings (+= or -=) to relative numbers. #7345
			if ( type === "string" && (ret = rrelNum.exec( value )) ) {
				value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
				// 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 'px' to the (except for certain CSS properties)
			if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
				value += "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( elem.style, 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 || jQuery.isNumeric( 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 ?
					jQuery.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 ) {
			// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
			// Work around by temporarily setting element display to inline-block
			return jQuery.swap( elem, { "display": "inline-block" },
				curCSS, [ elem, "marginRight" ] );
		}
	}
);

// 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 || "swing";
		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;

			if ( tween.elem[ tween.prop ] != null &&
				(!tween.elem.style || 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.style && ( 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;
	}
};

jQuery.fx = Tween.prototype.init;

// Back Compat <1.8 extension point
jQuery.fx.step = {};




var
	fxNow, timerId,
	rfxtypes = /^(?:toggle|show|hide)$/,
	rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
	rrun = /queueHooks$/,
	animationPrefilters = [ defaultPrefilter ],
	tweeners = {
		"*": [ function( prop, value ) {
			var tween = this.createTween( prop, value ),
				target = tween.cur(),
				parts = rfxnum.exec( value ),
				unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),

				// Starting value computation is required for potential unit mismatches
				start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
					rfxnum.exec( jQuery.css( tween.elem, prop ) ),
				scale = 1,
				maxIterations = 20;

			if ( start && start[ 3 ] !== unit ) {
				// Trust units reported by jQuery.css
				unit = unit || start[ 3 ];

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

				// Iteratively approximate from a nonzero starting point
				start = +target || 1;

				do {
					// If previous iteration zeroed out, double until we get *something*
					// Use a string for doubling factor so we don't accidentally see scale as unchanged below
					scale = scale || ".5";

					// Adjust and apply
					start = start / scale;
					jQuery.style( tween.elem, prop, start + unit );

				// Update scale, tolerating zero or NaN from tween.cur()
				// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
				} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
			}

			// Update tween properties
			if ( parts ) {
				start = tween.start = +start || +target || 0;
				tween.unit = unit;
				// If a +=/-= token was provided, we're doing a relative animation
				tween.end = parts[ 1 ] ?
					start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
					+parts[ 2 ];
			}

			return tween;
		} ]
	};

// Animations created synchronously will run synchronously
function createFxNow() {
	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 = ( tweeners[ prop ] || [] ).concat( 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 = animationPrefilters.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 ),
				// 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: {} }, 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.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 = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
		if ( 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, {
	tweener: function( props, callback ) {
		if ( jQuery.isFunction( props ) ) {
			callback = props;
			props = [ "*" ];
		} else {
			props = props.split(" ");
		}

		var prop,
			index = 0,
			length = props.length;

		for ( ; index < length ; index++ ) {
			prop = props[ index ];
			tweeners[ prop ] = tweeners[ prop ] || [];
			tweeners[ prop ].unshift( callback );
		}
	},

	prefilter: function( callback, prepend ) {
		if ( prepend ) {
			animationPrefilters.unshift( callback );
		} else {
			animationPrefilters.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 = setInterval( jQuery.fx.tick, jQuery.fx.interval );
	}
};

jQuery.fx.stop = function() {
	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://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 = setTimeout( next, time );
		hooks.stop = function() {
			clearTimeout( timeout );
		};
	});
};


(function() {
	// Minified: var a,b,c,d,e
	var input, div, select, a, opt;

	// 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 ];

	// First batch of tests.
	select = document.createElement("select");
	opt = select.appendChild( document.createElement("option") );
	input = div.getElementsByTagName("input")[ 0 ];

	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;

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)
					jQuery.trim( jQuery.text( elem ) );
			}
		},
		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 ) >= 0 ) {

						// 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 ) >= 0 );
			}
		}
	};
	if ( !support.checkOn ) {
		jQuery.valHooks[ this ].get = function( elem ) {
			// Support: Webkit
			// "" is returned instead of "on" if a value isn't specified
			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 hooks, ret,
			nType = elem.nodeType;

		// don't get/set attributes on text, comment and attribute nodes
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		// Fallback to prop when attributes are not supported
		if ( typeof elem.getAttribute === strundefined ) {
			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 );

			} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
				return ret;

			} else {
				elem.setAttribute( name, value + "" );
				return value;
			}

		} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
			return ret;

		} else {
			ret = jQuery.find.attr( elem, name );

			// Non-existent attributes return null, we normalize to undefined
			return ret == null ?
				undefined :
				ret;
		}
	},

	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 );
			}
		}
	},

	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 IE6-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;
				}
			}
		}
	}
});

// Hook 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 );

		// Use defaultChecked and defaultSelected for oldIE
		} else {
			elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
		}

		return name;
	}
};

// Retrieve booleans specially
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {

	var getter = attrHandle[ name ] || jQuery.find.attr;

	attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( 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;
		} :
		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 senstitivity 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({
	propFix: {
		"for": "htmlFor",
		"class": "className"
	},

	prop: function( elem, name, value ) {
		var ret, hooks, notxml,
			nType = elem.nodeType;

		// don't get/set properties on text, comment and attribute nodes
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );

		if ( notxml ) {
			// Fix name and attach hooks
			name = jQuery.propFix[ name ] || name;
			hooks = jQuery.propHooks[ name ];
		}

		if ( value !== undefined ) {
			return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
				ret :
				( elem[ name ] = value );

		} else {
			return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
				ret :
				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;
			}
		}
	}
});

// 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+
// mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
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;
		}
	};
}

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;

jQuery.fn.extend({
	addClass: function( value ) {
		var classes, elem, cur, clazz, j, finalValue,
			i = 0,
			len = this.length,
			proceed = typeof value === "string" && value;

		if ( jQuery.isFunction( value ) ) {
			return this.each(function( j ) {
				jQuery( this ).addClass( value.call( this, j, this.className ) );
			});
		}

		if ( proceed ) {
			// The disjunction here is for better compressibility (see removeClass)
			classes = ( value || "" ).match( rnotwhite ) || [];

			for ( ; i < len; i++ ) {
				elem = this[ i ];
				cur = elem.nodeType === 1 && ( elem.className ?
					( " " + elem.className + " " ).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 ( elem.className !== finalValue ) {
						elem.className = finalValue;
					}
				}
			}
		}

		return this;
	},

	removeClass: function( value ) {
		var classes, elem, cur, clazz, j, finalValue,
			i = 0,
			len = this.length,
			proceed = arguments.length === 0 || typeof value === "string" && value;

		if ( jQuery.isFunction( value ) ) {
			return this.each(function( j ) {
				jQuery( this ).removeClass( value.call( this, j, this.className ) );
			});
		}
		if ( proceed ) {
			classes = ( value || "" ).match( rnotwhite ) || [];

			for ( ; i < len; i++ ) {
				elem = this[ i ];
				// This expression is here for better compressibility (see addClass)
				cur = elem.nodeType === 1 && ( elem.className ?
					( " " + elem.className + " " ).replace( rclass, " " ) :
					""
				);

				if ( cur ) {
					j = 0;
					while ( (clazz = classes[j++]) ) {
						// Remove *all* instances
						while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
							cur = cur.replace( " " + clazz + " ", " " );
						}
					}

					// only assign if different to avoid unneeded rendering.
					finalValue = value ? jQuery.trim( cur ) : "";
					if ( elem.className !== finalValue ) {
						elem.className = 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, this.className, stateVal), stateVal );
			});
		}

		return this.each(function() {
			if ( type === "string" ) {
				// toggle individual class names
				var className,
					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 ( type === strundefined || type === "boolean" ) {
				if ( this.className ) {
					// store className if set
					jQuery._data( this, "__className__", this.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.
				this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
			}
		});
	},

	hasClass: function( selector ) {
		var className = " " + selector + " ",
			i = 0,
			l = this.length;
		for ( ; i < l; i++ ) {
			if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
				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 );
	},

	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 );
	}
});


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 DOMParser();
			xml = tmp.parseFromString( data, "text/xml" );
		} else { // IE
			xml = new 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
	// Document location
	ajaxLocParts,
	ajaxLocation,

	rhash = /#.*$/,
	rts = /([?&])_=[^&]*/,
	rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
	// #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("*");

// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
	ajaxLocation = location.href;
} catch( e ) {
	// Use the href attribute of an A element
	// since IE will modify it given document.location
	ajaxLocation = document.createElement( "a" );
	ajaxLocation.href = "";
	ajaxLocation = ajaxLocation.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" ] ) {
						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: /xml/,
			html: /html/,
			json: /json/
		},

		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 ] );
			}
			// Timeout
			if ( s.async && s.timeout > 0 ) {
				timeoutTimer = 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 ) {
				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;
		}

		return jQuery.ajax({
			url: url,
			type: method,
			dataType: type,
			data: data,
			success: callback
		});
	};
});


jQuery._evalUrl = function( url ) {
	return jQuery.ajax({
		url: url,
		type: "GET",
		dataType: "script",
		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();
	}
});


jQuery.expr.filters.hidden = function( elem ) {
	// Support: Opera <= 12.12
	// Opera reports offsetWidths and offsetHeights less than zero on some elements
	return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
		(!support.reliableHiddenOffsets() &&
			((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};

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" ? 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+
	function() {

		// XHR cannot access local files, always use ActiveX for that case
		return !this.isLocal &&

			// Support: IE7-8
			// 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"
			/^(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() );
						}
					};

					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
						setTimeout( callback );
					} else {
						// 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: /(?:java|ecma)script/
	},
	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") && 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() {
			// Restore preexisting value
			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 = jQuery.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, response, type,
		self = this,
		off = url.indexOf(" ");

	if ( off >= 0 ) {
		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
			type: type,
			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 );

		}).complete( callback && function( jqXHR, status ) {
			self.each( callback, 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;
};





var docElem = window.document.documentElement;

/**
 * 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 ) ) {
			options = options.call( elem, i, 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 !== strundefined ) {
			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 || docElem;

			while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
				offsetParent = offsetParent.offsetParent;
			}
			return offsetParent || docElem;
		});
	}
});

// 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 );
	};
});

// 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 );
		};
	});
});


// 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 ( typeof noGlobal === strundefined ) {
	window.jQuery = window.$ = jQuery;
}




return jQuery;

}));
/*! jQuery UI - v1.11.4 - 2015-03-11
* http://jqueryui.com
* Includes: core.js, widget.js, mouse.js, position.js, accordion.js, autocomplete.js, button.js, datepicker.js, dialog.js, draggable.js, droppable.js, effect.js, effect-blind.js, effect-bounce.js, effect-clip.js, effect-drop.js, effect-explode.js, effect-fade.js, effect-fold.js, effect-highlight.js, effect-puff.js, effect-pulsate.js, effect-scale.js, effect-shake.js, effect-size.js, effect-slide.js, effect-transfer.js, menu.js, progressbar.js, resizable.js, selectable.js, selectmenu.js, slider.js, sortable.js, spinner.js, tabs.js, tooltip.js
* Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */

(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define([ "jquery" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {
/*!
 * jQuery UI Core 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/category/ui-core/
 */


// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};

$.extend( $.ui, {
	version: "1.11.4",

	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
	}
});

// plugins
$.fn.extend({
	scrollParent: function( includeHidden ) {
		var position = this.css( "position" ),
			excludeStaticParent = position === "absolute",
			overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
			scrollParent = this.parents().filter( function() {
				var parent = $( this );
				if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
					return false;
				}
				return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) );
			}).eq( 0 );

		return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent;
	},

	uniqueId: (function() {
		var uuid = 0;

		return function() {
			return this.each(function() {
				if ( !this.id ) {
					this.id = "ui-id-" + ( ++uuid );
				}
			});
		};
	})(),

	removeUniqueId: function() {
		return this.each(function() {
			if ( /^ui-id-\d+$/.test( this.id ) ) {
				$( this ).removeAttr( "id" );
			}
		});
	}
});

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

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

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

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

	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" ),
			isTabIndexNaN = isNaN( tabIndex );
		return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
	}
});

// support: jQuery <1.8
if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
	$.each( [ "Width", "Height" ], function( i, name ) {
		var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
			type = name.toLowerCase(),
			orig = {
				innerWidth: $.fn.innerWidth,
				innerHeight: $.fn.innerHeight,
				outerWidth: $.fn.outerWidth,
				outerHeight: $.fn.outerHeight
			};

		function reduce( elem, size, border, margin ) {
			$.each( side, function() {
				size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
				if ( border ) {
					size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
				}
				if ( margin ) {
					size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
				}
			});
			return size;
		}

		$.fn[ "inner" + name ] = function( size ) {
			if ( size === undefined ) {
				return orig[ "inner" + name ].call( this );
			}

			return this.each(function() {
				$( this ).css( type, reduce( this, size ) + "px" );
			});
		};

		$.fn[ "outer" + name] = function( size, margin ) {
			if ( typeof size !== "number" ) {
				return orig[ "outer" + name ].call( this, size );
			}

			return this.each(function() {
				$( this).css( type, reduce( this, size, true, margin ) + "px" );
			});
		};
	});
}

// support: jQuery <1.8
if ( !$.fn.addBack ) {
	$.fn.addBack = function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	};
}

// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
	$.fn.removeData = (function( removeData ) {
		return function( key ) {
			if ( arguments.length ) {
				return removeData.call( this, $.camelCase( key ) );
			} else {
				return removeData.call( this );
			}
		};
	})( $.fn.removeData );
}

// deprecated
$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );

$.fn.extend({
	focus: (function( orig ) {
		return function( delay, fn ) {
			return typeof delay === "number" ?
				this.each(function() {
					var elem = this;
					setTimeout(function() {
						$( elem ).focus();
						if ( fn ) {
							fn.call( elem );
						}
					}, delay );
				}) :
				orig.apply( this, arguments );
		};
	})( $.fn.focus ),

	disableSelection: (function() {
		var eventType = "onselectstart" in document.createElement( "div" ) ?
			"selectstart" :
			"mousedown";

		return function() {
			return this.bind( eventType + ".ui-disableSelection", function( event ) {
				event.preventDefault();
			});
		};
	})(),

	enableSelection: function() {
		return this.unbind( ".ui-disableSelection" );
	},

	zIndex: function( zIndex ) {
		if ( zIndex !== undefined ) {
			return this.css( "zIndex", zIndex );
		}

		if ( this.length ) {
			var elem = $( this[ 0 ] ), position, value;
			while ( elem.length && elem[ 0 ] !== document ) {
				// Ignore z-index if position is set to a value where z-index is ignored by the browser
				// This makes behavior of this function consistent across browsers
				// WebKit always returns auto if the element is positioned
				position = elem.css( "position" );
				if ( position === "absolute" || position === "relative" || position === "fixed" ) {
					// IE returns 0 when zIndex is not specified
					// other browsers return a string
					// we ignore the case of nested elements with an explicit value of 0
					// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
					value = parseInt( elem.css( "zIndex" ), 10 );
					if ( !isNaN( value ) && value !== 0 ) {
						return value;
					}
				}
				elem = elem.parent();
			}
		}

		return 0;
	}
});

// $.ui.plugin is deprecated. Use $.widget() extensions instead.
$.ui.plugin = {
	add: function( module, option, set ) {
		var i,
			proto = $.ui[ module ].prototype;
		for ( i in set ) {
			proto.plugins[ i ] = proto.plugins[ i ] || [];
			proto.plugins[ i ].push( [ option, set[ i ] ] );
		}
	},
	call: function( instance, name, args, allowDisconnected ) {
		var i,
			set = instance.plugins[ name ];

		if ( !set ) {
			return;
		}

		if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
			return;
		}

		for ( i = 0; i < set.length; i++ ) {
			if ( instance.options[ set[ i ][ 0 ] ] ) {
				set[ i ][ 1 ].apply( instance.element, args );
			}
		}
	}
};


/*!
 * jQuery UI Widget 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/jQuery.widget/
 */


var widget_uuid = 0,
	widget_slice = Array.prototype.slice;

$.cleanData = (function( orig ) {
	return function( elems ) {
		var events, elem, i;
		for ( i = 0; (elem = elems[i]) != null; i++ ) {
			try {

				// Only trigger remove when necessary to save time
				events = $._data( elem, "events" );
				if ( events && events.remove ) {
					$( elem ).triggerHandler( "remove" );
				}

			// http://bugs.jquery.com/ticket/8235
			} catch ( e ) {}
		}
		orig( elems );
	};
})( $.cleanData );

$.widget = function( name, base, prototype ) {
	var fullName, existingConstructor, constructor, basePrototype,
		// proxiedPrototype allows the provided prototype to remain unmodified
		// so that it can be used as a mixin for multiple widgets (#8876)
		proxiedPrototype = {},
		namespace = name.split( "." )[ 0 ];

	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	// create selector for plugin
	$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
		return !!$.data( elem, fullName );
	};

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without "new" keyword
		if ( !this._createWidget ) {
			return new constructor( options, element );
		}

		// allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};
	// extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,
		// copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),
		// track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	});

	basePrototype = new base();
	// we need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
	basePrototype.options = $.widget.extend( {}, basePrototype.options );
	$.each( prototype, function( prop, value ) {
		if ( !$.isFunction( value ) ) {
			proxiedPrototype[ prop ] = value;
			return;
		}
		proxiedPrototype[ prop ] = (function() {
			var _super = function() {
					return base.prototype[ prop ].apply( this, arguments );
				},
				_superApply = function( args ) {
					return base.prototype[ prop ].apply( this, args );
				};
			return function() {
				var __super = this._super,
					__superApply = this._superApply,
					returnValue;

				this._super = _super;
				this._superApply = _superApply;

				returnValue = value.apply( this, arguments );

				this._super = __super;
				this._superApply = __superApply;

				return returnValue;
			};
		})();
	});
	constructor.prototype = $.widget.extend( basePrototype, {
		// TODO: remove support for widgetEventPrefix
		// always use the name + a colon as the prefix, e.g., draggable:start
		// don't prefix for widgets that aren't DOM-based
		widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name
	}, proxiedPrototype, {
		constructor: constructor,
		namespace: namespace,
		widgetName: name,
		widgetFullName: fullName
	});

	// If this widget is being redefined then we need to find all widgets that
	// are inheriting from it and redefine all of them so that they inherit from
	// the new version of this widget. We're essentially trying to replace one
	// level in the prototype chain.
	if ( existingConstructor ) {
		$.each( existingConstructor._childConstructors, function( i, child ) {
			var childPrototype = child.prototype;

			// redefine the child widget using the same prototype that was
			// originally used, but inherit from the new version of the base
			$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
		});
		// remove the list of existing child constructors from the old constructor
		// so the old child constructors can be garbage collected
		delete existingConstructor._childConstructors;
	} else {
		base._childConstructors.push( constructor );
	}

	$.widget.bridge( name, constructor );

	return constructor;
};

$.widget.extend = function( target ) {
	var input = widget_slice.call( arguments, 1 ),
		inputIndex = 0,
		inputLength = input.length,
		key,
		value;
	for ( ; inputIndex < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :
						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );
				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

$.widget.bridge = function( name, object ) {
	var fullName = object.prototype.widgetFullName || name;
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = widget_slice.call( arguments, 1 ),
			returnValue = this;

		if ( isMethodCall ) {
			this.each(function() {
				var methodValue,
					instance = $.data( this, fullName );
				if ( options === "instance" ) {
					returnValue = instance;
					return false;
				}
				if ( !instance ) {
					return $.error( "cannot call methods on " + name + " prior to initialization; " +
						"attempted to call method '" + options + "'" );
				}
				if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
					return $.error( "no such method '" + options + "' for " + name + " widget instance" );
				}
				methodValue = instance[ options ].apply( instance, args );
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue && methodValue.jquery ?
						returnValue.pushStack( methodValue.get() ) :
						methodValue;
					return false;
				}
			});
		} else {

			// Allow multiple hashes to be passed on init
			if ( args.length ) {
				options = $.widget.extend.apply( null, [ options ].concat(args) );
			}

			this.each(function() {
				var instance = $.data( this, fullName );
				if ( instance ) {
					instance.option( options || {} );
					if ( instance._init ) {
						instance._init();
					}
				} else {
					$.data( this, fullName, new object( options, this ) );
				}
			});
		}

		return returnValue;
	};
};

$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	defaultElement: "<div>",
	options: {
		disabled: false,

		// callbacks
		create: null
	},
	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = widget_uuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();

		if ( element !== this ) {
			$.data( element, this.widgetFullName, this );
			this._on( true, this.element, {
				remove: function( event ) {
					if ( event.target === element ) {
						this.destroy();
					}
				}
			});
			this.document = $( element.style ?
				// element within the document
				element.ownerDocument :
				// element is window or document
				element.document || element );
			this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
		}

		this.options = $.widget.extend( {},
			this.options,
			this._getCreateOptions(),
			options );

		this._create();
		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},
	_getCreateOptions: $.noop,
	_getCreateEventData: $.noop,
	_create: $.noop,
	_init: $.noop,

	destroy: function() {
		this._destroy();
		// we can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.unbind( this.eventNamespace )
			.removeData( this.widgetFullName )
			// support: jquery <1.6.3
			// http://bugs.jquery.com/ticket/9413
			.removeData( $.camelCase( this.widgetFullName ) );
		this.widget()
			.unbind( this.eventNamespace )
			.removeAttr( "aria-disabled" )
			.removeClass(
				this.widgetFullName + "-disabled " +
				"ui-state-disabled" );

		// clean up events and states
		this.bindings.unbind( this.eventNamespace );
		this.hoverable.removeClass( "ui-state-hover" );
		this.focusable.removeClass( "ui-state-focus" );
	},
	_destroy: $.noop,

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key,
			parts,
			curOption,
			i;

		if ( arguments.length === 0 ) {
			// don't return a reference to the internal hash
			return $.widget.extend( {}, this.options );
		}

		if ( typeof key === "string" ) {
			// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
			options = {};
			parts = key.split( "." );
			key = parts.shift();
			if ( parts.length ) {
				curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
				for ( i = 0; i < parts.length - 1; i++ ) {
					curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
					curOption = curOption[ parts[ i ] ];
				}
				key = parts.pop();
				if ( arguments.length === 1 ) {
					return curOption[ key ] === undefined ? null : curOption[ key ];
				}
				curOption[ key ] = value;
			} else {
				if ( arguments.length === 1 ) {
					return this.options[ key ] === undefined ? null : this.options[ key ];
				}
				options[ key ] = value;
			}
		}

		this._setOptions( options );

		return this;
	},
	_setOptions: function( options ) {
		var key;

		for ( key in options ) {
			this._setOption( key, options[ key ] );
		}

		return this;
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				.toggleClass( this.widgetFullName + "-disabled", !!value );

			// If the widget is becoming disabled, then nothing is interactive
			if ( value ) {
				this.hoverable.removeClass( "ui-state-hover" );
				this.focusable.removeClass( "ui-state-focus" );
			}
		}

		return this;
	},

	enable: function() {
		return this._setOptions({ disabled: false });
	},
	disable: function() {
		return this._setOptions({ disabled: true });
	},

	_on: function( suppressDisabledCheck, element, handlers ) {
		var delegateElement,
			instance = this;

		// no suppressDisabledCheck flag, shuffle arguments
		if ( typeof suppressDisabledCheck !== "boolean" ) {
			handlers = element;
			element = suppressDisabledCheck;
			suppressDisabledCheck = false;
		}

		// no element argument, shuffle and use this.element
		if ( !handlers ) {
			handlers = element;
			element = this.element;
			delegateElement = this.widget();
		} else {
			element = delegateElement = $( element );
			this.bindings = this.bindings.add( element );
		}

		$.each( handlers, function( event, handler ) {
			function handlerProxy() {
				// allow widgets to customize the disabled handling
				// - disabled as an array instead of boolean
				// - disabled class as method for disabling individual parts
				if ( !suppressDisabledCheck &&
						( instance.options.disabled === true ||
							$( this ).hasClass( "ui-state-disabled" ) ) ) {
					return;
				}
				return ( typeof handler === "string" ? instance[ handler ] : handler )
					.apply( instance, arguments );
			}

			// copy the guid so direct unbinding works
			if ( typeof handler !== "string" ) {
				handlerProxy.guid = handler.guid =
					handler.guid || handlerProxy.guid || $.guid++;
			}

			var match = event.match( /^([\w:-]*)\s*(.*)$/ ),
				eventName = match[1] + instance.eventNamespace,
				selector = match[2];
			if ( selector ) {
				delegateElement.delegate( selector, eventName, handlerProxy );
			} else {
				element.bind( eventName, handlerProxy );
			}
		});
	},

	_off: function( element, eventName ) {
		eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) +
			this.eventNamespace;
		element.unbind( eventName ).undelegate( eventName );

		// Clear the stack to avoid memory leaks (#10056)
		this.bindings = $( this.bindings.not( element ).get() );
		this.focusable = $( this.focusable.not( element ).get() );
		this.hoverable = $( this.hoverable.not( element ).get() );
	},

	_delay: function( handler, delay ) {
		function handlerProxy() {
			return ( typeof handler === "string" ? instance[ handler ] : handler )
				.apply( instance, arguments );
		}
		var instance = this;
		return setTimeout( handlerProxy, delay || 0 );
	},

	_hoverable: function( element ) {
		this.hoverable = this.hoverable.add( element );
		this._on( element, {
			mouseenter: function( event ) {
				$( event.currentTarget ).addClass( "ui-state-hover" );
			},
			mouseleave: function( event ) {
				$( event.currentTarget ).removeClass( "ui-state-hover" );
			}
		});
	},

	_focusable: function( element ) {
		this.focusable = this.focusable.add( element );
		this._on( element, {
			focusin: function( event ) {
				$( event.currentTarget ).addClass( "ui-state-focus" );
			},
			focusout: function( event ) {
				$( event.currentTarget ).removeClass( "ui-state-focus" );
			}
		});
	},

	_trigger: function( type, event, data ) {
		var prop, orig,
			callback = this.options[ type ];

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		// the original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

		// copy original event properties over to the new event
		orig = event.originalEvent;
		if ( orig ) {
			for ( prop in orig ) {
				if ( !( prop in event ) ) {
					event[ prop ] = orig[ prop ];
				}
			}
		}

		this.element.trigger( event, data );
		return !( $.isFunction( callback ) &&
			callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
			event.isDefaultPrevented() );
	}
};

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}
		var hasOptions,
			effectName = !options ?
				method :
				options === true || typeof options === "number" ?
					defaultEffect :
					options.effect || defaultEffect;
		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		}
		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;
		if ( options.delay ) {
			element.delay( options.delay );
		}
		if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue(function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			});
		}
	};
});

var widget = $.widget;


/*!
 * jQuery UI Mouse 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/mouse/
 */


var mouseHandled = false;
$( document ).mouseup( function() {
	mouseHandled = false;
});

var mouse = $.widget("ui.mouse", {
	version: "1.11.4",
	options: {
		cancel: "input,textarea,button,select,option",
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var that = this;

		this.element
			.bind("mousedown." + this.widgetName, function(event) {
				return that._mouseDown(event);
			})
			.bind("click." + this.widgetName, function(event) {
				if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
					$.removeData(event.target, that.widgetName + ".preventClickEvent");
					event.stopImmediatePropagation();
					return false;
				}
			});

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind("." + this.widgetName);
		if ( this._mouseMoveDelegate ) {
			this.document
				.unbind("mousemove." + this.widgetName, this._mouseMoveDelegate)
				.unbind("mouseup." + this.widgetName, this._mouseUpDelegate);
		}
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		if ( mouseHandled ) {
			return;
		}

		this._mouseMoved = false;

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = (event.which === 1),
			// event.target.nodeName works around a bug in IE 8 with
			// disabled inputs (#7620)
			elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				that.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
			$.removeData(event.target, this.widgetName + ".preventClickEvent");
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return that._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return that._mouseUp(event);
		};

		this.document
			.bind( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.bind( "mouseup." + this.widgetName, this._mouseUpDelegate );

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// Only check for mouseups outside the document if you've moved inside the document
		// at least once. This prevents the firing of mouseup in the case of IE<9, which will
		// fire a mousemove event if content is placed under the cursor. See #7778
		// Support: IE <9
		if ( this._mouseMoved ) {
			// IE mouseup check - mouseup happened when mouse was out of window
			if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
				return this._mouseUp(event);

			// Iframe mouseup check - mouseup occurred in another document
			} else if ( !event.which ) {
				return this._mouseUp( event );
			}
		}

		if ( event.which || event.button ) {
			this._mouseMoved = true;
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		this.document
			.unbind( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.unbind( "mouseup." + this.widgetName, this._mouseUpDelegate );

		if (this._mouseStarted) {
			this._mouseStarted = false;

			if (event.target === this._mouseDownEvent.target) {
				$.data(event.target, this.widgetName + ".preventClickEvent", true);
			}

			this._mouseStop(event);
		}

		mouseHandled = false;
		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(/* event */) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(/* event */) {},
	_mouseDrag: function(/* event */) {},
	_mouseStop: function(/* event */) {},
	_mouseCapture: function(/* event */) { return true; }
});


/*!
 * jQuery UI Position 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/position/
 */

(function() {

$.ui = $.ui || {};

var cachedScrollbarWidth, supportsOffsetFractions,
	max = Math.max,
	abs = Math.abs,
	round = Math.round,
	rhorizontal = /left|center|right/,
	rvertical = /top|center|bottom/,
	roffset = /[\+\-]\d+(\.[\d]+)?%?/,
	rposition = /^\w+/,
	rpercent = /%$/,
	_position = $.fn.position;

function getOffsets( offsets, width, height ) {
	return [
		parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
		parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
	];
}

function parseCss( element, property ) {
	return parseInt( $.css( element, property ), 10 ) || 0;
}

function getDimensions( elem ) {
	var raw = elem[0];
	if ( raw.nodeType === 9 ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: 0, left: 0 }
		};
	}
	if ( $.isWindow( raw ) ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
		};
	}
	if ( raw.preventDefault ) {
		return {
			width: 0,
			height: 0,
			offset: { top: raw.pageY, left: raw.pageX }
		};
	}
	return {
		width: elem.outerWidth(),
		height: elem.outerHeight(),
		offset: elem.offset()
	};
}

$.position = {
	scrollbarWidth: function() {
		if ( cachedScrollbarWidth !== undefined ) {
			return cachedScrollbarWidth;
		}
		var w1, w2,
			div = $( "<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
			innerDiv = div.children()[0];

		$( "body" ).append( div );
		w1 = innerDiv.offsetWidth;
		div.css( "overflow", "scroll" );

		w2 = innerDiv.offsetWidth;

		if ( w1 === w2 ) {
			w2 = div[0].clientWidth;
		}

		div.remove();

		return (cachedScrollbarWidth = w1 - w2);
	},
	getScrollInfo: function( within ) {
		var overflowX = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-x" ),
			overflowY = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-y" ),
			hasOverflowX = overflowX === "scroll" ||
				( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
			hasOverflowY = overflowY === "scroll" ||
				( overflowY === "auto" && within.height < within.element[0].scrollHeight );
		return {
			width: hasOverflowY ? $.position.scrollbarWidth() : 0,
			height: hasOverflowX ? $.position.scrollbarWidth() : 0
		};
	},
	getWithinInfo: function( element ) {
		var withinElement = $( element || window ),
			isWindow = $.isWindow( withinElement[0] ),
			isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9;
		return {
			element: withinElement,
			isWindow: isWindow,
			isDocument: isDocument,
			offset: withinElement.offset() || { left: 0, top: 0 },
			scrollLeft: withinElement.scrollLeft(),
			scrollTop: withinElement.scrollTop(),

			// support: jQuery 1.6.x
			// jQuery 1.6 doesn't support .outerWidth/Height() on documents or windows
			width: isWindow || isDocument ? withinElement.width() : withinElement.outerWidth(),
			height: isWindow || isDocument ? withinElement.height() : withinElement.outerHeight()
		};
	}
};

$.fn.position = function( options ) {
	if ( !options || !options.of ) {
		return _position.apply( this, arguments );
	}

	// make a copy, we don't want to modify arguments
	options = $.extend( {}, options );

	var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
		target = $( options.of ),
		within = $.position.getWithinInfo( options.within ),
		scrollInfo = $.position.getScrollInfo( within ),
		collision = ( options.collision || "flip" ).split( " " ),
		offsets = {};

	dimensions = getDimensions( target );
	if ( target[0].preventDefault ) {
		// force left top to allow flipping
		options.at = "left top";
	}
	targetWidth = dimensions.width;
	targetHeight = dimensions.height;
	targetOffset = dimensions.offset;
	// clone to reuse original targetOffset later
	basePosition = $.extend( {}, targetOffset );

	// force my and at to have valid horizontal and vertical positions
	// if a value is missing or invalid, it will be converted to center
	$.each( [ "my", "at" ], function() {
		var pos = ( options[ this ] || "" ).split( " " ),
			horizontalOffset,
			verticalOffset;

		if ( pos.length === 1) {
			pos = rhorizontal.test( pos[ 0 ] ) ?
				pos.concat( [ "center" ] ) :
				rvertical.test( pos[ 0 ] ) ?
					[ "center" ].concat( pos ) :
					[ "center", "center" ];
		}
		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";

		// calculate offsets
		horizontalOffset = roffset.exec( pos[ 0 ] );
		verticalOffset = roffset.exec( pos[ 1 ] );
		offsets[ this ] = [
			horizontalOffset ? horizontalOffset[ 0 ] : 0,
			verticalOffset ? verticalOffset[ 0 ] : 0
		];

		// reduce to just the positions without the offsets
		options[ this ] = [
			rposition.exec( pos[ 0 ] )[ 0 ],
			rposition.exec( pos[ 1 ] )[ 0 ]
		];
	});

	// normalize collision option
	if ( collision.length === 1 ) {
		collision[ 1 ] = collision[ 0 ];
	}

	if ( options.at[ 0 ] === "right" ) {
		basePosition.left += targetWidth;
	} else if ( options.at[ 0 ] === "center" ) {
		basePosition.left += targetWidth / 2;
	}

	if ( options.at[ 1 ] === "bottom" ) {
		basePosition.top += targetHeight;
	} else if ( options.at[ 1 ] === "center" ) {
		basePosition.top += targetHeight / 2;
	}

	atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
	basePosition.left += atOffset[ 0 ];
	basePosition.top += atOffset[ 1 ];

	return this.each(function() {
		var collisionPosition, using,
			elem = $( this ),
			elemWidth = elem.outerWidth(),
			elemHeight = elem.outerHeight(),
			marginLeft = parseCss( this, "marginLeft" ),
			marginTop = parseCss( this, "marginTop" ),
			collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
			collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
			position = $.extend( {}, basePosition ),
			myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );

		if ( options.my[ 0 ] === "right" ) {
			position.left -= elemWidth;
		} else if ( options.my[ 0 ] === "center" ) {
			position.left -= elemWidth / 2;
		}

		if ( options.my[ 1 ] === "bottom" ) {
			position.top -= elemHeight;
		} else if ( options.my[ 1 ] === "center" ) {
			position.top -= elemHeight / 2;
		}

		position.left += myOffset[ 0 ];
		position.top += myOffset[ 1 ];

		// if the browser doesn't support fractions, then round for consistent results
		if ( !supportsOffsetFractions ) {
			position.left = round( position.left );
			position.top = round( position.top );
		}

		collisionPosition = {
			marginLeft: marginLeft,
			marginTop: marginTop
		};

		$.each( [ "left", "top" ], function( i, dir ) {
			if ( $.ui.position[ collision[ i ] ] ) {
				$.ui.position[ collision[ i ] ][ dir ]( position, {
					targetWidth: targetWidth,
					targetHeight: targetHeight,
					elemWidth: elemWidth,
					elemHeight: elemHeight,
					collisionPosition: collisionPosition,
					collisionWidth: collisionWidth,
					collisionHeight: collisionHeight,
					offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
					my: options.my,
					at: options.at,
					within: within,
					elem: elem
				});
			}
		});

		if ( options.using ) {
			// adds feedback as second argument to using callback, if present
			using = function( props ) {
				var left = targetOffset.left - position.left,
					right = left + targetWidth - elemWidth,
					top = targetOffset.top - position.top,
					bottom = top + targetHeight - elemHeight,
					feedback = {
						target: {
							element: target,
							left: targetOffset.left,
							top: targetOffset.top,
							width: targetWidth,
							height: targetHeight
						},
						element: {
							element: elem,
							left: position.left,
							top: position.top,
							width: elemWidth,
							height: elemHeight
						},
						horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
						vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
					};
				if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
					feedback.horizontal = "center";
				}
				if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
					feedback.vertical = "middle";
				}
				if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
					feedback.important = "horizontal";
				} else {
					feedback.important = "vertical";
				}
				options.using.call( this, props, feedback );
			};
		}

		elem.offset( $.extend( position, { using: using } ) );
	});
};

$.ui.position = {
	fit: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
				outerWidth = within.width,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = withinOffset - collisionPosLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
				newOverRight;

			// element is wider than within
			if ( data.collisionWidth > outerWidth ) {
				// element is initially over the left side of within
				if ( overLeft > 0 && overRight <= 0 ) {
					newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
					position.left += overLeft - newOverRight;
				// element is initially over right side of within
				} else if ( overRight > 0 && overLeft <= 0 ) {
					position.left = withinOffset;
				// element is initially over both left and right sides of within
				} else {
					if ( overLeft > overRight ) {
						position.left = withinOffset + outerWidth - data.collisionWidth;
					} else {
						position.left = withinOffset;
					}
				}
			// too far left -> align with left edge
			} else if ( overLeft > 0 ) {
				position.left += overLeft;
			// too far right -> align with right edge
			} else if ( overRight > 0 ) {
				position.left -= overRight;
			// adjust based on position and margin
			} else {
				position.left = max( position.left - collisionPosLeft, position.left );
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
				outerHeight = data.within.height,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = withinOffset - collisionPosTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
				newOverBottom;

			// element is taller than within
			if ( data.collisionHeight > outerHeight ) {
				// element is initially over the top of within
				if ( overTop > 0 && overBottom <= 0 ) {
					newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
					position.top += overTop - newOverBottom;
				// element is initially over bottom of within
				} else if ( overBottom > 0 && overTop <= 0 ) {
					position.top = withinOffset;
				// element is initially over both top and bottom of within
				} else {
					if ( overTop > overBottom ) {
						position.top = withinOffset + outerHeight - data.collisionHeight;
					} else {
						position.top = withinOffset;
					}
				}
			// too far up -> align with top
			} else if ( overTop > 0 ) {
				position.top += overTop;
			// too far down -> align with bottom edge
			} else if ( overBottom > 0 ) {
				position.top -= overBottom;
			// adjust based on position and margin
			} else {
				position.top = max( position.top - collisionPosTop, position.top );
			}
		}
	},
	flip: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.left + within.scrollLeft,
				outerWidth = within.width,
				offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = collisionPosLeft - offsetLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
				myOffset = data.my[ 0 ] === "left" ?
					-data.elemWidth :
					data.my[ 0 ] === "right" ?
						data.elemWidth :
						0,
				atOffset = data.at[ 0 ] === "left" ?
					data.targetWidth :
					data.at[ 0 ] === "right" ?
						-data.targetWidth :
						0,
				offset = -2 * data.offset[ 0 ],
				newOverRight,
				newOverLeft;

			if ( overLeft < 0 ) {
				newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
				if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
					position.left += myOffset + atOffset + offset;
				}
			} else if ( overRight > 0 ) {
				newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
				if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
					position.left += myOffset + atOffset + offset;
				}
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.top + within.scrollTop,
				outerHeight = within.height,
				offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = collisionPosTop - offsetTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
				top = data.my[ 1 ] === "top",
				myOffset = top ?
					-data.elemHeight :
					data.my[ 1 ] === "bottom" ?
						data.elemHeight :
						0,
				atOffset = data.at[ 1 ] === "top" ?
					data.targetHeight :
					data.at[ 1 ] === "bottom" ?
						-data.targetHeight :
						0,
				offset = -2 * data.offset[ 1 ],
				newOverTop,
				newOverBottom;
			if ( overTop < 0 ) {
				newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
				if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {
					position.top += myOffset + atOffset + offset;
				}
			} else if ( overBottom > 0 ) {
				newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
				if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) {
					position.top += myOffset + atOffset + offset;
				}
			}
		}
	},
	flipfit: {
		left: function() {
			$.ui.position.flip.left.apply( this, arguments );
			$.ui.position.fit.left.apply( this, arguments );
		},
		top: function() {
			$.ui.position.flip.top.apply( this, arguments );
			$.ui.position.fit.top.apply( this, arguments );
		}
	}
};

// fraction support test
(function() {
	var testElement, testElementParent, testElementStyle, offsetLeft, i,
		body = document.getElementsByTagName( "body" )[ 0 ],
		div = document.createElement( "div" );

	//Create a "fake body" for testing based on method used in jQuery.support
	testElement = document.createElement( body ? "div" : "body" );
	testElementStyle = {
		visibility: "hidden",
		width: 0,
		height: 0,
		border: 0,
		margin: 0,
		background: "none"
	};
	if ( body ) {
		$.extend( testElementStyle, {
			position: "absolute",
			left: "-1000px",
			top: "-1000px"
		});
	}
	for ( i in testElementStyle ) {
		testElement.style[ i ] = testElementStyle[ i ];
	}
	testElement.appendChild( div );
	testElementParent = body || document.documentElement;
	testElementParent.insertBefore( testElement, testElementParent.firstChild );

	div.style.cssText = "position: absolute; left: 10.7432222px;";

	offsetLeft = $( div ).offset().left;
	supportsOffsetFractions = offsetLeft > 10 && offsetLeft < 11;

	testElement.innerHTML = "";
	testElementParent.removeChild( testElement );
})();

})();

var position = $.ui.position;


/*!
 * jQuery UI Accordion 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/accordion/
 */


var accordion = $.widget( "ui.accordion", {
	version: "1.11.4",
	options: {
		active: 0,
		animate: {},
		collapsible: false,
		event: "click",
		header: "> li > :first-child,> :not(li):even",
		heightStyle: "auto",
		icons: {
			activeHeader: "ui-icon-triangle-1-s",
			header: "ui-icon-triangle-1-e"
		},

		// callbacks
		activate: null,
		beforeActivate: null
	},

	hideProps: {
		borderTopWidth: "hide",
		borderBottomWidth: "hide",
		paddingTop: "hide",
		paddingBottom: "hide",
		height: "hide"
	},

	showProps: {
		borderTopWidth: "show",
		borderBottomWidth: "show",
		paddingTop: "show",
		paddingBottom: "show",
		height: "show"
	},

	_create: function() {
		var options = this.options;
		this.prevShow = this.prevHide = $();
		this.element.addClass( "ui-accordion ui-widget ui-helper-reset" )
			// ARIA
			.attr( "role", "tablist" );

		// don't allow collapsible: false and active: false / null
		if ( !options.collapsible && (options.active === false || options.active == null) ) {
			options.active = 0;
		}

		this._processPanels();
		// handle negative values
		if ( options.active < 0 ) {
			options.active += this.headers.length;
		}
		this._refresh();
	},

	_getCreateEventData: function() {
		return {
			header: this.active,
			panel: !this.active.length ? $() : this.active.next()
		};
	},

	_createIcons: function() {
		var icons = this.options.icons;
		if ( icons ) {
			$( "<span>" )
				.addClass( "ui-accordion-header-icon ui-icon " + icons.header )
				.prependTo( this.headers );
			this.active.children( ".ui-accordion-header-icon" )
				.removeClass( icons.header )
				.addClass( icons.activeHeader );
			this.headers.addClass( "ui-accordion-icons" );
		}
	},

	_destroyIcons: function() {
		this.headers
			.removeClass( "ui-accordion-icons" )
			.children( ".ui-accordion-header-icon" )
				.remove();
	},

	_destroy: function() {
		var contents;

		// clean up main element
		this.element
			.removeClass( "ui-accordion ui-widget ui-helper-reset" )
			.removeAttr( "role" );

		// clean up headers
		this.headers
			.removeClass( "ui-accordion-header ui-accordion-header-active ui-state-default " +
				"ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
			.removeAttr( "role" )
			.removeAttr( "aria-expanded" )
			.removeAttr( "aria-selected" )
			.removeAttr( "aria-controls" )
			.removeAttr( "tabIndex" )
			.removeUniqueId();

		this._destroyIcons();

		// clean up content panels
		contents = this.headers.next()
			.removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom " +
				"ui-accordion-content ui-accordion-content-active ui-state-disabled" )
			.css( "display", "" )
			.removeAttr( "role" )
			.removeAttr( "aria-hidden" )
			.removeAttr( "aria-labelledby" )
			.removeUniqueId();

		if ( this.options.heightStyle !== "content" ) {
			contents.css( "height", "" );
		}
	},

	_setOption: function( key, value ) {
		if ( key === "active" ) {
			// _activate() will handle invalid values and update this.options
			this._activate( value );
			return;
		}

		if ( key === "event" ) {
			if ( this.options.event ) {
				this._off( this.headers, this.options.event );
			}
			this._setupEvents( value );
		}

		this._super( key, value );

		// setting collapsible: false while collapsed; open first panel
		if ( key === "collapsible" && !value && this.options.active === false ) {
			this._activate( 0 );
		}

		if ( key === "icons" ) {
			this._destroyIcons();
			if ( value ) {
				this._createIcons();
			}
		}

		// #5332 - opacity doesn't cascade to positioned elements in IE
		// so we need to add the disabled class to the headers and panels
		if ( key === "disabled" ) {
			this.element
				.toggleClass( "ui-state-disabled", !!value )
				.attr( "aria-disabled", value );
			this.headers.add( this.headers.next() )
				.toggleClass( "ui-state-disabled", !!value );
		}
	},

	_keydown: function( event ) {
		if ( event.altKey || event.ctrlKey ) {
			return;
		}

		var keyCode = $.ui.keyCode,
			length = this.headers.length,
			currentIndex = this.headers.index( event.target ),
			toFocus = false;

		switch ( event.keyCode ) {
			case keyCode.RIGHT:
			case keyCode.DOWN:
				toFocus = this.headers[ ( currentIndex + 1 ) % length ];
				break;
			case keyCode.LEFT:
			case keyCode.UP:
				toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
				break;
			case keyCode.SPACE:
			case keyCode.ENTER:
				this._eventHandler( event );
				break;
			case keyCode.HOME:
				toFocus = this.headers[ 0 ];
				break;
			case keyCode.END:
				toFocus = this.headers[ length - 1 ];
				break;
		}

		if ( toFocus ) {
			$( event.target ).attr( "tabIndex", -1 );
			$( toFocus ).attr( "tabIndex", 0 );
			toFocus.focus();
			event.preventDefault();
		}
	},

	_panelKeyDown: function( event ) {
		if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
			$( event.currentTarget ).prev().focus();
		}
	},

	refresh: function() {
		var options = this.options;
		this._processPanels();

		// was collapsed or no panel
		if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) {
			options.active = false;
			this.active = $();
		// active false only when collapsible is true
		} else if ( options.active === false ) {
			this._activate( 0 );
		// was active, but active panel is gone
		} else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
			// all remaining panel are disabled
			if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) {
				options.active = false;
				this.active = $();
			// activate previous panel
			} else {
				this._activate( Math.max( 0, options.active - 1 ) );
			}
		// was active, active panel still exists
		} else {
			// make sure active index is correct
			options.active = this.headers.index( this.active );
		}

		this._destroyIcons();

		this._refresh();
	},

	_processPanels: function() {
		var prevHeaders = this.headers,
			prevPanels = this.panels;

		this.headers = this.element.find( this.options.header )
			.addClass( "ui-accordion-header ui-state-default ui-corner-all" );

		this.panels = this.headers.next()
			.addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" )
			.filter( ":not(.ui-accordion-content-active)" )
			.hide();

		// Avoid memory leaks (#10056)
		if ( prevPanels ) {
			this._off( prevHeaders.not( this.headers ) );
			this._off( prevPanels.not( this.panels ) );
		}
	},

	_refresh: function() {
		var maxHeight,
			options = this.options,
			heightStyle = options.heightStyle,
			parent = this.element.parent();

		this.active = this._findActive( options.active )
			.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" )
			.removeClass( "ui-corner-all" );
		this.active.next()
			.addClass( "ui-accordion-content-active" )
			.show();

		this.headers
			.attr( "role", "tab" )
			.each(function() {
				var header = $( this ),
					headerId = header.uniqueId().attr( "id" ),
					panel = header.next(),
					panelId = panel.uniqueId().attr( "id" );
				header.attr( "aria-controls", panelId );
				panel.attr( "aria-labelledby", headerId );
			})
			.next()
				.attr( "role", "tabpanel" );

		this.headers
			.not( this.active )
			.attr({
				"aria-selected": "false",
				"aria-expanded": "false",
				tabIndex: -1
			})
			.next()
				.attr({
					"aria-hidden": "true"
				})
				.hide();

		// make sure at least one header is in the tab order
		if ( !this.active.length ) {
			this.headers.eq( 0 ).attr( "tabIndex", 0 );
		} else {
			this.active.attr({
				"aria-selected": "true",
				"aria-expanded": "true",
				tabIndex: 0
			})
			.next()
				.attr({
					"aria-hidden": "false"
				});
		}

		this._createIcons();

		this._setupEvents( options.event );

		if ( heightStyle === "fill" ) {
			maxHeight = parent.height();
			this.element.siblings( ":visible" ).each(function() {
				var elem = $( this ),
					position = elem.css( "position" );

				if ( position === "absolute" || position === "fixed" ) {
					return;
				}
				maxHeight -= elem.outerHeight( true );
			});

			this.headers.each(function() {
				maxHeight -= $( this ).outerHeight( true );
			});

			this.headers.next()
				.each(function() {
					$( this ).height( Math.max( 0, maxHeight -
						$( this ).innerHeight() + $( this ).height() ) );
				})
				.css( "overflow", "auto" );
		} else if ( heightStyle === "auto" ) {
			maxHeight = 0;
			this.headers.next()
				.each(function() {
					maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
				})
				.height( maxHeight );
		}
	},

	_activate: function( index ) {
		var active = this._findActive( index )[ 0 ];

		// trying to activate the already active panel
		if ( active === this.active[ 0 ] ) {
			return;
		}

		// trying to collapse, simulate a click on the currently active header
		active = active || this.active[ 0 ];

		this._eventHandler({
			target: active,
			currentTarget: active,
			preventDefault: $.noop
		});
	},

	_findActive: function( selector ) {
		return typeof selector === "number" ? this.headers.eq( selector ) : $();
	},

	_setupEvents: function( event ) {
		var events = {
			keydown: "_keydown"
		};
		if ( event ) {
			$.each( event.split( " " ), function( index, eventName ) {
				events[ eventName ] = "_eventHandler";
			});
		}

		this._off( this.headers.add( this.headers.next() ) );
		this._on( this.headers, events );
		this._on( this.headers.next(), { keydown: "_panelKeyDown" });
		this._hoverable( this.headers );
		this._focusable( this.headers );
	},

	_eventHandler: function( event ) {
		var options = this.options,
			active = this.active,
			clicked = $( event.currentTarget ),
			clickedIsActive = clicked[ 0 ] === active[ 0 ],
			collapsing = clickedIsActive && options.collapsible,
			toShow = collapsing ? $() : clicked.next(),
			toHide = active.next(),
			eventData = {
				oldHeader: active,
				oldPanel: toHide,
				newHeader: collapsing ? $() : clicked,
				newPanel: toShow
			};

		event.preventDefault();

		if (
				// click on active header, but not collapsible
				( clickedIsActive && !options.collapsible ) ||
				// allow canceling activation
				( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
			return;
		}

		options.active = collapsing ? false : this.headers.index( clicked );

		// when the call to ._toggle() comes after the class changes
		// it causes a very odd bug in IE 8 (see #6720)
		this.active = clickedIsActive ? $() : clicked;
		this._toggle( eventData );

		// switch classes
		// corner classes on the previously active header stay after the animation
		active.removeClass( "ui-accordion-header-active ui-state-active" );
		if ( options.icons ) {
			active.children( ".ui-accordion-header-icon" )
				.removeClass( options.icons.activeHeader )
				.addClass( options.icons.header );
		}

		if ( !clickedIsActive ) {
			clicked
				.removeClass( "ui-corner-all" )
				.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" );
			if ( options.icons ) {
				clicked.children( ".ui-accordion-header-icon" )
					.removeClass( options.icons.header )
					.addClass( options.icons.activeHeader );
			}

			clicked
				.next()
				.addClass( "ui-accordion-content-active" );
		}
	},

	_toggle: function( data ) {
		var toShow = data.newPanel,
			toHide = this.prevShow.length ? this.prevShow : data.oldPanel;

		// handle activating a panel during the animation for another activation
		this.prevShow.add( this.prevHide ).stop( true, true );
		this.prevShow = toShow;
		this.prevHide = toHide;

		if ( this.options.animate ) {
			this._animate( toShow, toHide, data );
		} else {
			toHide.hide();
			toShow.show();
			this._toggleComplete( data );
		}

		toHide.attr({
			"aria-hidden": "true"
		});
		toHide.prev().attr({
			"aria-selected": "false",
			"aria-expanded": "false"
		});
		// if we're switching panels, remove the old header from the tab order
		// if we're opening from collapsed state, remove the previous header from the tab order
		// if we're collapsing, then keep the collapsing header in the tab order
		if ( toShow.length && toHide.length ) {
			toHide.prev().attr({
				"tabIndex": -1,
				"aria-expanded": "false"
			});
		} else if ( toShow.length ) {
			this.headers.filter(function() {
				return parseInt( $( this ).attr( "tabIndex" ), 10 ) === 0;
			})
			.attr( "tabIndex", -1 );
		}

		toShow
			.attr( "aria-hidden", "false" )
			.prev()
				.attr({
					"aria-selected": "true",
					"aria-expanded": "true",
					tabIndex: 0
				});
	},

	_animate: function( toShow, toHide, data ) {
		var total, easing, duration,
			that = this,
			adjust = 0,
			boxSizing = toShow.css( "box-sizing" ),
			down = toShow.length &&
				( !toHide.length || ( toShow.index() < toHide.index() ) ),
			animate = this.options.animate || {},
			options = down && animate.down || animate,
			complete = function() {
				that._toggleComplete( data );
			};

		if ( typeof options === "number" ) {
			duration = options;
		}
		if ( typeof options === "string" ) {
			easing = options;
		}
		// fall back from options to animation in case of partial down settings
		easing = easing || options.easing || animate.easing;
		duration = duration || options.duration || animate.duration;

		if ( !toHide.length ) {
			return toShow.animate( this.showProps, duration, easing, complete );
		}
		if ( !toShow.length ) {
			return toHide.animate( this.hideProps, duration, easing, complete );
		}

		total = toShow.show().outerHeight();
		toHide.animate( this.hideProps, {
			duration: duration,
			easing: easing,
			step: function( now, fx ) {
				fx.now = Math.round( now );
			}
		});
		toShow
			.hide()
			.animate( this.showProps, {
				duration: duration,
				easing: easing,
				complete: complete,
				step: function( now, fx ) {
					fx.now = Math.round( now );
					if ( fx.prop !== "height" ) {
						if ( boxSizing === "content-box" ) {
							adjust += fx.now;
						}
					} else if ( that.options.heightStyle !== "content" ) {
						fx.now = Math.round( total - toHide.outerHeight() - adjust );
						adjust = 0;
					}
				}
			});
	},

	_toggleComplete: function( data ) {
		var toHide = data.oldPanel;

		toHide
			.removeClass( "ui-accordion-content-active" )
			.prev()
				.removeClass( "ui-corner-top" )
				.addClass( "ui-corner-all" );

		// Work around for rendering bug in IE (#5421)
		if ( toHide.length ) {
			toHide.parent()[ 0 ].className = toHide.parent()[ 0 ].className;
		}
		this._trigger( "activate", null, data );
	}
});


/*!
 * jQuery UI Menu 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/menu/
 */


var menu = $.widget( "ui.menu", {
	version: "1.11.4",
	defaultElement: "<ul>",
	delay: 300,
	options: {
		icons: {
			submenu: "ui-icon-carat-1-e"
		},
		items: "> *",
		menus: "ul",
		position: {
			my: "left-1 top",
			at: "right top"
		},
		role: "menu",

		// callbacks
		blur: null,
		focus: null,
		select: null
	},

	_create: function() {
		this.activeMenu = this.element;

		// Flag used to prevent firing of the click handler
		// as the event bubbles up through nested menus
		this.mouseHandled = false;
		this.element
			.uniqueId()
			.addClass( "ui-menu ui-widget ui-widget-content" )
			.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length )
			.attr({
				role: this.options.role,
				tabIndex: 0
			});

		if ( this.options.disabled ) {
			this.element
				.addClass( "ui-state-disabled" )
				.attr( "aria-disabled", "true" );
		}

		this._on({
			// Prevent focus from sticking to links inside menu after clicking
			// them (focus should always stay on UL during navigation).
			"mousedown .ui-menu-item": function( event ) {
				event.preventDefault();
			},
			"click .ui-menu-item": function( event ) {
				var target = $( event.target );
				if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
					this.select( event );

					// Only set the mouseHandled flag if the event will bubble, see #9469.
					if ( !event.isPropagationStopped() ) {
						this.mouseHandled = true;
					}

					// Open submenu on click
					if ( target.has( ".ui-menu" ).length ) {
						this.expand( event );
					} else if ( !this.element.is( ":focus" ) && $( this.document[ 0 ].activeElement ).closest( ".ui-menu" ).length ) {

						// Redirect focus to the menu
						this.element.trigger( "focus", [ true ] );

						// If the active item is on the top level, let it stay active.
						// Otherwise, blur the active item since it is no longer visible.
						if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
							clearTimeout( this.timer );
						}
					}
				}
			},
			"mouseenter .ui-menu-item": function( event ) {
				// Ignore mouse events while typeahead is active, see #10458.
				// Prevents focusing the wrong item when typeahead causes a scroll while the mouse
				// is over an item in the menu
				if ( this.previousFilter ) {
					return;
				}
				var target = $( event.currentTarget );
				// Remove ui-state-active class from siblings of the newly focused menu item
				// to avoid a jump caused by adjacent elements both having a class with a border
				target.siblings( ".ui-state-active" ).removeClass( "ui-state-active" );
				this.focus( event, target );
			},
			mouseleave: "collapseAll",
			"mouseleave .ui-menu": "collapseAll",
			focus: function( event, keepActiveItem ) {
				// If there's already an active item, keep it active
				// If not, activate the first item
				var item = this.active || this.element.find( this.options.items ).eq( 0 );

				if ( !keepActiveItem ) {
					this.focus( event, item );
				}
			},
			blur: function( event ) {
				this._delay(function() {
					if ( !$.contains( this.element[0], this.document[0].activeElement ) ) {
						this.collapseAll( event );
					}
				});
			},
			keydown: "_keydown"
		});

		this.refresh();

		// Clicks outside of a menu collapse any open menus
		this._on( this.document, {
			click: function( event ) {
				if ( this._closeOnDocumentClick( event ) ) {
					this.collapseAll( event );
				}

				// Reset the mouseHandled flag
				this.mouseHandled = false;
			}
		});
	},

	_destroy: function() {
		// Destroy (sub)menus
		this.element
			.removeAttr( "aria-activedescendant" )
			.find( ".ui-menu" ).addBack()
				.removeClass( "ui-menu ui-widget ui-widget-content ui-menu-icons ui-front" )
				.removeAttr( "role" )
				.removeAttr( "tabIndex" )
				.removeAttr( "aria-labelledby" )
				.removeAttr( "aria-expanded" )
				.removeAttr( "aria-hidden" )
				.removeAttr( "aria-disabled" )
				.removeUniqueId()
				.show();

		// Destroy menu items
		this.element.find( ".ui-menu-item" )
			.removeClass( "ui-menu-item" )
			.removeAttr( "role" )
			.removeAttr( "aria-disabled" )
			.removeUniqueId()
			.removeClass( "ui-state-hover" )
			.removeAttr( "tabIndex" )
			.removeAttr( "role" )
			.removeAttr( "aria-haspopup" )
			.children().each( function() {
				var elem = $( this );
				if ( elem.data( "ui-menu-submenu-carat" ) ) {
					elem.remove();
				}
			});

		// Destroy menu dividers
		this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" );
	},

	_keydown: function( event ) {
		var match, prev, character, skip,
			preventDefault = true;

		switch ( event.keyCode ) {
		case $.ui.keyCode.PAGE_UP:
			this.previousPage( event );
			break;
		case $.ui.keyCode.PAGE_DOWN:
			this.nextPage( event );
			break;
		case $.ui.keyCode.HOME:
			this._move( "first", "first", event );
			break;
		case $.ui.keyCode.END:
			this._move( "last", "last", event );
			break;
		case $.ui.keyCode.UP:
			this.previous( event );
			break;
		case $.ui.keyCode.DOWN:
			this.next( event );
			break;
		case $.ui.keyCode.LEFT:
			this.collapse( event );
			break;
		case $.ui.keyCode.RIGHT:
			if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
				this.expand( event );
			}
			break;
		case $.ui.keyCode.ENTER:
		case $.ui.keyCode.SPACE:
			this._activate( event );
			break;
		case $.ui.keyCode.ESCAPE:
			this.collapse( event );
			break;
		default:
			preventDefault = false;
			prev = this.previousFilter || "";
			character = String.fromCharCode( event.keyCode );
			skip = false;

			clearTimeout( this.filterTimer );

			if ( character === prev ) {
				skip = true;
			} else {
				character = prev + character;
			}

			match = this._filterMenuItems( character );
			match = skip && match.index( this.active.next() ) !== -1 ?
				this.active.nextAll( ".ui-menu-item" ) :
				match;

			// If no matches on the current filter, reset to the last character pressed
			// to move down the menu to the first item that starts with that character
			if ( !match.length ) {
				character = String.fromCharCode( event.keyCode );
				match = this._filterMenuItems( character );
			}

			if ( match.length ) {
				this.focus( event, match );
				this.previousFilter = character;
				this.filterTimer = this._delay(function() {
					delete this.previousFilter;
				}, 1000 );
			} else {
				delete this.previousFilter;
			}
		}

		if ( preventDefault ) {
			event.preventDefault();
		}
	},

	_activate: function( event ) {
		if ( !this.active.is( ".ui-state-disabled" ) ) {
			if ( this.active.is( "[aria-haspopup='true']" ) ) {
				this.expand( event );
			} else {
				this.select( event );
			}
		}
	},

	refresh: function() {
		var menus, items,
			that = this,
			icon = this.options.icons.submenu,
			submenus = this.element.find( this.options.menus );

		this.element.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length );

		// Initialize nested menus
		submenus.filter( ":not(.ui-menu)" )
			.addClass( "ui-menu ui-widget ui-widget-content ui-front" )
			.hide()
			.attr({
				role: this.options.role,
				"aria-hidden": "true",
				"aria-expanded": "false"
			})
			.each(function() {
				var menu = $( this ),
					item = menu.parent(),
					submenuCarat = $( "<span>" )
						.addClass( "ui-menu-icon ui-icon " + icon )
						.data( "ui-menu-submenu-carat", true );

				item
					.attr( "aria-haspopup", "true" )
					.prepend( submenuCarat );
				menu.attr( "aria-labelledby", item.attr( "id" ) );
			});

		menus = submenus.add( this.element );
		items = menus.find( this.options.items );

		// Initialize menu-items containing spaces and/or dashes only as dividers
		items.not( ".ui-menu-item" ).each(function() {
			var item = $( this );
			if ( that._isDivider( item ) ) {
				item.addClass( "ui-widget-content ui-menu-divider" );
			}
		});

		// Don't refresh list items that are already adapted
		items.not( ".ui-menu-item, .ui-menu-divider" )
			.addClass( "ui-menu-item" )
			.uniqueId()
			.attr({
				tabIndex: -1,
				role: this._itemRole()
			});

		// Add aria-disabled attribute to any disabled menu item
		items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" );

		// If the active item has been removed, blur the menu
		if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
			this.blur();
		}
	},

	_itemRole: function() {
		return {
			menu: "menuitem",
			listbox: "option"
		}[ this.options.role ];
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			this.element.find( ".ui-menu-icon" )
				.removeClass( this.options.icons.submenu )
				.addClass( value.submenu );
		}
		if ( key === "disabled" ) {
			this.element
				.toggleClass( "ui-state-disabled", !!value )
				.attr( "aria-disabled", value );
		}
		this._super( key, value );
	},

	focus: function( event, item ) {
		var nested, focused;
		this.blur( event, event && event.type === "focus" );

		this._scrollIntoView( item );

		this.active = item.first();
		focused = this.active.addClass( "ui-state-focus" ).removeClass( "ui-state-active" );
		// Only update aria-activedescendant if there's a role
		// otherwise we assume focus is managed elsewhere
		if ( this.options.role ) {
			this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
		}

		// Highlight active parent menu item, if any
		this.active
			.parent()
			.closest( ".ui-menu-item" )
			.addClass( "ui-state-active" );

		if ( event && event.type === "keydown" ) {
			this._close();
		} else {
			this.timer = this._delay(function() {
				this._close();
			}, this.delay );
		}

		nested = item.children( ".ui-menu" );
		if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) {
			this._startOpening(nested);
		}
		this.activeMenu = item.parent();

		this._trigger( "focus", event, { item: item } );
	},

	_scrollIntoView: function( item ) {
		var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
		if ( this._hasScroll() ) {
			borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0;
			paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0;
			offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
			scroll = this.activeMenu.scrollTop();
			elementHeight = this.activeMenu.height();
			itemHeight = item.outerHeight();

			if ( offset < 0 ) {
				this.activeMenu.scrollTop( scroll + offset );
			} else if ( offset + itemHeight > elementHeight ) {
				this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
			}
		}
	},

	blur: function( event, fromFocus ) {
		if ( !fromFocus ) {
			clearTimeout( this.timer );
		}

		if ( !this.active ) {
			return;
		}

		this.active.removeClass( "ui-state-focus" );
		this.active = null;

		this._trigger( "blur", event, { item: this.active } );
	},

	_startOpening: function( submenu ) {
		clearTimeout( this.timer );

		// Don't open if already open fixes a Firefox bug that caused a .5 pixel
		// shift in the submenu position when mousing over the carat icon
		if ( submenu.attr( "aria-hidden" ) !== "true" ) {
			return;
		}

		this.timer = this._delay(function() {
			this._close();
			this._open( submenu );
		}, this.delay );
	},

	_open: function( submenu ) {
		var position = $.extend({
			of: this.active
		}, this.options.position );

		clearTimeout( this.timer );
		this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
			.hide()
			.attr( "aria-hidden", "true" );

		submenu
			.show()
			.removeAttr( "aria-hidden" )
			.attr( "aria-expanded", "true" )
			.position( position );
	},

	collapseAll: function( event, all ) {
		clearTimeout( this.timer );
		this.timer = this._delay(function() {
			// If we were passed an event, look for the submenu that contains the event
			var currentMenu = all ? this.element :
				$( event && event.target ).closest( this.element.find( ".ui-menu" ) );

			// If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
			if ( !currentMenu.length ) {
				currentMenu = this.element;
			}

			this._close( currentMenu );

			this.blur( event );
			this.activeMenu = currentMenu;
		}, this.delay );
	},

	// With no arguments, closes the currently active menu - if nothing is active
	// it closes all menus.  If passed an argument, it will search for menus BELOW
	_close: function( startMenu ) {
		if ( !startMenu ) {
			startMenu = this.active ? this.active.parent() : this.element;
		}

		startMenu
			.find( ".ui-menu" )
				.hide()
				.attr( "aria-hidden", "true" )
				.attr( "aria-expanded", "false" )
			.end()
			.find( ".ui-state-active" ).not( ".ui-state-focus" )
				.removeClass( "ui-state-active" );
	},

	_closeOnDocumentClick: function( event ) {
		return !$( event.target ).closest( ".ui-menu" ).length;
	},

	_isDivider: function( item ) {

		// Match hyphen, em dash, en dash
		return !/[^\-\u2014\u2013\s]/.test( item.text() );
	},

	collapse: function( event ) {
		var newItem = this.active &&
			this.active.parent().closest( ".ui-menu-item", this.element );
		if ( newItem && newItem.length ) {
			this._close();
			this.focus( event, newItem );
		}
	},

	expand: function( event ) {
		var newItem = this.active &&
			this.active
				.children( ".ui-menu " )
				.find( this.options.items )
				.first();

		if ( newItem && newItem.length ) {
			this._open( newItem.parent() );

			// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
			this._delay(function() {
				this.focus( event, newItem );
			});
		}
	},

	next: function( event ) {
		this._move( "next", "first", event );
	},

	previous: function( event ) {
		this._move( "prev", "last", event );
	},

	isFirstItem: function() {
		return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
	},

	isLastItem: function() {
		return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
	},

	_move: function( direction, filter, event ) {
		var next;
		if ( this.active ) {
			if ( direction === "first" || direction === "last" ) {
				next = this.active
					[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
					.eq( -1 );
			} else {
				next = this.active
					[ direction + "All" ]( ".ui-menu-item" )
					.eq( 0 );
			}
		}
		if ( !next || !next.length || !this.active ) {
			next = this.activeMenu.find( this.options.items )[ filter ]();
		}

		this.focus( event, next );
	},

	nextPage: function( event ) {
		var item, base, height;

		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isLastItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.nextAll( ".ui-menu-item" ).each(function() {
				item = $( this );
				return item.offset().top - base - height < 0;
			});

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.find( this.options.items )
				[ !this.active ? "first" : "last" ]() );
		}
	},

	previousPage: function( event ) {
		var item, base, height;
		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isFirstItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.prevAll( ".ui-menu-item" ).each(function() {
				item = $( this );
				return item.offset().top - base + height > 0;
			});

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.find( this.options.items ).first() );
		}
	},

	_hasScroll: function() {
		return this.element.outerHeight() < this.element.prop( "scrollHeight" );
	},

	select: function( event ) {
		// TODO: It should never be possible to not have an active item at this
		// point, but the tests don't trigger mouseenter before click.
		this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
		var ui = { item: this.active };
		if ( !this.active.has( ".ui-menu" ).length ) {
			this.collapseAll( event, true );
		}
		this._trigger( "select", event, ui );
	},

	_filterMenuItems: function(character) {
		var escapedCharacter = character.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ),
			regex = new RegExp( "^" + escapedCharacter, "i" );

		return this.activeMenu
			.find( this.options.items )

			// Only match on items, not dividers or other content (#10571)
			.filter( ".ui-menu-item" )
			.filter(function() {
				return regex.test( $.trim( $( this ).text() ) );
			});
	}
});


/*!
 * jQuery UI Autocomplete 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/autocomplete/
 */


$.widget( "ui.autocomplete", {
	version: "1.11.4",
	defaultElement: "<input>",
	options: {
		appendTo: null,
		autoFocus: false,
		delay: 300,
		minLength: 1,
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		source: null,

		// callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		response: null,
		search: null,
		select: null
	},

	requestIndex: 0,
	pending: 0,

	_create: function() {
		// Some browsers only repeat keydown events, not keypress events,
		// so we use the suppressKeyPress flag to determine if we've already
		// handled the keydown event. #7269
		// Unfortunately the code for & in keypress is the same as the up arrow,
		// so we use the suppressKeyPressRepeat flag to avoid handling keypress
		// events when we know the keydown event was used to modify the
		// search term. #7799
		var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
			nodeName = this.element[ 0 ].nodeName.toLowerCase(),
			isTextarea = nodeName === "textarea",
			isInput = nodeName === "input";

		this.isMultiLine =
			// Textareas are always multi-line
			isTextarea ? true :
			// Inputs are always single-line, even if inside a contentEditable element
			// IE also treats inputs as contentEditable
			isInput ? false :
			// All other element types are determined by whether or not they're contentEditable
			this.element.prop( "isContentEditable" );

		this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
		this.isNewMenu = true;

		this.element
			.addClass( "ui-autocomplete-input" )
			.attr( "autocomplete", "off" );

		this._on( this.element, {
			keydown: function( event ) {
				if ( this.element.prop( "readOnly" ) ) {
					suppressKeyPress = true;
					suppressInput = true;
					suppressKeyPressRepeat = true;
					return;
				}

				suppressKeyPress = false;
				suppressInput = false;
				suppressKeyPressRepeat = false;
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					suppressKeyPress = true;
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					suppressKeyPress = true;
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					suppressKeyPress = true;
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					suppressKeyPress = true;
					this._keyEvent( "next", event );
					break;
				case keyCode.ENTER:
					// when menu is open and has focus
					if ( this.menu.active ) {
						// #6055 - Opera still allows the keypress to occur
						// which causes forms to submit
						suppressKeyPress = true;
						event.preventDefault();
						this.menu.select( event );
					}
					break;
				case keyCode.TAB:
					if ( this.menu.active ) {
						this.menu.select( event );
					}
					break;
				case keyCode.ESCAPE:
					if ( this.menu.element.is( ":visible" ) ) {
						if ( !this.isMultiLine ) {
							this._value( this.term );
						}
						this.close( event );
						// Different browsers have different default behavior for escape
						// Single press can mean undo or clear
						// Double press in IE means clear the whole form
						event.preventDefault();
					}
					break;
				default:
					suppressKeyPressRepeat = true;
					// search timeout should be triggered before the input value is changed
					this._searchTimeout( event );
					break;
				}
			},
			keypress: function( event ) {
				if ( suppressKeyPress ) {
					suppressKeyPress = false;
					if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
						event.preventDefault();
					}
					return;
				}
				if ( suppressKeyPressRepeat ) {
					return;
				}

				// replicate some key handlers to allow them to repeat in Firefox and Opera
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					this._keyEvent( "next", event );
					break;
				}
			},
			input: function( event ) {
				if ( suppressInput ) {
					suppressInput = false;
					event.preventDefault();
					return;
				}
				this._searchTimeout( event );
			},
			focus: function() {
				this.selectedItem = null;
				this.previous = this._value();
			},
			blur: function( event ) {
				if ( this.cancelBlur ) {
					delete this.cancelBlur;
					return;
				}

				clearTimeout( this.searching );
				this.close( event );
				this._change( event );
			}
		});

		this._initSource();
		this.menu = $( "<ul>" )
			.addClass( "ui-autocomplete ui-front" )
			.appendTo( this._appendTo() )
			.menu({
				// disable ARIA support, the live region takes care of that
				role: null
			})
			.hide()
			.menu( "instance" );

		this._on( this.menu.element, {
			mousedown: function( event ) {
				// prevent moving focus out of the text field
				event.preventDefault();

				// IE doesn't prevent moving focus even with event.preventDefault()
				// so we set a flag to know when we should ignore the blur event
				this.cancelBlur = true;
				this._delay(function() {
					delete this.cancelBlur;
				});

				// clicking on the scrollbar causes focus to shift to the body
				// but we can't detect a mouseup or a click immediately afterward
				// so we have to track the next mousedown and close the menu if
				// the user clicks somewhere outside of the autocomplete
				var menuElement = this.menu.element[ 0 ];
				if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
					this._delay(function() {
						var that = this;
						this.document.one( "mousedown", function( event ) {
							if ( event.target !== that.element[ 0 ] &&
									event.target !== menuElement &&
									!$.contains( menuElement, event.target ) ) {
								that.close();
							}
						});
					});
				}
			},
			menufocus: function( event, ui ) {
				var label, item;
				// support: Firefox
				// Prevent accidental activation of menu items in Firefox (#7024 #9118)
				if ( this.isNewMenu ) {
					this.isNewMenu = false;
					if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
						this.menu.blur();

						this.document.one( "mousemove", function() {
							$( event.target ).trigger( event.originalEvent );
						});

						return;
					}
				}

				item = ui.item.data( "ui-autocomplete-item" );
				if ( false !== this._trigger( "focus", event, { item: item } ) ) {
					// use value to match what will end up in the input, if it was a key event
					if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
						this._value( item.value );
					}
				}

				// Announce the value in the liveRegion
				label = ui.item.attr( "aria-label" ) || item.value;
				if ( label && $.trim( label ).length ) {
					this.liveRegion.children().hide();
					$( "<div>" ).text( label ).appendTo( this.liveRegion );
				}
			},
			menuselect: function( event, ui ) {
				var item = ui.item.data( "ui-autocomplete-item" ),
					previous = this.previous;

				// only trigger when focus was lost (click on menu)
				if ( this.element[ 0 ] !== this.document[ 0 ].activeElement ) {
					this.element.focus();
					this.previous = previous;
					// #6109 - IE triggers two focus events and the second
					// is asynchronous, so we need to reset the previous
					// term synchronously and asynchronously :-(
					this._delay(function() {
						this.previous = previous;
						this.selectedItem = item;
					});
				}

				if ( false !== this._trigger( "select", event, { item: item } ) ) {
					this._value( item.value );
				}
				// reset the term after the select event
				// this allows custom select handling to work properly
				this.term = this._value();

				this.close( event );
				this.selectedItem = item;
			}
		});

		this.liveRegion = $( "<span>", {
				role: "status",
				"aria-live": "assertive",
				"aria-relevant": "additions"
			})
			.addClass( "ui-helper-hidden-accessible" )
			.appendTo( this.document[ 0 ].body );

		// turning off autocomplete prevents the browser from remembering the
		// value when navigating through history, so we re-enable autocomplete
		// if the page is unloaded before the widget is destroyed. #7790
		this._on( this.window, {
			beforeunload: function() {
				this.element.removeAttr( "autocomplete" );
			}
		});
	},

	_destroy: function() {
		clearTimeout( this.searching );
		this.element
			.removeClass( "ui-autocomplete-input" )
			.removeAttr( "autocomplete" );
		this.menu.element.remove();
		this.liveRegion.remove();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "source" ) {
			this._initSource();
		}
		if ( key === "appendTo" ) {
			this.menu.element.appendTo( this._appendTo() );
		}
		if ( key === "disabled" && value && this.xhr ) {
			this.xhr.abort();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element || !element[ 0 ] ) {
			element = this.element.closest( ".ui-front" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_initSource: function() {
		var array, url,
			that = this;
		if ( $.isArray( this.options.source ) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter( array, request.term ) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				if ( that.xhr ) {
					that.xhr.abort();
				}
				that.xhr = $.ajax({
					url: url,
					data: request,
					dataType: "json",
					success: function( data ) {
						response( data );
					},
					error: function() {
						response([]);
					}
				});
			};
		} else {
			this.source = this.options.source;
		}
	},

	_searchTimeout: function( event ) {
		clearTimeout( this.searching );
		this.searching = this._delay(function() {

			// Search if the value has changed, or if the user retypes the same value (see #7434)
			var equalValues = this.term === this._value(),
				menuVisible = this.menu.element.is( ":visible" ),
				modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;

			if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) {
				this.selectedItem = null;
				this.search( null, event );
			}
		}, this.options.delay );
	},

	search: function( value, event ) {
		value = value != null ? value : this._value();

		// always save the actual value, not the one passed as an argument
		this.term = this._value();

		if ( value.length < this.options.minLength ) {
			return this.close( event );
		}

		if ( this._trigger( "search", event ) === false ) {
			return;
		}

		return this._search( value );
	},

	_search: function( value ) {
		this.pending++;
		this.element.addClass( "ui-autocomplete-loading" );
		this.cancelSearch = false;

		this.source( { term: value }, this._response() );
	},

	_response: function() {
		var index = ++this.requestIndex;

		return $.proxy(function( content ) {
			if ( index === this.requestIndex ) {
				this.__response( content );
			}

			this.pending--;
			if ( !this.pending ) {
				this.element.removeClass( "ui-autocomplete-loading" );
			}
		}, this );
	},

	__response: function( content ) {
		if ( content ) {
			content = this._normalize( content );
		}
		this._trigger( "response", null, { content: content } );
		if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
			this._suggest( content );
			this._trigger( "open" );
		} else {
			// use ._close() instead of .close() so we don't cancel future searches
			this._close();
		}
	},

	close: function( event ) {
		this.cancelSearch = true;
		this._close( event );
	},

	_close: function( event ) {
		if ( this.menu.element.is( ":visible" ) ) {
			this.menu.element.hide();
			this.menu.blur();
			this.isNewMenu = true;
			this._trigger( "close", event );
		}
	},

	_change: function( event ) {
		if ( this.previous !== this._value() ) {
			this._trigger( "change", event, { item: this.selectedItem } );
		}
	},

	_normalize: function( items ) {
		// assume all items have the right format when the first item is complete
		if ( items.length && items[ 0 ].label && items[ 0 ].value ) {
			return items;
		}
		return $.map( items, function( item ) {
			if ( typeof item === "string" ) {
				return {
					label: item,
					value: item
				};
			}
			return $.extend( {}, item, {
				label: item.label || item.value,
				value: item.value || item.label
			});
		});
	},

	_suggest: function( items ) {
		var ul = this.menu.element.empty();
		this._renderMenu( ul, items );
		this.isNewMenu = true;
		this.menu.refresh();

		// size and position menu
		ul.show();
		this._resizeMenu();
		ul.position( $.extend({
			of: this.element
		}, this.options.position ) );

		if ( this.options.autoFocus ) {
			this.menu.next();
		}
	},

	_resizeMenu: function() {
		var ul = this.menu.element;
		ul.outerWidth( Math.max(
			// Firefox wraps long text (possibly a rounding bug)
			// so we add 1px to avoid the wrapping (#7513)
			ul.width( "" ).outerWidth() + 1,
			this.element.outerWidth()
		) );
	},

	_renderMenu: function( ul, items ) {
		var that = this;
		$.each( items, function( index, item ) {
			that._renderItemData( ul, item );
		});
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
	},

	_renderItem: function( ul, item ) {
		return $( "<li>" ).text( item.label ).appendTo( ul );
	},

	_move: function( direction, event ) {
		if ( !this.menu.element.is( ":visible" ) ) {
			this.search( null, event );
			return;
		}
		if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
				this.menu.isLastItem() && /^next/.test( direction ) ) {

			if ( !this.isMultiLine ) {
				this._value( this.term );
			}

			this.menu.blur();
			return;
		}
		this.menu[ direction ]( event );
	},

	widget: function() {
		return this.menu.element;
	},

	_value: function() {
		return this.valueMethod.apply( this.element, arguments );
	},

	_keyEvent: function( keyEvent, event ) {
		if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
			this._move( keyEvent, event );

			// prevents moving cursor to beginning/end of the text field in some browsers
			event.preventDefault();
		}
	}
});

$.extend( $.ui.autocomplete, {
	escapeRegex: function( value ) {
		return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
	},
	filter: function( array, term ) {
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" );
		return $.grep( array, function( value ) {
			return matcher.test( value.label || value.value || value );
		});
	}
});

// live region extension, adding a `messages` option
// NOTE: This is an experimental API. We are still investigating
// a full solution for string manipulation and internationalization.
$.widget( "ui.autocomplete", $.ui.autocomplete, {
	options: {
		messages: {
			noResults: "No search results.",
			results: function( amount ) {
				return amount + ( amount > 1 ? " results are" : " result is" ) +
					" available, use up and down arrow keys to navigate.";
			}
		}
	},

	__response: function( content ) {
		var message;
		this._superApply( arguments );
		if ( this.options.disabled || this.cancelSearch ) {
			return;
		}
		if ( content && content.length ) {
			message = this.options.messages.results( content.length );
		} else {
			message = this.options.messages.noResults;
		}
		this.liveRegion.children().hide();
		$( "<div>" ).text( message ).appendTo( this.liveRegion );
	}
});

var autocomplete = $.ui.autocomplete;


/*!
 * jQuery UI Button 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/button/
 */


var lastActive,
	baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
	typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",
	formResetHandler = function() {
		var form = $( this );
		setTimeout(function() {
			form.find( ":ui-button" ).button( "refresh" );
		}, 1 );
	},
	radioGroup = function( radio ) {
		var name = radio.name,
			form = radio.form,
			radios = $( [] );
		if ( name ) {
			name = name.replace( /'/g, "\\'" );
			if ( form ) {
				radios = $( form ).find( "[name='" + name + "'][type=radio]" );
			} else {
				radios = $( "[name='" + name + "'][type=radio]", radio.ownerDocument )
					.filter(function() {
						return !this.form;
					});
			}
		}
		return radios;
	};

$.widget( "ui.button", {
	version: "1.11.4",
	defaultElement: "<button>",
	options: {
		disabled: null,
		text: true,
		label: null,
		icons: {
			primary: null,
			secondary: null
		}
	},
	_create: function() {
		this.element.closest( "form" )
			.unbind( "reset" + this.eventNamespace )
			.bind( "reset" + this.eventNamespace, formResetHandler );

		if ( typeof this.options.disabled !== "boolean" ) {
			this.options.disabled = !!this.element.prop( "disabled" );
		} else {
			this.element.prop( "disabled", this.options.disabled );
		}

		this._determineButtonType();
		this.hasTitle = !!this.buttonElement.attr( "title" );

		var that = this,
			options = this.options,
			toggleButton = this.type === "checkbox" || this.type === "radio",
			activeClass = !toggleButton ? "ui-state-active" : "";

		if ( options.label === null ) {
			options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html());
		}

		this._hoverable( this.buttonElement );

		this.buttonElement
			.addClass( baseClasses )
			.attr( "role", "button" )
			.bind( "mouseenter" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return;
				}
				if ( this === lastActive ) {
					$( this ).addClass( "ui-state-active" );
				}
			})
			.bind( "mouseleave" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).removeClass( activeClass );
			})
			.bind( "click" + this.eventNamespace, function( event ) {
				if ( options.disabled ) {
					event.preventDefault();
					event.stopImmediatePropagation();
				}
			});

		// Can't use _focusable() because the element that receives focus
		// and the element that gets the ui-state-focus class are different
		this._on({
			focus: function() {
				this.buttonElement.addClass( "ui-state-focus" );
			},
			blur: function() {
				this.buttonElement.removeClass( "ui-state-focus" );
			}
		});

		if ( toggleButton ) {
			this.element.bind( "change" + this.eventNamespace, function() {
				that.refresh();
			});
		}

		if ( this.type === "checkbox" ) {
			this.buttonElement.bind( "click" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return false;
				}
			});
		} else if ( this.type === "radio" ) {
			this.buttonElement.bind( "click" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return false;
				}
				$( this ).addClass( "ui-state-active" );
				that.buttonElement.attr( "aria-pressed", "true" );

				var radio = that.element[ 0 ];
				radioGroup( radio )
					.not( radio )
					.map(function() {
						return $( this ).button( "widget" )[ 0 ];
					})
					.removeClass( "ui-state-active" )
					.attr( "aria-pressed", "false" );
			});
		} else {
			this.buttonElement
				.bind( "mousedown" + this.eventNamespace, function() {
					if ( options.disabled ) {
						return false;
					}
					$( this ).addClass( "ui-state-active" );
					lastActive = this;
					that.document.one( "mouseup", function() {
						lastActive = null;
					});
				})
				.bind( "mouseup" + this.eventNamespace, function() {
					if ( options.disabled ) {
						return false;
					}
					$( this ).removeClass( "ui-state-active" );
				})
				.bind( "keydown" + this.eventNamespace, function(event) {
					if ( options.disabled ) {
						return false;
					}
					if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) {
						$( this ).addClass( "ui-state-active" );
					}
				})
				// see #8559, we bind to blur here in case the button element loses
				// focus between keydown and keyup, it would be left in an "active" state
				.bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() {
					$( this ).removeClass( "ui-state-active" );
				});

			if ( this.buttonElement.is("a") ) {
				this.buttonElement.keyup(function(event) {
					if ( event.keyCode === $.ui.keyCode.SPACE ) {
						// TODO pass through original event correctly (just as 2nd argument doesn't work)
						$( this ).click();
					}
				});
			}
		}

		this._setOption( "disabled", options.disabled );
		this._resetButton();
	},

	_determineButtonType: function() {
		var ancestor, labelSelector, checked;

		if ( this.element.is("[type=checkbox]") ) {
			this.type = "checkbox";
		} else if ( this.element.is("[type=radio]") ) {
			this.type = "radio";
		} else if ( this.element.is("input") ) {
			this.type = "input";
		} else {
			this.type = "button";
		}

		if ( this.type === "checkbox" || this.type === "radio" ) {
			// we don't search against the document in case the element
			// is disconnected from the DOM
			ancestor = this.element.parents().last();
			labelSelector = "label[for='" + this.element.attr("id") + "']";
			this.buttonElement = ancestor.find( labelSelector );
			if ( !this.buttonElement.length ) {
				ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings();
				this.buttonElement = ancestor.filter( labelSelector );
				if ( !this.buttonElement.length ) {
					this.buttonElement = ancestor.find( labelSelector );
				}
			}
			this.element.addClass( "ui-helper-hidden-accessible" );

			checked = this.element.is( ":checked" );
			if ( checked ) {
				this.buttonElement.addClass( "ui-state-active" );
			}
			this.buttonElement.prop( "aria-pressed", checked );
		} else {
			this.buttonElement = this.element;
		}
	},

	widget: function() {
		return this.buttonElement;
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-helper-hidden-accessible" );
		this.buttonElement
			.removeClass( baseClasses + " ui-state-active " + typeClasses )
			.removeAttr( "role" )
			.removeAttr( "aria-pressed" )
			.html( this.buttonElement.find(".ui-button-text").html() );

		if ( !this.hasTitle ) {
			this.buttonElement.removeAttr( "title" );
		}
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "disabled" ) {
			this.widget().toggleClass( "ui-state-disabled", !!value );
			this.element.prop( "disabled", !!value );
			if ( value ) {
				if ( this.type === "checkbox" || this.type === "radio" ) {
					this.buttonElement.removeClass( "ui-state-focus" );
				} else {
					this.buttonElement.removeClass( "ui-state-focus ui-state-active" );
				}
			}
			return;
		}
		this._resetButton();
	},

	refresh: function() {
		//See #8237 & #8828
		var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" );

		if ( isDisabled !== this.options.disabled ) {
			this._setOption( "disabled", isDisabled );
		}
		if ( this.type === "radio" ) {
			radioGroup( this.element[0] ).each(function() {
				if ( $( this ).is( ":checked" ) ) {
					$( this ).button( "widget" )
						.addClass( "ui-state-active" )
						.attr( "aria-pressed", "true" );
				} else {
					$( this ).button( "widget" )
						.removeClass( "ui-state-active" )
						.attr( "aria-pressed", "false" );
				}
			});
		} else if ( this.type === "checkbox" ) {
			if ( this.element.is( ":checked" ) ) {
				this.buttonElement
					.addClass( "ui-state-active" )
					.attr( "aria-pressed", "true" );
			} else {
				this.buttonElement
					.removeClass( "ui-state-active" )
					.attr( "aria-pressed", "false" );
			}
		}
	},

	_resetButton: function() {
		if ( this.type === "input" ) {
			if ( this.options.label ) {
				this.element.val( this.options.label );
			}
			return;
		}
		var buttonElement = this.buttonElement.removeClass( typeClasses ),
			buttonText = $( "<span></span>", this.document[0] )
				.addClass( "ui-button-text" )
				.html( this.options.label )
				.appendTo( buttonElement.empty() )
				.text(),
			icons = this.options.icons,
			multipleIcons = icons.primary && icons.secondary,
			buttonClasses = [];

		if ( icons.primary || icons.secondary ) {
			if ( this.options.text ) {
				buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) );
			}

			if ( icons.primary ) {
				buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" );
			}

			if ( icons.secondary ) {
				buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" );
			}

			if ( !this.options.text ) {
				buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" );

				if ( !this.hasTitle ) {
					buttonElement.attr( "title", $.trim( buttonText ) );
				}
			}
		} else {
			buttonClasses.push( "ui-button-text-only" );
		}
		buttonElement.addClass( buttonClasses.join( " " ) );
	}
});

$.widget( "ui.buttonset", {
	version: "1.11.4",
	options: {
		items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"
	},

	_create: function() {
		this.element.addClass( "ui-buttonset" );
	},

	_init: function() {
		this.refresh();
	},

	_setOption: function( key, value ) {
		if ( key === "disabled" ) {
			this.buttons.button( "option", key, value );
		}

		this._super( key, value );
	},

	refresh: function() {
		var rtl = this.element.css( "direction" ) === "rtl",
			allButtons = this.element.find( this.options.items ),
			existingButtons = allButtons.filter( ":ui-button" );

		// Initialize new buttons
		allButtons.not( ":ui-button" ).button();

		// Refresh existing buttons
		existingButtons.button( "refresh" );

		this.buttons = allButtons
			.map(function() {
				return $( this ).button( "widget" )[ 0 ];
			})
				.removeClass( "ui-corner-all ui-corner-left ui-corner-right" )
				.filter( ":first" )
					.addClass( rtl ? "ui-corner-right" : "ui-corner-left" )
				.end()
				.filter( ":last" )
					.addClass( rtl ? "ui-corner-left" : "ui-corner-right" )
				.end()
			.end();
	},

	_destroy: function() {
		this.element.removeClass( "ui-buttonset" );
		this.buttons
			.map(function() {
				return $( this ).button( "widget" )[ 0 ];
			})
				.removeClass( "ui-corner-left ui-corner-right" )
			.end()
			.button( "destroy" );
	}
});

var button = $.ui.button;


/*!
 * jQuery UI Datepicker 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/datepicker/
 */


$.extend($.ui, { datepicker: { version: "1.11.4" } });

var datepicker_instActive;

function datepicker_getZindex( elem ) {
	var position, value;
	while ( elem.length && elem[ 0 ] !== document ) {
		// Ignore z-index if position is set to a value where z-index is ignored by the browser
		// This makes behavior of this function consistent across browsers
		// WebKit always returns auto if the element is positioned
		position = elem.css( "position" );
		if ( position === "absolute" || position === "relative" || position === "fixed" ) {
			// IE returns 0 when zIndex is not specified
			// other browsers return a string
			// we ignore the case of nested elements with an explicit value of 0
			// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
			value = parseInt( elem.css( "zIndex" ), 10 );
			if ( !isNaN( value ) && value !== 0 ) {
				return value;
			}
		}
		elem = elem.parent();
	}

	return 0;
}
/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
	this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
	this._appendClass = "ui-datepicker-append"; // The name of the append marker class
	this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
	this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
	this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
	this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
	this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
	this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[""] = { // Default regional settings
		closeText: "Done", // Display text for close link
		prevText: "Prev", // Display text for previous month link
		nextText: "Next", // Display text for next month link
		currentText: "Today", // Display text for current month link
		monthNames: ["January","February","March","April","May","June",
			"July","August","September","October","November","December"], // Names of months for drop-down and formatting
		monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting
		dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting
		dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting
		dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday
		weekHeader: "Wk", // Column header for week of the year
		dateFormat: "mm/dd/yy", // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false, // True if right-to-left language, false if left-to-right
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearSuffix: "" // Additional text to append to the year in the month headers
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: "focus", // "focus" for popup on focus,
			// "button" for trigger button, or "both" for either
		showAnim: "fadeIn", // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: "", // Display text following the input box, e.g. showing the format
		buttonText: "...", // Text for trigger button
		buttonImage: "", // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		yearRange: "c-10:c+10", // Range of years to display in drop-down,
			// either relative to today's year (-nn:+nn), relative to currently displayed year
			// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
		showWeek: false, // True to show week of the year, false to not show it
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: "+10", // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with "+" for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: "fast", // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: "", // Selector for an alternate field to store selected dates into
		altFormat: "", // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false, // True to show button panel, false to not show it
		autoSize: false, // True to size the input for the date format, false to leave as is
		disabled: false // The initial disabled state
	};
	$.extend(this._defaults, this.regional[""]);
	this.regional.en = $.extend( true, {}, this.regional[ "" ]);
	this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
	this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));
}

$.extend(Datepicker.prototype, {
	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: "hasDatepicker",

	//Keep track of the maximum number of rows displayed (see #7043)
	maxRows: 4,

	// TODO rename to "widget" when switching to widget factory
	_widgetDatepicker: function() {
		return this.dpDiv;
	},

	/* Override the default settings for all instances of the date picker.
	 * @param  settings  object - the new settings to use as defaults (anonymous object)
	 * @return the manager object
	 */
	setDefaults: function(settings) {
		datepicker_extendRemove(this._defaults, settings || {});
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 * @param  settings  object - the new settings to use for this date picker instance (anonymous)
	 */
	_attachDatepicker: function(target, settings) {
		var nodeName, inline, inst;
		nodeName = target.nodeName.toLowerCase();
		inline = (nodeName === "div" || nodeName === "span");
		if (!target.id) {
			this.uuid += 1;
			target.id = "dp" + this.uuid;
		}
		inst = this._newInst($(target), inline);
		inst.settings = $.extend({}, settings || {});
		if (nodeName === "input") {
			this._connectDatepicker(target, inst);
		} else if (inline) {
			this._inlineDatepicker(target, inst);
		}
	},

	/* Create a new instance object. */
	_newInst: function(target, inline) {
		var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars
		return {id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: (!inline ? this.dpDiv : // presentation div
			datepicker_bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))};
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function(target, inst) {
		var input = $(target);
		inst.append = $([]);
		inst.trigger = $([]);
		if (input.hasClass(this.markerClassName)) {
			return;
		}
		this._attachments(input, inst);
		input.addClass(this.markerClassName).keydown(this._doKeyDown).
			keypress(this._doKeyPress).keyup(this._doKeyUp);
		this._autoSize(inst);
		$.data(target, "datepicker", inst);
		//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
		if( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}
	},

	/* Make attachments based on settings. */
	_attachments: function(input, inst) {
		var showOn, buttonText, buttonImage,
			appendText = this._get(inst, "appendText"),
			isRTL = this._get(inst, "isRTL");

		if (inst.append) {
			inst.append.remove();
		}
		if (appendText) {
			inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
			input[isRTL ? "before" : "after"](inst.append);
		}

		input.unbind("focus", this._showDatepicker);

		if (inst.trigger) {
			inst.trigger.remove();
		}

		showOn = this._get(inst, "showOn");
		if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field
			input.focus(this._showDatepicker);
		}
		if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked
			buttonText = this._get(inst, "buttonText");
			buttonImage = this._get(inst, "buttonImage");
			inst.trigger = $(this._get(inst, "buttonImageOnly") ?
				$("<img/>").addClass(this._triggerClass).
					attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
				$("<button type='button'></button>").addClass(this._triggerClass).
					html(!buttonImage ? buttonText : $("<img/>").attr(
					{ src:buttonImage, alt:buttonText, title:buttonText })));
			input[isRTL ? "before" : "after"](inst.trigger);
			inst.trigger.click(function() {
				if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) {
					$.datepicker._hideDatepicker();
				} else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) {
					$.datepicker._hideDatepicker();
					$.datepicker._showDatepicker(input[0]);
				} else {
					$.datepicker._showDatepicker(input[0]);
				}
				return false;
			});
		}
	},

	/* Apply the maximum length for the date format. */
	_autoSize: function(inst) {
		if (this._get(inst, "autoSize") && !inst.inline) {
			var findMax, max, maxI, i,
				date = new Date(2009, 12 - 1, 20), // Ensure double digits
				dateFormat = this._get(inst, "dateFormat");

			if (dateFormat.match(/[DM]/)) {
				findMax = function(names) {
					max = 0;
					maxI = 0;
					for (i = 0; i < names.length; i++) {
						if (names[i].length > max) {
							max = names[i].length;
							maxI = i;
						}
					}
					return maxI;
				};
				date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
					"monthNames" : "monthNamesShort"))));
				date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
					"dayNames" : "dayNamesShort"))) + 20 - date.getDay());
			}
			inst.input.attr("size", this._formatDate(inst, date).length);
		}
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function(target, inst) {
		var divSpan = $(target);
		if (divSpan.hasClass(this.markerClassName)) {
			return;
		}
		divSpan.addClass(this.markerClassName).append(inst.dpDiv);
		$.data(target, "datepicker", inst);
		this._setDate(inst, this._getDefaultDate(inst), true);
		this._updateDatepicker(inst);
		this._updateAlternate(inst);
		//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
		if( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}
		// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
		// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
		inst.dpDiv.css( "display", "block" );
	},

	/* Pop-up the date picker in a "dialog" box.
	 * @param  input element - ignored
	 * @param  date	string or Date - the initial date to display
	 * @param  onSelect  function - the function to call when a date is selected
	 * @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	 * @param  pos int[2] - coordinates for the dialog's position within the screen or
	 *					event - with x/y coordinates or
	 *					leave empty for default (screen centre)
	 * @return the manager object
	 */
	_dialogDatepicker: function(input, date, onSelect, settings, pos) {
		var id, browserWidth, browserHeight, scrollX, scrollY,
			inst = this._dialogInst; // internal instance

		if (!inst) {
			this.uuid += 1;
			id = "dp" + this.uuid;
			this._dialogInput = $("<input type='text' id='" + id +
				"' style='position: absolute; top: -100px; width: 0px;'/>");
			this._dialogInput.keydown(this._doKeyDown);
			$("body").append(this._dialogInput);
			inst = this._dialogInst = this._newInst(this._dialogInput, false);
			inst.settings = {};
			$.data(this._dialogInput[0], "datepicker", inst);
		}
		datepicker_extendRemove(inst.settings, settings || {});
		date = (date && date.constructor === Date ? this._formatDate(inst, date) : date);
		this._dialogInput.val(date);

		this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
		if (!this._pos) {
			browserWidth = document.documentElement.clientWidth;
			browserHeight = document.documentElement.clientHeight;
			scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
		}

		// move input on screen for focus, but hidden behind dialog
		this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px");
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass(this._dialogClass);
		this._showDatepicker(this._dialogInput[0]);
		if ($.blockUI) {
			$.blockUI(this.dpDiv);
		}
		$.data(this._dialogInput[0], "datepicker", inst);
		return this;
	},

	/* Detach a datepicker from its control.
	 * @param  target	element - the target input field or division or span
	 */
	_destroyDatepicker: function(target) {
		var nodeName,
			$target = $(target),
			inst = $.data(target, "datepicker");

		if (!$target.hasClass(this.markerClassName)) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		$.removeData(target, "datepicker");
		if (nodeName === "input") {
			inst.append.remove();
			inst.trigger.remove();
			$target.removeClass(this.markerClassName).
				unbind("focus", this._showDatepicker).
				unbind("keydown", this._doKeyDown).
				unbind("keypress", this._doKeyPress).
				unbind("keyup", this._doKeyUp);
		} else if (nodeName === "div" || nodeName === "span") {
			$target.removeClass(this.markerClassName).empty();
		}

		if ( datepicker_instActive === inst ) {
			datepicker_instActive = null;
		}
	},

	/* Enable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_enableDatepicker: function(target) {
		var nodeName, inline,
			$target = $(target),
			inst = $.data(target, "datepicker");

		if (!$target.hasClass(this.markerClassName)) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if (nodeName === "input") {
			target.disabled = false;
			inst.trigger.filter("button").
				each(function() { this.disabled = false; }).end().
				filter("img").css({opacity: "1.0", cursor: ""});
		} else if (nodeName === "div" || nodeName === "span") {
			inline = $target.children("." + this._inlineClass);
			inline.children().removeClass("ui-state-disabled");
			inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
				prop("disabled", false);
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value === target ? null : value); }); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_disableDatepicker: function(target) {
		var nodeName, inline,
			$target = $(target),
			inst = $.data(target, "datepicker");

		if (!$target.hasClass(this.markerClassName)) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if (nodeName === "input") {
			target.disabled = true;
			inst.trigger.filter("button").
				each(function() { this.disabled = true; }).end().
				filter("img").css({opacity: "0.5", cursor: "default"});
		} else if (nodeName === "div" || nodeName === "span") {
			inline = $target.children("." + this._inlineClass);
			inline.children().addClass("ui-state-disabled");
			inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
				prop("disabled", true);
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value === target ? null : value); }); // delete entry
		this._disabledInputs[this._disabledInputs.length] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	 * @param  target	element - the target input field or division or span
	 * @return boolean - true if disabled, false if enabled
	 */
	_isDisabledDatepicker: function(target) {
		if (!target) {
			return false;
		}
		for (var i = 0; i < this._disabledInputs.length; i++) {
			if (this._disabledInputs[i] === target) {
				return true;
			}
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	 * @param  target  element - the target input field or division or span
	 * @return  object - the associated instance data
	 * @throws  error if a jQuery problem getting data
	 */
	_getInst: function(target) {
		try {
			return $.data(target, "datepicker");
		}
		catch (err) {
			throw "Missing instance data for this datepicker";
		}
	},

	/* Update or retrieve the settings for a date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 * @param  name	object - the new settings to update or
	 *				string - the name of the setting to change or retrieve,
	 *				when retrieving also "all" for all instance settings or
	 *				"defaults" for all global defaults
	 * @param  value   any - the new value for the setting
	 *				(omit if above is an object or to retrieve a value)
	 */
	_optionDatepicker: function(target, name, value) {
		var settings, date, minDate, maxDate,
			inst = this._getInst(target);

		if (arguments.length === 2 && typeof name === "string") {
			return (name === "defaults" ? $.extend({}, $.datepicker._defaults) :
				(inst ? (name === "all" ? $.extend({}, inst.settings) :
				this._get(inst, name)) : null));
		}

		settings = name || {};
		if (typeof name === "string") {
			settings = {};
			settings[name] = value;
		}

		if (inst) {
			if (this._curInst === inst) {
				this._hideDatepicker();
			}

			date = this._getDateDatepicker(target, true);
			minDate = this._getMinMaxDate(inst, "min");
			maxDate = this._getMinMaxDate(inst, "max");
			datepicker_extendRemove(inst.settings, settings);
			// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
			if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) {
				inst.settings.minDate = this._formatDate(inst, minDate);
			}
			if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) {
				inst.settings.maxDate = this._formatDate(inst, maxDate);
			}
			if ( "disabled" in settings ) {
				if ( settings.disabled ) {
					this._disableDatepicker(target);
				} else {
					this._enableDatepicker(target);
				}
			}
			this._attachments($(target), inst);
			this._autoSize(inst);
			this._setDate(inst, date);
			this._updateAlternate(inst);
			this._updateDatepicker(inst);
		}
	},

	// change method deprecated
	_changeDatepicker: function(target, name, value) {
		this._optionDatepicker(target, name, value);
	},

	/* Redraw the date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 */
	_refreshDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst) {
			this._updateDatepicker(inst);
		}
	},

	/* Set the dates for a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  date	Date - the new date
	 */
	_setDateDatepicker: function(target, date) {
		var inst = this._getInst(target);
		if (inst) {
			this._setDate(inst, date);
			this._updateDatepicker(inst);
			this._updateAlternate(inst);
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  noDefault boolean - true if no default date is to be used
	 * @return Date - the current date
	 */
	_getDateDatepicker: function(target, noDefault) {
		var inst = this._getInst(target);
		if (inst && !inst.inline) {
			this._setDateFromField(inst, noDefault);
		}
		return (inst ? this._getDate(inst) : null);
	},

	/* Handle keystrokes. */
	_doKeyDown: function(event) {
		var onSelect, dateStr, sel,
			inst = $.datepicker._getInst(event.target),
			handled = true,
			isRTL = inst.dpDiv.is(".ui-datepicker-rtl");

		inst._keyEvent = true;
		if ($.datepicker._datepickerShowing) {
			switch (event.keyCode) {
				case 9: $.datepicker._hideDatepicker();
						handled = false;
						break; // hide on tab out
				case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." +
									$.datepicker._currentClass + ")", inst.dpDiv);
						if (sel[0]) {
							$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
						}

						onSelect = $.datepicker._get(inst, "onSelect");
						if (onSelect) {
							dateStr = $.datepicker._formatDate(inst);

							// trigger custom callback
							onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
						} else {
							$.datepicker._hideDatepicker();
						}

						return false; // don't submit the form
				case 27: $.datepicker._hideDatepicker();
						break; // hide on escape
				case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							-$.datepicker._get(inst, "stepBigMonths") :
							-$.datepicker._get(inst, "stepMonths")), "M");
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							+$.datepicker._get(inst, "stepBigMonths") :
							+$.datepicker._get(inst, "stepMonths")), "M");
						break; // next month/year on page down/+ ctrl
				case 35: if (event.ctrlKey || event.metaKey) {
							$.datepicker._clearDate(event.target);
						}
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if (event.ctrlKey || event.metaKey) {
							$.datepicker._gotoToday(event.target);
						}
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if (event.ctrlKey || event.metaKey) {
							$.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
						}
						handled = event.ctrlKey || event.metaKey;
						// -1 day on ctrl or command +left
						if (event.originalEvent.altKey) {
							$.datepicker._adjustDate(event.target, (event.ctrlKey ?
								-$.datepicker._get(inst, "stepBigMonths") :
								-$.datepicker._get(inst, "stepMonths")), "M");
						}
						// next month/year on alt +left on Mac
						break;
				case 38: if (event.ctrlKey || event.metaKey) {
							$.datepicker._adjustDate(event.target, -7, "D");
						}
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if (event.ctrlKey || event.metaKey) {
							$.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
						}
						handled = event.ctrlKey || event.metaKey;
						// +1 day on ctrl or command +right
						if (event.originalEvent.altKey) {
							$.datepicker._adjustDate(event.target, (event.ctrlKey ?
								+$.datepicker._get(inst, "stepBigMonths") :
								+$.datepicker._get(inst, "stepMonths")), "M");
						}
						// next month/year on alt +right
						break;
				case 40: if (event.ctrlKey || event.metaKey) {
							$.datepicker._adjustDate(event.target, +7, "D");
						}
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		} else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
			$.datepicker._showDatepicker(this);
		} else {
			handled = false;
		}

		if (handled) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function(event) {
		var chars, chr,
			inst = $.datepicker._getInst(event.target);

		if ($.datepicker._get(inst, "constrainInput")) {
			chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat"));
			chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode);
			return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1);
		}
	},

	/* Synchronise manual entry and field/alternate field. */
	_doKeyUp: function(event) {
		var date,
			inst = $.datepicker._getInst(event.target);

		if (inst.input.val() !== inst.lastVal) {
			try {
				date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
					(inst.input ? inst.input.val() : null),
					$.datepicker._getFormatConfig(inst));

				if (date) { // only if valid
					$.datepicker._setDateFromField(inst);
					$.datepicker._updateAlternate(inst);
					$.datepicker._updateDatepicker(inst);
				}
			}
			catch (err) {
			}
		}
		return true;
	},

	/* Pop-up the date picker for a given input field.
	 * If false returned from beforeShow event handler do not show.
	 * @param  input  element - the input field attached to the date picker or
	 *					event - if triggered by focus
	 */
	_showDatepicker: function(input) {
		input = input.target || input;
		if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger
			input = $("input", input.parentNode)[0];
		}

		if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here
			return;
		}

		var inst, beforeShow, beforeShowSettings, isFixed,
			offset, showAnim, duration;

		inst = $.datepicker._getInst(input);
		if ($.datepicker._curInst && $.datepicker._curInst !== inst) {
			$.datepicker._curInst.dpDiv.stop(true, true);
			if ( inst && $.datepicker._datepickerShowing ) {
				$.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
			}
		}

		beforeShow = $.datepicker._get(inst, "beforeShow");
		beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
		if(beforeShowSettings === false){
			return;
		}
		datepicker_extendRemove(inst.settings, beforeShowSettings);

		inst.lastVal = null;
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField(inst);

		if ($.datepicker._inDialog) { // hide cursor
			input.value = "";
		}
		if (!$.datepicker._pos) { // position below input
			$.datepicker._pos = $.datepicker._findPos(input);
			$.datepicker._pos[1] += input.offsetHeight; // add the height
		}

		isFixed = false;
		$(input).parents().each(function() {
			isFixed |= $(this).css("position") === "fixed";
			return !isFixed;
		});

		offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
		$.datepicker._pos = null;
		//to avoid flashes on Firefox
		inst.dpDiv.empty();
		// determine sizing offscreen
		inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"});
		$.datepicker._updateDatepicker(inst);
		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset(inst, offset, isFixed);
		inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
			"static" : (isFixed ? "fixed" : "absolute")), display: "none",
			left: offset.left + "px", top: offset.top + "px"});

		if (!inst.inline) {
			showAnim = $.datepicker._get(inst, "showAnim");
			duration = $.datepicker._get(inst, "duration");
			inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 );
			$.datepicker._datepickerShowing = true;

			if ( $.effects && $.effects.effect[ showAnim ] ) {
				inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration);
			} else {
				inst.dpDiv[showAnim || "show"](showAnim ? duration : null);
			}

			if ( $.datepicker._shouldFocusInput( inst ) ) {
				inst.input.focus();
			}

			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function(inst) {
		this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
		datepicker_instActive = inst; // for delegate hover events
		inst.dpDiv.empty().append(this._generateHTML(inst));
		this._attachHandlers(inst);

		var origyearshtml,
			numMonths = this._getNumberOfMonths(inst),
			cols = numMonths[1],
			width = 17,
			activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" );

		if ( activeCell.length > 0 ) {
			datepicker_handleMouseover.apply( activeCell.get( 0 ) );
		}

		inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");
		if (cols > 1) {
			inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");
		}
		inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") +
			"Class"]("ui-datepicker-multi");
		inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") +
			"Class"]("ui-datepicker-rtl");

		if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
			inst.input.focus();
		}

		// deffered render of the years select (to avoid flashes on Firefox)
		if( inst.yearshtml ){
			origyearshtml = inst.yearshtml;
			setTimeout(function(){
				//assure that inst.yearshtml didn't change.
				if( origyearshtml === inst.yearshtml && inst.yearshtml ){
					inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml);
				}
				origyearshtml = inst.yearshtml = null;
			}, 0);
		}
	},

	// #6694 - don't focus the input if it's already focused
	// this breaks the change event in IE
	// Support: IE and jQuery <1.9
	_shouldFocusInput: function( inst ) {
		return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function(inst, offset, isFixed) {
		var dpWidth = inst.dpDiv.outerWidth(),
			dpHeight = inst.dpDiv.outerHeight(),
			inputWidth = inst.input ? inst.input.outerWidth() : 0,
			inputHeight = inst.input ? inst.input.outerHeight() : 0,
			viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
			viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());

		offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
		offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
		offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;

		// now check if datepicker is showing outside window viewport - move to a better place if so.
		offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
			Math.abs(offset.left + dpWidth - viewWidth) : 0);
		offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
			Math.abs(dpHeight + inputHeight) : 0);

		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function(obj) {
		var position,
			inst = this._getInst(obj),
			isRTL = this._get(inst, "isRTL");

		while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
			obj = obj[isRTL ? "previousSibling" : "nextSibling"];
		}

		position = $(obj).offset();
		return [position.left, position.top];
	},

	/* Hide the date picker from view.
	 * @param  input  element - the input field attached to the date picker
	 */
	_hideDatepicker: function(input) {
		var showAnim, duration, postProcess, onClose,
			inst = this._curInst;

		if (!inst || (input && inst !== $.data(input, "datepicker"))) {
			return;
		}

		if (this._datepickerShowing) {
			showAnim = this._get(inst, "showAnim");
			duration = this._get(inst, "duration");
			postProcess = function() {
				$.datepicker._tidyDialog(inst);
			};

			// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
			if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
				inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess);
			} else {
				inst.dpDiv[(showAnim === "slideDown" ? "slideUp" :
					(showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess);
			}

			if (!showAnim) {
				postProcess();
			}
			this._datepickerShowing = false;

			onClose = this._get(inst, "onClose");
			if (onClose) {
				onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]);
			}

			this._lastInput = null;
			if (this._inDialog) {
				this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" });
				if ($.blockUI) {
					$.unblockUI();
					$("body").append(this.dpDiv);
				}
			}
			this._inDialog = false;
		}
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function(inst) {
		inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar");
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function(event) {
		if (!$.datepicker._curInst) {
			return;
		}

		var $target = $(event.target),
			inst = $.datepicker._getInst($target[0]);

		if ( ( ( $target[0].id !== $.datepicker._mainDivId &&
				$target.parents("#" + $.datepicker._mainDivId).length === 0 &&
				!$target.hasClass($.datepicker.markerClassName) &&
				!$target.closest("." + $.datepicker._triggerClass).length &&
				$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
			( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) {
				$.datepicker._hideDatepicker();
		}
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function(id, offset, period) {
		var target = $(id),
			inst = this._getInst(target[0]);

		if (this._isDisabledDatepicker(target[0])) {
			return;
		}
		this._adjustInstDate(inst, offset +
			(period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
			period);
		this._updateDatepicker(inst);
	},

	/* Action for current link. */
	_gotoToday: function(id) {
		var date,
			target = $(id),
			inst = this._getInst(target[0]);

		if (this._get(inst, "gotoCurrent") && inst.currentDay) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		} else {
			date = new Date();
			inst.selectedDay = date.getDate();
			inst.drawMonth = inst.selectedMonth = date.getMonth();
			inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function(id, select, period) {
		var target = $(id),
			inst = this._getInst(target[0]);

		inst["selected" + (period === "M" ? "Month" : "Year")] =
		inst["draw" + (period === "M" ? "Month" : "Year")] =
			parseInt(select.options[select.selectedIndex].value,10);

		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a day. */
	_selectDay: function(id, month, year, td) {
		var inst,
			target = $(id);

		if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
			return;
		}

		inst = this._getInst(target[0]);
		inst.selectedDay = inst.currentDay = $("a", td).html();
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		this._selectDate(id, this._formatDate(inst,
			inst.currentDay, inst.currentMonth, inst.currentYear));
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function(id) {
		var target = $(id);
		this._selectDate(target, "");
	},

	/* Update the input field with the selected date. */
	_selectDate: function(id, dateStr) {
		var onSelect,
			target = $(id),
			inst = this._getInst(target[0]);

		dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
		if (inst.input) {
			inst.input.val(dateStr);
		}
		this._updateAlternate(inst);

		onSelect = this._get(inst, "onSelect");
		if (onSelect) {
			onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
		} else if (inst.input) {
			inst.input.trigger("change"); // fire the change event
		}

		if (inst.inline){
			this._updateDatepicker(inst);
		} else {
			this._hideDatepicker();
			this._lastInput = inst.input[0];
			if (typeof(inst.input[0]) !== "object") {
				inst.input.focus(); // restore focus
			}
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function(inst) {
		var altFormat, date, dateStr,
			altField = this._get(inst, "altField");

		if (altField) { // update alternate field too
			altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
			date = this._getDate(inst);
			dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
			$(altField).each(function() { $(this).val(dateStr); });
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	 * @param  date  Date - the date to customise
	 * @return [boolean, string] - is this date selectable?, what is its CSS class?
	 */
	noWeekends: function(date) {
		var day = date.getDay();
		return [(day > 0 && day < 6), ""];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	 * @param  date  Date - the date to get the week for
	 * @return  number - the number of the week within the year that contains this date
	 */
	iso8601Week: function(date) {
		var time,
			checkDate = new Date(date.getTime());

		// Find Thursday of this week starting on Monday
		checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));

		time = checkDate.getTime();
		checkDate.setMonth(0); // Compare with Jan 1
		checkDate.setDate(1);
		return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
	},

	/* Parse a string value into a date object.
	 * See formatDate below for the possible formats.
	 *
	 * @param  format string - the expected format of the date
	 * @param  value string - the date in the above format
	 * @param  settings Object - attributes include:
	 *					shortYearCutoff  number - the cutoff year for determining the century (optional)
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  Date - the extracted date value or null if value is blank
	 */
	parseDate: function (format, value, settings) {
		if (format == null || value == null) {
			throw "Invalid arguments";
		}

		value = (typeof value === "object" ? value.toString() : value + "");
		if (value === "") {
			return null;
		}

		var iFormat, dim, extra,
			iValue = 0,
			shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff,
			shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
				new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)),
			dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
			dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
			monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
			monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
			year = -1,
			month = -1,
			day = -1,
			doy = -1,
			literal = false,
			date,
			// Check whether a format character is doubled
			lookAhead = function(match) {
				var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
				if (matches) {
					iFormat++;
				}
				return matches;
			},
			// Extract a number from the string value
			getNumber = function(match) {
				var isDoubled = lookAhead(match),
					size = (match === "@" ? 14 : (match === "!" ? 20 :
					(match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))),
					minSize = (match === "y" ? size : 1),
					digits = new RegExp("^\\d{" + minSize + "," + size + "}"),
					num = value.substring(iValue).match(digits);
				if (!num) {
					throw "Missing number at position " + iValue;
				}
				iValue += num[0].length;
				return parseInt(num[0], 10);
			},
			// Extract a name from the string value and convert to an index
			getName = function(match, shortNames, longNames) {
				var index = -1,
					names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
						return [ [k, v] ];
					}).sort(function (a, b) {
						return -(a[1].length - b[1].length);
					});

				$.each(names, function (i, pair) {
					var name = pair[1];
					if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) {
						index = pair[0];
						iValue += name.length;
						return false;
					}
				});
				if (index !== -1) {
					return index + 1;
				} else {
					throw "Unknown name at position " + iValue;
				}
			},
			// Confirm that a literal character matches the string value
			checkLiteral = function() {
				if (value.charAt(iValue) !== format.charAt(iFormat)) {
					throw "Unexpected literal at position " + iValue;
				}
				iValue++;
			};

		for (iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal) {
				if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
					literal = false;
				} else {
					checkLiteral();
				}
			} else {
				switch (format.charAt(iFormat)) {
					case "d":
						day = getNumber("d");
						break;
					case "D":
						getName("D", dayNamesShort, dayNames);
						break;
					case "o":
						doy = getNumber("o");
						break;
					case "m":
						month = getNumber("m");
						break;
					case "M":
						month = getName("M", monthNamesShort, monthNames);
						break;
					case "y":
						year = getNumber("y");
						break;
					case "@":
						date = new Date(getNumber("@"));
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "!":
						date = new Date((getNumber("!") - this._ticksTo1970) / 10000);
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if (lookAhead("'")){
							checkLiteral();
						} else {
							literal = true;
						}
						break;
					default:
						checkLiteral();
				}
			}
		}

		if (iValue < value.length){
			extra = value.substr(iValue);
			if (!/^\s+/.test(extra)) {
				throw "Extra/unparsed characters found in date: " + extra;
			}
		}

		if (year === -1) {
			year = new Date().getFullYear();
		} else if (year < 100) {
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				(year <= shortYearCutoff ? 0 : -100);
		}

		if (doy > -1) {
			month = 1;
			day = doy;
			do {
				dim = this._getDaysInMonth(year, month - 1);
				if (day <= dim) {
					break;
				}
				month++;
				day -= dim;
			} while (true);
		}

		date = this._daylightSavingAdjust(new Date(year, month - 1, day));
		if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
			throw "Invalid date"; // E.g. 31/02/00
		}
		return date;
	},

	/* Standard date formats. */
	ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
	COOKIE: "D, dd M yy",
	ISO_8601: "yy-mm-dd",
	RFC_822: "D, d M y",
	RFC_850: "DD, dd-M-y",
	RFC_1036: "D, d M y",
	RFC_1123: "D, d M yy",
	RFC_2822: "D, d M yy",
	RSS: "D, d M y", // RFC 822
	TICKS: "!",
	TIMESTAMP: "@",
	W3C: "yy-mm-dd", // ISO 8601

	_ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
		Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),

	/* Format a date object into a string value.
	 * The format can be combinations of the following:
	 * d  - day of month (no leading zero)
	 * dd - day of month (two digit)
	 * o  - day of year (no leading zeros)
	 * oo - day of year (three digit)
	 * D  - day name short
	 * DD - day name long
	 * m  - month of year (no leading zero)
	 * mm - month of year (two digit)
	 * M  - month name short
	 * MM - month name long
	 * y  - year (two digit)
	 * yy - year (four digit)
	 * @ - Unix timestamp (ms since 01/01/1970)
	 * ! - Windows ticks (100ns since 01/01/0001)
	 * "..." - literal text
	 * '' - single quote
	 *
	 * @param  format string - the desired format of the date
	 * @param  date Date - the date value to format
	 * @param  settings Object - attributes include:
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  string - the date in the above format
	 */
	formatDate: function (format, date, settings) {
		if (!date) {
			return "";
		}

		var iFormat,
			dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
			dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
			monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
			monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
			// Check whether a format character is doubled
			lookAhead = function(match) {
				var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
				if (matches) {
					iFormat++;
				}
				return matches;
			},
			// Format a number, with leading zero if necessary
			formatNumber = function(match, value, len) {
				var num = "" + value;
				if (lookAhead(match)) {
					while (num.length < len) {
						num = "0" + num;
					}
				}
				return num;
			},
			// Format a name, short or long as requested
			formatName = function(match, value, shortNames, longNames) {
				return (lookAhead(match) ? longNames[value] : shortNames[value]);
			},
			output = "",
			literal = false;

		if (date) {
			for (iFormat = 0; iFormat < format.length; iFormat++) {
				if (literal) {
					if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
						literal = false;
					} else {
						output += format.charAt(iFormat);
					}
				} else {
					switch (format.charAt(iFormat)) {
						case "d":
							output += formatNumber("d", date.getDate(), 2);
							break;
						case "D":
							output += formatName("D", date.getDay(), dayNamesShort, dayNames);
							break;
						case "o":
							output += formatNumber("o",
								Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
							break;
						case "m":
							output += formatNumber("m", date.getMonth() + 1, 2);
							break;
						case "M":
							output += formatName("M", date.getMonth(), monthNamesShort, monthNames);
							break;
						case "y":
							output += (lookAhead("y") ? date.getFullYear() :
								(date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100);
							break;
						case "@":
							output += date.getTime();
							break;
						case "!":
							output += date.getTime() * 10000 + this._ticksTo1970;
							break;
						case "'":
							if (lookAhead("'")) {
								output += "'";
							} else {
								literal = true;
							}
							break;
						default:
							output += format.charAt(iFormat);
					}
				}
			}
		}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function (format) {
		var iFormat,
			chars = "",
			literal = false,
			// Check whether a format character is doubled
			lookAhead = function(match) {
				var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
				if (matches) {
					iFormat++;
				}
				return matches;
			};

		for (iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal) {
				if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
					literal = false;
				} else {
					chars += format.charAt(iFormat);
				}
			} else {
				switch (format.charAt(iFormat)) {
					case "d": case "m": case "y": case "@":
						chars += "0123456789";
						break;
					case "D": case "M":
						return null; // Accept anything
					case "'":
						if (lookAhead("'")) {
							chars += "'";
						} else {
							literal = true;
						}
						break;
					default:
						chars += format.charAt(iFormat);
				}
			}
		}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function(inst, name) {
		return inst.settings[name] !== undefined ?
			inst.settings[name] : this._defaults[name];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function(inst, noDefault) {
		if (inst.input.val() === inst.lastVal) {
			return;
		}

		var dateFormat = this._get(inst, "dateFormat"),
			dates = inst.lastVal = inst.input ? inst.input.val() : null,
			defaultDate = this._getDefaultDate(inst),
			date = defaultDate,
			settings = this._getFormatConfig(inst);

		try {
			date = this.parseDate(dateFormat, dates, settings) || defaultDate;
		} catch (event) {
			dates = (noDefault ? "" : dates);
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = (dates ? date.getDate() : 0);
		inst.currentMonth = (dates ? date.getMonth() : 0);
		inst.currentYear = (dates ? date.getFullYear() : 0);
		this._adjustInstDate(inst);
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function(inst) {
		return this._restrictMinMax(inst,
			this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function(inst, date, defaultDate) {
		var offsetNumeric = function(offset) {
				var date = new Date();
				date.setDate(date.getDate() + offset);
				return date;
			},
			offsetString = function(offset) {
				try {
					return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
						offset, $.datepicker._getFormatConfig(inst));
				}
				catch (e) {
					// Ignore
				}

				var date = (offset.toLowerCase().match(/^c/) ?
					$.datepicker._getDate(inst) : null) || new Date(),
					year = date.getFullYear(),
					month = date.getMonth(),
					day = date.getDate(),
					pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
					matches = pattern.exec(offset);

				while (matches) {
					switch (matches[2] || "d") {
						case "d" : case "D" :
							day += parseInt(matches[1],10); break;
						case "w" : case "W" :
							day += parseInt(matches[1],10) * 7; break;
						case "m" : case "M" :
							month += parseInt(matches[1],10);
							day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
							break;
						case "y": case "Y" :
							year += parseInt(matches[1],10);
							day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
							break;
					}
					matches = pattern.exec(offset);
				}
				return new Date(year, month, day);
			},
			newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
				(typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));

		newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
		if (newDate) {
			newDate.setHours(0);
			newDate.setMinutes(0);
			newDate.setSeconds(0);
			newDate.setMilliseconds(0);
		}
		return this._daylightSavingAdjust(newDate);
	},

	/* Handle switch to/from daylight saving.
	 * Hours may be non-zero on daylight saving cut-over:
	 * > 12 when midnight changeover, but then cannot generate
	 * midnight datetime, so jump to 1AM, otherwise reset.
	 * @param  date  (Date) the date to check
	 * @return  (Date) the corrected date
	 */
	_daylightSavingAdjust: function(date) {
		if (!date) {
			return null;
		}
		date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function(inst, date, noChange) {
		var clear = !date,
			origMonth = inst.selectedMonth,
			origYear = inst.selectedYear,
			newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));

		inst.selectedDay = inst.currentDay = newDate.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
		if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
			this._notifyChange(inst);
		}
		this._adjustInstDate(inst);
		if (inst.input) {
			inst.input.val(clear ? "" : this._formatDate(inst));
		}
	},

	/* Retrieve the date(s) directly. */
	_getDate: function(inst) {
		var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null :
			this._daylightSavingAdjust(new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay)));
			return startDate;
	},

	/* Attach the onxxx handlers.  These are declared statically so
	 * they work with static code transformers like Caja.
	 */
	_attachHandlers: function(inst) {
		var stepMonths = this._get(inst, "stepMonths"),
			id = "#" + inst.id.replace( /\\\\/g, "\\" );
		inst.dpDiv.find("[data-handler]").map(function () {
			var handler = {
				prev: function () {
					$.datepicker._adjustDate(id, -stepMonths, "M");
				},
				next: function () {
					$.datepicker._adjustDate(id, +stepMonths, "M");
				},
				hide: function () {
					$.datepicker._hideDatepicker();
				},
				today: function () {
					$.datepicker._gotoToday(id);
				},
				selectDay: function () {
					$.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this);
					return false;
				},
				selectMonth: function () {
					$.datepicker._selectMonthYear(id, this, "M");
					return false;
				},
				selectYear: function () {
					$.datepicker._selectMonthYear(id, this, "Y");
					return false;
				}
			};
			$(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]);
		});
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function(inst) {
		var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
			controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
			monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
			selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
			cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
			printDate, dRow, tbody, daySettings, otherMonth, unselectable,
			tempDate = new Date(),
			today = this._daylightSavingAdjust(
				new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time
			isRTL = this._get(inst, "isRTL"),
			showButtonPanel = this._get(inst, "showButtonPanel"),
			hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"),
			navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"),
			numMonths = this._getNumberOfMonths(inst),
			showCurrentAtPos = this._get(inst, "showCurrentAtPos"),
			stepMonths = this._get(inst, "stepMonths"),
			isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1),
			currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
				new Date(inst.currentYear, inst.currentMonth, inst.currentDay))),
			minDate = this._getMinMaxDate(inst, "min"),
			maxDate = this._getMinMaxDate(inst, "max"),
			drawMonth = inst.drawMonth - showCurrentAtPos,
			drawYear = inst.drawYear;

		if (drawMonth < 0) {
			drawMonth += 12;
			drawYear--;
		}
		if (maxDate) {
			maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
				maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
			while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
				drawMonth--;
				if (drawMonth < 0) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;

		prevText = this._get(inst, "prevText");
		prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
			this._getFormatConfig(inst)));

		prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
			"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
			" title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
			(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));

		nextText = this._get(inst, "nextText");
		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
			this._getFormatConfig(inst)));

		next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
			"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
			" title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
			(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));

		currentText = this._get(inst, "currentText");
		gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today);
		currentText = (!navigationAsDateFormat ? currentText :
			this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));

		controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
			this._get(inst, "closeText") + "</button>" : "");

		buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
			(this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
			">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";

		firstDay = parseInt(this._get(inst, "firstDay"),10);
		firstDay = (isNaN(firstDay) ? 0 : firstDay);

		showWeek = this._get(inst, "showWeek");
		dayNames = this._get(inst, "dayNames");
		dayNamesMin = this._get(inst, "dayNamesMin");
		monthNames = this._get(inst, "monthNames");
		monthNamesShort = this._get(inst, "monthNamesShort");
		beforeShowDay = this._get(inst, "beforeShowDay");
		showOtherMonths = this._get(inst, "showOtherMonths");
		selectOtherMonths = this._get(inst, "selectOtherMonths");
		defaultDate = this._getDefaultDate(inst);
		html = "";
		dow;
		for (row = 0; row < numMonths[0]; row++) {
			group = "";
			this.maxRows = 4;
			for (col = 0; col < numMonths[1]; col++) {
				selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
				cornerClass = " ui-corner-all";
				calender = "";
				if (isMultiMonth) {
					calender += "<div class='ui-datepicker-group";
					if (numMonths[1] > 1) {
						switch (col) {
							case 0: calender += " ui-datepicker-group-first";
								cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break;
							case numMonths[1]-1: calender += " ui-datepicker-group-last";
								cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break;
							default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
						}
					}
					calender += "'>";
				}
				calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
					(/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
					(/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
					this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
					row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
					"</div><table class='ui-datepicker-calendar'><thead>" +
					"<tr>";
				thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : "");
				for (dow = 0; dow < 7; dow++) { // days of the week
					day = (dow + firstDay) % 7;
					thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" +
						"<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>";
				}
				calender += thead + "</tr></thead><tbody>";
				daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
				if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) {
					inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
				}
				leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
				curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
				numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
				this.maxRows = numRows;
				printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
				for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows
					calender += "<tr>";
					tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
						this._get(inst, "calculateWeek")(printDate) + "</td>");
					for (dow = 0; dow < 7; dow++) { // create date picker days
						daySettings = (beforeShowDay ?
							beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]);
						otherMonth = (printDate.getMonth() !== drawMonth);
						unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
						tbody += "<td class='" +
							((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends
							(otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months
							((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key
							(defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?
							// or defaultDate is current printedDate and defaultDate is selectedDate
							" " + this._dayOverClass : "") + // highlight selected day
							(unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") +  // highlight unselectable days
							(otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates
							(printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day
							(printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different)
							((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "&#39;") + "'" : "") + // cell title
							(unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions
							(otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months
							(unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
							(printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") +
							(printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day
							(otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months
							"' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date
						printDate.setDate(printDate.getDate() + 1);
						printDate = this._daylightSavingAdjust(printDate);
					}
					calender += tbody + "</tr>";
				}
				drawMonth++;
				if (drawMonth > 11) {
					drawMonth = 0;
					drawYear++;
				}
				calender += "</tbody></table>" + (isMultiMonth ? "</div>" +
							((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : "");
				group += calender;
			}
			html += group;
		}
		html += buttonPanel;
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
			secondary, monthNames, monthNamesShort) {

		var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
			changeMonth = this._get(inst, "changeMonth"),
			changeYear = this._get(inst, "changeYear"),
			showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
			html = "<div class='ui-datepicker-title'>",
			monthHtml = "";

		// month selection
		if (secondary || !changeMonth) {
			monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
		} else {
			inMinYear = (minDate && minDate.getFullYear() === drawYear);
			inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
			monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
			for ( month = 0; month < 12; month++) {
				if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
					monthHtml += "<option value='" + month + "'" +
						(month === drawMonth ? " selected='selected'" : "") +
						">" + monthNamesShort[month] + "</option>";
				}
			}
			monthHtml += "</select>";
		}

		if (!showMonthAfterYear) {
			html += monthHtml + (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "");
		}

		// year selection
		if ( !inst.yearshtml ) {
			inst.yearshtml = "";
			if (secondary || !changeYear) {
				html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
			} else {
				// determine range of years to display
				years = this._get(inst, "yearRange").split(":");
				thisYear = new Date().getFullYear();
				determineYear = function(value) {
					var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
						(value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
						parseInt(value, 10)));
					return (isNaN(year) ? thisYear : year);
				};
				year = determineYear(years[0]);
				endYear = Math.max(year, determineYear(years[1] || ""));
				year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
				endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
				inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
				for (; year <= endYear; year++) {
					inst.yearshtml += "<option value='" + year + "'" +
						(year === drawYear ? " selected='selected'" : "") +
						">" + year + "</option>";
				}
				inst.yearshtml += "</select>";

				html += inst.yearshtml;
				inst.yearshtml = null;
			}
		}

		html += this._get(inst, "yearSuffix");
		if (showMonthAfterYear) {
			html += (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "") + monthHtml;
		}
		html += "</div>"; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function(inst, offset, period) {
		var year = inst.drawYear + (period === "Y" ? offset : 0),
			month = inst.drawMonth + (period === "M" ? offset : 0),
			day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0),
			date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));

		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if (period === "M" || period === "Y") {
			this._notifyChange(inst);
		}
	},

	/* Ensure a date is within any min/max bounds. */
	_restrictMinMax: function(inst, date) {
		var minDate = this._getMinMaxDate(inst, "min"),
			maxDate = this._getMinMaxDate(inst, "max"),
			newDate = (minDate && date < minDate ? minDate : date);
		return (maxDate && newDate > maxDate ? maxDate : newDate);
	},

	/* Notify change of month/year. */
	_notifyChange: function(inst) {
		var onChange = this._get(inst, "onChangeMonthYear");
		if (onChange) {
			onChange.apply((inst.input ? inst.input[0] : null),
				[inst.selectedYear, inst.selectedMonth + 1, inst]);
		}
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function(inst) {
		var numMonths = this._get(inst, "numberOfMonths");
		return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths));
	},

	/* Determine the current maximum date - ensure no time components are set. */
	_getMinMaxDate: function(inst, minMax) {
		return this._determineDate(inst, this._get(inst, minMax + "Date"), null);
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function(year, month) {
		return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function(year, month) {
		return new Date(year, month, 1).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function(inst, offset, curYear, curMonth) {
		var numMonths = this._getNumberOfMonths(inst),
			date = this._daylightSavingAdjust(new Date(curYear,
			curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));

		if (offset < 0) {
			date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
		}
		return this._isInRange(inst, date);
	},

	/* Is the given date in the accepted range? */
	_isInRange: function(inst, date) {
		var yearSplit, currentYear,
			minDate = this._getMinMaxDate(inst, "min"),
			maxDate = this._getMinMaxDate(inst, "max"),
			minYear = null,
			maxYear = null,
			years = this._get(inst, "yearRange");
			if (years){
				yearSplit = years.split(":");
				currentYear = new Date().getFullYear();
				minYear = parseInt(yearSplit[0], 10);
				maxYear = parseInt(yearSplit[1], 10);
				if ( yearSplit[0].match(/[+\-].*/) ) {
					minYear += currentYear;
				}
				if ( yearSplit[1].match(/[+\-].*/) ) {
					maxYear += currentYear;
				}
			}

		return ((!minDate || date.getTime() >= minDate.getTime()) &&
			(!maxDate || date.getTime() <= maxDate.getTime()) &&
			(!minYear || date.getFullYear() >= minYear) &&
			(!maxYear || date.getFullYear() <= maxYear));
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function(inst) {
		var shortYearCutoff = this._get(inst, "shortYearCutoff");
		shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
		return {shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"),
			monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")};
	},

	/* Format the given date for display. */
	_formatDate: function(inst, day, month, year) {
		if (!day) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = (day ? (typeof day === "object" ? day :
			this._daylightSavingAdjust(new Date(year, month, day))) :
			this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst));
	}
});

/*
 * Bind hover events for datepicker elements.
 * Done via delegate so the binding only occurs once in the lifetime of the parent div.
 * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
 */
function datepicker_bindHover(dpDiv) {
	var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
	return dpDiv.delegate(selector, "mouseout", function() {
			$(this).removeClass("ui-state-hover");
			if (this.className.indexOf("ui-datepicker-prev") !== -1) {
				$(this).removeClass("ui-datepicker-prev-hover");
			}
			if (this.className.indexOf("ui-datepicker-next") !== -1) {
				$(this).removeClass("ui-datepicker-next-hover");
			}
		})
		.delegate( selector, "mouseover", datepicker_handleMouseover );
}

function datepicker_handleMouseover() {
	if (!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? datepicker_instActive.dpDiv.parent()[0] : datepicker_instActive.input[0])) {
		$(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");
		$(this).addClass("ui-state-hover");
		if (this.className.indexOf("ui-datepicker-prev") !== -1) {
			$(this).addClass("ui-datepicker-prev-hover");
		}
		if (this.className.indexOf("ui-datepicker-next") !== -1) {
			$(this).addClass("ui-datepicker-next-hover");
		}
	}
}

/* jQuery extend now ignores nulls! */
function datepicker_extendRemove(target, props) {
	$.extend(target, props);
	for (var name in props) {
		if (props[name] == null) {
			target[name] = props[name];
		}
	}
	return target;
}

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
					Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function(options){

	/* Verify an empty collection wasn't passed - Fixes #6976 */
	if ( !this.length ) {
		return this;
	}

	/* Initialise the date picker. */
	if (!$.datepicker.initialized) {
		$(document).mousedown($.datepicker._checkExternalClick);
		$.datepicker.initialized = true;
	}

	/* Append datepicker main container to body if not exist. */
	if ($("#"+$.datepicker._mainDivId).length === 0) {
		$("body").append($.datepicker.dpDiv);
	}

	var otherArgs = Array.prototype.slice.call(arguments, 1);
	if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) {
		return $.datepicker["_" + options + "Datepicker"].
			apply($.datepicker, [this[0]].concat(otherArgs));
	}
	if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") {
		return $.datepicker["_" + options + "Datepicker"].
			apply($.datepicker, [this[0]].concat(otherArgs));
	}
	return this.each(function() {
		typeof options === "string" ?
			$.datepicker["_" + options + "Datepicker"].
				apply($.datepicker, [this].concat(otherArgs)) :
			$.datepicker._attachDatepicker(this, options);
	});
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.11.4";

var datepicker = $.datepicker;


/*!
 * jQuery UI Draggable 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/draggable/
 */


$.widget("ui.draggable", $.ui.mouse, {
	version: "1.11.4",
	widgetEventPrefix: "drag",
	options: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false,

		// callbacks
		drag: null,
		start: null,
		stop: null
	},
	_create: function() {

		if ( this.options.helper === "original" ) {
			this._setPositionRelative();
		}
		if (this.options.addClasses){
			this.element.addClass("ui-draggable");
		}
		if (this.options.disabled){
			this.element.addClass("ui-draggable-disabled");
		}
		this._setHandleClassName();

		this._mouseInit();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "handle" ) {
			this._removeHandleClassName();
			this._setHandleClassName();
		}
	},

	_destroy: function() {
		if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) {
			this.destroyOnClear = true;
			return;
		}
		this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" );
		this._removeHandleClassName();
		this._mouseDestroy();
	},

	_mouseCapture: function(event) {
		var o = this.options;

		this._blurActiveElement( event );

		// among others, prevent a drag on a resizable-handle
		if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) {
			return false;
		}

		//Quit if we're not on a valid handle
		this.handle = this._getHandle(event);
		if (!this.handle) {
			return false;
		}

		this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix );

		return true;

	},

	_blockFrames: function( selector ) {
		this.iframeBlocks = this.document.find( selector ).map(function() {
			var iframe = $( this );

			return $( "<div>" )
				.css( "position", "absolute" )
				.appendTo( iframe.parent() )
				.outerWidth( iframe.outerWidth() )
				.outerHeight( iframe.outerHeight() )
				.offset( iframe.offset() )[ 0 ];
		});
	},

	_unblockFrames: function() {
		if ( this.iframeBlocks ) {
			this.iframeBlocks.remove();
			delete this.iframeBlocks;
		}
	},

	_blurActiveElement: function( event ) {
		var document = this.document[ 0 ];

		// Only need to blur if the event occurred on the draggable itself, see #10527
		if ( !this.handleElement.is( event.target ) ) {
			return;
		}

		// support: IE9
		// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
		try {

			// Support: IE9, IE10
			// If the <body> is blurred, IE will switch windows, see #9520
			if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) {

				// Blur any element that currently has focus, see #4261
				$( document.activeElement ).blur();
			}
		} catch ( error ) {}
	},

	_mouseStart: function(event) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		this.helper.addClass("ui-draggable-dragging");

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if ($.ui.ddmanager) {
			$.ui.ddmanager.current = this;
		}

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css( "position" );
		this.scrollParent = this.helper.scrollParent( true );
		this.offsetParent = this.helper.offsetParent();
		this.hasFixedAncestor = this.helper.parents().filter(function() {
				return $( this ).css( "position" ) === "fixed";
			}).length > 0;

		//The element's absolute position on the page minus margins
		this.positionAbs = this.element.offset();
		this._refreshOffsets( event );

		//Generate the original position
		this.originalPosition = this.position = this._generatePosition( event, false );
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

		//Set a containment if given in the options
		this._setContainment();

		//Trigger event + callbacks
		if (this._trigger("start", event) === false) {
			this._clear();
			return false;
		}

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ($.ui.ddmanager && !o.dropBehaviour) {
			$.ui.ddmanager.prepareOffsets(this, event);
		}

		// Reset helper's right/bottom css if they're set and set explicit width/height instead
		// as this prevents resizing of elements with right/bottom set (see #7772)
		this._normalizeRightBottom();

		this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position

		//If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStart(this, event);
		}

		return true;
	},

	_refreshOffsets: function( event ) {
		this.offset = {
			top: this.positionAbs.top - this.margins.top,
			left: this.positionAbs.left - this.margins.left,
			scroll: false,
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset()
		};

		this.offset.click = {
			left: event.pageX - this.offset.left,
			top: event.pageY - this.offset.top
		};
	},

	_mouseDrag: function(event, noPropagation) {
		// reset any necessary cached properties (see #5009)
		if ( this.hasFixedAncestor ) {
			this.offset.parent = this._getParentOffset();
		}

		//Compute the helpers position
		this.position = this._generatePosition( event, true );
		this.positionAbs = this._convertPositionTo("absolute");

		//Call plugins and callbacks and use the resulting position if something is returned
		if (!noPropagation) {
			var ui = this._uiHash();
			if (this._trigger("drag", event, ui) === false) {
				this._mouseUp({});
				return false;
			}
			this.position = ui.position;
		}

		this.helper[ 0 ].style.left = this.position.left + "px";
		this.helper[ 0 ].style.top = this.position.top + "px";

		if ($.ui.ddmanager) {
			$.ui.ddmanager.drag(this, event);
		}

		return false;
	},

	_mouseStop: function(event) {

		//If we are using droppables, inform the manager about the drop
		var that = this,
			dropped = false;
		if ($.ui.ddmanager && !this.options.dropBehaviour) {
			dropped = $.ui.ddmanager.drop(this, event);
		}

		//if a drop comes from outside (a sortable)
		if (this.dropped) {
			dropped = this.dropped;
			this.dropped = false;
		}

		if ((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
			$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
				if (that._trigger("stop", event) !== false) {
					that._clear();
				}
			});
		} else {
			if (this._trigger("stop", event) !== false) {
				this._clear();
			}
		}

		return false;
	},

	_mouseUp: function( event ) {
		this._unblockFrames();

		//If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStop(this, event);
		}

		// Only need to focus if the event occurred on the draggable itself, see #10527
		if ( this.handleElement.is( event.target ) ) {
			// The interaction is over; whether or not the click resulted in a drag, focus the element
			this.element.focus();
		}

		return $.ui.mouse.prototype._mouseUp.call(this, event);
	},

	cancel: function() {

		if (this.helper.is(".ui-draggable-dragging")) {
			this._mouseUp({});
		} else {
			this._clear();
		}

		return this;

	},

	_getHandle: function(event) {
		return this.options.handle ?
			!!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
			true;
	},

	_setHandleClassName: function() {
		this.handleElement = this.options.handle ?
			this.element.find( this.options.handle ) : this.element;
		this.handleElement.addClass( "ui-draggable-handle" );
	},

	_removeHandleClassName: function() {
		this.handleElement.removeClass( "ui-draggable-handle" );
	},

	_createHelper: function(event) {

		var o = this.options,
			helperIsFunction = $.isFunction( o.helper ),
			helper = helperIsFunction ?
				$( o.helper.apply( this.element[ 0 ], [ event ] ) ) :
				( o.helper === "clone" ?
					this.element.clone().removeAttr( "id" ) :
					this.element );

		if (!helper.parents("body").length) {
			helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo));
		}

		// http://bugs.jqueryui.com/ticket/9446
		// a helper function can return the original element
		// which wouldn't have been set to relative in _create
		if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) {
			this._setPositionRelative();
		}

		if (helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) {
			helper.css("position", "absolute");
		}

		return helper;

	},

	_setPositionRelative: function() {
		if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) {
			this.element[ 0 ].style.position = "relative";
		}
	},

	_adjustOffsetFromHelper: function(obj) {
		if (typeof obj === "string") {
			obj = obj.split(" ");
		}
		if ($.isArray(obj)) {
			obj = { left: +obj[0], top: +obj[1] || 0 };
		}
		if ("left" in obj) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ("right" in obj) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ("top" in obj) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ("bottom" in obj) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_isRootNode: function( element ) {
		return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ];
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		var po = this.offsetParent.offset(),
			document = this.document[ 0 ];

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if ( this._isRootNode( this.offsetParent[ 0 ] ) ) {
			po = { top: 0, left: 0 };
		}

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0)
		};

	},

	_getRelativeOffset: function() {
		if ( this.cssPosition !== "relative" ) {
			return { top: 0, left: 0 };
		}

		var p = this.element.position(),
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: p.top - ( parseInt(this.helper.css( "top" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ),
			left: p.left - ( parseInt(this.helper.css( "left" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 )
		};

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.element.css("marginLeft"), 10) || 0),
			top: (parseInt(this.element.css("marginTop"), 10) || 0),
			right: (parseInt(this.element.css("marginRight"), 10) || 0),
			bottom: (parseInt(this.element.css("marginBottom"), 10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var isUserScrollable, c, ce,
			o = this.options,
			document = this.document[ 0 ];

		this.relativeContainer = null;

		if ( !o.containment ) {
			this.containment = null;
			return;
		}

		if ( o.containment === "window" ) {
			this.containment = [
				$( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
				$( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
				$( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left,
				$( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment === "document") {
			this.containment = [
				0,
				0,
				$( document ).width() - this.helperProportions.width - this.margins.left,
				( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment.constructor === Array ) {
			this.containment = o.containment;
			return;
		}

		if ( o.containment === "parent" ) {
			o.containment = this.helper[ 0 ].parentNode;
		}

		c = $( o.containment );
		ce = c[ 0 ];

		if ( !ce ) {
			return;
		}

		isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) );

		this.containment = [
			( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
			( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ),
			( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
				( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) -
				this.helperProportions.width -
				this.margins.left -
				this.margins.right,
			( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
				( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) -
				this.helperProportions.height -
				this.margins.top -
				this.margins.bottom
		];
		this.relativeContainer = c;
	},

	_convertPositionTo: function(d, pos) {

		if (!pos) {
			pos = this.position;
		}

		var mod = d === "absolute" ? 1 : -1,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: (
				pos.top	+																// The absolute mouse position
				this.offset.relative.top * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top * mod -										// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod)
			),
			left: (
				pos.left +																// The absolute mouse position
				this.offset.relative.left * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left * mod	-										// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod)
			)
		};

	},

	_generatePosition: function( event, constrainPosition ) {

		var containment, co, top, left,
			o = this.options,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ),
			pageX = event.pageX,
			pageY = event.pageY;

		// Cache the scroll
		if ( !scrollIsRootNode || !this.offset.scroll ) {
			this.offset.scroll = {
				top: this.scrollParent.scrollTop(),
				left: this.scrollParent.scrollLeft()
			};
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		// If we are not dragging yet, we won't check for options
		if ( constrainPosition ) {
			if ( this.containment ) {
				if ( this.relativeContainer ){
					co = this.relativeContainer.offset();
					containment = [
						this.containment[ 0 ] + co.left,
						this.containment[ 1 ] + co.top,
						this.containment[ 2 ] + co.left,
						this.containment[ 3 ] + co.top
					];
				} else {
					containment = this.containment;
				}

				if (event.pageX - this.offset.click.left < containment[0]) {
					pageX = containment[0] + this.offset.click.left;
				}
				if (event.pageY - this.offset.click.top < containment[1]) {
					pageY = containment[1] + this.offset.click.top;
				}
				if (event.pageX - this.offset.click.left > containment[2]) {
					pageX = containment[2] + this.offset.click.left;
				}
				if (event.pageY - this.offset.click.top > containment[3]) {
					pageY = containment[3] + this.offset.click.top;
				}
			}

			if (o.grid) {
				//Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950)
				top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
				pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX;
				pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

			if ( o.axis === "y" ) {
				pageX = this.originalPageX;
			}

			if ( o.axis === "x" ) {
				pageY = this.originalPageY;
			}
		}

		return {
			top: (
				pageY -																	// The absolute mouse position
				this.offset.click.top	-												// Click offset (relative to the element)
				this.offset.relative.top -												// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top +												// The offsetParent's offset without borders (offset + border)
				( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) )
			),
			left: (
				pageX -																	// The absolute mouse position
				this.offset.click.left -												// Click offset (relative to the element)
				this.offset.relative.left -												// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left +												// The offsetParent's offset without borders (offset + border)
				( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) )
			)
		};

	},

	_clear: function() {
		this.helper.removeClass("ui-draggable-dragging");
		if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
			this.helper.remove();
		}
		this.helper = null;
		this.cancelHelperRemoval = false;
		if ( this.destroyOnClear ) {
			this.destroy();
		}
	},

	_normalizeRightBottom: function() {
		if ( this.options.axis !== "y" && this.helper.css( "right" ) !== "auto" ) {
			this.helper.width( this.helper.width() );
			this.helper.css( "right", "auto" );
		}
		if ( this.options.axis !== "x" && this.helper.css( "bottom" ) !== "auto" ) {
			this.helper.height( this.helper.height() );
			this.helper.css( "bottom", "auto" );
		}
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function( type, event, ui ) {
		ui = ui || this._uiHash();
		$.ui.plugin.call( this, type, [ event, ui, this ], true );

		// Absolute position and offset (see #6884 ) have to be recalculated after plugins
		if ( /^(drag|start|stop)/.test( type ) ) {
			this.positionAbs = this._convertPositionTo( "absolute" );
			ui.offset = this.positionAbs;
		}
		return $.Widget.prototype._trigger.call( this, type, event, ui );
	},

	plugins: {},

	_uiHash: function() {
		return {
			helper: this.helper,
			position: this.position,
			originalPosition: this.originalPosition,
			offset: this.positionAbs
		};
	}

});

$.ui.plugin.add( "draggable", "connectToSortable", {
	start: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		});

		draggable.sortables = [];
		$( draggable.options.connectToSortable ).each(function() {
			var sortable = $( this ).sortable( "instance" );

			if ( sortable && !sortable.options.disabled ) {
				draggable.sortables.push( sortable );

				// refreshPositions is called at drag start to refresh the containerCache
				// which is used in drag. This ensures it's initialized and synchronized
				// with any changes that might have happened on the page since initialization.
				sortable.refreshPositions();
				sortable._trigger("activate", event, uiSortable);
			}
		});
	},
	stop: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		});

		draggable.cancelHelperRemoval = false;

		$.each( draggable.sortables, function() {
			var sortable = this;

			if ( sortable.isOver ) {
				sortable.isOver = 0;

				// Allow this sortable to handle removing the helper
				draggable.cancelHelperRemoval = true;
				sortable.cancelHelperRemoval = false;

				// Use _storedCSS To restore properties in the sortable,
				// as this also handles revert (#9675) since the draggable
				// may have modified them in unexpected ways (#8809)
				sortable._storedCSS = {
					position: sortable.placeholder.css( "position" ),
					top: sortable.placeholder.css( "top" ),
					left: sortable.placeholder.css( "left" )
				};

				sortable._mouseStop(event);

				// Once drag has ended, the sortable should return to using
				// its original helper, not the shared helper from draggable
				sortable.options.helper = sortable.options._helper;
			} else {
				// Prevent this Sortable from removing the helper.
				// However, don't set the draggable to remove the helper
				// either as another connected Sortable may yet handle the removal.
				sortable.cancelHelperRemoval = true;

				sortable._trigger( "deactivate", event, uiSortable );
			}
		});
	},
	drag: function( event, ui, draggable ) {
		$.each( draggable.sortables, function() {
			var innermostIntersecting = false,
				sortable = this;

			// Copy over variables that sortable's _intersectsWith uses
			sortable.positionAbs = draggable.positionAbs;
			sortable.helperProportions = draggable.helperProportions;
			sortable.offset.click = draggable.offset.click;

			if ( sortable._intersectsWith( sortable.containerCache ) ) {
				innermostIntersecting = true;

				$.each( draggable.sortables, function() {
					// Copy over variables that sortable's _intersectsWith uses
					this.positionAbs = draggable.positionAbs;
					this.helperProportions = draggable.helperProportions;
					this.offset.click = draggable.offset.click;

					if ( this !== sortable &&
							this._intersectsWith( this.containerCache ) &&
							$.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) {
						innermostIntersecting = false;
					}

					return innermostIntersecting;
				});
			}

			if ( innermostIntersecting ) {
				// If it intersects, we use a little isOver variable and set it once,
				// so that the move-in stuff gets fired only once.
				if ( !sortable.isOver ) {
					sortable.isOver = 1;

					// Store draggable's parent in case we need to reappend to it later.
					draggable._parent = ui.helper.parent();

					sortable.currentItem = ui.helper
						.appendTo( sortable.element )
						.data( "ui-sortable-item", true );

					// Store helper option to later restore it
					sortable.options._helper = sortable.options.helper;

					sortable.options.helper = function() {
						return ui.helper[ 0 ];
					};

					// Fire the start events of the sortable with our passed browser event,
					// and our own helper (so it doesn't create a new one)
					event.target = sortable.currentItem[ 0 ];
					sortable._mouseCapture( event, true );
					sortable._mouseStart( event, true, true );

					// Because the browser event is way off the new appended portlet,
					// modify necessary variables to reflect the changes
					sortable.offset.click.top = draggable.offset.click.top;
					sortable.offset.click.left = draggable.offset.click.left;
					sortable.offset.parent.left -= draggable.offset.parent.left -
						sortable.offset.parent.left;
					sortable.offset.parent.top -= draggable.offset.parent.top -
						sortable.offset.parent.top;

					draggable._trigger( "toSortable", event );

					// Inform draggable that the helper is in a valid drop zone,
					// used solely in the revert option to handle "valid/invalid".
					draggable.dropped = sortable.element;

					// Need to refreshPositions of all sortables in the case that
					// adding to one sortable changes the location of the other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					});

					// hack so receive/update callbacks work (mostly)
					draggable.currentItem = draggable.element;
					sortable.fromOutside = draggable;
				}

				if ( sortable.currentItem ) {
					sortable._mouseDrag( event );
					// Copy the sortable's position because the draggable's can potentially reflect
					// a relative position, while sortable is always absolute, which the dragged
					// element has now become. (#8809)
					ui.position = sortable.position;
				}
			} else {
				// If it doesn't intersect with the sortable, and it intersected before,
				// we fake the drag stop of the sortable, but make sure it doesn't remove
				// the helper by using cancelHelperRemoval.
				if ( sortable.isOver ) {

					sortable.isOver = 0;
					sortable.cancelHelperRemoval = true;

					// Calling sortable's mouseStop would trigger a revert,
					// so revert must be temporarily false until after mouseStop is called.
					sortable.options._revert = sortable.options.revert;
					sortable.options.revert = false;

					sortable._trigger( "out", event, sortable._uiHash( sortable ) );
					sortable._mouseStop( event, true );

					// restore sortable behaviors that were modfied
					// when the draggable entered the sortable area (#9481)
					sortable.options.revert = sortable.options._revert;
					sortable.options.helper = sortable.options._helper;

					if ( sortable.placeholder ) {
						sortable.placeholder.remove();
					}

					// Restore and recalculate the draggable's offset considering the sortable
					// may have modified them in unexpected ways. (#8809, #10669)
					ui.helper.appendTo( draggable._parent );
					draggable._refreshOffsets( event );
					ui.position = draggable._generatePosition( event, true );

					draggable._trigger( "fromSortable", event );

					// Inform draggable that the helper is no longer in a valid drop zone
					draggable.dropped = false;

					// Need to refreshPositions of all sortables just in case removing
					// from one sortable changes the location of other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					});
				}
			}
		});
	}
});

$.ui.plugin.add("draggable", "cursor", {
	start: function( event, ui, instance ) {
		var t = $( "body" ),
			o = instance.options;

		if (t.css("cursor")) {
			o._cursor = t.css("cursor");
		}
		t.css("cursor", o.cursor);
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if (o._cursor) {
			$("body").css("cursor", o._cursor);
		}
	}
});

$.ui.plugin.add("draggable", "opacity", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;
		if (t.css("opacity")) {
			o._opacity = t.css("opacity");
		}
		t.css("opacity", o.opacity);
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if (o._opacity) {
			$(ui.helper).css("opacity", o._opacity);
		}
	}
});

$.ui.plugin.add("draggable", "scroll", {
	start: function( event, ui, i ) {
		if ( !i.scrollParentNotHidden ) {
			i.scrollParentNotHidden = i.helper.scrollParent( false );
		}

		if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] && i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) {
			i.overflowOffset = i.scrollParentNotHidden.offset();
		}
	},
	drag: function( event, ui, i  ) {

		var o = i.options,
			scrolled = false,
			scrollParent = i.scrollParentNotHidden[ 0 ],
			document = i.document[ 0 ];

		if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) {
			if ( !o.axis || o.axis !== "x" ) {
				if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY < o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed;
				} else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed;
				}
			}

			if ( !o.axis || o.axis !== "y" ) {
				if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX < o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed;
				} else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed;
				}
			}

		} else {

			if (!o.axis || o.axis !== "x") {
				if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				} else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
				}
			}

			if (!o.axis || o.axis !== "y") {
				if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				} else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
				}
			}

		}

		if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
			$.ui.ddmanager.prepareOffsets(i, event);
		}

	}
});

$.ui.plugin.add("draggable", "snap", {
	start: function( event, ui, i ) {

		var o = i.options;

		i.snapElements = [];

		$(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() {
			var $t = $(this),
				$o = $t.offset();
			if (this !== i.element[0]) {
				i.snapElements.push({
					item: this,
					width: $t.outerWidth(), height: $t.outerHeight(),
					top: $o.top, left: $o.left
				});
			}
		});

	},
	drag: function( event, ui, inst ) {

		var ts, bs, ls, rs, l, r, t, b, i, first,
			o = inst.options,
			d = o.snapTolerance,
			x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for (i = inst.snapElements.length - 1; i >= 0; i--){

			l = inst.snapElements[i].left - inst.margins.left;
			r = l + inst.snapElements[i].width;
			t = inst.snapElements[i].top - inst.margins.top;
			b = t + inst.snapElements[i].height;

			if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) {
				if (inst.snapElements[i].snapping) {
					(inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
				}
				inst.snapElements[i].snapping = false;
				continue;
			}

			if (o.snapMode !== "inner") {
				ts = Math.abs(t - y2) <= d;
				bs = Math.abs(b - y1) <= d;
				ls = Math.abs(l - x2) <= d;
				rs = Math.abs(r - x1) <= d;
				if (ts) {
					ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top;
				}
				if (bs) {
					ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top;
				}
				if (ls) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left;
				}
				if (rs) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left;
				}
			}

			first = (ts || bs || ls || rs);

			if (o.snapMode !== "outer") {
				ts = Math.abs(t - y1) <= d;
				bs = Math.abs(b - y2) <= d;
				ls = Math.abs(l - x1) <= d;
				rs = Math.abs(r - x2) <= d;
				if (ts) {
					ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top;
				}
				if (bs) {
					ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top;
				}
				if (ls) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left;
				}
				if (rs) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left;
				}
			}

			if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
				(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
			}
			inst.snapElements[i].snapping = (ts || bs || ls || rs || first);

		}

	}
});

$.ui.plugin.add("draggable", "stack", {
	start: function( event, ui, instance ) {
		var min,
			o = instance.options,
			group = $.makeArray($(o.stack)).sort(function(a, b) {
				return (parseInt($(a).css("zIndex"), 10) || 0) - (parseInt($(b).css("zIndex"), 10) || 0);
			});

		if (!group.length) { return; }

		min = parseInt($(group[0]).css("zIndex"), 10) || 0;
		$(group).each(function(i) {
			$(this).css("zIndex", min + i);
		});
		this.css("zIndex", (min + group.length));
	}
});

$.ui.plugin.add("draggable", "zIndex", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;

		if (t.css("zIndex")) {
			o._zIndex = t.css("zIndex");
		}
		t.css("zIndex", o.zIndex);
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;

		if (o._zIndex) {
			$(ui.helper).css("zIndex", o._zIndex);
		}
	}
});

var draggable = $.ui.draggable;


/*!
 * jQuery UI Resizable 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/resizable/
 */


$.widget("ui.resizable", $.ui.mouse, {
	version: "1.11.4",
	widgetEventPrefix: "resize",
	options: {
		alsoResize: false,
		animate: false,
		animateDuration: "slow",
		animateEasing: "swing",
		aspectRatio: false,
		autoHide: false,
		containment: false,
		ghost: false,
		grid: false,
		handles: "e,s,se",
		helper: false,
		maxHeight: null,
		maxWidth: null,
		minHeight: 10,
		minWidth: 10,
		// See #7960
		zIndex: 90,

		// callbacks
		resize: null,
		start: null,
		stop: null
	},

	_num: function( value ) {
		return parseInt( value, 10 ) || 0;
	},

	_isNumber: function( value ) {
		return !isNaN( parseInt( value, 10 ) );
	},

	_hasScroll: function( el, a ) {

		if ( $( el ).css( "overflow" ) === "hidden") {
			return false;
		}

		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;

		if ( el[ scroll ] > 0 ) {
			return true;
		}

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[ scroll ] = 1;
		has = ( el[ scroll ] > 0 );
		el[ scroll ] = 0;
		return has;
	},

	_create: function() {

		var n, i, handle, axis, hname,
			that = this,
			o = this.options;
		this.element.addClass("ui-resizable");

		$.extend(this, {
			_aspectRatio: !!(o.aspectRatio),
			aspectRatio: o.aspectRatio,
			originalElement: this.element,
			_proportionallyResizeElements: [],
			_helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
		});

		// Wrap the element if it cannot hold child nodes
		if (this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)) {

			this.element.wrap(
				$("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({
					position: this.element.css("position"),
					width: this.element.outerWidth(),
					height: this.element.outerHeight(),
					top: this.element.css("top"),
					left: this.element.css("left")
				})
			);

			this.element = this.element.parent().data(
				"ui-resizable", this.element.resizable( "instance" )
			);

			this.elementIsWrapper = true;

			this.element.css({
				marginLeft: this.originalElement.css("marginLeft"),
				marginTop: this.originalElement.css("marginTop"),
				marginRight: this.originalElement.css("marginRight"),
				marginBottom: this.originalElement.css("marginBottom")
			});
			this.originalElement.css({
				marginLeft: 0,
				marginTop: 0,
				marginRight: 0,
				marginBottom: 0
			});
			// support: Safari
			// Prevent Safari textarea resize
			this.originalResizeStyle = this.originalElement.css("resize");
			this.originalElement.css("resize", "none");

			this._proportionallyResizeElements.push( this.originalElement.css({
				position: "static",
				zoom: 1,
				display: "block"
			}) );

			// support: IE9
			// avoid IE jump (hard set the margin)
			this.originalElement.css({ margin: this.originalElement.css("margin") });

			this._proportionallyResize();
		}

		this.handles = o.handles ||
			( !$(".ui-resizable-handle", this.element).length ?
				"e,s,se" : {
					n: ".ui-resizable-n",
					e: ".ui-resizable-e",
					s: ".ui-resizable-s",
					w: ".ui-resizable-w",
					se: ".ui-resizable-se",
					sw: ".ui-resizable-sw",
					ne: ".ui-resizable-ne",
					nw: ".ui-resizable-nw"
				} );

		this._handles = $();
		if ( this.handles.constructor === String ) {

			if ( this.handles === "all") {
				this.handles = "n,e,s,w,se,sw,ne,nw";
			}

			n = this.handles.split(",");
			this.handles = {};

			for (i = 0; i < n.length; i++) {

				handle = $.trim(n[i]);
				hname = "ui-resizable-" + handle;
				axis = $("<div class='ui-resizable-handle " + hname + "'></div>");

				axis.css({ zIndex: o.zIndex });

				// TODO : What's going on here?
				if ("se" === handle) {
					axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se");
				}

				this.handles[handle] = ".ui-resizable-" + handle;
				this.element.append(axis);
			}

		}

		this._renderAxis = function(target) {

			var i, axis, padPos, padWrapper;

			target = target || this.element;

			for (i in this.handles) {

				if (this.handles[i].constructor === String) {
					this.handles[i] = this.element.children( this.handles[ i ] ).first().show();
				} else if ( this.handles[ i ].jquery || this.handles[ i ].nodeType ) {
					this.handles[ i ] = $( this.handles[ i ] );
					this._on( this.handles[ i ], { "mousedown": that._mouseDown });
				}

				if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)) {

					axis = $(this.handles[i], this.element);

					padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();

					padPos = [ "padding",
						/ne|nw|n/.test(i) ? "Top" :
						/se|sw|s/.test(i) ? "Bottom" :
						/^e$/.test(i) ? "Right" : "Left" ].join("");

					target.css(padPos, padWrapper);

					this._proportionallyResize();
				}

				this._handles = this._handles.add( this.handles[ i ] );
			}
		};

		// TODO: make renderAxis a prototype function
		this._renderAxis(this.element);

		this._handles = this._handles.add( this.element.find( ".ui-resizable-handle" ) );
		this._handles.disableSelection();

		this._handles.mouseover(function() {
			if (!that.resizing) {
				if (this.className) {
					axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
				}
				that.axis = axis && axis[1] ? axis[1] : "se";
			}
		});

		if (o.autoHide) {
			this._handles.hide();
			$(this.element)
				.addClass("ui-resizable-autohide")
				.mouseenter(function() {
					if (o.disabled) {
						return;
					}
					$(this).removeClass("ui-resizable-autohide");
					that._handles.show();
				})
				.mouseleave(function() {
					if (o.disabled) {
						return;
					}
					if (!that.resizing) {
						$(this).addClass("ui-resizable-autohide");
						that._handles.hide();
					}
				});
		}

		this._mouseInit();
	},

	_destroy: function() {

		this._mouseDestroy();

		var wrapper,
			_destroy = function(exp) {
				$(exp)
					.removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
					.removeData("resizable")
					.removeData("ui-resizable")
					.unbind(".resizable")
					.find(".ui-resizable-handle")
						.remove();
			};

		// TODO: Unwrap at same DOM position
		if (this.elementIsWrapper) {
			_destroy(this.element);
			wrapper = this.element;
			this.originalElement.css({
				position: wrapper.css("position"),
				width: wrapper.outerWidth(),
				height: wrapper.outerHeight(),
				top: wrapper.css("top"),
				left: wrapper.css("left")
			}).insertAfter( wrapper );
			wrapper.remove();
		}

		this.originalElement.css("resize", this.originalResizeStyle);
		_destroy(this.originalElement);

		return this;
	},

	_mouseCapture: function(event) {
		var i, handle,
			capture = false;

		for (i in this.handles) {
			handle = $(this.handles[i])[0];
			if (handle === event.target || $.contains(handle, event.target)) {
				capture = true;
			}
		}

		return !this.options.disabled && capture;
	},

	_mouseStart: function(event) {

		var curleft, curtop, cursor,
			o = this.options,
			el = this.element;

		this.resizing = true;

		this._renderProxy();

		curleft = this._num(this.helper.css("left"));
		curtop = this._num(this.helper.css("top"));

		if (o.containment) {
			curleft += $(o.containment).scrollLeft() || 0;
			curtop += $(o.containment).scrollTop() || 0;
		}

		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };

		this.size = this._helper ? {
				width: this.helper.width(),
				height: this.helper.height()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.originalSize = this._helper ? {
				width: el.outerWidth(),
				height: el.outerHeight()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.sizeDiff = {
			width: el.outerWidth() - el.width(),
			height: el.outerHeight() - el.height()
		};

		this.originalPosition = { left: curleft, top: curtop };
		this.originalMousePosition = { left: event.pageX, top: event.pageY };

		this.aspectRatio = (typeof o.aspectRatio === "number") ?
			o.aspectRatio :
			((this.originalSize.width / this.originalSize.height) || 1);

		cursor = $(".ui-resizable-" + this.axis).css("cursor");
		$("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor);

		el.addClass("ui-resizable-resizing");
		this._propagate("start", event);
		return true;
	},

	_mouseDrag: function(event) {

		var data, props,
			smp = this.originalMousePosition,
			a = this.axis,
			dx = (event.pageX - smp.left) || 0,
			dy = (event.pageY - smp.top) || 0,
			trigger = this._change[a];

		this._updatePrevProperties();

		if (!trigger) {
			return false;
		}

		data = trigger.apply(this, [ event, dx, dy ]);

		this._updateVirtualBoundaries(event.shiftKey);
		if (this._aspectRatio || event.shiftKey) {
			data = this._updateRatio(data, event);
		}

		data = this._respectSize(data, event);

		this._updateCache(data);

		this._propagate("resize", event);

		props = this._applyChanges();

		if ( !this._helper && this._proportionallyResizeElements.length ) {
			this._proportionallyResize();
		}

		if ( !$.isEmptyObject( props ) ) {
			this._updatePrevProperties();
			this._trigger( "resize", event, this.ui() );
			this._applyChanges();
		}

		return false;
	},

	_mouseStop: function(event) {

		this.resizing = false;
		var pr, ista, soffseth, soffsetw, s, left, top,
			o = this.options, that = this;

		if (this._helper) {

			pr = this._proportionallyResizeElements;
			ista = pr.length && (/textarea/i).test(pr[0].nodeName);
			soffseth = ista && this._hasScroll(pr[0], "left") ? 0 : that.sizeDiff.height;
			soffsetw = ista ? 0 : that.sizeDiff.width;

			s = {
				width: (that.helper.width()  - soffsetw),
				height: (that.helper.height() - soffseth)
			};
			left = (parseInt(that.element.css("left"), 10) +
				(that.position.left - that.originalPosition.left)) || null;
			top = (parseInt(that.element.css("top"), 10) +
				(that.position.top - that.originalPosition.top)) || null;

			if (!o.animate) {
				this.element.css($.extend(s, { top: top, left: left }));
			}

			that.helper.height(that.size.height);
			that.helper.width(that.size.width);

			if (this._helper && !o.animate) {
				this._proportionallyResize();
			}
		}

		$("body").css("cursor", "auto");

		this.element.removeClass("ui-resizable-resizing");

		this._propagate("stop", event);

		if (this._helper) {
			this.helper.remove();
		}

		return false;

	},

	_updatePrevProperties: function() {
		this.prevPosition = {
			top: this.position.top,
			left: this.position.left
		};
		this.prevSize = {
			width: this.size.width,
			height: this.size.height
		};
	},

	_applyChanges: function() {
		var props = {};

		if ( this.position.top !== this.prevPosition.top ) {
			props.top = this.position.top + "px";
		}
		if ( this.position.left !== this.prevPosition.left ) {
			props.left = this.position.left + "px";
		}
		if ( this.size.width !== this.prevSize.width ) {
			props.width = this.size.width + "px";
		}
		if ( this.size.height !== this.prevSize.height ) {
			props.height = this.size.height + "px";
		}

		this.helper.css( props );

		return props;
	},

	_updateVirtualBoundaries: function(forceAspectRatio) {
		var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
			o = this.options;

		b = {
			minWidth: this._isNumber(o.minWidth) ? o.minWidth : 0,
			maxWidth: this._isNumber(o.maxWidth) ? o.maxWidth : Infinity,
			minHeight: this._isNumber(o.minHeight) ? o.minHeight : 0,
			maxHeight: this._isNumber(o.maxHeight) ? o.maxHeight : Infinity
		};

		if (this._aspectRatio || forceAspectRatio) {
			pMinWidth = b.minHeight * this.aspectRatio;
			pMinHeight = b.minWidth / this.aspectRatio;
			pMaxWidth = b.maxHeight * this.aspectRatio;
			pMaxHeight = b.maxWidth / this.aspectRatio;

			if (pMinWidth > b.minWidth) {
				b.minWidth = pMinWidth;
			}
			if (pMinHeight > b.minHeight) {
				b.minHeight = pMinHeight;
			}
			if (pMaxWidth < b.maxWidth) {
				b.maxWidth = pMaxWidth;
			}
			if (pMaxHeight < b.maxHeight) {
				b.maxHeight = pMaxHeight;
			}
		}
		this._vBoundaries = b;
	},

	_updateCache: function(data) {
		this.offset = this.helper.offset();
		if (this._isNumber(data.left)) {
			this.position.left = data.left;
		}
		if (this._isNumber(data.top)) {
			this.position.top = data.top;
		}
		if (this._isNumber(data.height)) {
			this.size.height = data.height;
		}
		if (this._isNumber(data.width)) {
			this.size.width = data.width;
		}
	},

	_updateRatio: function( data ) {

		var cpos = this.position,
			csize = this.size,
			a = this.axis;

		if (this._isNumber(data.height)) {
			data.width = (data.height * this.aspectRatio);
		} else if (this._isNumber(data.width)) {
			data.height = (data.width / this.aspectRatio);
		}

		if (a === "sw") {
			data.left = cpos.left + (csize.width - data.width);
			data.top = null;
		}
		if (a === "nw") {
			data.top = cpos.top + (csize.height - data.height);
			data.left = cpos.left + (csize.width - data.width);
		}

		return data;
	},

	_respectSize: function( data ) {

		var o = this._vBoundaries,
			a = this.axis,
			ismaxw = this._isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width),
			ismaxh = this._isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
			isminw = this._isNumber(data.width) && o.minWidth && (o.minWidth > data.width),
			isminh = this._isNumber(data.height) && o.minHeight && (o.minHeight > data.height),
			dw = this.originalPosition.left + this.originalSize.width,
			dh = this.position.top + this.size.height,
			cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);
		if (isminw) {
			data.width = o.minWidth;
		}
		if (isminh) {
			data.height = o.minHeight;
		}
		if (ismaxw) {
			data.width = o.maxWidth;
		}
		if (ismaxh) {
			data.height = o.maxHeight;
		}

		if (isminw && cw) {
			data.left = dw - o.minWidth;
		}
		if (ismaxw && cw) {
			data.left = dw - o.maxWidth;
		}
		if (isminh && ch) {
			data.top = dh - o.minHeight;
		}
		if (ismaxh && ch) {
			data.top = dh - o.maxHeight;
		}

		// Fixing jump error on top/left - bug #2330
		if (!data.width && !data.height && !data.left && data.top) {
			data.top = null;
		} else if (!data.width && !data.height && !data.top && data.left) {
			data.left = null;
		}

		return data;
	},

	_getPaddingPlusBorderDimensions: function( element ) {
		var i = 0,
			widths = [],
			borders = [
				element.css( "borderTopWidth" ),
				element.css( "borderRightWidth" ),
				element.css( "borderBottomWidth" ),
				element.css( "borderLeftWidth" )
			],
			paddings = [
				element.css( "paddingTop" ),
				element.css( "paddingRight" ),
				element.css( "paddingBottom" ),
				element.css( "paddingLeft" )
			];

		for ( ; i < 4; i++ ) {
			widths[ i ] = ( parseInt( borders[ i ], 10 ) || 0 );
			widths[ i ] += ( parseInt( paddings[ i ], 10 ) || 0 );
		}

		return {
			height: widths[ 0 ] + widths[ 2 ],
			width: widths[ 1 ] + widths[ 3 ]
		};
	},

	_proportionallyResize: function() {

		if (!this._proportionallyResizeElements.length) {
			return;
		}

		var prel,
			i = 0,
			element = this.helper || this.element;

		for ( ; i < this._proportionallyResizeElements.length; i++) {

			prel = this._proportionallyResizeElements[i];

			// TODO: Seems like a bug to cache this.outerDimensions
			// considering that we are in a loop.
			if (!this.outerDimensions) {
				this.outerDimensions = this._getPaddingPlusBorderDimensions( prel );
			}

			prel.css({
				height: (element.height() - this.outerDimensions.height) || 0,
				width: (element.width() - this.outerDimensions.width) || 0
			});

		}

	},

	_renderProxy: function() {

		var el = this.element, o = this.options;
		this.elementOffset = el.offset();

		if (this._helper) {

			this.helper = this.helper || $("<div style='overflow:hidden;'></div>");

			this.helper.addClass(this._helper).css({
				width: this.element.outerWidth() - 1,
				height: this.element.outerHeight() - 1,
				position: "absolute",
				left: this.elementOffset.left + "px",
				top: this.elementOffset.top + "px",
				zIndex: ++o.zIndex //TODO: Don't modify option
			});

			this.helper
				.appendTo("body")
				.disableSelection();

		} else {
			this.helper = this.element;
		}

	},

	_change: {
		e: function(event, dx) {
			return { width: this.originalSize.width + dx };
		},
		w: function(event, dx) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { left: sp.left + dx, width: cs.width - dx };
		},
		n: function(event, dx, dy) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { top: sp.top + dy, height: cs.height - dy };
		},
		s: function(event, dx, dy) {
			return { height: this.originalSize.height + dy };
		},
		se: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments),
				this._change.e.apply(this, [ event, dx, dy ]));
		},
		sw: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments),
				this._change.w.apply(this, [ event, dx, dy ]));
		},
		ne: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments),
				this._change.e.apply(this, [ event, dx, dy ]));
		},
		nw: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments),
				this._change.w.apply(this, [ event, dx, dy ]));
		}
	},

	_propagate: function(n, event) {
		$.ui.plugin.call(this, n, [ event, this.ui() ]);
		(n !== "resize" && this._trigger(n, event, this.ui()));
	},

	plugins: {},

	ui: function() {
		return {
			originalElement: this.originalElement,
			element: this.element,
			helper: this.helper,
			position: this.position,
			size: this.size,
			originalSize: this.originalSize,
			originalPosition: this.originalPosition
		};
	}

});

/*
 * Resizable Extensions
 */

$.ui.plugin.add("resizable", "animate", {

	stop: function( event ) {
		var that = $(this).resizable( "instance" ),
			o = that.options,
			pr = that._proportionallyResizeElements,
			ista = pr.length && (/textarea/i).test(pr[0].nodeName),
			soffseth = ista && that._hasScroll(pr[0], "left") ? 0 : that.sizeDiff.height,
			soffsetw = ista ? 0 : that.sizeDiff.width,
			style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) },
			left = (parseInt(that.element.css("left"), 10) +
				(that.position.left - that.originalPosition.left)) || null,
			top = (parseInt(that.element.css("top"), 10) +
				(that.position.top - that.originalPosition.top)) || null;

		that.element.animate(
			$.extend(style, top && left ? { top: top, left: left } : {}), {
				duration: o.animateDuration,
				easing: o.animateEasing,
				step: function() {

					var data = {
						width: parseInt(that.element.css("width"), 10),
						height: parseInt(that.element.css("height"), 10),
						top: parseInt(that.element.css("top"), 10),
						left: parseInt(that.element.css("left"), 10)
					};

					if (pr && pr.length) {
						$(pr[0]).css({ width: data.width, height: data.height });
					}

					// propagating resize, and updating values for each animation step
					that._updateCache(data);
					that._propagate("resize", event);

				}
			}
		);
	}

});

$.ui.plugin.add( "resizable", "containment", {

	start: function() {
		var element, p, co, ch, cw, width, height,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			el = that.element,
			oc = o.containment,
			ce = ( oc instanceof $ ) ? oc.get( 0 ) : ( /parent/.test( oc ) ) ? el.parent().get( 0 ) : oc;

		if ( !ce ) {
			return;
		}

		that.containerElement = $( ce );

		if ( /document/.test( oc ) || oc === document ) {
			that.containerOffset = {
				left: 0,
				top: 0
			};
			that.containerPosition = {
				left: 0,
				top: 0
			};

			that.parentData = {
				element: $( document ),
				left: 0,
				top: 0,
				width: $( document ).width(),
				height: $( document ).height() || document.body.parentNode.scrollHeight
			};
		} else {
			element = $( ce );
			p = [];
			$([ "Top", "Right", "Left", "Bottom" ]).each(function( i, name ) {
				p[ i ] = that._num( element.css( "padding" + name ) );
			});

			that.containerOffset = element.offset();
			that.containerPosition = element.position();
			that.containerSize = {
				height: ( element.innerHeight() - p[ 3 ] ),
				width: ( element.innerWidth() - p[ 1 ] )
			};

			co = that.containerOffset;
			ch = that.containerSize.height;
			cw = that.containerSize.width;
			width = ( that._hasScroll ( ce, "left" ) ? ce.scrollWidth : cw );
			height = ( that._hasScroll ( ce ) ? ce.scrollHeight : ch ) ;

			that.parentData = {
				element: ce,
				left: co.left,
				top: co.top,
				width: width,
				height: height
			};
		}
	},

	resize: function( event ) {
		var woset, hoset, isParent, isOffsetRelative,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cp = that.position,
			pRatio = that._aspectRatio || event.shiftKey,
			cop = {
				top: 0,
				left: 0
			},
			ce = that.containerElement,
			continueResize = true;

		if ( ce[ 0 ] !== document && ( /static/ ).test( ce.css( "position" ) ) ) {
			cop = co;
		}

		if ( cp.left < ( that._helper ? co.left : 0 ) ) {
			that.size.width = that.size.width +
				( that._helper ?
					( that.position.left - co.left ) :
					( that.position.left - cop.left ) );

			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
			that.position.left = o.helper ? co.left : 0;
		}

		if ( cp.top < ( that._helper ? co.top : 0 ) ) {
			that.size.height = that.size.height +
				( that._helper ?
					( that.position.top - co.top ) :
					that.position.top );

			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
			that.position.top = that._helper ? co.top : 0;
		}

		isParent = that.containerElement.get( 0 ) === that.element.parent().get( 0 );
		isOffsetRelative = /relative|absolute/.test( that.containerElement.css( "position" ) );

		if ( isParent && isOffsetRelative ) {
			that.offset.left = that.parentData.left + that.position.left;
			that.offset.top = that.parentData.top + that.position.top;
		} else {
			that.offset.left = that.element.offset().left;
			that.offset.top = that.element.offset().top;
		}

		woset = Math.abs( that.sizeDiff.width +
			(that._helper ?
				that.offset.left - cop.left :
				(that.offset.left - co.left)) );

		hoset = Math.abs( that.sizeDiff.height +
			(that._helper ?
				that.offset.top - cop.top :
				(that.offset.top - co.top)) );

		if ( woset + that.size.width >= that.parentData.width ) {
			that.size.width = that.parentData.width - woset;
			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
		}

		if ( hoset + that.size.height >= that.parentData.height ) {
			that.size.height = that.parentData.height - hoset;
			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
		}

		if ( !continueResize ) {
			that.position.left = that.prevPosition.left;
			that.position.top = that.prevPosition.top;
			that.size.width = that.prevSize.width;
			that.size.height = that.prevSize.height;
		}
	},

	stop: function() {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cop = that.containerPosition,
			ce = that.containerElement,
			helper = $( that.helper ),
			ho = helper.offset(),
			w = helper.outerWidth() - that.sizeDiff.width,
			h = helper.outerHeight() - that.sizeDiff.height;

		if ( that._helper && !o.animate && ( /relative/ ).test( ce.css( "position" ) ) ) {
			$( this ).css({
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			});
		}

		if ( that._helper && !o.animate && ( /static/ ).test( ce.css( "position" ) ) ) {
			$( this ).css({
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			});
		}
	}
});

$.ui.plugin.add("resizable", "alsoResize", {

	start: function() {
		var that = $(this).resizable( "instance" ),
			o = that.options;

		$(o.alsoResize).each(function() {
			var el = $(this);
			el.data("ui-resizable-alsoresize", {
				width: parseInt(el.width(), 10), height: parseInt(el.height(), 10),
				left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10)
			});
		});
	},

	resize: function(event, ui) {
		var that = $(this).resizable( "instance" ),
			o = that.options,
			os = that.originalSize,
			op = that.originalPosition,
			delta = {
				height: (that.size.height - os.height) || 0,
				width: (that.size.width - os.width) || 0,
				top: (that.position.top - op.top) || 0,
				left: (that.position.left - op.left) || 0
			};

			$(o.alsoResize).each(function() {
				var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {},
					css = el.parents(ui.originalElement[0]).length ?
							[ "width", "height" ] :
							[ "width", "height", "top", "left" ];

				$.each(css, function(i, prop) {
					var sum = (start[prop] || 0) + (delta[prop] || 0);
					if (sum && sum >= 0) {
						style[prop] = sum || null;
					}
				});

				el.css(style);
			});
	},

	stop: function() {
		$(this).removeData("resizable-alsoresize");
	}
});

$.ui.plugin.add("resizable", "ghost", {

	start: function() {

		var that = $(this).resizable( "instance" ), o = that.options, cs = that.size;

		that.ghost = that.originalElement.clone();
		that.ghost
			.css({
				opacity: 0.25,
				display: "block",
				position: "relative",
				height: cs.height,
				width: cs.width,
				margin: 0,
				left: 0,
				top: 0
			})
			.addClass("ui-resizable-ghost")
			.addClass(typeof o.ghost === "string" ? o.ghost : "");

		that.ghost.appendTo(that.helper);

	},

	resize: function() {
		var that = $(this).resizable( "instance" );
		if (that.ghost) {
			that.ghost.css({
				position: "relative",
				height: that.size.height,
				width: that.size.width
			});
		}
	},

	stop: function() {
		var that = $(this).resizable( "instance" );
		if (that.ghost && that.helper) {
			that.helper.get(0).removeChild(that.ghost.get(0));
		}
	}

});

$.ui.plugin.add("resizable", "grid", {

	resize: function() {
		var outerDimensions,
			that = $(this).resizable( "instance" ),
			o = that.options,
			cs = that.size,
			os = that.originalSize,
			op = that.originalPosition,
			a = that.axis,
			grid = typeof o.grid === "number" ? [ o.grid, o.grid ] : o.grid,
			gridX = (grid[0] || 1),
			gridY = (grid[1] || 1),
			ox = Math.round((cs.width - os.width) / gridX) * gridX,
			oy = Math.round((cs.height - os.height) / gridY) * gridY,
			newWidth = os.width + ox,
			newHeight = os.height + oy,
			isMaxWidth = o.maxWidth && (o.maxWidth < newWidth),
			isMaxHeight = o.maxHeight && (o.maxHeight < newHeight),
			isMinWidth = o.minWidth && (o.minWidth > newWidth),
			isMinHeight = o.minHeight && (o.minHeight > newHeight);

		o.grid = grid;

		if (isMinWidth) {
			newWidth += gridX;
		}
		if (isMinHeight) {
			newHeight += gridY;
		}
		if (isMaxWidth) {
			newWidth -= gridX;
		}
		if (isMaxHeight) {
			newHeight -= gridY;
		}

		if (/^(se|s|e)$/.test(a)) {
			that.size.width = newWidth;
			that.size.height = newHeight;
		} else if (/^(ne)$/.test(a)) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.top = op.top - oy;
		} else if (/^(sw)$/.test(a)) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.left = op.left - ox;
		} else {
			if ( newHeight - gridY <= 0 || newWidth - gridX <= 0) {
				outerDimensions = that._getPaddingPlusBorderDimensions( this );
			}

			if ( newHeight - gridY > 0 ) {
				that.size.height = newHeight;
				that.position.top = op.top - oy;
			} else {
				newHeight = gridY - outerDimensions.height;
				that.size.height = newHeight;
				that.position.top = op.top + os.height - newHeight;
			}
			if ( newWidth - gridX > 0 ) {
				that.size.width = newWidth;
				that.position.left = op.left - ox;
			} else {
				newWidth = gridX - outerDimensions.width;
				that.size.width = newWidth;
				that.position.left = op.left + os.width - newWidth;
			}
		}
	}

});

var resizable = $.ui.resizable;


/*!
 * jQuery UI Dialog 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/dialog/
 */


var dialog = $.widget( "ui.dialog", {
	version: "1.11.4",
	options: {
		appendTo: "body",
		autoOpen: true,
		buttons: [],
		closeOnEscape: true,
		closeText: "Close",
		dialogClass: "",
		draggable: true,
		hide: null,
		height: "auto",
		maxHeight: null,
		maxWidth: null,
		minHeight: 150,
		minWidth: 150,
		modal: false,
		position: {
			my: "center",
			at: "center",
			of: window,
			collision: "fit",
			// Ensure the titlebar is always visible
			using: function( pos ) {
				var topOffset = $( this ).css( pos ).offset().top;
				if ( topOffset < 0 ) {
					$( this ).css( "top", pos.top - topOffset );
				}
			}
		},
		resizable: true,
		show: null,
		title: null,
		width: 300,

		// callbacks
		beforeClose: null,
		close: null,
		drag: null,
		dragStart: null,
		dragStop: null,
		focus: null,
		open: null,
		resize: null,
		resizeStart: null,
		resizeStop: null
	},

	sizeRelatedOptions: {
		buttons: true,
		height: true,
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true,
		width: true
	},

	resizableRelatedOptions: {
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true
	},

	_create: function() {
		this.originalCss = {
			display: this.element[ 0 ].style.display,
			width: this.element[ 0 ].style.width,
			minHeight: this.element[ 0 ].style.minHeight,
			maxHeight: this.element[ 0 ].style.maxHeight,
			height: this.element[ 0 ].style.height
		};
		this.originalPosition = {
			parent: this.element.parent(),
			index: this.element.parent().children().index( this.element )
		};
		this.originalTitle = this.element.attr( "title" );
		this.options.title = this.options.title || this.originalTitle;

		this._createWrapper();

		this.element
			.show()
			.removeAttr( "title" )
			.addClass( "ui-dialog-content ui-widget-content" )
			.appendTo( this.uiDialog );

		this._createTitlebar();
		this._createButtonPane();

		if ( this.options.draggable && $.fn.draggable ) {
			this._makeDraggable();
		}
		if ( this.options.resizable && $.fn.resizable ) {
			this._makeResizable();
		}

		this._isOpen = false;

		this._trackFocus();
	},

	_init: function() {
		if ( this.options.autoOpen ) {
			this.open();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;
		if ( element && (element.jquery || element.nodeType) ) {
			return $( element );
		}
		return this.document.find( element || "body" ).eq( 0 );
	},

	_destroy: function() {
		var next,
			originalPosition = this.originalPosition;

		this._untrackInstance();
		this._destroyOverlay();

		this.element
			.removeUniqueId()
			.removeClass( "ui-dialog-content ui-widget-content" )
			.css( this.originalCss )
			// Without detaching first, the following becomes really slow
			.detach();

		this.uiDialog.stop( true, true ).remove();

		if ( this.originalTitle ) {
			this.element.attr( "title", this.originalTitle );
		}

		next = originalPosition.parent.children().eq( originalPosition.index );
		// Don't try to place the dialog next to itself (#8613)
		if ( next.length && next[ 0 ] !== this.element[ 0 ] ) {
			next.before( this.element );
		} else {
			originalPosition.parent.append( this.element );
		}
	},

	widget: function() {
		return this.uiDialog;
	},

	disable: $.noop,
	enable: $.noop,

	close: function( event ) {
		var activeElement,
			that = this;

		if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) {
			return;
		}

		this._isOpen = false;
		this._focusedElement = null;
		this._destroyOverlay();
		this._untrackInstance();

		if ( !this.opener.filter( ":focusable" ).focus().length ) {

			// support: IE9
			// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
			try {
				activeElement = this.document[ 0 ].activeElement;

				// Support: IE9, IE10
				// If the <body> is blurred, IE will switch windows, see #4520
				if ( activeElement && activeElement.nodeName.toLowerCase() !== "body" ) {

					// Hiding a focused element doesn't trigger blur in WebKit
					// so in case we have nothing to focus on, explicitly blur the active element
					// https://bugs.webkit.org/show_bug.cgi?id=47182
					$( activeElement ).blur();
				}
			} catch ( error ) {}
		}

		this._hide( this.uiDialog, this.options.hide, function() {
			that._trigger( "close", event );
		});
	},

	isOpen: function() {
		return this._isOpen;
	},

	moveToTop: function() {
		this._moveToTop();
	},

	_moveToTop: function( event, silent ) {
		var moved = false,
			zIndices = this.uiDialog.siblings( ".ui-front:visible" ).map(function() {
				return +$( this ).css( "z-index" );
			}).get(),
			zIndexMax = Math.max.apply( null, zIndices );

		if ( zIndexMax >= +this.uiDialog.css( "z-index" ) ) {
			this.uiDialog.css( "z-index", zIndexMax + 1 );
			moved = true;
		}

		if ( moved && !silent ) {
			this._trigger( "focus", event );
		}
		return moved;
	},

	open: function() {
		var that = this;
		if ( this._isOpen ) {
			if ( this._moveToTop() ) {
				this._focusTabbable();
			}
			return;
		}

		this._isOpen = true;
		this.opener = $( this.document[ 0 ].activeElement );

		this._size();
		this._position();
		this._createOverlay();
		this._moveToTop( null, true );

		// Ensure the overlay is moved to the top with the dialog, but only when
		// opening. The overlay shouldn't move after the dialog is open so that
		// modeless dialogs opened after the modal dialog stack properly.
		if ( this.overlay ) {
			this.overlay.css( "z-index", this.uiDialog.css( "z-index" ) - 1 );
		}

		this._show( this.uiDialog, this.options.show, function() {
			that._focusTabbable();
			that._trigger( "focus" );
		});

		// Track the dialog immediately upon openening in case a focus event
		// somehow occurs outside of the dialog before an element inside the
		// dialog is focused (#10152)
		this._makeFocusTarget();

		this._trigger( "open" );
	},

	_focusTabbable: function() {
		// Set focus to the first match:
		// 1. An element that was focused previously
		// 2. First element inside the dialog matching [autofocus]
		// 3. Tabbable element inside the content element
		// 4. Tabbable element inside the buttonpane
		// 5. The close button
		// 6. The dialog itself
		var hasFocus = this._focusedElement;
		if ( !hasFocus ) {
			hasFocus = this.element.find( "[autofocus]" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.element.find( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialogButtonPane.find( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialogTitlebarClose.filter( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialog;
		}
		hasFocus.eq( 0 ).focus();
	},

	_keepFocus: function( event ) {
		function checkFocus() {
			var activeElement = this.document[0].activeElement,
				isActive = this.uiDialog[0] === activeElement ||
					$.contains( this.uiDialog[0], activeElement );
			if ( !isActive ) {
				this._focusTabbable();
			}
		}
		event.preventDefault();
		checkFocus.call( this );
		// support: IE
		// IE <= 8 doesn't prevent moving focus even with event.preventDefault()
		// so we check again later
		this._delay( checkFocus );
	},

	_createWrapper: function() {
		this.uiDialog = $("<div>")
			.addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " +
				this.options.dialogClass )
			.hide()
			.attr({
				// Setting tabIndex makes the div focusable
				tabIndex: -1,
				role: "dialog"
			})
			.appendTo( this._appendTo() );

		this._on( this.uiDialog, {
			keydown: function( event ) {
				if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
						event.keyCode === $.ui.keyCode.ESCAPE ) {
					event.preventDefault();
					this.close( event );
					return;
				}

				// prevent tabbing out of dialogs
				if ( event.keyCode !== $.ui.keyCode.TAB || event.isDefaultPrevented() ) {
					return;
				}
				var tabbables = this.uiDialog.find( ":tabbable" ),
					first = tabbables.filter( ":first" ),
					last = tabbables.filter( ":last" );

				if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) {
					this._delay(function() {
						first.focus();
					});
					event.preventDefault();
				} else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) {
					this._delay(function() {
						last.focus();
					});
					event.preventDefault();
				}
			},
			mousedown: function( event ) {
				if ( this._moveToTop( event ) ) {
					this._focusTabbable();
				}
			}
		});

		// We assume that any existing aria-describedby attribute means
		// that the dialog content is marked up properly
		// otherwise we brute force the content as the description
		if ( !this.element.find( "[aria-describedby]" ).length ) {
			this.uiDialog.attr({
				"aria-describedby": this.element.uniqueId().attr( "id" )
			});
		}
	},

	_createTitlebar: function() {
		var uiDialogTitle;

		this.uiDialogTitlebar = $( "<div>" )
			.addClass( "ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix" )
			.prependTo( this.uiDialog );
		this._on( this.uiDialogTitlebar, {
			mousedown: function( event ) {
				// Don't prevent click on close button (#8838)
				// Focusing a dialog that is partially scrolled out of view
				// causes the browser to scroll it into view, preventing the click event
				if ( !$( event.target ).closest( ".ui-dialog-titlebar-close" ) ) {
					// Dialog isn't getting focus when dragging (#8063)
					this.uiDialog.focus();
				}
			}
		});

		// support: IE
		// Use type="button" to prevent enter keypresses in textboxes from closing the
		// dialog in IE (#9312)
		this.uiDialogTitlebarClose = $( "<button type='button'></button>" )
			.button({
				label: this.options.closeText,
				icons: {
					primary: "ui-icon-closethick"
				},
				text: false
			})
			.addClass( "ui-dialog-titlebar-close" )
			.appendTo( this.uiDialogTitlebar );
		this._on( this.uiDialogTitlebarClose, {
			click: function( event ) {
				event.preventDefault();
				this.close( event );
			}
		});

		uiDialogTitle = $( "<span>" )
			.uniqueId()
			.addClass( "ui-dialog-title" )
			.prependTo( this.uiDialogTitlebar );
		this._title( uiDialogTitle );

		this.uiDialog.attr({
			"aria-labelledby": uiDialogTitle.attr( "id" )
		});
	},

	_title: function( title ) {
		if ( !this.options.title ) {
			title.html( "&#160;" );
		}
		title.text( this.options.title );
	},

	_createButtonPane: function() {
		this.uiDialogButtonPane = $( "<div>" )
			.addClass( "ui-dialog-buttonpane ui-widget-content ui-helper-clearfix" );

		this.uiButtonSet = $( "<div>" )
			.addClass( "ui-dialog-buttonset" )
			.appendTo( this.uiDialogButtonPane );

		this._createButtons();
	},

	_createButtons: function() {
		var that = this,
			buttons = this.options.buttons;

		// if we already have a button pane, remove it
		this.uiDialogButtonPane.remove();
		this.uiButtonSet.empty();

		if ( $.isEmptyObject( buttons ) || ($.isArray( buttons ) && !buttons.length) ) {
			this.uiDialog.removeClass( "ui-dialog-buttons" );
			return;
		}

		$.each( buttons, function( name, props ) {
			var click, buttonOptions;
			props = $.isFunction( props ) ?
				{ click: props, text: name } :
				props;
			// Default to a non-submitting button
			props = $.extend( { type: "button" }, props );
			// Change the context for the click callback to be the main element
			click = props.click;
			props.click = function() {
				click.apply( that.element[ 0 ], arguments );
			};
			buttonOptions = {
				icons: props.icons,
				text: props.showText
			};
			delete props.icons;
			delete props.showText;
			$( "<button></button>", props )
				.button( buttonOptions )
				.appendTo( that.uiButtonSet );
		});
		this.uiDialog.addClass( "ui-dialog-buttons" );
		this.uiDialogButtonPane.appendTo( this.uiDialog );
	},

	_makeDraggable: function() {
		var that = this,
			options = this.options;

		function filteredUi( ui ) {
			return {
				position: ui.position,
				offset: ui.offset
			};
		}

		this.uiDialog.draggable({
			cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
			handle: ".ui-dialog-titlebar",
			containment: "document",
			start: function( event, ui ) {
				$( this ).addClass( "ui-dialog-dragging" );
				that._blockFrames();
				that._trigger( "dragStart", event, filteredUi( ui ) );
			},
			drag: function( event, ui ) {
				that._trigger( "drag", event, filteredUi( ui ) );
			},
			stop: function( event, ui ) {
				var left = ui.offset.left - that.document.scrollLeft(),
					top = ui.offset.top - that.document.scrollTop();

				options.position = {
					my: "left top",
					at: "left" + (left >= 0 ? "+" : "") + left + " " +
						"top" + (top >= 0 ? "+" : "") + top,
					of: that.window
				};
				$( this ).removeClass( "ui-dialog-dragging" );
				that._unblockFrames();
				that._trigger( "dragStop", event, filteredUi( ui ) );
			}
		});
	},

	_makeResizable: function() {
		var that = this,
			options = this.options,
			handles = options.resizable,
			// .ui-resizable has position: relative defined in the stylesheet
			// but dialogs have to use absolute or fixed positioning
			position = this.uiDialog.css("position"),
			resizeHandles = typeof handles === "string" ?
				handles	:
				"n,e,s,w,se,sw,ne,nw";

		function filteredUi( ui ) {
			return {
				originalPosition: ui.originalPosition,
				originalSize: ui.originalSize,
				position: ui.position,
				size: ui.size
			};
		}

		this.uiDialog.resizable({
			cancel: ".ui-dialog-content",
			containment: "document",
			alsoResize: this.element,
			maxWidth: options.maxWidth,
			maxHeight: options.maxHeight,
			minWidth: options.minWidth,
			minHeight: this._minHeight(),
			handles: resizeHandles,
			start: function( event, ui ) {
				$( this ).addClass( "ui-dialog-resizing" );
				that._blockFrames();
				that._trigger( "resizeStart", event, filteredUi( ui ) );
			},
			resize: function( event, ui ) {
				that._trigger( "resize", event, filteredUi( ui ) );
			},
			stop: function( event, ui ) {
				var offset = that.uiDialog.offset(),
					left = offset.left - that.document.scrollLeft(),
					top = offset.top - that.document.scrollTop();

				options.height = that.uiDialog.height();
				options.width = that.uiDialog.width();
				options.position = {
					my: "left top",
					at: "left" + (left >= 0 ? "+" : "") + left + " " +
						"top" + (top >= 0 ? "+" : "") + top,
					of: that.window
				};
				$( this ).removeClass( "ui-dialog-resizing" );
				that._unblockFrames();
				that._trigger( "resizeStop", event, filteredUi( ui ) );
			}
		})
		.css( "position", position );
	},

	_trackFocus: function() {
		this._on( this.widget(), {
			focusin: function( event ) {
				this._makeFocusTarget();
				this._focusedElement = $( event.target );
			}
		});
	},

	_makeFocusTarget: function() {
		this._untrackInstance();
		this._trackingInstances().unshift( this );
	},

	_untrackInstance: function() {
		var instances = this._trackingInstances(),
			exists = $.inArray( this, instances );
		if ( exists !== -1 ) {
			instances.splice( exists, 1 );
		}
	},

	_trackingInstances: function() {
		var instances = this.document.data( "ui-dialog-instances" );
		if ( !instances ) {
			instances = [];
			this.document.data( "ui-dialog-instances", instances );
		}
		return instances;
	},

	_minHeight: function() {
		var options = this.options;

		return options.height === "auto" ?
			options.minHeight :
			Math.min( options.minHeight, options.height );
	},

	_position: function() {
		// Need to show the dialog to get the actual offset in the position plugin
		var isVisible = this.uiDialog.is( ":visible" );
		if ( !isVisible ) {
			this.uiDialog.show();
		}
		this.uiDialog.position( this.options.position );
		if ( !isVisible ) {
			this.uiDialog.hide();
		}
	},

	_setOptions: function( options ) {
		var that = this,
			resize = false,
			resizableOptions = {};

		$.each( options, function( key, value ) {
			that._setOption( key, value );

			if ( key in that.sizeRelatedOptions ) {
				resize = true;
			}
			if ( key in that.resizableRelatedOptions ) {
				resizableOptions[ key ] = value;
			}
		});

		if ( resize ) {
			this._size();
			this._position();
		}
		if ( this.uiDialog.is( ":data(ui-resizable)" ) ) {
			this.uiDialog.resizable( "option", resizableOptions );
		}
	},

	_setOption: function( key, value ) {
		var isDraggable, isResizable,
			uiDialog = this.uiDialog;

		if ( key === "dialogClass" ) {
			uiDialog
				.removeClass( this.options.dialogClass )
				.addClass( value );
		}

		if ( key === "disabled" ) {
			return;
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.uiDialog.appendTo( this._appendTo() );
		}

		if ( key === "buttons" ) {
			this._createButtons();
		}

		if ( key === "closeText" ) {
			this.uiDialogTitlebarClose.button({
				// Ensure that we always pass a string
				label: "" + value
			});
		}

		if ( key === "draggable" ) {
			isDraggable = uiDialog.is( ":data(ui-draggable)" );
			if ( isDraggable && !value ) {
				uiDialog.draggable( "destroy" );
			}

			if ( !isDraggable && value ) {
				this._makeDraggable();
			}
		}

		if ( key === "position" ) {
			this._position();
		}

		if ( key === "resizable" ) {
			// currently resizable, becoming non-resizable
			isResizable = uiDialog.is( ":data(ui-resizable)" );
			if ( isResizable && !value ) {
				uiDialog.resizable( "destroy" );
			}

			// currently resizable, changing handles
			if ( isResizable && typeof value === "string" ) {
				uiDialog.resizable( "option", "handles", value );
			}

			// currently non-resizable, becoming resizable
			if ( !isResizable && value !== false ) {
				this._makeResizable();
			}
		}

		if ( key === "title" ) {
			this._title( this.uiDialogTitlebar.find( ".ui-dialog-title" ) );
		}
	},

	_size: function() {
		// If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
		// divs will both have width and height set, so we need to reset them
		var nonContentHeight, minContentHeight, maxContentHeight,
			options = this.options;

		// Reset content sizing
		this.element.show().css({
			width: "auto",
			minHeight: 0,
			maxHeight: "none",
			height: 0
		});

		if ( options.minWidth > options.width ) {
			options.width = options.minWidth;
		}

		// reset wrapper sizing
		// determine the height of all the non-content elements
		nonContentHeight = this.uiDialog.css({
				height: "auto",
				width: options.width
			})
			.outerHeight();
		minContentHeight = Math.max( 0, options.minHeight - nonContentHeight );
		maxContentHeight = typeof options.maxHeight === "number" ?
			Math.max( 0, options.maxHeight - nonContentHeight ) :
			"none";

		if ( options.height === "auto" ) {
			this.element.css({
				minHeight: minContentHeight,
				maxHeight: maxContentHeight,
				height: "auto"
			});
		} else {
			this.element.height( Math.max( 0, options.height - nonContentHeight ) );
		}

		if ( this.uiDialog.is( ":data(ui-resizable)" ) ) {
			this.uiDialog.resizable( "option", "minHeight", this._minHeight() );
		}
	},

	_blockFrames: function() {
		this.iframeBlocks = this.document.find( "iframe" ).map(function() {
			var iframe = $( this );

			return $( "<div>" )
				.css({
					position: "absolute",
					width: iframe.outerWidth(),
					height: iframe.outerHeight()
				})
				.appendTo( iframe.parent() )
				.offset( iframe.offset() )[0];
		});
	},

	_unblockFrames: function() {
		if ( this.iframeBlocks ) {
			this.iframeBlocks.remove();
			delete this.iframeBlocks;
		}
	},

	_allowInteraction: function( event ) {
		if ( $( event.target ).closest( ".ui-dialog" ).length ) {
			return true;
		}

		// TODO: Remove hack when datepicker implements
		// the .ui-front logic (#8989)
		return !!$( event.target ).closest( ".ui-datepicker" ).length;
	},

	_createOverlay: function() {
		if ( !this.options.modal ) {
			return;
		}

		// We use a delay in case the overlay is created from an
		// event that we're going to be cancelling (#2804)
		var isOpening = true;
		this._delay(function() {
			isOpening = false;
		});

		if ( !this.document.data( "ui-dialog-overlays" ) ) {

			// Prevent use of anchors and inputs
			// Using _on() for an event handler shared across many instances is
			// safe because the dialogs stack and must be closed in reverse order
			this._on( this.document, {
				focusin: function( event ) {
					if ( isOpening ) {
						return;
					}

					if ( !this._allowInteraction( event ) ) {
						event.preventDefault();
						this._trackingInstances()[ 0 ]._focusTabbable();
					}
				}
			});
		}

		this.overlay = $( "<div>" )
			.addClass( "ui-widget-overlay ui-front" )
			.appendTo( this._appendTo() );
		this._on( this.overlay, {
			mousedown: "_keepFocus"
		});
		this.document.data( "ui-dialog-overlays",
			(this.document.data( "ui-dialog-overlays" ) || 0) + 1 );
	},

	_destroyOverlay: function() {
		if ( !this.options.modal ) {
			return;
		}

		if ( this.overlay ) {
			var overlays = this.document.data( "ui-dialog-overlays" ) - 1;

			if ( !overlays ) {
				this.document
					.unbind( "focusin" )
					.removeData( "ui-dialog-overlays" );
			} else {
				this.document.data( "ui-dialog-overlays", overlays );
			}

			this.overlay.remove();
			this.overlay = null;
		}
	}
});


/*!
 * jQuery UI Droppable 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/droppable/
 */


$.widget( "ui.droppable", {
	version: "1.11.4",
	widgetEventPrefix: "drop",
	options: {
		accept: "*",
		activeClass: false,
		addClasses: true,
		greedy: false,
		hoverClass: false,
		scope: "default",
		tolerance: "intersect",

		// callbacks
		activate: null,
		deactivate: null,
		drop: null,
		out: null,
		over: null
	},
	_create: function() {

		var proportions,
			o = this.options,
			accept = o.accept;

		this.isover = false;
		this.isout = true;

		this.accept = $.isFunction( accept ) ? accept : function( d ) {
			return d.is( accept );
		};

		this.proportions = function( /* valueToWrite */ ) {
			if ( arguments.length ) {
				// Store the droppable's proportions
				proportions = arguments[ 0 ];
			} else {
				// Retrieve or derive the droppable's proportions
				return proportions ?
					proportions :
					proportions = {
						width: this.element[ 0 ].offsetWidth,
						height: this.element[ 0 ].offsetHeight
					};
			}
		};

		this._addToManager( o.scope );

		o.addClasses && this.element.addClass( "ui-droppable" );

	},

	_addToManager: function( scope ) {
		// Add the reference and positions to the manager
		$.ui.ddmanager.droppables[ scope ] = $.ui.ddmanager.droppables[ scope ] || [];
		$.ui.ddmanager.droppables[ scope ].push( this );
	},

	_splice: function( drop ) {
		var i = 0;
		for ( ; i < drop.length; i++ ) {
			if ( drop[ i ] === this ) {
				drop.splice( i, 1 );
			}
		}
	},

	_destroy: function() {
		var drop = $.ui.ddmanager.droppables[ this.options.scope ];

		this._splice( drop );

		this.element.removeClass( "ui-droppable ui-droppable-disabled" );
	},

	_setOption: function( key, value ) {

		if ( key === "accept" ) {
			this.accept = $.isFunction( value ) ? value : function( d ) {
				return d.is( value );
			};
		} else if ( key === "scope" ) {
			var drop = $.ui.ddmanager.droppables[ this.options.scope ];

			this._splice( drop );
			this._addToManager( value );
		}

		this._super( key, value );
	},

	_activate: function( event ) {
		var draggable = $.ui.ddmanager.current;
		if ( this.options.activeClass ) {
			this.element.addClass( this.options.activeClass );
		}
		if ( draggable ){
			this._trigger( "activate", event, this.ui( draggable ) );
		}
	},

	_deactivate: function( event ) {
		var draggable = $.ui.ddmanager.current;
		if ( this.options.activeClass ) {
			this.element.removeClass( this.options.activeClass );
		}
		if ( draggable ){
			this._trigger( "deactivate", event, this.ui( draggable ) );
		}
	},

	_over: function( event ) {

		var draggable = $.ui.ddmanager.current;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return;
		}

		if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
			if ( this.options.hoverClass ) {
				this.element.addClass( this.options.hoverClass );
			}
			this._trigger( "over", event, this.ui( draggable ) );
		}

	},

	_out: function( event ) {

		var draggable = $.ui.ddmanager.current;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return;
		}

		if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
			if ( this.options.hoverClass ) {
				this.element.removeClass( this.options.hoverClass );
			}
			this._trigger( "out", event, this.ui( draggable ) );
		}

	},

	_drop: function( event, custom ) {

		var draggable = custom || $.ui.ddmanager.current,
			childrenIntersection = false;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return false;
		}

		this.element.find( ":data(ui-droppable)" ).not( ".ui-draggable-dragging" ).each(function() {
			var inst = $( this ).droppable( "instance" );
			if (
				inst.options.greedy &&
				!inst.options.disabled &&
				inst.options.scope === draggable.options.scope &&
				inst.accept.call( inst.element[ 0 ], ( draggable.currentItem || draggable.element ) ) &&
				$.ui.intersect( draggable, $.extend( inst, { offset: inst.element.offset() } ), inst.options.tolerance, event )
			) { childrenIntersection = true; return false; }
		});
		if ( childrenIntersection ) {
			return false;
		}

		if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
			if ( this.options.activeClass ) {
				this.element.removeClass( this.options.activeClass );
			}
			if ( this.options.hoverClass ) {
				this.element.removeClass( this.options.hoverClass );
			}
			this._trigger( "drop", event, this.ui( draggable ) );
			return this.element;
		}

		return false;

	},

	ui: function( c ) {
		return {
			draggable: ( c.currentItem || c.element ),
			helper: c.helper,
			position: c.position,
			offset: c.positionAbs
		};
	}

});

$.ui.intersect = (function() {
	function isOverAxis( x, reference, size ) {
		return ( x >= reference ) && ( x < ( reference + size ) );
	}

	return function( draggable, droppable, toleranceMode, event ) {

		if ( !droppable.offset ) {
			return false;
		}

		var x1 = ( draggable.positionAbs || draggable.position.absolute ).left + draggable.margins.left,
			y1 = ( draggable.positionAbs || draggable.position.absolute ).top + draggable.margins.top,
			x2 = x1 + draggable.helperProportions.width,
			y2 = y1 + draggable.helperProportions.height,
			l = droppable.offset.left,
			t = droppable.offset.top,
			r = l + droppable.proportions().width,
			b = t + droppable.proportions().height;

		switch ( toleranceMode ) {
		case "fit":
			return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b );
		case "intersect":
			return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half
				x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half
				t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half
				y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half
		case "pointer":
			return isOverAxis( event.pageY, t, droppable.proportions().height ) && isOverAxis( event.pageX, l, droppable.proportions().width );
		case "touch":
			return (
				( y1 >= t && y1 <= b ) || // Top edge touching
				( y2 >= t && y2 <= b ) || // Bottom edge touching
				( y1 < t && y2 > b ) // Surrounded vertically
			) && (
				( x1 >= l && x1 <= r ) || // Left edge touching
				( x2 >= l && x2 <= r ) || // Right edge touching
				( x1 < l && x2 > r ) // Surrounded horizontally
			);
		default:
			return false;
		}
	};
})();

/*
	This manager tracks offsets of draggables and droppables
*/
$.ui.ddmanager = {
	current: null,
	droppables: { "default": [] },
	prepareOffsets: function( t, event ) {

		var i, j,
			m = $.ui.ddmanager.droppables[ t.options.scope ] || [],
			type = event ? event.type : null, // workaround for #2317
			list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack();

		droppablesLoop: for ( i = 0; i < m.length; i++ ) {

			// No disabled and non-accepted
			if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ], ( t.currentItem || t.element ) ) ) ) {
				continue;
			}

			// Filter out elements in the current dragged item
			for ( j = 0; j < list.length; j++ ) {
				if ( list[ j ] === m[ i ].element[ 0 ] ) {
					m[ i ].proportions().height = 0;
					continue droppablesLoop;
				}
			}

			m[ i ].visible = m[ i ].element.css( "display" ) !== "none";
			if ( !m[ i ].visible ) {
				continue;
			}

			// Activate the droppable if used directly from draggables
			if ( type === "mousedown" ) {
				m[ i ]._activate.call( m[ i ], event );
			}

			m[ i ].offset = m[ i ].element.offset();
			m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth, height: m[ i ].element[ 0 ].offsetHeight });

		}

	},
	drop: function( draggable, event ) {

		var dropped = false;
		// Create a copy of the droppables in case the list changes during the drop (#9116)
		$.each( ( $.ui.ddmanager.droppables[ draggable.options.scope ] || [] ).slice(), function() {

			if ( !this.options ) {
				return;
			}
			if ( !this.options.disabled && this.visible && $.ui.intersect( draggable, this, this.options.tolerance, event ) ) {
				dropped = this._drop.call( this, event ) || dropped;
			}

			if ( !this.options.disabled && this.visible && this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
				this.isout = true;
				this.isover = false;
				this._deactivate.call( this, event );
			}

		});
		return dropped;

	},
	dragStart: function( draggable, event ) {
		// Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003)
		draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() {
			if ( !draggable.options.refreshPositions ) {
				$.ui.ddmanager.prepareOffsets( draggable, event );
			}
		});
	},
	drag: function( draggable, event ) {

		// If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
		if ( draggable.options.refreshPositions ) {
			$.ui.ddmanager.prepareOffsets( draggable, event );
		}

		// Run through all droppables and check their positions based on specific tolerance options
		$.each( $.ui.ddmanager.droppables[ draggable.options.scope ] || [], function() {

			if ( this.options.disabled || this.greedyChild || !this.visible ) {
				return;
			}

			var parentInstance, scope, parent,
				intersects = $.ui.intersect( draggable, this, this.options.tolerance, event ),
				c = !intersects && this.isover ? "isout" : ( intersects && !this.isover ? "isover" : null );
			if ( !c ) {
				return;
			}

			if ( this.options.greedy ) {
				// find droppable parents with same scope
				scope = this.options.scope;
				parent = this.element.parents( ":data(ui-droppable)" ).filter(function() {
					return $( this ).droppable( "instance" ).options.scope === scope;
				});

				if ( parent.length ) {
					parentInstance = $( parent[ 0 ] ).droppable( "instance" );
					parentInstance.greedyChild = ( c === "isover" );
				}
			}

			// we just moved into a greedy child
			if ( parentInstance && c === "isover" ) {
				parentInstance.isover = false;
				parentInstance.isout = true;
				parentInstance._out.call( parentInstance, event );
			}

			this[ c ] = true;
			this[c === "isout" ? "isover" : "isout"] = false;
			this[c === "isover" ? "_over" : "_out"].call( this, event );

			// we just moved out of a greedy child
			if ( parentInstance && c === "isout" ) {
				parentInstance.isout = false;
				parentInstance.isover = true;
				parentInstance._over.call( parentInstance, event );
			}
		});

	},
	dragStop: function( draggable, event ) {
		draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" );
		// Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003)
		if ( !draggable.options.refreshPositions ) {
			$.ui.ddmanager.prepareOffsets( draggable, event );
		}
	}
};

var droppable = $.ui.droppable;


/*!
 * jQuery UI Effects 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/category/effects-core/
 */


var dataSpace = "ui-effects-",

	// Create a local jQuery because jQuery Color relies on it and the
	// global may not exist with AMD and a custom build (#10199)
	jQuery = $;

$.effects = {
	effect: {}
};

/*!
 * jQuery Color Animations v2.1.2
 * https://github.com/jquery/jquery-color
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * Date: Wed Jan 16 08:47:09 2013 -0600
 */
(function( jQuery, undefined ) {

	var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",

	// plusequals test for += 100 -= 100
	rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
	// a set of RE's that can match strings and generate color tuples.
	stringParsers = [ {
			re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ],
					execResult[ 3 ],
					execResult[ 4 ]
				];
			}
		}, {
			re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ] * 2.55,
					execResult[ 2 ] * 2.55,
					execResult[ 3 ] * 2.55,
					execResult[ 4 ]
				];
			}
		}, {
			// this regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ], 16 )
				];
			}
		}, {
			// this regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
				];
			}
		}, {
			re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			space: "hsla",
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ] / 100,
					execResult[ 3 ] / 100,
					execResult[ 4 ]
				];
			}
		} ],

	// jQuery.Color( )
	color = jQuery.Color = function( color, green, blue, alpha ) {
		return new jQuery.Color.fn.parse( color, green, blue, alpha );
	},
	spaces = {
		rgba: {
			props: {
				red: {
					idx: 0,
					type: "byte"
				},
				green: {
					idx: 1,
					type: "byte"
				},
				blue: {
					idx: 2,
					type: "byte"
				}
			}
		},

		hsla: {
			props: {
				hue: {
					idx: 0,
					type: "degrees"
				},
				saturation: {
					idx: 1,
					type: "percent"
				},
				lightness: {
					idx: 2,
					type: "percent"
				}
			}
		}
	},
	propTypes = {
		"byte": {
			floor: true,
			max: 255
		},
		"percent": {
			max: 1
		},
		"degrees": {
			mod: 360,
			floor: true
		}
	},
	support = color.support = {},

	// element for support tests
	supportElem = jQuery( "<p>" )[ 0 ],

	// colors = jQuery.Color.names
	colors,

	// local aliases of functions called often
	each = jQuery.each;

// determine rgba support immediately
supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;

// define cache name and alpha properties
// for rgba and hsla spaces
each( spaces, function( spaceName, space ) {
	space.cache = "_" + spaceName;
	space.props.alpha = {
		idx: 3,
		type: "percent",
		def: 1
	};
});

function clamp( value, prop, allowEmpty ) {
	var type = propTypes[ prop.type ] || {};

	if ( value == null ) {
		return (allowEmpty || !prop.def) ? null : prop.def;
	}

	// ~~ is an short way of doing floor for positive numbers
	value = type.floor ? ~~value : parseFloat( value );

	// IE will pass in empty strings as value for alpha,
	// which will hit this case
	if ( isNaN( value ) ) {
		return prop.def;
	}

	if ( type.mod ) {
		// we add mod before modding to make sure that negatives values
		// get converted properly: -10 -> 350
		return (value + type.mod) % type.mod;
	}

	// for now all property types without mod have min and max
	return 0 > value ? 0 : type.max < value ? type.max : value;
}

function stringParse( string ) {
	var inst = color(),
		rgba = inst._rgba = [];

	string = string.toLowerCase();

	each( stringParsers, function( i, parser ) {
		var parsed,
			match = parser.re.exec( string ),
			values = match && parser.parse( match ),
			spaceName = parser.space || "rgba";

		if ( values ) {
			parsed = inst[ spaceName ]( values );

			// if this was an rgba parse the assignment might happen twice
			// oh well....
			inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
			rgba = inst._rgba = parsed._rgba;

			// exit each( stringParsers ) here because we matched
			return false;
		}
	});

	// Found a stringParser that handled it
	if ( rgba.length ) {

		// if this came from a parsed string, force "transparent" when alpha is 0
		// chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
		if ( rgba.join() === "0,0,0,0" ) {
			jQuery.extend( rgba, colors.transparent );
		}
		return inst;
	}

	// named colors
	return colors[ string ];
}

color.fn = jQuery.extend( color.prototype, {
	parse: function( red, green, blue, alpha ) {
		if ( red === undefined ) {
			this._rgba = [ null, null, null, null ];
			return this;
		}
		if ( red.jquery || red.nodeType ) {
			red = jQuery( red ).css( green );
			green = undefined;
		}

		var inst = this,
			type = jQuery.type( red ),
			rgba = this._rgba = [];

		// more than 1 argument specified - assume ( red, green, blue, alpha )
		if ( green !== undefined ) {
			red = [ red, green, blue, alpha ];
			type = "array";
		}

		if ( type === "string" ) {
			return this.parse( stringParse( red ) || colors._default );
		}

		if ( type === "array" ) {
			each( spaces.rgba.props, function( key, prop ) {
				rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
			});
			return this;
		}

		if ( type === "object" ) {
			if ( red instanceof color ) {
				each( spaces, function( spaceName, space ) {
					if ( red[ space.cache ] ) {
						inst[ space.cache ] = red[ space.cache ].slice();
					}
				});
			} else {
				each( spaces, function( spaceName, space ) {
					var cache = space.cache;
					each( space.props, function( key, prop ) {

						// if the cache doesn't exist, and we know how to convert
						if ( !inst[ cache ] && space.to ) {

							// if the value was null, we don't need to copy it
							// if the key was alpha, we don't need to copy it either
							if ( key === "alpha" || red[ key ] == null ) {
								return;
							}
							inst[ cache ] = space.to( inst._rgba );
						}

						// this is the only case where we allow nulls for ALL properties.
						// call clamp with alwaysAllowEmpty
						inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
					});

					// everything defined but alpha?
					if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {
						// use the default of 1
						inst[ cache ][ 3 ] = 1;
						if ( space.from ) {
							inst._rgba = space.from( inst[ cache ] );
						}
					}
				});
			}
			return this;
		}
	},
	is: function( compare ) {
		var is = color( compare ),
			same = true,
			inst = this;

		each( spaces, function( _, space ) {
			var localCache,
				isCache = is[ space.cache ];
			if (isCache) {
				localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
				each( space.props, function( _, prop ) {
					if ( isCache[ prop.idx ] != null ) {
						same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
						return same;
					}
				});
			}
			return same;
		});
		return same;
	},
	_space: function() {
		var used = [],
			inst = this;
		each( spaces, function( spaceName, space ) {
			if ( inst[ space.cache ] ) {
				used.push( spaceName );
			}
		});
		return used.pop();
	},
	transition: function( other, distance ) {
		var end = color( other ),
			spaceName = end._space(),
			space = spaces[ spaceName ],
			startColor = this.alpha() === 0 ? color( "transparent" ) : this,
			start = startColor[ space.cache ] || space.to( startColor._rgba ),
			result = start.slice();

		end = end[ space.cache ];
		each( space.props, function( key, prop ) {
			var index = prop.idx,
				startValue = start[ index ],
				endValue = end[ index ],
				type = propTypes[ prop.type ] || {};

			// if null, don't override start value
			if ( endValue === null ) {
				return;
			}
			// if null - use end
			if ( startValue === null ) {
				result[ index ] = endValue;
			} else {
				if ( type.mod ) {
					if ( endValue - startValue > type.mod / 2 ) {
						startValue += type.mod;
					} else if ( startValue - endValue > type.mod / 2 ) {
						startValue -= type.mod;
					}
				}
				result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
			}
		});
		return this[ spaceName ]( result );
	},
	blend: function( opaque ) {
		// if we are already opaque - return ourself
		if ( this._rgba[ 3 ] === 1 ) {
			return this;
		}

		var rgb = this._rgba.slice(),
			a = rgb.pop(),
			blend = color( opaque )._rgba;

		return color( jQuery.map( rgb, function( v, i ) {
			return ( 1 - a ) * blend[ i ] + a * v;
		}));
	},
	toRgbaString: function() {
		var prefix = "rgba(",
			rgba = jQuery.map( this._rgba, function( v, i ) {
				return v == null ? ( i > 2 ? 1 : 0 ) : v;
			});

		if ( rgba[ 3 ] === 1 ) {
			rgba.pop();
			prefix = "rgb(";
		}

		return prefix + rgba.join() + ")";
	},
	toHslaString: function() {
		var prefix = "hsla(",
			hsla = jQuery.map( this.hsla(), function( v, i ) {
				if ( v == null ) {
					v = i > 2 ? 1 : 0;
				}

				// catch 1 and 2
				if ( i && i < 3 ) {
					v = Math.round( v * 100 ) + "%";
				}
				return v;
			});

		if ( hsla[ 3 ] === 1 ) {
			hsla.pop();
			prefix = "hsl(";
		}
		return prefix + hsla.join() + ")";
	},
	toHexString: function( includeAlpha ) {
		var rgba = this._rgba.slice(),
			alpha = rgba.pop();

		if ( includeAlpha ) {
			rgba.push( ~~( alpha * 255 ) );
		}

		return "#" + jQuery.map( rgba, function( v ) {

			// default to 0 when nulls exist
			v = ( v || 0 ).toString( 16 );
			return v.length === 1 ? "0" + v : v;
		}).join("");
	},
	toString: function() {
		return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
	}
});
color.fn.parse.prototype = color.fn;

// hsla conversions adapted from:
// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021

function hue2rgb( p, q, h ) {
	h = ( h + 1 ) % 1;
	if ( h * 6 < 1 ) {
		return p + ( q - p ) * h * 6;
	}
	if ( h * 2 < 1) {
		return q;
	}
	if ( h * 3 < 2 ) {
		return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6;
	}
	return p;
}

spaces.hsla.to = function( rgba ) {
	if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
		return [ null, null, null, rgba[ 3 ] ];
	}
	var r = rgba[ 0 ] / 255,
		g = rgba[ 1 ] / 255,
		b = rgba[ 2 ] / 255,
		a = rgba[ 3 ],
		max = Math.max( r, g, b ),
		min = Math.min( r, g, b ),
		diff = max - min,
		add = max + min,
		l = add * 0.5,
		h, s;

	if ( min === max ) {
		h = 0;
	} else if ( r === max ) {
		h = ( 60 * ( g - b ) / diff ) + 360;
	} else if ( g === max ) {
		h = ( 60 * ( b - r ) / diff ) + 120;
	} else {
		h = ( 60 * ( r - g ) / diff ) + 240;
	}

	// chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
	// otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
	if ( diff === 0 ) {
		s = 0;
	} else if ( l <= 0.5 ) {
		s = diff / add;
	} else {
		s = diff / ( 2 - add );
	}
	return [ Math.round(h) % 360, s, l, a == null ? 1 : a ];
};

spaces.hsla.from = function( hsla ) {
	if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
		return [ null, null, null, hsla[ 3 ] ];
	}
	var h = hsla[ 0 ] / 360,
		s = hsla[ 1 ],
		l = hsla[ 2 ],
		a = hsla[ 3 ],
		q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
		p = 2 * l - q;

	return [
		Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
		Math.round( hue2rgb( p, q, h ) * 255 ),
		Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
		a
	];
};

each( spaces, function( spaceName, space ) {
	var props = space.props,
		cache = space.cache,
		to = space.to,
		from = space.from;

	// makes rgba() and hsla()
	color.fn[ spaceName ] = function( value ) {

		// generate a cache for this space if it doesn't exist
		if ( to && !this[ cache ] ) {
			this[ cache ] = to( this._rgba );
		}
		if ( value === undefined ) {
			return this[ cache ].slice();
		}

		var ret,
			type = jQuery.type( value ),
			arr = ( type === "array" || type === "object" ) ? value : arguments,
			local = this[ cache ].slice();

		each( props, function( key, prop ) {
			var val = arr[ type === "object" ? key : prop.idx ];
			if ( val == null ) {
				val = local[ prop.idx ];
			}
			local[ prop.idx ] = clamp( val, prop );
		});

		if ( from ) {
			ret = color( from( local ) );
			ret[ cache ] = local;
			return ret;
		} else {
			return color( local );
		}
	};

	// makes red() green() blue() alpha() hue() saturation() lightness()
	each( props, function( key, prop ) {
		// alpha is included in more than one space
		if ( color.fn[ key ] ) {
			return;
		}
		color.fn[ key ] = function( value ) {
			var vtype = jQuery.type( value ),
				fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
				local = this[ fn ](),
				cur = local[ prop.idx ],
				match;

			if ( vtype === "undefined" ) {
				return cur;
			}

			if ( vtype === "function" ) {
				value = value.call( this, cur );
				vtype = jQuery.type( value );
			}
			if ( value == null && prop.empty ) {
				return this;
			}
			if ( vtype === "string" ) {
				match = rplusequals.exec( value );
				if ( match ) {
					value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
				}
			}
			local[ prop.idx ] = value;
			return this[ fn ]( local );
		};
	});
});

// add cssHook and .fx.step function for each named hook.
// accept a space separated string of properties
color.hook = function( hook ) {
	var hooks = hook.split( " " );
	each( hooks, function( i, hook ) {
		jQuery.cssHooks[ hook ] = {
			set: function( elem, value ) {
				var parsed, curElem,
					backgroundColor = "";

				if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) {
					value = color( parsed || value );
					if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
						curElem = hook === "backgroundColor" ? elem.parentNode : elem;
						while (
							(backgroundColor === "" || backgroundColor === "transparent") &&
							curElem && curElem.style
						) {
							try {
								backgroundColor = jQuery.css( curElem, "backgroundColor" );
								curElem = curElem.parentNode;
							} catch ( e ) {
							}
						}

						value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
							backgroundColor :
							"_default" );
					}

					value = value.toRgbaString();
				}
				try {
					elem.style[ hook ] = value;
				} catch ( e ) {
					// wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit'
				}
			}
		};
		jQuery.fx.step[ hook ] = function( fx ) {
			if ( !fx.colorInit ) {
				fx.start = color( fx.elem, hook );
				fx.end = color( fx.end );
				fx.colorInit = true;
			}
			jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
		};
	});

};

color.hook( stepHooks );

jQuery.cssHooks.borderColor = {
	expand: function( value ) {
		var expanded = {};

		each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
			expanded[ "border" + part + "Color" ] = value;
		});
		return expanded;
	}
};

// Basic color names only.
// Usage of any of the other color names requires adding yourself or including
// jquery.color.svg-names.js.
colors = jQuery.Color.names = {
	// 4.1. Basic color keywords
	aqua: "#00ffff",
	black: "#000000",
	blue: "#0000ff",
	fuchsia: "#ff00ff",
	gray: "#808080",
	green: "#008000",
	lime: "#00ff00",
	maroon: "#800000",
	navy: "#000080",
	olive: "#808000",
	purple: "#800080",
	red: "#ff0000",
	silver: "#c0c0c0",
	teal: "#008080",
	white: "#ffffff",
	yellow: "#ffff00",

	// 4.2.3. "transparent" color keyword
	transparent: [ null, null, null, 0 ],

	_default: "#ffffff"
};

})( jQuery );

/******************************************************************************/
/****************************** CLASS ANIMATIONS ******************************/
/******************************************************************************/
(function() {

var classAnimationActions = [ "add", "remove", "toggle" ],
	shorthandStyles = {
		border: 1,
		borderBottom: 1,
		borderColor: 1,
		borderLeft: 1,
		borderRight: 1,
		borderTop: 1,
		borderWidth: 1,
		margin: 1,
		padding: 1
	};

$.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) {
	$.fx.step[ prop ] = function( fx ) {
		if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
			jQuery.style( fx.elem, prop, fx.end );
			fx.setAttr = true;
		}
	};
});

function getElementStyles( elem ) {
	var key, len,
		style = elem.ownerDocument.defaultView ?
			elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
			elem.currentStyle,
		styles = {};

	if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
		len = style.length;
		while ( len-- ) {
			key = style[ len ];
			if ( typeof style[ key ] === "string" ) {
				styles[ $.camelCase( key ) ] = style[ key ];
			}
		}
	// support: Opera, IE <9
	} else {
		for ( key in style ) {
			if ( typeof style[ key ] === "string" ) {
				styles[ key ] = style[ key ];
			}
		}
	}

	return styles;
}

function styleDifference( oldStyle, newStyle ) {
	var diff = {},
		name, value;

	for ( name in newStyle ) {
		value = newStyle[ name ];
		if ( oldStyle[ name ] !== value ) {
			if ( !shorthandStyles[ name ] ) {
				if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
					diff[ name ] = value;
				}
			}
		}
	}

	return diff;
}

// support: jQuery <1.8
if ( !$.fn.addBack ) {
	$.fn.addBack = function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	};
}

$.effects.animateClass = function( value, duration, easing, callback ) {
	var o = $.speed( duration, easing, callback );

	return this.queue( function() {
		var animated = $( this ),
			baseClass = animated.attr( "class" ) || "",
			applyClassChange,
			allAnimations = o.children ? animated.find( "*" ).addBack() : animated;

		// map the animated objects to store the original styles.
		allAnimations = allAnimations.map(function() {
			var el = $( this );
			return {
				el: el,
				start: getElementStyles( this )
			};
		});

		// apply class change
		applyClassChange = function() {
			$.each( classAnimationActions, function(i, action) {
				if ( value[ action ] ) {
					animated[ action + "Class" ]( value[ action ] );
				}
			});
		};
		applyClassChange();

		// map all animated objects again - calculate new styles and diff
		allAnimations = allAnimations.map(function() {
			this.end = getElementStyles( this.el[ 0 ] );
			this.diff = styleDifference( this.start, this.end );
			return this;
		});

		// apply original class
		animated.attr( "class", baseClass );

		// map all animated objects again - this time collecting a promise
		allAnimations = allAnimations.map(function() {
			var styleInfo = this,
				dfd = $.Deferred(),
				opts = $.extend({}, o, {
					queue: false,
					complete: function() {
						dfd.resolve( styleInfo );
					}
				});

			this.el.animate( this.diff, opts );
			return dfd.promise();
		});

		// once all animations have completed:
		$.when.apply( $, allAnimations.get() ).done(function() {

			// set the final class
			applyClassChange();

			// for each animated element,
			// clear all css properties that were animated
			$.each( arguments, function() {
				var el = this.el;
				$.each( this.diff, function(key) {
					el.css( key, "" );
				});
			});

			// this is guarnteed to be there if you use jQuery.speed()
			// it also handles dequeuing the next anim...
			o.complete.call( animated[ 0 ] );
		});
	});
};

$.fn.extend({
	addClass: (function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return speed ?
				$.effects.animateClass.call( this,
					{ add: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	})( $.fn.addClass ),

	removeClass: (function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return arguments.length > 1 ?
				$.effects.animateClass.call( this,
					{ remove: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	})( $.fn.removeClass ),

	toggleClass: (function( orig ) {
		return function( classNames, force, speed, easing, callback ) {
			if ( typeof force === "boolean" || force === undefined ) {
				if ( !speed ) {
					// without speed parameter
					return orig.apply( this, arguments );
				} else {
					return $.effects.animateClass.call( this,
						(force ? { add: classNames } : { remove: classNames }),
						speed, easing, callback );
				}
			} else {
				// without force parameter
				return $.effects.animateClass.call( this,
					{ toggle: classNames }, force, speed, easing );
			}
		};
	})( $.fn.toggleClass ),

	switchClass: function( remove, add, speed, easing, callback) {
		return $.effects.animateClass.call( this, {
			add: add,
			remove: remove
		}, speed, easing, callback );
	}
});

})();

/******************************************************************************/
/*********************************** EFFECTS **********************************/
/******************************************************************************/

(function() {

$.extend( $.effects, {
	version: "1.11.4",

	// Saves a set of properties in a data storage
	save: function( element, set ) {
		for ( var i = 0; i < set.length; i++ ) {
			if ( set[ i ] !== null ) {
				element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
			}
		}
	},

	// Restores a set of previously saved properties from a data storage
	restore: function( element, set ) {
		var val, i;
		for ( i = 0; i < set.length; i++ ) {
			if ( set[ i ] !== null ) {
				val = element.data( dataSpace + set[ i ] );
				// support: jQuery 1.6.2
				// http://bugs.jquery.com/ticket/9917
				// jQuery 1.6.2 incorrectly returns undefined for any falsy value.
				// We can't differentiate between "" and 0 here, so we just assume
				// empty string since it's likely to be a more common value...
				if ( val === undefined ) {
					val = "";
				}
				element.css( set[ i ], val );
			}
		}
	},

	setMode: function( el, mode ) {
		if (mode === "toggle") {
			mode = el.is( ":hidden" ) ? "show" : "hide";
		}
		return mode;
	},

	// Translates a [top,left] array into a baseline value
	// this should be a little more flexible in the future to handle a string & hash
	getBaseline: function( origin, original ) {
		var y, x;
		switch ( origin[ 0 ] ) {
			case "top": y = 0; break;
			case "middle": y = 0.5; break;
			case "bottom": y = 1; break;
			default: y = origin[ 0 ] / original.height;
		}
		switch ( origin[ 1 ] ) {
			case "left": x = 0; break;
			case "center": x = 0.5; break;
			case "right": x = 1; break;
			default: x = origin[ 1 ] / original.width;
		}
		return {
			x: x,
			y: y
		};
	},

	// Wraps the element around a wrapper that copies position properties
	createWrapper: function( element ) {

		// if the element is already wrapped, return it
		if ( element.parent().is( ".ui-effects-wrapper" )) {
			return element.parent();
		}

		// wrap the element
		var props = {
				width: element.outerWidth(true),
				height: element.outerHeight(true),
				"float": element.css( "float" )
			},
			wrapper = $( "<div></div>" )
				.addClass( "ui-effects-wrapper" )
				.css({
					fontSize: "100%",
					background: "transparent",
					border: "none",
					margin: 0,
					padding: 0
				}),
			// Store the size in case width/height are defined in % - Fixes #5245
			size = {
				width: element.width(),
				height: element.height()
			},
			active = document.activeElement;

		// support: Firefox
		// Firefox incorrectly exposes anonymous content
		// https://bugzilla.mozilla.org/show_bug.cgi?id=561664
		try {
			active.id;
		} catch ( e ) {
			active = document.body;
		}

		element.wrap( wrapper );

		// Fixes #7595 - Elements lose focus when wrapped.
		if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
			$( active ).focus();
		}

		wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element

		// transfer positioning properties to the wrapper
		if ( element.css( "position" ) === "static" ) {
			wrapper.css({ position: "relative" });
			element.css({ position: "relative" });
		} else {
			$.extend( props, {
				position: element.css( "position" ),
				zIndex: element.css( "z-index" )
			});
			$.each([ "top", "left", "bottom", "right" ], function(i, pos) {
				props[ pos ] = element.css( pos );
				if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
					props[ pos ] = "auto";
				}
			});
			element.css({
				position: "relative",
				top: 0,
				left: 0,
				right: "auto",
				bottom: "auto"
			});
		}
		element.css(size);

		return wrapper.css( props ).show();
	},

	removeWrapper: function( element ) {
		var active = document.activeElement;

		if ( element.parent().is( ".ui-effects-wrapper" ) ) {
			element.parent().replaceWith( element );

			// Fixes #7595 - Elements lose focus when wrapped.
			if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
				$( active ).focus();
			}
		}

		return element;
	},

	setTransition: function( element, list, factor, value ) {
		value = value || {};
		$.each( list, function( i, x ) {
			var unit = element.cssUnit( x );
			if ( unit[ 0 ] > 0 ) {
				value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
			}
		});
		return value;
	}
});

// return an effect options object for the given parameters:
function _normalizeArguments( effect, options, speed, callback ) {

	// allow passing all options as the first parameter
	if ( $.isPlainObject( effect ) ) {
		options = effect;
		effect = effect.effect;
	}

	// convert to an object
	effect = { effect: effect };

	// catch (effect, null, ...)
	if ( options == null ) {
		options = {};
	}

	// catch (effect, callback)
	if ( $.isFunction( options ) ) {
		callback = options;
		speed = null;
		options = {};
	}

	// catch (effect, speed, ?)
	if ( typeof options === "number" || $.fx.speeds[ options ] ) {
		callback = speed;
		speed = options;
		options = {};
	}

	// catch (effect, options, callback)
	if ( $.isFunction( speed ) ) {
		callback = speed;
		speed = null;
	}

	// add options to effect
	if ( options ) {
		$.extend( effect, options );
	}

	speed = speed || options.duration;
	effect.duration = $.fx.off ? 0 :
		typeof speed === "number" ? speed :
		speed in $.fx.speeds ? $.fx.speeds[ speed ] :
		$.fx.speeds._default;

	effect.complete = callback || options.complete;

	return effect;
}

function standardAnimationOption( option ) {
	// Valid standard speeds (nothing, number, named speed)
	if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
		return true;
	}

	// Invalid strings - treat as "normal" speed
	if ( typeof option === "string" && !$.effects.effect[ option ] ) {
		return true;
	}

	// Complete callback
	if ( $.isFunction( option ) ) {
		return true;
	}

	// Options hash (but not naming an effect)
	if ( typeof option === "object" && !option.effect ) {
		return true;
	}

	// Didn't match any standard API
	return false;
}

$.fn.extend({
	effect: function( /* effect, options, speed, callback */ ) {
		var args = _normalizeArguments.apply( this, arguments ),
			mode = args.mode,
			queue = args.queue,
			effectMethod = $.effects.effect[ args.effect ];

		if ( $.fx.off || !effectMethod ) {
			// delegate to the original method (e.g., .show()) if possible
			if ( mode ) {
				return this[ mode ]( args.duration, args.complete );
			} else {
				return this.each( function() {
					if ( args.complete ) {
						args.complete.call( this );
					}
				});
			}
		}

		function run( next ) {
			var elem = $( this ),
				complete = args.complete,
				mode = args.mode;

			function done() {
				if ( $.isFunction( complete ) ) {
					complete.call( elem[0] );
				}
				if ( $.isFunction( next ) ) {
					next();
				}
			}

			// If the element already has the correct final state, delegate to
			// the core methods so the internal tracking of "olddisplay" works.
			if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {
				elem[ mode ]();
				done();
			} else {
				effectMethod.call( elem[0], args, done );
			}
		}

		return queue === false ? this.each( run ) : this.queue( queue || "fx", run );
	},

	show: (function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "show";
				return this.effect.call( this, args );
			}
		};
	})( $.fn.show ),

	hide: (function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "hide";
				return this.effect.call( this, args );
			}
		};
	})( $.fn.hide ),

	toggle: (function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "toggle";
				return this.effect.call( this, args );
			}
		};
	})( $.fn.toggle ),

	// helper functions
	cssUnit: function(key) {
		var style = this.css( key ),
			val = [];

		$.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
			if ( style.indexOf( unit ) > 0 ) {
				val = [ parseFloat( style ), unit ];
			}
		});
		return val;
	}
});

})();

/******************************************************************************/
/*********************************** EASING ***********************************/
/******************************************************************************/

(function() {

// based on easing equations from Robert Penner (http://www.robertpenner.com/easing)

var baseEasings = {};

$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
	baseEasings[ name ] = function( p ) {
		return Math.pow( p, i + 2 );
	};
});

$.extend( baseEasings, {
	Sine: function( p ) {
		return 1 - Math.cos( p * Math.PI / 2 );
	},
	Circ: function( p ) {
		return 1 - Math.sqrt( 1 - p * p );
	},
	Elastic: function( p ) {
		return p === 0 || p === 1 ? p :
			-Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 );
	},
	Back: function( p ) {
		return p * p * ( 3 * p - 2 );
	},
	Bounce: function( p ) {
		var pow2,
			bounce = 4;

		while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
		return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
	}
});

$.each( baseEasings, function( name, easeIn ) {
	$.easing[ "easeIn" + name ] = easeIn;
	$.easing[ "easeOut" + name ] = function( p ) {
		return 1 - easeIn( 1 - p );
	};
	$.easing[ "easeInOut" + name ] = function( p ) {
		return p < 0.5 ?
			easeIn( p * 2 ) / 2 :
			1 - easeIn( p * -2 + 2 ) / 2;
	};
});

})();

var effect = $.effects;


/*!
 * jQuery UI Effects Blind 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/blind-effect/
 */


var effectBlind = $.effects.effect.blind = function( o, done ) {
	// Create element
	var el = $( this ),
		rvertical = /up|down|vertical/,
		rpositivemotion = /up|left|vertical|horizontal/,
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "hide" ),
		direction = o.direction || "up",
		vertical = rvertical.test( direction ),
		ref = vertical ? "height" : "width",
		ref2 = vertical ? "top" : "left",
		motion = rpositivemotion.test( direction ),
		animation = {},
		show = mode === "show",
		wrapper, distance, margin;

	// if already wrapped, the wrapper's properties are my property. #6245
	if ( el.parent().is( ".ui-effects-wrapper" ) ) {
		$.effects.save( el.parent(), props );
	} else {
		$.effects.save( el, props );
	}
	el.show();
	wrapper = $.effects.createWrapper( el ).css({
		overflow: "hidden"
	});

	distance = wrapper[ ref ]();
	margin = parseFloat( wrapper.css( ref2 ) ) || 0;

	animation[ ref ] = show ? distance : 0;
	if ( !motion ) {
		el
			.css( vertical ? "bottom" : "right", 0 )
			.css( vertical ? "top" : "left", "auto" )
			.css({ position: "absolute" });

		animation[ ref2 ] = show ? margin : distance + margin;
	}

	// start at 0 if we are showing
	if ( show ) {
		wrapper.css( ref, 0 );
		if ( !motion ) {
			wrapper.css( ref2, margin + distance );
		}
	}

	// Animate
	wrapper.animate( animation, {
		duration: o.duration,
		easing: o.easing,
		queue: false,
		complete: function() {
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		}
	});
};


/*!
 * jQuery UI Effects Bounce 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/bounce-effect/
 */


var effectBounce = $.effects.effect.bounce = function( o, done ) {
	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],

		// defaults:
		mode = $.effects.setMode( el, o.mode || "effect" ),
		hide = mode === "hide",
		show = mode === "show",
		direction = o.direction || "up",
		distance = o.distance,
		times = o.times || 5,

		// number of internal animations
		anims = times * 2 + ( show || hide ? 1 : 0 ),
		speed = o.duration / anims,
		easing = o.easing,

		// utility:
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ),
		i,
		upAnim,
		downAnim,

		// we will need to re-assemble the queue to stack our animations in place
		queue = el.queue(),
		queuelen = queue.length;

	// Avoid touching opacity to prevent clearType and PNG issues in IE
	if ( show || hide ) {
		props.push( "opacity" );
	}

	$.effects.save( el, props );
	el.show();
	$.effects.createWrapper( el ); // Create Wrapper

	// default distance for the BIGGEST bounce is the outer Distance / 3
	if ( !distance ) {
		distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
	}

	if ( show ) {
		downAnim = { opacity: 1 };
		downAnim[ ref ] = 0;

		// if we are showing, force opacity 0 and set the initial position
		// then do the "first" animation
		el.css( "opacity", 0 )
			.css( ref, motion ? -distance * 2 : distance * 2 )
			.animate( downAnim, speed, easing );
	}

	// start at the smallest distance if we are hiding
	if ( hide ) {
		distance = distance / Math.pow( 2, times - 1 );
	}

	downAnim = {};
	downAnim[ ref ] = 0;
	// Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
	for ( i = 0; i < times; i++ ) {
		upAnim = {};
		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;

		el.animate( upAnim, speed, easing )
			.animate( downAnim, speed, easing );

		distance = hide ? distance * 2 : distance / 2;
	}

	// Last Bounce when Hiding
	if ( hide ) {
		upAnim = { opacity: 0 };
		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;

		el.animate( upAnim, speed, easing );
	}

	el.queue(function() {
		if ( hide ) {
			el.hide();
		}
		$.effects.restore( el, props );
		$.effects.removeWrapper( el );
		done();
	});

	// inject all the animations we just queued to be first in line (after "inprogress")
	if ( queuelen > 1) {
		queue.splice.apply( queue,
			[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
	}
	el.dequeue();

};


/*!
 * jQuery UI Effects Clip 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/clip-effect/
 */


var effectClip = $.effects.effect.clip = function( o, done ) {
	// Create element
	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "hide" ),
		show = mode === "show",
		direction = o.direction || "vertical",
		vert = direction === "vertical",
		size = vert ? "height" : "width",
		position = vert ? "top" : "left",
		animation = {},
		wrapper, animate, distance;

	// Save & Show
	$.effects.save( el, props );
	el.show();

	// Create Wrapper
	wrapper = $.effects.createWrapper( el ).css({
		overflow: "hidden"
	});
	animate = ( el[0].tagName === "IMG" ) ? wrapper : el;
	distance = animate[ size ]();

	// Shift
	if ( show ) {
		animate.css( size, 0 );
		animate.css( position, distance / 2 );
	}

	// Create Animation Object:
	animation[ size ] = show ? distance : 0;
	animation[ position ] = show ? 0 : distance / 2;

	// Animate
	animate.animate( animation, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: function() {
			if ( !show ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		}
	});

};


/*!
 * jQuery UI Effects Drop 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/drop-effect/
 */


var effectDrop = $.effects.effect.drop = function( o, done ) {

	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "hide" ),
		show = mode === "show",
		direction = o.direction || "left",
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg",
		animation = {
			opacity: show ? 1 : 0
		},
		distance;

	// Adjust
	$.effects.save( el, props );
	el.show();
	$.effects.createWrapper( el );

	distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ) / 2;

	if ( show ) {
		el
			.css( "opacity", 0 )
			.css( ref, motion === "pos" ? -distance : distance );
	}

	// Animation
	animation[ ref ] = ( show ?
		( motion === "pos" ? "+=" : "-=" ) :
		( motion === "pos" ? "-=" : "+=" ) ) +
		distance;

	// Animate
	el.animate( animation, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: function() {
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		}
	});
};


/*!
 * jQuery UI Effects Explode 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/explode-effect/
 */


var effectExplode = $.effects.effect.explode = function( o, done ) {

	var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3,
		cells = rows,
		el = $( this ),
		mode = $.effects.setMode( el, o.mode || "hide" ),
		show = mode === "show",

		// show and then visibility:hidden the element before calculating offset
		offset = el.show().css( "visibility", "hidden" ).offset(),

		// width and height of a piece
		width = Math.ceil( el.outerWidth() / cells ),
		height = Math.ceil( el.outerHeight() / rows ),
		pieces = [],

		// loop
		i, j, left, top, mx, my;

	// children animate complete:
	function childComplete() {
		pieces.push( this );
		if ( pieces.length === rows * cells ) {
			animComplete();
		}
	}

	// clone the element for each row and cell.
	for ( i = 0; i < rows ; i++ ) { // ===>
		top = offset.top + i * height;
		my = i - ( rows - 1 ) / 2 ;

		for ( j = 0; j < cells ; j++ ) { // |||
			left = offset.left + j * width;
			mx = j - ( cells - 1 ) / 2 ;

			// Create a clone of the now hidden main element that will be absolute positioned
			// within a wrapper div off the -left and -top equal to size of our pieces
			el
				.clone()
				.appendTo( "body" )
				.wrap( "<div></div>" )
				.css({
					position: "absolute",
					visibility: "visible",
					left: -j * width,
					top: -i * height
				})

			// select the wrapper - make it overflow: hidden and absolute positioned based on
			// where the original was located +left and +top equal to the size of pieces
				.parent()
				.addClass( "ui-effects-explode" )
				.css({
					position: "absolute",
					overflow: "hidden",
					width: width,
					height: height,
					left: left + ( show ? mx * width : 0 ),
					top: top + ( show ? my * height : 0 ),
					opacity: show ? 0 : 1
				}).animate({
					left: left + ( show ? 0 : mx * width ),
					top: top + ( show ? 0 : my * height ),
					opacity: show ? 1 : 0
				}, o.duration || 500, o.easing, childComplete );
		}
	}

	function animComplete() {
		el.css({
			visibility: "visible"
		});
		$( pieces ).remove();
		if ( !show ) {
			el.hide();
		}
		done();
	}
};


/*!
 * jQuery UI Effects Fade 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/fade-effect/
 */


var effectFade = $.effects.effect.fade = function( o, done ) {
	var el = $( this ),
		mode = $.effects.setMode( el, o.mode || "toggle" );

	el.animate({
		opacity: mode
	}, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: done
	});
};


/*!
 * jQuery UI Effects Fold 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/fold-effect/
 */


var effectFold = $.effects.effect.fold = function( o, done ) {

	// Create element
	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "hide" ),
		show = mode === "show",
		hide = mode === "hide",
		size = o.size || 15,
		percent = /([0-9]+)%/.exec( size ),
		horizFirst = !!o.horizFirst,
		widthFirst = show !== horizFirst,
		ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ],
		duration = o.duration / 2,
		wrapper, distance,
		animation1 = {},
		animation2 = {};

	$.effects.save( el, props );
	el.show();

	// Create Wrapper
	wrapper = $.effects.createWrapper( el ).css({
		overflow: "hidden"
	});
	distance = widthFirst ?
		[ wrapper.width(), wrapper.height() ] :
		[ wrapper.height(), wrapper.width() ];

	if ( percent ) {
		size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
	}
	if ( show ) {
		wrapper.css( horizFirst ? {
			height: 0,
			width: size
		} : {
			height: size,
			width: 0
		});
	}

	// Animation
	animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size;
	animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0;

	// Animate
	wrapper
		.animate( animation1, duration, o.easing )
		.animate( animation2, duration, o.easing, function() {
			if ( hide ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		});

};


/*!
 * jQuery UI Effects Highlight 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/highlight-effect/
 */


var effectHighlight = $.effects.effect.highlight = function( o, done ) {
	var elem = $( this ),
		props = [ "backgroundImage", "backgroundColor", "opacity" ],
		mode = $.effects.setMode( elem, o.mode || "show" ),
		animation = {
			backgroundColor: elem.css( "backgroundColor" )
		};

	if (mode === "hide") {
		animation.opacity = 0;
	}

	$.effects.save( elem, props );

	elem
		.show()
		.css({
			backgroundImage: "none",
			backgroundColor: o.color || "#ffff99"
		})
		.animate( animation, {
			queue: false,
			duration: o.duration,
			easing: o.easing,
			complete: function() {
				if ( mode === "hide" ) {
					elem.hide();
				}
				$.effects.restore( elem, props );
				done();
			}
		});
};


/*!
 * jQuery UI Effects Size 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/size-effect/
 */


var effectSize = $.effects.effect.size = function( o, done ) {

	// Create element
	var original, baseline, factor,
		el = $( this ),
		props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ],

		// Always restore
		props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ],

		// Copy for children
		props2 = [ "width", "height", "overflow" ],
		cProps = [ "fontSize" ],
		vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
		hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],

		// Set options
		mode = $.effects.setMode( el, o.mode || "effect" ),
		restore = o.restore || mode !== "effect",
		scale = o.scale || "both",
		origin = o.origin || [ "middle", "center" ],
		position = el.css( "position" ),
		props = restore ? props0 : props1,
		zero = {
			height: 0,
			width: 0,
			outerHeight: 0,
			outerWidth: 0
		};

	if ( mode === "show" ) {
		el.show();
	}
	original = {
		height: el.height(),
		width: el.width(),
		outerHeight: el.outerHeight(),
		outerWidth: el.outerWidth()
	};

	if ( o.mode === "toggle" && mode === "show" ) {
		el.from = o.to || zero;
		el.to = o.from || original;
	} else {
		el.from = o.from || ( mode === "show" ? zero : original );
		el.to = o.to || ( mode === "hide" ? zero : original );
	}

	// Set scaling factor
	factor = {
		from: {
			y: el.from.height / original.height,
			x: el.from.width / original.width
		},
		to: {
			y: el.to.height / original.height,
			x: el.to.width / original.width
		}
	};

	// Scale the css box
	if ( scale === "box" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			props = props.concat( vProps );
			el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from );
			el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to );
		}

		// Horizontal props scaling
		if ( factor.from.x !== factor.to.x ) {
			props = props.concat( hProps );
			el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from );
			el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to );
		}
	}

	// Scale the content
	if ( scale === "content" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			props = props.concat( cProps ).concat( props2 );
			el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from );
			el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to );
		}
	}

	$.effects.save( el, props );
	el.show();
	$.effects.createWrapper( el );
	el.css( "overflow", "hidden" ).css( el.from );

	// Adjust
	if (origin) { // Calculate baseline shifts
		baseline = $.effects.getBaseline( origin, original );
		el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y;
		el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x;
		el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y;
		el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x;
	}
	el.css( el.from ); // set top & left

	// Animate
	if ( scale === "content" || scale === "both" ) { // Scale the children

		// Add margins/font-size
		vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps);
		hProps = hProps.concat([ "marginLeft", "marginRight" ]);
		props2 = props0.concat(vProps).concat(hProps);

		el.find( "*[width]" ).each( function() {
			var child = $( this ),
				c_original = {
					height: child.height(),
					width: child.width(),
					outerHeight: child.outerHeight(),
					outerWidth: child.outerWidth()
				};
			if (restore) {
				$.effects.save(child, props2);
			}

			child.from = {
				height: c_original.height * factor.from.y,
				width: c_original.width * factor.from.x,
				outerHeight: c_original.outerHeight * factor.from.y,
				outerWidth: c_original.outerWidth * factor.from.x
			};
			child.to = {
				height: c_original.height * factor.to.y,
				width: c_original.width * factor.to.x,
				outerHeight: c_original.height * factor.to.y,
				outerWidth: c_original.width * factor.to.x
			};

			// Vertical props scaling
			if ( factor.from.y !== factor.to.y ) {
				child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from );
				child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to );
			}

			// Horizontal props scaling
			if ( factor.from.x !== factor.to.x ) {
				child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from );
				child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to );
			}

			// Animate children
			child.css( child.from );
			child.animate( child.to, o.duration, o.easing, function() {

				// Restore children
				if ( restore ) {
					$.effects.restore( child, props2 );
				}
			});
		});
	}

	// Animate
	el.animate( el.to, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: function() {
			if ( el.to.opacity === 0 ) {
				el.css( "opacity", el.from.opacity );
			}
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			if ( !restore ) {

				// we need to calculate our new positioning based on the scaling
				if ( position === "static" ) {
					el.css({
						position: "relative",
						top: el.to.top,
						left: el.to.left
					});
				} else {
					$.each([ "top", "left" ], function( idx, pos ) {
						el.css( pos, function( _, str ) {
							var val = parseInt( str, 10 ),
								toRef = idx ? el.to.left : el.to.top;

							// if original was "auto", recalculate the new value from wrapper
							if ( str === "auto" ) {
								return toRef + "px";
							}

							return val + toRef + "px";
						});
					});
				}
			}

			$.effects.removeWrapper( el );
			done();
		}
	});

};


/*!
 * jQuery UI Effects Scale 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/scale-effect/
 */


var effectScale = $.effects.effect.scale = function( o, done ) {

	// Create element
	var el = $( this ),
		options = $.extend( true, {}, o ),
		mode = $.effects.setMode( el, o.mode || "effect" ),
		percent = parseInt( o.percent, 10 ) ||
			( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ),
		direction = o.direction || "both",
		origin = o.origin,
		original = {
			height: el.height(),
			width: el.width(),
			outerHeight: el.outerHeight(),
			outerWidth: el.outerWidth()
		},
		factor = {
			y: direction !== "horizontal" ? (percent / 100) : 1,
			x: direction !== "vertical" ? (percent / 100) : 1
		};

	// We are going to pass this effect to the size effect:
	options.effect = "size";
	options.queue = false;
	options.complete = done;

	// Set default origin and restore for show/hide
	if ( mode !== "effect" ) {
		options.origin = origin || [ "middle", "center" ];
		options.restore = true;
	}

	options.from = o.from || ( mode === "show" ? {
		height: 0,
		width: 0,
		outerHeight: 0,
		outerWidth: 0
	} : original );
	options.to = {
		height: original.height * factor.y,
		width: original.width * factor.x,
		outerHeight: original.outerHeight * factor.y,
		outerWidth: original.outerWidth * factor.x
	};

	// Fade option to support puff
	if ( options.fade ) {
		if ( mode === "show" ) {
			options.from.opacity = 0;
			options.to.opacity = 1;
		}
		if ( mode === "hide" ) {
			options.from.opacity = 1;
			options.to.opacity = 0;
		}
	}

	// Animate
	el.effect( options );

};


/*!
 * jQuery UI Effects Puff 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/puff-effect/
 */


var effectPuff = $.effects.effect.puff = function( o, done ) {
	var elem = $( this ),
		mode = $.effects.setMode( elem, o.mode || "hide" ),
		hide = mode === "hide",
		percent = parseInt( o.percent, 10 ) || 150,
		factor = percent / 100,
		original = {
			height: elem.height(),
			width: elem.width(),
			outerHeight: elem.outerHeight(),
			outerWidth: elem.outerWidth()
		};

	$.extend( o, {
		effect: "scale",
		queue: false,
		fade: true,
		mode: mode,
		complete: done,
		percent: hide ? percent : 100,
		from: hide ?
			original :
			{
				height: original.height * factor,
				width: original.width * factor,
				outerHeight: original.outerHeight * factor,
				outerWidth: original.outerWidth * factor
			}
	});

	elem.effect( o );
};


/*!
 * jQuery UI Effects Pulsate 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/pulsate-effect/
 */


var effectPulsate = $.effects.effect.pulsate = function( o, done ) {
	var elem = $( this ),
		mode = $.effects.setMode( elem, o.mode || "show" ),
		show = mode === "show",
		hide = mode === "hide",
		showhide = ( show || mode === "hide" ),

		// showing or hiding leaves of the "last" animation
		anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
		duration = o.duration / anims,
		animateTo = 0,
		queue = elem.queue(),
		queuelen = queue.length,
		i;

	if ( show || !elem.is(":visible")) {
		elem.css( "opacity", 0 ).show();
		animateTo = 1;
	}

	// anims - 1 opacity "toggles"
	for ( i = 1; i < anims; i++ ) {
		elem.animate({
			opacity: animateTo
		}, duration, o.easing );
		animateTo = 1 - animateTo;
	}

	elem.animate({
		opacity: animateTo
	}, duration, o.easing);

	elem.queue(function() {
		if ( hide ) {
			elem.hide();
		}
		done();
	});

	// We just queued up "anims" animations, we need to put them next in the queue
	if ( queuelen > 1 ) {
		queue.splice.apply( queue,
			[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
	}
	elem.dequeue();
};


/*!
 * jQuery UI Effects Shake 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/shake-effect/
 */


var effectShake = $.effects.effect.shake = function( o, done ) {

	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "effect" ),
		direction = o.direction || "left",
		distance = o.distance || 20,
		times = o.times || 3,
		anims = times * 2 + 1,
		speed = Math.round( o.duration / anims ),
		ref = (direction === "up" || direction === "down") ? "top" : "left",
		positiveMotion = (direction === "up" || direction === "left"),
		animation = {},
		animation1 = {},
		animation2 = {},
		i,

		// we will need to re-assemble the queue to stack our animations in place
		queue = el.queue(),
		queuelen = queue.length;

	$.effects.save( el, props );
	el.show();
	$.effects.createWrapper( el );

	// Animation
	animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
	animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
	animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;

	// Animate
	el.animate( animation, speed, o.easing );

	// Shakes
	for ( i = 1; i < times; i++ ) {
		el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing );
	}
	el
		.animate( animation1, speed, o.easing )
		.animate( animation, speed / 2, o.easing )
		.queue(function() {
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		});

	// inject all the animations we just queued to be first in line (after "inprogress")
	if ( queuelen > 1) {
		queue.splice.apply( queue,
			[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
	}
	el.dequeue();

};


/*!
 * jQuery UI Effects Slide 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/slide-effect/
 */


var effectSlide = $.effects.effect.slide = function( o, done ) {

	// Create element
	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "width", "height" ],
		mode = $.effects.setMode( el, o.mode || "show" ),
		show = mode === "show",
		direction = o.direction || "left",
		ref = (direction === "up" || direction === "down") ? "top" : "left",
		positiveMotion = (direction === "up" || direction === "left"),
		distance,
		animation = {};

	// Adjust
	$.effects.save( el, props );
	el.show();
	distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true );

	$.effects.createWrapper( el ).css({
		overflow: "hidden"
	});

	if ( show ) {
		el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance );
	}

	// Animation
	animation[ ref ] = ( show ?
		( positiveMotion ? "+=" : "-=") :
		( positiveMotion ? "-=" : "+=")) +
		distance;

	// Animate
	el.animate( animation, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: function() {
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		}
	});
};


/*!
 * jQuery UI Effects Transfer 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/transfer-effect/
 */


var effectTransfer = $.effects.effect.transfer = function( o, done ) {
	var elem = $( this ),
		target = $( o.to ),
		targetFixed = target.css( "position" ) === "fixed",
		body = $("body"),
		fixTop = targetFixed ? body.scrollTop() : 0,
		fixLeft = targetFixed ? body.scrollLeft() : 0,
		endPosition = target.offset(),
		animation = {
			top: endPosition.top - fixTop,
			left: endPosition.left - fixLeft,
			height: target.innerHeight(),
			width: target.innerWidth()
		},
		startPosition = elem.offset(),
		transfer = $( "<div class='ui-effects-transfer'></div>" )
			.appendTo( document.body )
			.addClass( o.className )
			.css({
				top: startPosition.top - fixTop,
				left: startPosition.left - fixLeft,
				height: elem.innerHeight(),
				width: elem.innerWidth(),
				position: targetFixed ? "fixed" : "absolute"
			})
			.animate( animation, o.duration, o.easing, function() {
				transfer.remove();
				done();
			});
};


/*!
 * jQuery UI Progressbar 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/progressbar/
 */


var progressbar = $.widget( "ui.progressbar", {
	version: "1.11.4",
	options: {
		max: 100,
		value: 0,

		change: null,
		complete: null
	},

	min: 0,

	_create: function() {
		// Constrain initial value
		this.oldValue = this.options.value = this._constrainedValue();

		this.element
			.addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
			.attr({
				// Only set static values, aria-valuenow and aria-valuemax are
				// set inside _refreshValue()
				role: "progressbar",
				"aria-valuemin": this.min
			});

		this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" )
			.appendTo( this.element );

		this._refreshValue();
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
			.removeAttr( "role" )
			.removeAttr( "aria-valuemin" )
			.removeAttr( "aria-valuemax" )
			.removeAttr( "aria-valuenow" );

		this.valueDiv.remove();
	},

	value: function( newValue ) {
		if ( newValue === undefined ) {
			return this.options.value;
		}

		this.options.value = this._constrainedValue( newValue );
		this._refreshValue();
	},

	_constrainedValue: function( newValue ) {
		if ( newValue === undefined ) {
			newValue = this.options.value;
		}

		this.indeterminate = newValue === false;

		// sanitize value
		if ( typeof newValue !== "number" ) {
			newValue = 0;
		}

		return this.indeterminate ? false :
			Math.min( this.options.max, Math.max( this.min, newValue ) );
	},

	_setOptions: function( options ) {
		// Ensure "value" option is set after other values (like max)
		var value = options.value;
		delete options.value;

		this._super( options );

		this.options.value = this._constrainedValue( value );
		this._refreshValue();
	},

	_setOption: function( key, value ) {
		if ( key === "max" ) {
			// Don't allow a max less than min
			value = Math.max( this.min, value );
		}
		if ( key === "disabled" ) {
			this.element
				.toggleClass( "ui-state-disabled", !!value )
				.attr( "aria-disabled", value );
		}
		this._super( key, value );
	},

	_percentage: function() {
		return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min );
	},

	_refreshValue: function() {
		var value = this.options.value,
			percentage = this._percentage();

		this.valueDiv
			.toggle( this.indeterminate || value > this.min )
			.toggleClass( "ui-corner-right", value === this.options.max )
			.width( percentage.toFixed(0) + "%" );

		this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate );

		if ( this.indeterminate ) {
			this.element.removeAttr( "aria-valuenow" );
			if ( !this.overlayDiv ) {
				this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv );
			}
		} else {
			this.element.attr({
				"aria-valuemax": this.options.max,
				"aria-valuenow": value
			});
			if ( this.overlayDiv ) {
				this.overlayDiv.remove();
				this.overlayDiv = null;
			}
		}

		if ( this.oldValue !== value ) {
			this.oldValue = value;
			this._trigger( "change" );
		}
		if ( value === this.options.max ) {
			this._trigger( "complete" );
		}
	}
});


/*!
 * jQuery UI Selectable 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/selectable/
 */


var selectable = $.widget("ui.selectable", $.ui.mouse, {
	version: "1.11.4",
	options: {
		appendTo: "body",
		autoRefresh: true,
		distance: 0,
		filter: "*",
		tolerance: "touch",

		// callbacks
		selected: null,
		selecting: null,
		start: null,
		stop: null,
		unselected: null,
		unselecting: null
	},
	_create: function() {
		var selectees,
			that = this;

		this.element.addClass("ui-selectable");

		this.dragged = false;

		// cache selectee children based on filter
		this.refresh = function() {
			selectees = $(that.options.filter, that.element[0]);
			selectees.addClass("ui-selectee");
			selectees.each(function() {
				var $this = $(this),
					pos = $this.offset();
				$.data(this, "selectable-item", {
					element: this,
					$element: $this,
					left: pos.left,
					top: pos.top,
					right: pos.left + $this.outerWidth(),
					bottom: pos.top + $this.outerHeight(),
					startselected: false,
					selected: $this.hasClass("ui-selected"),
					selecting: $this.hasClass("ui-selecting"),
					unselecting: $this.hasClass("ui-unselecting")
				});
			});
		};
		this.refresh();

		this.selectees = selectees.addClass("ui-selectee");

		this._mouseInit();

		this.helper = $("<div class='ui-selectable-helper'></div>");
	},

	_destroy: function() {
		this.selectees
			.removeClass("ui-selectee")
			.removeData("selectable-item");
		this.element
			.removeClass("ui-selectable ui-selectable-disabled");
		this._mouseDestroy();
	},

	_mouseStart: function(event) {
		var that = this,
			options = this.options;

		this.opos = [ event.pageX, event.pageY ];

		if (this.options.disabled) {
			return;
		}

		this.selectees = $(options.filter, this.element[0]);

		this._trigger("start", event);

		$(options.appendTo).append(this.helper);
		// position helper (lasso)
		this.helper.css({
			"left": event.pageX,
			"top": event.pageY,
			"width": 0,
			"height": 0
		});

		if (options.autoRefresh) {
			this.refresh();
		}

		this.selectees.filter(".ui-selected").each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.startselected = true;
			if (!event.metaKey && !event.ctrlKey) {
				selectee.$element.removeClass("ui-selected");
				selectee.selected = false;
				selectee.$element.addClass("ui-unselecting");
				selectee.unselecting = true;
				// selectable UNSELECTING callback
				that._trigger("unselecting", event, {
					unselecting: selectee.element
				});
			}
		});

		$(event.target).parents().addBack().each(function() {
			var doSelect,
				selectee = $.data(this, "selectable-item");
			if (selectee) {
				doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected");
				selectee.$element
					.removeClass(doSelect ? "ui-unselecting" : "ui-selected")
					.addClass(doSelect ? "ui-selecting" : "ui-unselecting");
				selectee.unselecting = !doSelect;
				selectee.selecting = doSelect;
				selectee.selected = doSelect;
				// selectable (UN)SELECTING callback
				if (doSelect) {
					that._trigger("selecting", event, {
						selecting: selectee.element
					});
				} else {
					that._trigger("unselecting", event, {
						unselecting: selectee.element
					});
				}
				return false;
			}
		});

	},

	_mouseDrag: function(event) {

		this.dragged = true;

		if (this.options.disabled) {
			return;
		}

		var tmp,
			that = this,
			options = this.options,
			x1 = this.opos[0],
			y1 = this.opos[1],
			x2 = event.pageX,
			y2 = event.pageY;

		if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; }
		if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; }
		this.helper.css({ left: x1, top: y1, width: x2 - x1, height: y2 - y1 });

		this.selectees.each(function() {
			var selectee = $.data(this, "selectable-item"),
				hit = false;

			//prevent helper from being selected if appendTo: selectable
			if (!selectee || selectee.element === that.element[0]) {
				return;
			}

			if (options.tolerance === "touch") {
				hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) );
			} else if (options.tolerance === "fit") {
				hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
			}

			if (hit) {
				// SELECT
				if (selectee.selected) {
					selectee.$element.removeClass("ui-selected");
					selectee.selected = false;
				}
				if (selectee.unselecting) {
					selectee.$element.removeClass("ui-unselecting");
					selectee.unselecting = false;
				}
				if (!selectee.selecting) {
					selectee.$element.addClass("ui-selecting");
					selectee.selecting = true;
					// selectable SELECTING callback
					that._trigger("selecting", event, {
						selecting: selectee.element
					});
				}
			} else {
				// UNSELECT
				if (selectee.selecting) {
					if ((event.metaKey || event.ctrlKey) && selectee.startselected) {
						selectee.$element.removeClass("ui-selecting");
						selectee.selecting = false;
						selectee.$element.addClass("ui-selected");
						selectee.selected = true;
					} else {
						selectee.$element.removeClass("ui-selecting");
						selectee.selecting = false;
						if (selectee.startselected) {
							selectee.$element.addClass("ui-unselecting");
							selectee.unselecting = true;
						}
						// selectable UNSELECTING callback
						that._trigger("unselecting", event, {
							unselecting: selectee.element
						});
					}
				}
				if (selectee.selected) {
					if (!event.metaKey && !event.ctrlKey && !selectee.startselected) {
						selectee.$element.removeClass("ui-selected");
						selectee.selected = false;

						selectee.$element.addClass("ui-unselecting");
						selectee.unselecting = true;
						// selectable UNSELECTING callback
						that._trigger("unselecting", event, {
							unselecting: selectee.element
						});
					}
				}
			}
		});

		return false;
	},

	_mouseStop: function(event) {
		var that = this;

		this.dragged = false;

		$(".ui-unselecting", this.element[0]).each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.$element.removeClass("ui-unselecting");
			selectee.unselecting = false;
			selectee.startselected = false;
			that._trigger("unselected", event, {
				unselected: selectee.element
			});
		});
		$(".ui-selecting", this.element[0]).each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.$element.removeClass("ui-selecting").addClass("ui-selected");
			selectee.selecting = false;
			selectee.selected = true;
			selectee.startselected = true;
			that._trigger("selected", event, {
				selected: selectee.element
			});
		});
		this._trigger("stop", event);

		this.helper.remove();

		return false;
	}

});


/*!
 * jQuery UI Selectmenu 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/selectmenu
 */


var selectmenu = $.widget( "ui.selectmenu", {
	version: "1.11.4",
	defaultElement: "<select>",
	options: {
		appendTo: null,
		disabled: null,
		icons: {
			button: "ui-icon-triangle-1-s"
		},
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		width: null,

		// callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		select: null
	},

	_create: function() {
		var selectmenuId = this.element.uniqueId().attr( "id" );
		this.ids = {
			element: selectmenuId,
			button: selectmenuId + "-button",
			menu: selectmenuId + "-menu"
		};

		this._drawButton();
		this._drawMenu();

		if ( this.options.disabled ) {
			this.disable();
		}
	},

	_drawButton: function() {
		var that = this;

		// Associate existing label with the new button
		this.label = $( "label[for='" + this.ids.element + "']" ).attr( "for", this.ids.button );
		this._on( this.label, {
			click: function( event ) {
				this.button.focus();
				event.preventDefault();
			}
		});

		// Hide original select element
		this.element.hide();

		// Create button
		this.button = $( "<span>", {
			"class": "ui-selectmenu-button ui-widget ui-state-default ui-corner-all",
			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"
		})
			.insertAfter( this.element );

		$( "<span>", {
			"class": "ui-icon " + this.options.icons.button
		})
			.prependTo( this.button );

		this.buttonText = $( "<span>", {
			"class": "ui-selectmenu-text"
		})
			.appendTo( this.button );

		this._setText( this.buttonText, this.element.find( "option:selected" ).text() );
		this._resizeButton();

		this._on( this.button, this._buttonEvents );
		this.button.one( "focusin", function() {

			// Delay rendering the menu items until the button receives focus.
			// The menu may have already been rendered via a programmatic open.
			if ( !that.menuItems ) {
				that._refreshMenu();
			}
		});
		this._hoverable( this.button );
		this._focusable( this.button );
	},

	_drawMenu: function() {
		var that = this;

		// Create menu
		this.menu = $( "<ul>", {
			"aria-hidden": "true",
			"aria-labelledby": this.ids.button,
			id: this.ids.menu
		});

		// Wrap menu
		this.menuWrap = $( "<div>", {
			"class": "ui-selectmenu-menu ui-front"
		})
			.append( this.menu )
			.appendTo( this._appendTo() );

		// Initialize menu widget
		this.menuInstance = this.menu
			.menu({
				role: "listbox",
				select: function( event, ui ) {
					event.preventDefault();

					// support: IE8
					// If the item was selected via a click, the text selection
					// will be destroyed in IE
					that._setSelection();

					that._select( ui.item.data( "ui-selectmenu-item" ), event );
				},
				focus: function( event, ui ) {
					var item = ui.item.data( "ui-selectmenu-item" );

					// Prevent inital focus from firing and check if its a newly focused item
					if ( that.focusIndex != null && item.index !== that.focusIndex ) {
						that._trigger( "focus", event, { item: item } );
						if ( !that.isOpen ) {
							that._select( item, event );
						}
					}
					that.focusIndex = item.index;

					that.button.attr( "aria-activedescendant",
						that.menuItems.eq( item.index ).attr( "id" ) );
				}
			})
			.menu( "instance" );

		// Adjust menu styles to dropdown
		this.menu
			.addClass( "ui-corner-bottom" )
			.removeClass( "ui-corner-all" );

		// Don't close the menu on mouseleave
		this.menuInstance._off( this.menu, "mouseleave" );

		// Cancel the menu's collapseAll on document click
		this.menuInstance._closeOnDocumentClick = function() {
			return false;
		};

		// Selects often contain empty items, but never contain dividers
		this.menuInstance._isDivider = function() {
			return false;
		};
	},

	refresh: function() {
		this._refreshMenu();
		this._setText( this.buttonText, this._getSelectedItem().text() );
		if ( !this.options.width ) {
			this._resizeButton();
		}
	},

	_refreshMenu: function() {
		this.menu.empty();

		var item,
			options = this.element.find( "option" );

		if ( !options.length ) {
			return;
		}

		this._parseOptions( options );
		this._renderMenu( this.menu, this.items );

		this.menuInstance.refresh();
		this.menuItems = this.menu.find( "li" ).not( ".ui-selectmenu-optgroup" );

		item = this._getSelectedItem();

		// Update the menu to have the correct item focused
		this.menuInstance.focus( null, item );
		this._setAria( item.data( "ui-selectmenu-item" ) );

		// Set disabled state
		this._setOption( "disabled", this.element.prop( "disabled" ) );
	},

	open: function( event ) {
		if ( this.options.disabled ) {
			return;
		}

		// If this is the first time the menu is being opened, render the items
		if ( !this.menuItems ) {
			this._refreshMenu();
		} else {

			// Menu clears focus on close, reset focus to selected item
			this.menu.find( ".ui-state-focus" ).removeClass( "ui-state-focus" );
			this.menuInstance.focus( null, this._getSelectedItem() );
		}

		this.isOpen = true;
		this._toggleAttr();
		this._resizeMenu();
		this._position();

		this._on( this.document, this._documentClick );

		this._trigger( "open", event );
	},

	_position: function() {
		this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) );
	},

	close: function( event ) {
		if ( !this.isOpen ) {
			return;
		}

		this.isOpen = false;
		this._toggleAttr();

		this.range = null;
		this._off( this.document );

		this._trigger( "close", event );
	},

	widget: function() {
		return this.button;
	},

	menuWidget: function() {
		return this.menu;
	},

	_renderMenu: function( ul, items ) {
		var that = this,
			currentOptgroup = "";

		$.each( items, function( index, item ) {
			if ( item.optgroup !== currentOptgroup ) {
				$( "<li>", {
					"class": "ui-selectmenu-optgroup ui-menu-divider" +
						( item.element.parent( "optgroup" ).prop( "disabled" ) ?
							" ui-state-disabled" :
							"" ),
					text: item.optgroup
				})
					.appendTo( ul );

				currentOptgroup = item.optgroup;
			}

			that._renderItemData( ul, item );
		});
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-selectmenu-item", item );
	},

	_renderItem: function( ul, item ) {
		var li = $( "<li>" );

		if ( item.disabled ) {
			li.addClass( "ui-state-disabled" );
		}
		this._setText( li, item.label );

		return li.appendTo( ul );
	},

	_setText: function( element, value ) {
		if ( value ) {
			element.text( value );
		} else {
			element.html( "&#160;" );
		}
	},

	_move: function( direction, event ) {
		var item, next,
			filter = ".ui-menu-item";

		if ( this.isOpen ) {
			item = this.menuItems.eq( this.focusIndex );
		} else {
			item = this.menuItems.eq( this.element[ 0 ].selectedIndex );
			filter += ":not(.ui-state-disabled)";
		}

		if ( direction === "first" || direction === "last" ) {
			next = item[ direction === "first" ? "prevAll" : "nextAll" ]( filter ).eq( -1 );
		} else {
			next = item[ direction + "All" ]( filter ).eq( 0 );
		}

		if ( next.length ) {
			this.menuInstance.focus( event, next );
		}
	},

	_getSelectedItem: function() {
		return this.menuItems.eq( this.element[ 0 ].selectedIndex );
	},

	_toggle: function( event ) {
		this[ this.isOpen ? "close" : "open" ]( event );
	},

	_setSelection: function() {
		var selection;

		if ( !this.range ) {
			return;
		}

		if ( window.getSelection ) {
			selection = window.getSelection();
			selection.removeAllRanges();
			selection.addRange( this.range );

		// support: IE8
		} else {
			this.range.select();
		}

		// support: IE
		// Setting the text selection kills the button focus in IE, but
		// restoring the focus doesn't kill the selection.
		this.button.focus();
	},

	_documentClick: {
		mousedown: function( event ) {
			if ( !this.isOpen ) {
				return;
			}

			if ( !$( event.target ).closest( ".ui-selectmenu-menu, #" + this.ids.button ).length ) {
				this.close( event );
			}
		}
	},

	_buttonEvents: {

		// Prevent text selection from being reset when interacting with the selectmenu (#10144)
		mousedown: function() {
			var selection;

			if ( window.getSelection ) {
				selection = window.getSelection();
				if ( selection.rangeCount ) {
					this.range = selection.getRangeAt( 0 );
				}

			// support: IE8
			} else {
				this.range = document.selection.createRange();
			}
		},

		click: function( event ) {
			this._setSelection();
			this._toggle( event );
		},

		keydown: function( event ) {
			var preventDefault = true;
			switch ( event.keyCode ) {
				case $.ui.keyCode.TAB:
				case $.ui.keyCode.ESCAPE:
					this.close( event );
					preventDefault = false;
					break;
				case $.ui.keyCode.ENTER:
					if ( this.isOpen ) {
						this._selectFocusedItem( event );
					}
					break;
				case $.ui.keyCode.UP:
					if ( event.altKey ) {
						this._toggle( event );
					} else {
						this._move( "prev", event );
					}
					break;
				case $.ui.keyCode.DOWN:
					if ( event.altKey ) {
						this._toggle( event );
					} else {
						this._move( "next", event );
					}
					break;
				case $.ui.keyCode.SPACE:
					if ( this.isOpen ) {
						this._selectFocusedItem( event );
					} else {
						this._toggle( event );
					}
					break;
				case $.ui.keyCode.LEFT:
					this._move( "prev", event );
					break;
				case $.ui.keyCode.RIGHT:
					this._move( "next", event );
					break;
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.PAGE_UP:
					this._move( "first", event );
					break;
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_DOWN:
					this._move( "last", event );
					break;
				default:
					this.menu.trigger( event );
					preventDefault = false;
			}

			if ( preventDefault ) {
				event.preventDefault();
			}
		}
	},

	_selectFocusedItem: function( event ) {
		var item = this.menuItems.eq( this.focusIndex );
		if ( !item.hasClass( "ui-state-disabled" ) ) {
			this._select( item.data( "ui-selectmenu-item" ), event );
		}
	},

	_select: function( item, event ) {
		var oldIndex = this.element[ 0 ].selectedIndex;

		// Change native select element
		this.element[ 0 ].selectedIndex = item.index;
		this._setText( this.buttonText, item.label );
		this._setAria( item );
		this._trigger( "select", event, { item: item } );

		if ( item.index !== oldIndex ) {
			this._trigger( "change", event, { item: item } );
		}

		this.close( event );
	},

	_setAria: function( item ) {
		var id = this.menuItems.eq( item.index ).attr( "id" );

		this.button.attr({
			"aria-labelledby": id,
			"aria-activedescendant": id
		});
		this.menu.attr( "aria-activedescendant", id );
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			this.button.find( "span.ui-icon" )
				.removeClass( this.options.icons.button )
				.addClass( value.button );
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.menuWrap.appendTo( this._appendTo() );
		}

		if ( key === "disabled" ) {
			this.menuInstance.option( "disabled", value );
			this.button
				.toggleClass( "ui-state-disabled", value )
				.attr( "aria-disabled", value );

			this.element.prop( "disabled", value );
			if ( value ) {
				this.button.attr( "tabindex", -1 );
				this.close();
			} else {
				this.button.attr( "tabindex", 0 );
			}
		}

		if ( key === "width" ) {
			this._resizeButton();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element || !element[ 0 ] ) {
			element = this.element.closest( ".ui-front" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_toggleAttr: function() {
		this.button
			.toggleClass( "ui-corner-top", this.isOpen )
			.toggleClass( "ui-corner-all", !this.isOpen )
			.attr( "aria-expanded", this.isOpen );
		this.menuWrap.toggleClass( "ui-selectmenu-open", this.isOpen );
		this.menu.attr( "aria-hidden", !this.isOpen );
	},

	_resizeButton: function() {
		var width = this.options.width;

		if ( !width ) {
			width = this.element.show().outerWidth();
			this.element.hide();
		}

		this.button.outerWidth( width );
	},

	_resizeMenu: function() {
		this.menu.outerWidth( Math.max(
			this.button.outerWidth(),

			// support: IE10
			// IE10 wraps long text (possibly a rounding bug)
			// so we add 1px to avoid the wrapping
			this.menu.width( "" ).outerWidth() + 1
		) );
	},

	_getCreateOptions: function() {
		return { disabled: this.element.prop( "disabled" ) };
	},

	_parseOptions: function( options ) {
		var data = [];
		options.each(function( index, item ) {
			var option = $( item ),
				optgroup = option.parent( "optgroup" );
			data.push({
				element: option,
				index: index,
				value: option.val(),
				label: option.text(),
				optgroup: optgroup.attr( "label" ) || "",
				disabled: optgroup.prop( "disabled" ) || option.prop( "disabled" )
			});
		});
		this.items = data;
	},

	_destroy: function() {
		this.menuWrap.remove();
		this.button.remove();
		this.element.show();
		this.element.removeUniqueId();
		this.label.attr( "for", this.ids.element );
	}
});


/*!
 * jQuery UI Slider 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/slider/
 */


var slider = $.widget( "ui.slider", $.ui.mouse, {
	version: "1.11.4",
	widgetEventPrefix: "slide",

	options: {
		animate: false,
		distance: 0,
		max: 100,
		min: 0,
		orientation: "horizontal",
		range: false,
		step: 1,
		value: 0,
		values: null,

		// callbacks
		change: null,
		slide: null,
		start: null,
		stop: null
	},

	// number of pages in a slider
	// (how many times can you page up/down to go through the whole range)
	numPages: 5,

	_create: function() {
		this._keySliding = false;
		this._mouseSliding = false;
		this._animateOff = true;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();
		this._calculateNewMax();

		this.element
			.addClass( "ui-slider" +
				" ui-slider-" + this.orientation +
				" ui-widget" +
				" ui-widget-content" +
				" ui-corner-all");

		this._refresh();
		this._setOption( "disabled", this.options.disabled );

		this._animateOff = false;
	},

	_refresh: function() {
		this._createRange();
		this._createHandles();
		this._setupEvents();
		this._refreshValue();
	},

	_createHandles: function() {
		var i, handleCount,
			options = this.options,
			existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ),
			handle = "<span class='ui-slider-handle ui-state-default ui-corner-all' tabindex='0'></span>",
			handles = [];

		handleCount = ( options.values && options.values.length ) || 1;

		if ( existingHandles.length > handleCount ) {
			existingHandles.slice( handleCount ).remove();
			existingHandles = existingHandles.slice( 0, handleCount );
		}

		for ( i = existingHandles.length; i < handleCount; i++ ) {
			handles.push( handle );
		}

		this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );

		this.handle = this.handles.eq( 0 );

		this.handles.each(function( i ) {
			$( this ).data( "ui-slider-handle-index", i );
		});
	},

	_createRange: function() {
		var options = this.options,
			classes = "";

		if ( options.range ) {
			if ( options.range === true ) {
				if ( !options.values ) {
					options.values = [ this._valueMin(), this._valueMin() ];
				} else if ( options.values.length && options.values.length !== 2 ) {
					options.values = [ options.values[0], options.values[0] ];
				} else if ( $.isArray( options.values ) ) {
					options.values = options.values.slice(0);
				}
			}

			if ( !this.range || !this.range.length ) {
				this.range = $( "<div></div>" )
					.appendTo( this.element );

				classes = "ui-slider-range" +
				// note: this isn't the most fittingly semantic framework class for this element,
				// but worked best visually with a variety of themes
				" ui-widget-header ui-corner-all";
			} else {
				this.range.removeClass( "ui-slider-range-min ui-slider-range-max" )
					// Handle range switching from true to min/max
					.css({
						"left": "",
						"bottom": ""
					});
			}

			this.range.addClass( classes +
				( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) );
		} else {
			if ( this.range ) {
				this.range.remove();
			}
			this.range = null;
		}
	},

	_setupEvents: function() {
		this._off( this.handles );
		this._on( this.handles, this._handleEvents );
		this._hoverable( this.handles );
		this._focusable( this.handles );
	},

	_destroy: function() {
		this.handles.remove();
		if ( this.range ) {
			this.range.remove();
		}

		this.element
			.removeClass( "ui-slider" +
				" ui-slider-horizontal" +
				" ui-slider-vertical" +
				" ui-widget" +
				" ui-widget-content" +
				" ui-corner-all" );

		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
			that = this,
			o = this.options;

		if ( o.disabled ) {
			return false;
		}

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		position = { x: event.pageX, y: event.pageY };
		normValue = this._normValueFromMouse( position );
		distance = this._valueMax() - this._valueMin() + 1;
		this.handles.each(function( i ) {
			var thisDistance = Math.abs( normValue - that.values(i) );
			if (( distance > thisDistance ) ||
				( distance === thisDistance &&
					(i === that._lastChangedValue || that.values(i) === o.min ))) {
				distance = thisDistance;
				closestHandle = $( this );
				index = i;
			}
		});

		allowed = this._start( event, index );
		if ( allowed === false ) {
			return false;
		}
		this._mouseSliding = true;

		this._handleIndex = index;

		closestHandle
			.addClass( "ui-state-active" )
			.focus();

		offset = closestHandle.offset();
		mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
			top: event.pageY - offset.top -
				( closestHandle.height() / 2 ) -
				( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) -
				( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) +
				( parseInt( closestHandle.css("marginTop"), 10 ) || 0)
		};

		if ( !this.handles.hasClass( "ui-state-hover" ) ) {
			this._slide( event, index, normValue );
		}
		this._animateOff = true;
		return true;
	},

	_mouseStart: function() {
		return true;
	},

	_mouseDrag: function( event ) {
		var position = { x: event.pageX, y: event.pageY },
			normValue = this._normValueFromMouse( position );

		this._slide( event, this._handleIndex, normValue );

		return false;
	},

	_mouseStop: function( event ) {
		this.handles.removeClass( "ui-state-active" );
		this._mouseSliding = false;

		this._stop( event, this._handleIndex );
		this._change( event, this._handleIndex );

		this._handleIndex = null;
		this._clickOffset = null;
		this._animateOff = false;

		return false;
	},

	_detectOrientation: function() {
		this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
	},

	_normValueFromMouse: function( position ) {
		var pixelTotal,
			pixelMouse,
			percentMouse,
			valueTotal,
			valueMouse;

		if ( this.orientation === "horizontal" ) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 );
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 );
		}

		percentMouse = ( pixelMouse / pixelTotal );
		if ( percentMouse > 1 ) {
			percentMouse = 1;
		}
		if ( percentMouse < 0 ) {
			percentMouse = 0;
		}
		if ( this.orientation === "vertical" ) {
			percentMouse = 1 - percentMouse;
		}

		valueTotal = this._valueMax() - this._valueMin();
		valueMouse = this._valueMin() + percentMouse * valueTotal;

		return this._trimAlignValue( valueMouse );
	},

	_start: function( event, index ) {
		var uiHash = {
			handle: this.handles[ index ],
			value: this.value()
		};
		if ( this.options.values && this.options.values.length ) {
			uiHash.value = this.values( index );
			uiHash.values = this.values();
		}
		return this._trigger( "start", event, uiHash );
	},

	_slide: function( event, index, newVal ) {
		var otherVal,
			newValues,
			allowed;

		if ( this.options.values && this.options.values.length ) {
			otherVal = this.values( index ? 0 : 1 );

			if ( ( this.options.values.length === 2 && this.options.range === true ) &&
					( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
				) {
				newVal = otherVal;
			}

			if ( newVal !== this.values( index ) ) {
				newValues = this.values();
				newValues[ index ] = newVal;
				// A slide can be canceled by returning false from the slide callback
				allowed = this._trigger( "slide", event, {
					handle: this.handles[ index ],
					value: newVal,
					values: newValues
				} );
				otherVal = this.values( index ? 0 : 1 );
				if ( allowed !== false ) {
					this.values( index, newVal );
				}
			}
		} else {
			if ( newVal !== this.value() ) {
				// A slide can be canceled by returning false from the slide callback
				allowed = this._trigger( "slide", event, {
					handle: this.handles[ index ],
					value: newVal
				} );
				if ( allowed !== false ) {
					this.value( newVal );
				}
			}
		}
	},

	_stop: function( event, index ) {
		var uiHash = {
			handle: this.handles[ index ],
			value: this.value()
		};
		if ( this.options.values && this.options.values.length ) {
			uiHash.value = this.values( index );
			uiHash.values = this.values();
		}

		this._trigger( "stop", event, uiHash );
	},

	_change: function( event, index ) {
		if ( !this._keySliding && !this._mouseSliding ) {
			var uiHash = {
				handle: this.handles[ index ],
				value: this.value()
			};
			if ( this.options.values && this.options.values.length ) {
				uiHash.value = this.values( index );
				uiHash.values = this.values();
			}

			//store the last changed value index for reference when handles overlap
			this._lastChangedValue = index;

			this._trigger( "change", event, uiHash );
		}
	},

	value: function( newValue ) {
		if ( arguments.length ) {
			this.options.value = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, 0 );
			return;
		}

		return this._value();
	},

	values: function( index, newValue ) {
		var vals,
			newValues,
			i;

		if ( arguments.length > 1 ) {
			this.options.values[ index ] = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, index );
			return;
		}

		if ( arguments.length ) {
			if ( $.isArray( arguments[ 0 ] ) ) {
				vals = this.options.values;
				newValues = arguments[ 0 ];
				for ( i = 0; i < vals.length; i += 1 ) {
					vals[ i ] = this._trimAlignValue( newValues[ i ] );
					this._change( null, i );
				}
				this._refreshValue();
			} else {
				if ( this.options.values && this.options.values.length ) {
					return this._values( index );
				} else {
					return this.value();
				}
			}
		} else {
			return this._values();
		}
	},

	_setOption: function( key, value ) {
		var i,
			valsLength = 0;

		if ( key === "range" && this.options.range === true ) {
			if ( value === "min" ) {
				this.options.value = this._values( 0 );
				this.options.values = null;
			} else if ( value === "max" ) {
				this.options.value = this._values( this.options.values.length - 1 );
				this.options.values = null;
			}
		}

		if ( $.isArray( this.options.values ) ) {
			valsLength = this.options.values.length;
		}

		if ( key === "disabled" ) {
			this.element.toggleClass( "ui-state-disabled", !!value );
		}

		this._super( key, value );

		switch ( key ) {
			case "orientation":
				this._detectOrientation();
				this.element
					.removeClass( "ui-slider-horizontal ui-slider-vertical" )
					.addClass( "ui-slider-" + this.orientation );
				this._refreshValue();

				// Reset positioning from previous orientation
				this.handles.css( value === "horizontal" ? "bottom" : "left", "" );
				break;
			case "value":
				this._animateOff = true;
				this._refreshValue();
				this._change( null, 0 );
				this._animateOff = false;
				break;
			case "values":
				this._animateOff = true;
				this._refreshValue();
				for ( i = 0; i < valsLength; i += 1 ) {
					this._change( null, i );
				}
				this._animateOff = false;
				break;
			case "step":
			case "min":
			case "max":
				this._animateOff = true;
				this._calculateNewMax();
				this._refreshValue();
				this._animateOff = false;
				break;
			case "range":
				this._animateOff = true;
				this._refresh();
				this._animateOff = false;
				break;
		}
	},

	//internal value getter
	// _value() returns value trimmed by min and max, aligned by step
	_value: function() {
		var val = this.options.value;
		val = this._trimAlignValue( val );

		return val;
	},

	//internal values getter
	// _values() returns array of values trimmed by min and max, aligned by step
	// _values( index ) returns single value trimmed by min and max, aligned by step
	_values: function( index ) {
		var val,
			vals,
			i;

		if ( arguments.length ) {
			val = this.options.values[ index ];
			val = this._trimAlignValue( val );

			return val;
		} else if ( this.options.values && this.options.values.length ) {
			// .slice() creates a copy of the array
			// this copy gets trimmed by min and max and then returned
			vals = this.options.values.slice();
			for ( i = 0; i < vals.length; i += 1) {
				vals[ i ] = this._trimAlignValue( vals[ i ] );
			}

			return vals;
		} else {
			return [];
		}
	},

	// returns the step-aligned value that val is closest to, between (inclusive) min and max
	_trimAlignValue: function( val ) {
		if ( val <= this._valueMin() ) {
			return this._valueMin();
		}
		if ( val >= this._valueMax() ) {
			return this._valueMax();
		}
		var step = ( this.options.step > 0 ) ? this.options.step : 1,
			valModStep = (val - this._valueMin()) % step,
			alignValue = val - valModStep;

		if ( Math.abs(valModStep) * 2 >= step ) {
			alignValue += ( valModStep > 0 ) ? step : ( -step );
		}

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat( alignValue.toFixed(5) );
	},

	_calculateNewMax: function() {
		var max = this.options.max,
			min = this._valueMin(),
			step = this.options.step,
			aboveMin = Math.floor( ( +( max - min ).toFixed( this._precision() ) ) / step ) * step;
		max = aboveMin + min;
		this.max = parseFloat( max.toFixed( this._precision() ) );
	},

	_precision: function() {
		var precision = this._precisionOf( this.options.step );
		if ( this.options.min !== null ) {
			precision = Math.max( precision, this._precisionOf( this.options.min ) );
		}
		return precision;
	},

	_precisionOf: function( num ) {
		var str = num.toString(),
			decimal = str.indexOf( "." );
		return decimal === -1 ? 0 : str.length - decimal - 1;
	},

	_valueMin: function() {
		return this.options.min;
	},

	_valueMax: function() {
		return this.max;
	},

	_refreshValue: function() {
		var lastValPercent, valPercent, value, valueMin, valueMax,
			oRange = this.options.range,
			o = this.options,
			that = this,
			animate = ( !this._animateOff ) ? o.animate : false,
			_set = {};

		if ( this.options.values && this.options.values.length ) {
			this.handles.each(function( i ) {
				valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100;
				_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
				$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
				if ( that.options.range === true ) {
					if ( that.orientation === "horizontal" ) {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
						}
					} else {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
						}
					}
				}
				lastValPercent = valPercent;
			});
		} else {
			value = this.value();
			valueMin = this._valueMin();
			valueMax = this._valueMax();
			valPercent = ( valueMax !== valueMin ) ?
					( value - valueMin ) / ( valueMax - valueMin ) * 100 :
					0;
			_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
			this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );

			if ( oRange === "min" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate );
			}
			if ( oRange === "max" && this.orientation === "horizontal" ) {
				this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
			}
			if ( oRange === "min" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate );
			}
			if ( oRange === "max" && this.orientation === "vertical" ) {
				this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
			}
		}
	},

	_handleEvents: {
		keydown: function( event ) {
			var allowed, curVal, newVal, step,
				index = $( event.target ).data( "ui-slider-handle-index" );

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_UP:
				case $.ui.keyCode.PAGE_DOWN:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					event.preventDefault();
					if ( !this._keySliding ) {
						this._keySliding = true;
						$( event.target ).addClass( "ui-state-active" );
						allowed = this._start( event, index );
						if ( allowed === false ) {
							return;
						}
					}
					break;
			}

			step = this.options.step;
			if ( this.options.values && this.options.values.length ) {
				curVal = newVal = this.values( index );
			} else {
				curVal = newVal = this.value();
			}

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
					newVal = this._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = this._valueMax();
					break;
				case $.ui.keyCode.PAGE_UP:
					newVal = this._trimAlignValue(
						curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages )
					);
					break;
				case $.ui.keyCode.PAGE_DOWN:
					newVal = this._trimAlignValue(
						curVal - ( (this._valueMax() - this._valueMin()) / this.numPages ) );
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					if ( curVal === this._valueMax() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal + step );
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if ( curVal === this._valueMin() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal - step );
					break;
			}

			this._slide( event, index, newVal );
		},
		keyup: function( event ) {
			var index = $( event.target ).data( "ui-slider-handle-index" );

			if ( this._keySliding ) {
				this._keySliding = false;
				this._stop( event, index );
				this._change( event, index );
				$( event.target ).removeClass( "ui-state-active" );
			}
		}
	}
});


/*!
 * jQuery UI Sortable 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/sortable/
 */


var sortable = $.widget("ui.sortable", $.ui.mouse, {
	version: "1.11.4",
	widgetEventPrefix: "sort",
	ready: false,
	options: {
		appendTo: "parent",
		axis: false,
		connectWith: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		dropOnEmpty: true,
		forcePlaceholderSize: false,
		forceHelperSize: false,
		grid: false,
		handle: false,
		helper: "original",
		items: "> *",
		opacity: false,
		placeholder: false,
		revert: false,
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		scope: "default",
		tolerance: "intersect",
		zIndex: 1000,

		// callbacks
		activate: null,
		beforeStop: null,
		change: null,
		deactivate: null,
		out: null,
		over: null,
		receive: null,
		remove: null,
		sort: null,
		start: null,
		stop: null,
		update: null
	},

	_isOverAxis: function( x, reference, size ) {
		return ( x >= reference ) && ( x < ( reference + size ) );
	},

	_isFloating: function( item ) {
		return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display"));
	},

	_create: function() {
		this.containerCache = {};
		this.element.addClass("ui-sortable");

		//Get the items
		this.refresh();

		//Let's determine the parent's offset
		this.offset = this.element.offset();

		//Initialize mouse events for interaction
		this._mouseInit();

		this._setHandleClassName();

		//We're ready to go
		this.ready = true;

	},

	_setOption: function( key, value ) {
		this._super( key, value );

		if ( key === "handle" ) {
			this._setHandleClassName();
		}
	},

	_setHandleClassName: function() {
		this.element.find( ".ui-sortable-handle" ).removeClass( "ui-sortable-handle" );
		$.each( this.items, function() {
			( this.instance.options.handle ?
				this.item.find( this.instance.options.handle ) : this.item )
				.addClass( "ui-sortable-handle" );
		});
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-sortable ui-sortable-disabled" )
			.find( ".ui-sortable-handle" )
				.removeClass( "ui-sortable-handle" );
		this._mouseDestroy();

		for ( var i = this.items.length - 1; i >= 0; i-- ) {
			this.items[i].item.removeData(this.widgetName + "-item");
		}

		return this;
	},

	_mouseCapture: function(event, overrideHandle) {
		var currentItem = null,
			validHandle = false,
			that = this;

		if (this.reverting) {
			return false;
		}

		if(this.options.disabled || this.options.type === "static") {
			return false;
		}

		//We have to refresh the items data once first
		this._refreshItems(event);

		//Find out if the clicked node (or one of its parents) is a actual item in this.items
		$(event.target).parents().each(function() {
			if($.data(this, that.widgetName + "-item") === that) {
				currentItem = $(this);
				return false;
			}
		});
		if($.data(event.target, that.widgetName + "-item") === that) {
			currentItem = $(event.target);
		}

		if(!currentItem) {
			return false;
		}
		if(this.options.handle && !overrideHandle) {
			$(this.options.handle, currentItem).find("*").addBack().each(function() {
				if(this === event.target) {
					validHandle = true;
				}
			});
			if(!validHandle) {
				return false;
			}
		}

		this.currentItem = currentItem;
		this._removeCurrentsFromItems();
		return true;

	},

	_mouseStart: function(event, overrideHandle, noActivation) {

		var i, body,
			o = this.options;

		this.currentContainer = this;

		//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
		this.refreshPositions();

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Get the next scrolling parent
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.currentItem.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		// Only after we got the offset, we can change the helper's position to absolute
		// TODO: Still need to figure out a way to make relative sorting possible
		this.helper.css("position", "absolute");
		this.cssPosition = this.helper.css("position");

		//Generate the original position
		this.originalPosition = this._generatePosition(event);
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

		//Cache the former DOM position
		this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };

		//If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
		if(this.helper[0] !== this.currentItem[0]) {
			this.currentItem.hide();
		}

		//Create the placeholder
		this._createPlaceholder();

		//Set a containment if given in the options
		if(o.containment) {
			this._setContainment();
		}

		if( o.cursor && o.cursor !== "auto" ) { // cursor option
			body = this.document.find( "body" );

			// support: IE
			this.storedCursor = body.css( "cursor" );
			body.css( "cursor", o.cursor );

			this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body );
		}

		if(o.opacity) { // opacity option
			if (this.helper.css("opacity")) {
				this._storedOpacity = this.helper.css("opacity");
			}
			this.helper.css("opacity", o.opacity);
		}

		if(o.zIndex) { // zIndex option
			if (this.helper.css("zIndex")) {
				this._storedZIndex = this.helper.css("zIndex");
			}
			this.helper.css("zIndex", o.zIndex);
		}

		//Prepare scrolling
		if(this.scrollParent[0] !== this.document[0] && this.scrollParent[0].tagName !== "HTML") {
			this.overflowOffset = this.scrollParent.offset();
		}

		//Call callbacks
		this._trigger("start", event, this._uiHash());

		//Recache the helper size
		if(!this._preserveHelperProportions) {
			this._cacheHelperProportions();
		}


		//Post "activate" events to possible containers
		if( !noActivation ) {
			for ( i = this.containers.length - 1; i >= 0; i-- ) {
				this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
			}
		}

		//Prepare possible droppables
		if($.ui.ddmanager) {
			$.ui.ddmanager.current = this;
		}

		if ($.ui.ddmanager && !o.dropBehaviour) {
			$.ui.ddmanager.prepareOffsets(this, event);
		}

		this.dragging = true;

		this.helper.addClass("ui-sortable-helper");
		this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;

	},

	_mouseDrag: function(event) {
		var i, item, itemElement, intersection,
			o = this.options,
			scrolled = false;

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		if (!this.lastPositionAbs) {
			this.lastPositionAbs = this.positionAbs;
		}

		//Do scrolling
		if(this.options.scroll) {
			if(this.scrollParent[0] !== this.document[0] && this.scrollParent[0].tagName !== "HTML") {

				if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
				} else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
				}

				if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
				} else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
				}

			} else {

				if(event.pageY - this.document.scrollTop() < o.scrollSensitivity) {
					scrolled = this.document.scrollTop(this.document.scrollTop() - o.scrollSpeed);
				} else if(this.window.height() - (event.pageY - this.document.scrollTop()) < o.scrollSensitivity) {
					scrolled = this.document.scrollTop(this.document.scrollTop() + o.scrollSpeed);
				}

				if(event.pageX - this.document.scrollLeft() < o.scrollSensitivity) {
					scrolled = this.document.scrollLeft(this.document.scrollLeft() - o.scrollSpeed);
				} else if(this.window.width() - (event.pageX - this.document.scrollLeft()) < o.scrollSensitivity) {
					scrolled = this.document.scrollLeft(this.document.scrollLeft() + o.scrollSpeed);
				}

			}

			if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
				$.ui.ddmanager.prepareOffsets(this, event);
			}
		}

		//Regenerate the absolute position used for position checks
		this.positionAbs = this._convertPositionTo("absolute");

		//Set the helper position
		if(!this.options.axis || this.options.axis !== "y") {
			this.helper[0].style.left = this.position.left+"px";
		}
		if(!this.options.axis || this.options.axis !== "x") {
			this.helper[0].style.top = this.position.top+"px";
		}

		//Rearrange
		for (i = this.items.length - 1; i >= 0; i--) {

			//Cache variables and intersection, continue if no intersection
			item = this.items[i];
			itemElement = item.item[0];
			intersection = this._intersectsWithPointer(item);
			if (!intersection) {
				continue;
			}

			// Only put the placeholder inside the current Container, skip all
			// items from other containers. This works because when moving
			// an item from one container to another the
			// currentContainer is switched before the placeholder is moved.
			//
			// Without this, moving items in "sub-sortables" can cause
			// the placeholder to jitter between the outer and inner container.
			if (item.instance !== this.currentContainer) {
				continue;
			}

			// cannot intersect with itself
			// no useless actions that have been done before
			// no action if the item moved is the parent of the item checked
			if (itemElement !== this.currentItem[0] &&
				this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
				!$.contains(this.placeholder[0], itemElement) &&
				(this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true)
			) {

				this.direction = intersection === 1 ? "down" : "up";

				if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) {
					this._rearrange(event, item);
				} else {
					break;
				}

				this._trigger("change", event, this._uiHash());
				break;
			}
		}

		//Post events to containers
		this._contactContainers(event);

		//Interconnect with droppables
		if($.ui.ddmanager) {
			$.ui.ddmanager.drag(this, event);
		}

		//Call callbacks
		this._trigger("sort", event, this._uiHash());

		this.lastPositionAbs = this.positionAbs;
		return false;

	},

	_mouseStop: function(event, noPropagation) {

		if(!event) {
			return;
		}

		//If we are using droppables, inform the manager about the drop
		if ($.ui.ddmanager && !this.options.dropBehaviour) {
			$.ui.ddmanager.drop(this, event);
		}

		if(this.options.revert) {
			var that = this,
				cur = this.placeholder.offset(),
				axis = this.options.axis,
				animation = {};

			if ( !axis || axis === "x" ) {
				animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === this.document[0].body ? 0 : this.offsetParent[0].scrollLeft);
			}
			if ( !axis || axis === "y" ) {
				animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === this.document[0].body ? 0 : this.offsetParent[0].scrollTop);
			}
			this.reverting = true;
			$(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() {
				that._clear(event);
			});
		} else {
			this._clear(event, noPropagation);
		}

		return false;

	},

	cancel: function() {

		if(this.dragging) {

			this._mouseUp({ target: null });

			if(this.options.helper === "original") {
				this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
			} else {
				this.currentItem.show();
			}

			//Post deactivating events to containers
			for (var i = this.containers.length - 1; i >= 0; i--){
				this.containers[i]._trigger("deactivate", null, this._uiHash(this));
				if(this.containers[i].containerCache.over) {
					this.containers[i]._trigger("out", null, this._uiHash(this));
					this.containers[i].containerCache.over = 0;
				}
			}

		}

		if (this.placeholder) {
			//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
			if(this.placeholder[0].parentNode) {
				this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
			}
			if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) {
				this.helper.remove();
			}

			$.extend(this, {
				helper: null,
				dragging: false,
				reverting: false,
				_noFinalSort: null
			});

			if(this.domPosition.prev) {
				$(this.domPosition.prev).after(this.currentItem);
			} else {
				$(this.domPosition.parent).prepend(this.currentItem);
			}
		}

		return this;

	},

	serialize: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected),
			str = [];
		o = o || {};

		$(items).each(function() {
			var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/));
			if (res) {
				str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2]));
			}
		});

		if(!str.length && o.key) {
			str.push(o.key + "=");
		}

		return str.join("&");

	},

	toArray: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected),
			ret = [];

		o = o || {};

		items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); });
		return ret;

	},

	/* Be careful with the following core functions */
	_intersectsWith: function(item) {

		var x1 = this.positionAbs.left,
			x2 = x1 + this.helperProportions.width,
			y1 = this.positionAbs.top,
			y2 = y1 + this.helperProportions.height,
			l = item.left,
			r = l + item.width,
			t = item.top,
			b = t + item.height,
			dyClick = this.offset.click.top,
			dxClick = this.offset.click.left,
			isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ),
			isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ),
			isOverElement = isOverElementHeight && isOverElementWidth;

		if ( this.options.tolerance === "pointer" ||
			this.options.forcePointerForContainers ||
			(this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"])
		) {
			return isOverElement;
		} else {

			return (l < x1 + (this.helperProportions.width / 2) && // Right Half
				x2 - (this.helperProportions.width / 2) < r && // Left Half
				t < y1 + (this.helperProportions.height / 2) && // Bottom Half
				y2 - (this.helperProportions.height / 2) < b ); // Top Half

		}
	},

	_intersectsWithPointer: function(item) {

		var isOverElementHeight = (this.options.axis === "x") || this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
			isOverElementWidth = (this.options.axis === "y") || this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
			isOverElement = isOverElementHeight && isOverElementWidth,
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if (!isOverElement) {
			return false;
		}

		return this.floating ?
			( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 )
			: ( verticalDirection && (verticalDirection === "down" ? 2 : 1) );

	},

	_intersectsWithSides: function(item) {

		var isOverBottomHalf = this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
			isOverRightHalf = this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if (this.floating && horizontalDirection) {
			return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf));
		} else {
			return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf));
		}

	},

	_getDragVerticalDirection: function() {
		var delta = this.positionAbs.top - this.lastPositionAbs.top;
		return delta !== 0 && (delta > 0 ? "down" : "up");
	},

	_getDragHorizontalDirection: function() {
		var delta = this.positionAbs.left - this.lastPositionAbs.left;
		return delta !== 0 && (delta > 0 ? "right" : "left");
	},

	refresh: function(event) {
		this._refreshItems(event);
		this._setHandleClassName();
		this.refreshPositions();
		return this;
	},

	_connectWith: function() {
		var options = this.options;
		return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith;
	},

	_getItemsAsjQuery: function(connected) {

		var i, j, cur, inst,
			items = [],
			queries = [],
			connectWith = this._connectWith();

		if(connectWith && connected) {
			for (i = connectWith.length - 1; i >= 0; i--){
				cur = $(connectWith[i], this.document[0]);
				for ( j = cur.length - 1; j >= 0; j--){
					inst = $.data(cur[j], this.widgetFullName);
					if(inst && inst !== this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]);
					}
				}
			}
		}

		queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]);

		function addItems() {
			items.push( this );
		}
		for (i = queries.length - 1; i >= 0; i--){
			queries[i][0].each( addItems );
		}

		return $(items);

	},

	_removeCurrentsFromItems: function() {

		var list = this.currentItem.find(":data(" + this.widgetName + "-item)");

		this.items = $.grep(this.items, function (item) {
			for (var j=0; j < list.length; j++) {
				if(list[j] === item.item[0]) {
					return false;
				}
			}
			return true;
		});

	},

	_refreshItems: function(event) {

		this.items = [];
		this.containers = [this];

		var i, j, cur, inst, targetData, _queries, item, queriesLength,
			items = this.items,
			queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]],
			connectWith = this._connectWith();

		if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
			for (i = connectWith.length - 1; i >= 0; i--){
				cur = $(connectWith[i], this.document[0]);
				for (j = cur.length - 1; j >= 0; j--){
					inst = $.data(cur[j], this.widgetFullName);
					if(inst && inst !== this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
						this.containers.push(inst);
					}
				}
			}
		}

		for (i = queries.length - 1; i >= 0; i--) {
			targetData = queries[i][1];
			_queries = queries[i][0];

			for (j=0, queriesLength = _queries.length; j < queriesLength; j++) {
				item = $(_queries[j]);

				item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager)

				items.push({
					item: item,
					instance: targetData,
					width: 0, height: 0,
					left: 0, top: 0
				});
			}
		}

	},

	refreshPositions: function(fast) {

		// Determine whether items are being displayed horizontally
		this.floating = this.items.length ?
			this.options.axis === "x" || this._isFloating( this.items[ 0 ].item ) :
			false;

		//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
		if(this.offsetParent && this.helper) {
			this.offset.parent = this._getParentOffset();
		}

		var i, item, t, p;

		for (i = this.items.length - 1; i >= 0; i--){
			item = this.items[i];

			//We ignore calculating positions of all connected containers when we're not over them
			if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) {
				continue;
			}

			t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;

			if (!fast) {
				item.width = t.outerWidth();
				item.height = t.outerHeight();
			}

			p = t.offset();
			item.left = p.left;
			item.top = p.top;
		}

		if(this.options.custom && this.options.custom.refreshContainers) {
			this.options.custom.refreshContainers.call(this);
		} else {
			for (i = this.containers.length - 1; i >= 0; i--){
				p = this.containers[i].element.offset();
				this.containers[i].containerCache.left = p.left;
				this.containers[i].containerCache.top = p.top;
				this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
				this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
			}
		}

		return this;
	},

	_createPlaceholder: function(that) {
		that = that || this;
		var className,
			o = that.options;

		if(!o.placeholder || o.placeholder.constructor === String) {
			className = o.placeholder;
			o.placeholder = {
				element: function() {

					var nodeName = that.currentItem[0].nodeName.toLowerCase(),
						element = $( "<" + nodeName + ">", that.document[0] )
							.addClass(className || that.currentItem[0].className+" ui-sortable-placeholder")
							.removeClass("ui-sortable-helper");

					if ( nodeName === "tbody" ) {
						that._createTrPlaceholder(
							that.currentItem.find( "tr" ).eq( 0 ),
							$( "<tr>", that.document[ 0 ] ).appendTo( element )
						);
					} else if ( nodeName === "tr" ) {
						that._createTrPlaceholder( that.currentItem, element );
					} else if ( nodeName === "img" ) {
						element.attr( "src", that.currentItem.attr( "src" ) );
					}

					if ( !className ) {
						element.css( "visibility", "hidden" );
					}

					return element;
				},
				update: function(container, p) {

					// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
					// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
					if(className && !o.forcePlaceholderSize) {
						return;
					}

					//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
					if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); }
					if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); }
				}
			};
		}

		//Create the placeholder
		that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));

		//Append it after the actual current item
		that.currentItem.after(that.placeholder);

		//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
		o.placeholder.update(that, that.placeholder);

	},

	_createTrPlaceholder: function( sourceTr, targetTr ) {
		var that = this;

		sourceTr.children().each(function() {
			$( "<td>&#160;</td>", that.document[ 0 ] )
				.attr( "colspan", $( this ).attr( "colspan" ) || 1 )
				.appendTo( targetTr );
		});
	},

	_contactContainers: function(event) {
		var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom, floating, axis,
			innermostContainer = null,
			innermostIndex = null;

		// get innermost container that intersects with item
		for (i = this.containers.length - 1; i >= 0; i--) {

			// never consider a container that's located within the item itself
			if($.contains(this.currentItem[0], this.containers[i].element[0])) {
				continue;
			}

			if(this._intersectsWith(this.containers[i].containerCache)) {

				// if we've already found a container and it's more "inner" than this, then continue
				if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) {
					continue;
				}

				innermostContainer = this.containers[i];
				innermostIndex = i;

			} else {
				// container doesn't intersect. trigger "out" event if necessary
				if(this.containers[i].containerCache.over) {
					this.containers[i]._trigger("out", event, this._uiHash(this));
					this.containers[i].containerCache.over = 0;
				}
			}

		}

		// if no intersecting containers found, return
		if(!innermostContainer) {
			return;
		}

		// move the item into the container if it's not there already
		if(this.containers.length === 1) {
			if (!this.containers[innermostIndex].containerCache.over) {
				this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
				this.containers[innermostIndex].containerCache.over = 1;
			}
		} else {

			//When entering a new container, we will find the item with the least distance and append our item near it
			dist = 10000;
			itemWithLeastDistance = null;
			floating = innermostContainer.floating || this._isFloating(this.currentItem);
			posProperty = floating ? "left" : "top";
			sizeProperty = floating ? "width" : "height";
			axis = floating ? "clientX" : "clientY";

			for (j = this.items.length - 1; j >= 0; j--) {
				if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) {
					continue;
				}
				if(this.items[j].item[0] === this.currentItem[0]) {
					continue;
				}

				cur = this.items[j].item.offset()[posProperty];
				nearBottom = false;
				if ( event[ axis ] - cur > this.items[ j ][ sizeProperty ] / 2 ) {
					nearBottom = true;
				}

				if ( Math.abs( event[ axis ] - cur ) < dist ) {
					dist = Math.abs( event[ axis ] - cur );
					itemWithLeastDistance = this.items[ j ];
					this.direction = nearBottom ? "up": "down";
				}
			}

			//Check if dropOnEmpty is enabled
			if(!itemWithLeastDistance && !this.options.dropOnEmpty) {
				return;
			}

			if(this.currentContainer === this.containers[innermostIndex]) {
				if ( !this.currentContainer.containerCache.over ) {
					this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash() );
					this.currentContainer.containerCache.over = 1;
				}
				return;
			}

			itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
			this._trigger("change", event, this._uiHash());
			this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
			this.currentContainer = this.containers[innermostIndex];

			//Update the placeholder
			this.options.placeholder.update(this.currentContainer, this.placeholder);

			this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
			this.containers[innermostIndex].containerCache.over = 1;
		}


	},

	_createHelper: function(event) {

		var o = this.options,
			helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem);

		//Add the helper to the DOM if that didn't happen already
		if(!helper.parents("body").length) {
			$(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
		}

		if(helper[0] === this.currentItem[0]) {
			this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
		}

		if(!helper[0].style.width || o.forceHelperSize) {
			helper.width(this.currentItem.width());
		}
		if(!helper[0].style.height || o.forceHelperSize) {
			helper.height(this.currentItem.height());
		}

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if (typeof obj === "string") {
			obj = obj.split(" ");
		}
		if ($.isArray(obj)) {
			obj = {left: +obj[0], top: +obj[1] || 0};
		}
		if ("left" in obj) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ("right" in obj) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ("top" in obj) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ("bottom" in obj) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_getParentOffset: function() {


		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(this.cssPosition === "absolute" && this.scrollParent[0] !== this.document[0] && $.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		// This needs to be actually done for all browsers, since pageX/pageY includes this information
		// with an ugly IE fix
		if( this.offsetParent[0] === this.document[0].body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
			po = { top: 0, left: 0 };
		}

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition === "relative") {
			var p = this.currentItem.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
			top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var ce, co, over,
			o = this.options;
		if(o.containment === "parent") {
			o.containment = this.helper[0].parentNode;
		}
		if(o.containment === "document" || o.containment === "window") {
			this.containment = [
				0 - this.offset.relative.left - this.offset.parent.left,
				0 - this.offset.relative.top - this.offset.parent.top,
				o.containment === "document" ? this.document.width() : this.window.width() - this.helperProportions.width - this.margins.left,
				(o.containment === "document" ? this.document.width() : this.window.height() || this.document[0].body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
			];
		}

		if(!(/^(document|window|parent)$/).test(o.containment)) {
			ce = $(o.containment)[0];
			co = $(o.containment).offset();
			over = ($(ce).css("overflow") !== "hidden");

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
			];
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) {
			pos = this.position;
		}
		var mod = d === "absolute" ? 1 : -1,
			scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== this.document[0] && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
			scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top	+																// The absolute mouse position
				this.offset.relative.top * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top * mod -											// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
			),
			left: (
				pos.left +																// The absolute mouse position
				this.offset.relative.left * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left * mod	-										// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
			)
		};

	},

	_generatePosition: function(event) {

		var top, left,
			o = this.options,
			pageX = event.pageX,
			pageY = event.pageY,
			scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== this.document[0] && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if(this.cssPosition === "relative" && !(this.scrollParent[0] !== this.document[0] && this.scrollParent[0] !== this.offsetParent[0])) {
			this.offset.relative = this._getRelativeOffset();
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if(this.originalPosition) { //If we are not dragging yet, we won't check for options

			if(this.containment) {
				if(event.pageX - this.offset.click.left < this.containment[0]) {
					pageX = this.containment[0] + this.offset.click.left;
				}
				if(event.pageY - this.offset.click.top < this.containment[1]) {
					pageY = this.containment[1] + this.offset.click.top;
				}
				if(event.pageX - this.offset.click.left > this.containment[2]) {
					pageX = this.containment[2] + this.offset.click.left;
				}
				if(event.pageY - this.offset.click.top > this.containment[3]) {
					pageY = this.containment[3] + this.offset.click.top;
				}
			}

			if(o.grid) {
				top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
				pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
				pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

		}

		return {
			top: (
				pageY -																// The absolute mouse position
				this.offset.click.top -													// Click offset (relative to the element)
				this.offset.relative.top	-											// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top +												// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
			),
			left: (
				pageX -																// The absolute mouse position
				this.offset.click.left -												// Click offset (relative to the element)
				this.offset.relative.left	-											// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left +												// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
			)
		};

	},

	_rearrange: function(event, i, a, hardRefresh) {

		a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling));

		//Various things done here to improve the performance:
		// 1. we create a setTimeout, that calls refreshPositions
		// 2. on the instance, we have a counter variable, that get's higher after every append
		// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
		// 4. this lets only the last addition to the timeout stack through
		this.counter = this.counter ? ++this.counter : 1;
		var counter = this.counter;

		this._delay(function() {
			if(counter === this.counter) {
				this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
			}
		});

	},

	_clear: function(event, noPropagation) {

		this.reverting = false;
		// We delay all events that have to be triggered to after the point where the placeholder has been removed and
		// everything else normalized again
		var i,
			delayedTriggers = [];

		// We first have to update the dom position of the actual currentItem
		// Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
		if(!this._noFinalSort && this.currentItem.parent().length) {
			this.placeholder.before(this.currentItem);
		}
		this._noFinalSort = null;

		if(this.helper[0] === this.currentItem[0]) {
			for(i in this._storedCSS) {
				if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") {
					this._storedCSS[i] = "";
				}
			}
			this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
		} else {
			this.currentItem.show();
		}

		if(this.fromOutside && !noPropagation) {
			delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
		}
		if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) {
			delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
		}

		// Check if the items Container has Changed and trigger appropriate
		// events.
		if (this !== this.currentContainer) {
			if(!noPropagation) {
				delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
				delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); };  }).call(this, this.currentContainer));
				delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this));  }; }).call(this, this.currentContainer));
			}
		}


		//Post events to containers
		function delayEvent( type, instance, container ) {
			return function( event ) {
				container._trigger( type, event, instance._uiHash( instance ) );
			};
		}
		for (i = this.containers.length - 1; i >= 0; i--){
			if (!noPropagation) {
				delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) );
			}
			if(this.containers[i].containerCache.over) {
				delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) );
				this.containers[i].containerCache.over = 0;
			}
		}

		//Do what was originally in plugins
		if ( this.storedCursor ) {
			this.document.find( "body" ).css( "cursor", this.storedCursor );
			this.storedStylesheet.remove();
		}
		if(this._storedOpacity) {
			this.helper.css("opacity", this._storedOpacity);
		}
		if(this._storedZIndex) {
			this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex);
		}

		this.dragging = false;

		if(!noPropagation) {
			this._trigger("beforeStop", event, this._uiHash());
		}

		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
		this.placeholder[0].parentNode.removeChild(this.placeholder[0]);

		if ( !this.cancelHelperRemoval ) {
			if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
				this.helper.remove();
			}
			this.helper = null;
		}

		if(!noPropagation) {
			for (i=0; i < delayedTriggers.length; i++) {
				delayedTriggers[i].call(this, event);
			} //Trigger all delayed events
			this._trigger("stop", event, this._uiHash());
		}

		this.fromOutside = false;
		return !this.cancelHelperRemoval;

	},

	_trigger: function() {
		if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
			this.cancel();
		}
	},

	_uiHash: function(_inst) {
		var inst = _inst || this;
		return {
			helper: inst.helper,
			placeholder: inst.placeholder || $([]),
			position: inst.position,
			originalPosition: inst.originalPosition,
			offset: inst.positionAbs,
			item: inst.currentItem,
			sender: _inst ? _inst.element : null
		};
	}

});


/*!
 * jQuery UI Spinner 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/spinner/
 */


function spinner_modifier( fn ) {
	return function() {
		var previous = this.element.val();
		fn.apply( this, arguments );
		this._refresh();
		if ( previous !== this.element.val() ) {
			this._trigger( "change" );
		}
	};
}

var spinner = $.widget( "ui.spinner", {
	version: "1.11.4",
	defaultElement: "<input>",
	widgetEventPrefix: "spin",
	options: {
		culture: null,
		icons: {
			down: "ui-icon-triangle-1-s",
			up: "ui-icon-triangle-1-n"
		},
		incremental: true,
		max: null,
		min: null,
		numberFormat: null,
		page: 10,
		step: 1,

		change: null,
		spin: null,
		start: null,
		stop: null
	},

	_create: function() {
		// handle string values that need to be parsed
		this._setOption( "max", this.options.max );
		this._setOption( "min", this.options.min );
		this._setOption( "step", this.options.step );

		// Only format if there is a value, prevents the field from being marked
		// as invalid in Firefox, see #9573.
		if ( this.value() !== "" ) {
			// Format the value, but don't constrain.
			this._value( this.element.val(), true );
		}

		this._draw();
		this._on( this._events );
		this._refresh();

		// turning off autocomplete prevents the browser from remembering the
		// value when navigating through history, so we re-enable autocomplete
		// if the page is unloaded before the widget is destroyed. #7790
		this._on( this.window, {
			beforeunload: function() {
				this.element.removeAttr( "autocomplete" );
			}
		});
	},

	_getCreateOptions: function() {
		var options = {},
			element = this.element;

		$.each( [ "min", "max", "step" ], function( i, option ) {
			var value = element.attr( option );
			if ( value !== undefined && value.length ) {
				options[ option ] = value;
			}
		});

		return options;
	},

	_events: {
		keydown: function( event ) {
			if ( this._start( event ) && this._keydown( event ) ) {
				event.preventDefault();
			}
		},
		keyup: "_stop",
		focus: function() {
			this.previous = this.element.val();
		},
		blur: function( event ) {
			if ( this.cancelBlur ) {
				delete this.cancelBlur;
				return;
			}

			this._stop();
			this._refresh();
			if ( this.previous !== this.element.val() ) {
				this._trigger( "change", event );
			}
		},
		mousewheel: function( event, delta ) {
			if ( !delta ) {
				return;
			}
			if ( !this.spinning && !this._start( event ) ) {
				return false;
			}

			this._spin( (delta > 0 ? 1 : -1) * this.options.step, event );
			clearTimeout( this.mousewheelTimer );
			this.mousewheelTimer = this._delay(function() {
				if ( this.spinning ) {
					this._stop( event );
				}
			}, 100 );
			event.preventDefault();
		},
		"mousedown .ui-spinner-button": function( event ) {
			var previous;

			// We never want the buttons to have focus; whenever the user is
			// interacting with the spinner, the focus should be on the input.
			// If the input is focused then this.previous is properly set from
			// when the input first received focus. If the input is not focused
			// then we need to set this.previous based on the value before spinning.
			previous = this.element[0] === this.document[0].activeElement ?
				this.previous : this.element.val();
			function checkFocus() {
				var isActive = this.element[0] === this.document[0].activeElement;
				if ( !isActive ) {
					this.element.focus();
					this.previous = previous;
					// support: IE
					// IE sets focus asynchronously, so we need to check if focus
					// moved off of the input because the user clicked on the button.
					this._delay(function() {
						this.previous = previous;
					});
				}
			}

			// ensure focus is on (or stays on) the text field
			event.preventDefault();
			checkFocus.call( this );

			// support: IE
			// IE doesn't prevent moving focus even with event.preventDefault()
			// so we set a flag to know when we should ignore the blur event
			// and check (again) if focus moved off of the input.
			this.cancelBlur = true;
			this._delay(function() {
				delete this.cancelBlur;
				checkFocus.call( this );
			});

			if ( this._start( event ) === false ) {
				return;
			}

			this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
		},
		"mouseup .ui-spinner-button": "_stop",
		"mouseenter .ui-spinner-button": function( event ) {
			// button will add ui-state-active if mouse was down while mouseleave and kept down
			if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) {
				return;
			}

			if ( this._start( event ) === false ) {
				return false;
			}
			this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
		},
		// TODO: do we really want to consider this a stop?
		// shouldn't we just stop the repeater and wait until mouseup before
		// we trigger the stop event?
		"mouseleave .ui-spinner-button": "_stop"
	},

	_draw: function() {
		var uiSpinner = this.uiSpinner = this.element
			.addClass( "ui-spinner-input" )
			.attr( "autocomplete", "off" )
			.wrap( this._uiSpinnerHtml() )
			.parent()
				// add buttons
				.append( this._buttonHtml() );

		this.element.attr( "role", "spinbutton" );

		// button bindings
		this.buttons = uiSpinner.find( ".ui-spinner-button" )
			.attr( "tabIndex", -1 )
			.button()
			.removeClass( "ui-corner-all" );

		// IE 6 doesn't understand height: 50% for the buttons
		// unless the wrapper has an explicit height
		if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) &&
				uiSpinner.height() > 0 ) {
			uiSpinner.height( uiSpinner.height() );
		}

		// disable spinner if element was already disabled
		if ( this.options.disabled ) {
			this.disable();
		}
	},

	_keydown: function( event ) {
		var options = this.options,
			keyCode = $.ui.keyCode;

		switch ( event.keyCode ) {
		case keyCode.UP:
			this._repeat( null, 1, event );
			return true;
		case keyCode.DOWN:
			this._repeat( null, -1, event );
			return true;
		case keyCode.PAGE_UP:
			this._repeat( null, options.page, event );
			return true;
		case keyCode.PAGE_DOWN:
			this._repeat( null, -options.page, event );
			return true;
		}

		return false;
	},

	_uiSpinnerHtml: function() {
		return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>";
	},

	_buttonHtml: function() {
		return "" +
			"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" +
				"<span class='ui-icon " + this.options.icons.up + "'>&#9650;</span>" +
			"</a>" +
			"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" +
				"<span class='ui-icon " + this.options.icons.down + "'>&#9660;</span>" +
			"</a>";
	},

	_start: function( event ) {
		if ( !this.spinning && this._trigger( "start", event ) === false ) {
			return false;
		}

		if ( !this.counter ) {
			this.counter = 1;
		}
		this.spinning = true;
		return true;
	},

	_repeat: function( i, steps, event ) {
		i = i || 500;

		clearTimeout( this.timer );
		this.timer = this._delay(function() {
			this._repeat( 40, steps, event );
		}, i );

		this._spin( steps * this.options.step, event );
	},

	_spin: function( step, event ) {
		var value = this.value() || 0;

		if ( !this.counter ) {
			this.counter = 1;
		}

		value = this._adjustValue( value + step * this._increment( this.counter ) );

		if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) {
			this._value( value );
			this.counter++;
		}
	},

	_increment: function( i ) {
		var incremental = this.options.incremental;

		if ( incremental ) {
			return $.isFunction( incremental ) ?
				incremental( i ) :
				Math.floor( i * i * i / 50000 - i * i / 500 + 17 * i / 200 + 1 );
		}

		return 1;
	},

	_precision: function() {
		var precision = this._precisionOf( this.options.step );
		if ( this.options.min !== null ) {
			precision = Math.max( precision, this._precisionOf( this.options.min ) );
		}
		return precision;
	},

	_precisionOf: function( num ) {
		var str = num.toString(),
			decimal = str.indexOf( "." );
		return decimal === -1 ? 0 : str.length - decimal - 1;
	},

	_adjustValue: function( value ) {
		var base, aboveMin,
			options = this.options;

		// make sure we're at a valid step
		// - find out where we are relative to the base (min or 0)
		base = options.min !== null ? options.min : 0;
		aboveMin = value - base;
		// - round to the nearest step
		aboveMin = Math.round(aboveMin / options.step) * options.step;
		// - rounding is based on 0, so adjust back to our base
		value = base + aboveMin;

		// fix precision from bad JS floating point math
		value = parseFloat( value.toFixed( this._precision() ) );

		// clamp the value
		if ( options.max !== null && value > options.max) {
			return options.max;
		}
		if ( options.min !== null && value < options.min ) {
			return options.min;
		}

		return value;
	},

	_stop: function( event ) {
		if ( !this.spinning ) {
			return;
		}

		clearTimeout( this.timer );
		clearTimeout( this.mousewheelTimer );
		this.counter = 0;
		this.spinning = false;
		this._trigger( "stop", event );
	},

	_setOption: function( key, value ) {
		if ( key === "culture" || key === "numberFormat" ) {
			var prevValue = this._parse( this.element.val() );
			this.options[ key ] = value;
			this.element.val( this._format( prevValue ) );
			return;
		}

		if ( key === "max" || key === "min" || key === "step" ) {
			if ( typeof value === "string" ) {
				value = this._parse( value );
			}
		}
		if ( key === "icons" ) {
			this.buttons.first().find( ".ui-icon" )
				.removeClass( this.options.icons.up )
				.addClass( value.up );
			this.buttons.last().find( ".ui-icon" )
				.removeClass( this.options.icons.down )
				.addClass( value.down );
		}

		this._super( key, value );

		if ( key === "disabled" ) {
			this.widget().toggleClass( "ui-state-disabled", !!value );
			this.element.prop( "disabled", !!value );
			this.buttons.button( value ? "disable" : "enable" );
		}
	},

	_setOptions: spinner_modifier(function( options ) {
		this._super( options );
	}),

	_parse: function( val ) {
		if ( typeof val === "string" && val !== "" ) {
			val = window.Globalize && this.options.numberFormat ?
				Globalize.parseFloat( val, 10, this.options.culture ) : +val;
		}
		return val === "" || isNaN( val ) ? null : val;
	},

	_format: function( value ) {
		if ( value === "" ) {
			return "";
		}
		return window.Globalize && this.options.numberFormat ?
			Globalize.format( value, this.options.numberFormat, this.options.culture ) :
			value;
	},

	_refresh: function() {
		this.element.attr({
			"aria-valuemin": this.options.min,
			"aria-valuemax": this.options.max,
			// TODO: what should we do with values that can't be parsed?
			"aria-valuenow": this._parse( this.element.val() )
		});
	},

	isValid: function() {
		var value = this.value();

		// null is invalid
		if ( value === null ) {
			return false;
		}

		// if value gets adjusted, it's invalid
		return value === this._adjustValue( value );
	},

	// update the value without triggering change
	_value: function( value, allowAny ) {
		var parsed;
		if ( value !== "" ) {
			parsed = this._parse( value );
			if ( parsed !== null ) {
				if ( !allowAny ) {
					parsed = this._adjustValue( parsed );
				}
				value = this._format( parsed );
			}
		}
		this.element.val( value );
		this._refresh();
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-spinner-input" )
			.prop( "disabled", false )
			.removeAttr( "autocomplete" )
			.removeAttr( "role" )
			.removeAttr( "aria-valuemin" )
			.removeAttr( "aria-valuemax" )
			.removeAttr( "aria-valuenow" );
		this.uiSpinner.replaceWith( this.element );
	},

	stepUp: spinner_modifier(function( steps ) {
		this._stepUp( steps );
	}),
	_stepUp: function( steps ) {
		if ( this._start() ) {
			this._spin( (steps || 1) * this.options.step );
			this._stop();
		}
	},

	stepDown: spinner_modifier(function( steps ) {
		this._stepDown( steps );
	}),
	_stepDown: function( steps ) {
		if ( this._start() ) {
			this._spin( (steps || 1) * -this.options.step );
			this._stop();
		}
	},

	pageUp: spinner_modifier(function( pages ) {
		this._stepUp( (pages || 1) * this.options.page );
	}),

	pageDown: spinner_modifier(function( pages ) {
		this._stepDown( (pages || 1) * this.options.page );
	}),

	value: function( newVal ) {
		if ( !arguments.length ) {
			return this._parse( this.element.val() );
		}
		spinner_modifier( this._value ).call( this, newVal );
	},

	widget: function() {
		return this.uiSpinner;
	}
});


/*!
 * jQuery UI Tabs 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/tabs/
 */


var tabs = $.widget( "ui.tabs", {
	version: "1.11.4",
	delay: 300,
	options: {
		active: null,
		collapsible: false,
		event: "click",
		heightStyle: "content",
		hide: null,
		show: null,

		// callbacks
		activate: null,
		beforeActivate: null,
		beforeLoad: null,
		load: null
	},

	_isLocal: (function() {
		var rhash = /#.*$/;

		return function( anchor ) {
			var anchorUrl, locationUrl;

			// support: IE7
			// IE7 doesn't normalize the href property when set via script (#9317)
			anchor = anchor.cloneNode( false );

			anchorUrl = anchor.href.replace( rhash, "" );
			locationUrl = location.href.replace( rhash, "" );

			// decoding may throw an error if the URL isn't UTF-8 (#9518)
			try {
				anchorUrl = decodeURIComponent( anchorUrl );
			} catch ( error ) {}
			try {
				locationUrl = decodeURIComponent( locationUrl );
			} catch ( error ) {}

			return anchor.hash.length > 1 && anchorUrl === locationUrl;
		};
	})(),

	_create: function() {
		var that = this,
			options = this.options;

		this.running = false;

		this.element
			.addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" )
			.toggleClass( "ui-tabs-collapsible", options.collapsible );

		this._processTabs();
		options.active = this._initialActive();

		// Take disabling tabs via class attribute from HTML
		// into account and update option properly.
		if ( $.isArray( options.disabled ) ) {
			options.disabled = $.unique( options.disabled.concat(
				$.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) {
					return that.tabs.index( li );
				})
			) ).sort();
		}

		// check for length avoids error when initializing empty list
		if ( this.options.active !== false && this.anchors.length ) {
			this.active = this._findActive( options.active );
		} else {
			this.active = $();
		}

		this._refresh();

		if ( this.active.length ) {
			this.load( options.active );
		}
	},

	_initialActive: function() {
		var active = this.options.active,
			collapsible = this.options.collapsible,
			locationHash = location.hash.substring( 1 );

		if ( active === null ) {
			// check the fragment identifier in the URL
			if ( locationHash ) {
				this.tabs.each(function( i, tab ) {
					if ( $( tab ).attr( "aria-controls" ) === locationHash ) {
						active = i;
						return false;
					}
				});
			}

			// check for a tab marked active via a class
			if ( active === null ) {
				active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) );
			}

			// no active tab, set to false
			if ( active === null || active === -1 ) {
				active = this.tabs.length ? 0 : false;
			}
		}

		// handle numbers: negative, out of range
		if ( active !== false ) {
			active = this.tabs.index( this.tabs.eq( active ) );
			if ( active === -1 ) {
				active = collapsible ? false : 0;
			}
		}

		// don't allow collapsible: false and active: false
		if ( !collapsible && active === false && this.anchors.length ) {
			active = 0;
		}

		return active;
	},

	_getCreateEventData: function() {
		return {
			tab: this.active,
			panel: !this.active.length ? $() : this._getPanelForTab( this.active )
		};
	},

	_tabKeydown: function( event ) {
		var focusedTab = $( this.document[0].activeElement ).closest( "li" ),
			selectedIndex = this.tabs.index( focusedTab ),
			goingForward = true;

		if ( this._handlePageNav( event ) ) {
			return;
		}

		switch ( event.keyCode ) {
			case $.ui.keyCode.RIGHT:
			case $.ui.keyCode.DOWN:
				selectedIndex++;
				break;
			case $.ui.keyCode.UP:
			case $.ui.keyCode.LEFT:
				goingForward = false;
				selectedIndex--;
				break;
			case $.ui.keyCode.END:
				selectedIndex = this.anchors.length - 1;
				break;
			case $.ui.keyCode.HOME:
				selectedIndex = 0;
				break;
			case $.ui.keyCode.SPACE:
				// Activate only, no collapsing
				event.preventDefault();
				clearTimeout( this.activating );
				this._activate( selectedIndex );
				return;
			case $.ui.keyCode.ENTER:
				// Toggle (cancel delayed activation, allow collapsing)
				event.preventDefault();
				clearTimeout( this.activating );
				// Determine if we should collapse or activate
				this._activate( selectedIndex === this.options.active ? false : selectedIndex );
				return;
			default:
				return;
		}

		// Focus the appropriate tab, based on which key was pressed
		event.preventDefault();
		clearTimeout( this.activating );
		selectedIndex = this._focusNextTab( selectedIndex, goingForward );

		// Navigating with control/command key will prevent automatic activation
		if ( !event.ctrlKey && !event.metaKey ) {

			// Update aria-selected immediately so that AT think the tab is already selected.
			// Otherwise AT may confuse the user by stating that they need to activate the tab,
			// but the tab will already be activated by the time the announcement finishes.
			focusedTab.attr( "aria-selected", "false" );
			this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" );

			this.activating = this._delay(function() {
				this.option( "active", selectedIndex );
			}, this.delay );
		}
	},

	_panelKeydown: function( event ) {
		if ( this._handlePageNav( event ) ) {
			return;
		}

		// Ctrl+up moves focus to the current tab
		if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) {
			event.preventDefault();
			this.active.focus();
		}
	},

	// Alt+page up/down moves focus to the previous/next tab (and activates)
	_handlePageNav: function( event ) {
		if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) {
			this._activate( this._focusNextTab( this.options.active - 1, false ) );
			return true;
		}
		if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) {
			this._activate( this._focusNextTab( this.options.active + 1, true ) );
			return true;
		}
	},

	_findNextTab: function( index, goingForward ) {
		var lastTabIndex = this.tabs.length - 1;

		function constrain() {
			if ( index > lastTabIndex ) {
				index = 0;
			}
			if ( index < 0 ) {
				index = lastTabIndex;
			}
			return index;
		}

		while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) {
			index = goingForward ? index + 1 : index - 1;
		}

		return index;
	},

	_focusNextTab: function( index, goingForward ) {
		index = this._findNextTab( index, goingForward );
		this.tabs.eq( index ).focus();
		return index;
	},

	_setOption: function( key, value ) {
		if ( key === "active" ) {
			// _activate() will handle invalid values and update this.options
			this._activate( value );
			return;
		}

		if ( key === "disabled" ) {
			// don't use the widget factory's disabled handling
			this._setupDisabled( value );
			return;
		}

		this._super( key, value);

		if ( key === "collapsible" ) {
			this.element.toggleClass( "ui-tabs-collapsible", value );
			// Setting collapsible: false while collapsed; open first panel
			if ( !value && this.options.active === false ) {
				this._activate( 0 );
			}
		}

		if ( key === "event" ) {
			this._setupEvents( value );
		}

		if ( key === "heightStyle" ) {
			this._setupHeightStyle( value );
		}
	},

	_sanitizeSelector: function( hash ) {
		return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : "";
	},

	refresh: function() {
		var options = this.options,
			lis = this.tablist.children( ":has(a[href])" );

		// get disabled tabs from class attribute from HTML
		// this will get converted to a boolean if needed in _refresh()
		options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) {
			return lis.index( tab );
		});

		this._processTabs();

		// was collapsed or no tabs
		if ( options.active === false || !this.anchors.length ) {
			options.active = false;
			this.active = $();
		// was active, but active tab is gone
		} else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) {
			// all remaining tabs are disabled
			if ( this.tabs.length === options.disabled.length ) {
				options.active = false;
				this.active = $();
			// activate previous tab
			} else {
				this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) );
			}
		// was active, active tab still exists
		} else {
			// make sure active index is correct
			options.active = this.tabs.index( this.active );
		}

		this._refresh();
	},

	_refresh: function() {
		this._setupDisabled( this.options.disabled );
		this._setupEvents( this.options.event );
		this._setupHeightStyle( this.options.heightStyle );

		this.tabs.not( this.active ).attr({
			"aria-selected": "false",
			"aria-expanded": "false",
			tabIndex: -1
		});
		this.panels.not( this._getPanelForTab( this.active ) )
			.hide()
			.attr({
				"aria-hidden": "true"
			});

		// Make sure one tab is in the tab order
		if ( !this.active.length ) {
			this.tabs.eq( 0 ).attr( "tabIndex", 0 );
		} else {
			this.active
				.addClass( "ui-tabs-active ui-state-active" )
				.attr({
					"aria-selected": "true",
					"aria-expanded": "true",
					tabIndex: 0
				});
			this._getPanelForTab( this.active )
				.show()
				.attr({
					"aria-hidden": "false"
				});
		}
	},

	_processTabs: function() {
		var that = this,
			prevTabs = this.tabs,
			prevAnchors = this.anchors,
			prevPanels = this.panels;

		this.tablist = this._getList()
			.addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
			.attr( "role", "tablist" )

			// Prevent users from focusing disabled tabs via click
			.delegate( "> li", "mousedown" + this.eventNamespace, function( event ) {
				if ( $( this ).is( ".ui-state-disabled" ) ) {
					event.preventDefault();
				}
			})

			// support: IE <9
			// Preventing the default action in mousedown doesn't prevent IE
			// from focusing the element, so if the anchor gets focused, blur.
			// We don't have to worry about focusing the previously focused
			// element since clicking on a non-focusable element should focus
			// the body anyway.
			.delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() {
				if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) {
					this.blur();
				}
			});

		this.tabs = this.tablist.find( "> li:has(a[href])" )
			.addClass( "ui-state-default ui-corner-top" )
			.attr({
				role: "tab",
				tabIndex: -1
			});

		this.anchors = this.tabs.map(function() {
				return $( "a", this )[ 0 ];
			})
			.addClass( "ui-tabs-anchor" )
			.attr({
				role: "presentation",
				tabIndex: -1
			});

		this.panels = $();

		this.anchors.each(function( i, anchor ) {
			var selector, panel, panelId,
				anchorId = $( anchor ).uniqueId().attr( "id" ),
				tab = $( anchor ).closest( "li" ),
				originalAriaControls = tab.attr( "aria-controls" );

			// inline tab
			if ( that._isLocal( anchor ) ) {
				selector = anchor.hash;
				panelId = selector.substring( 1 );
				panel = that.element.find( that._sanitizeSelector( selector ) );
			// remote tab
			} else {
				// If the tab doesn't already have aria-controls,
				// generate an id by using a throw-away element
				panelId = tab.attr( "aria-controls" ) || $( {} ).uniqueId()[ 0 ].id;
				selector = "#" + panelId;
				panel = that.element.find( selector );
				if ( !panel.length ) {
					panel = that._createPanel( panelId );
					panel.insertAfter( that.panels[ i - 1 ] || that.tablist );
				}
				panel.attr( "aria-live", "polite" );
			}

			if ( panel.length) {
				that.panels = that.panels.add( panel );
			}
			if ( originalAriaControls ) {
				tab.data( "ui-tabs-aria-controls", originalAriaControls );
			}
			tab.attr({
				"aria-controls": panelId,
				"aria-labelledby": anchorId
			});
			panel.attr( "aria-labelledby", anchorId );
		});

		this.panels
			.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
			.attr( "role", "tabpanel" );

		// Avoid memory leaks (#10056)
		if ( prevTabs ) {
			this._off( prevTabs.not( this.tabs ) );
			this._off( prevAnchors.not( this.anchors ) );
			this._off( prevPanels.not( this.panels ) );
		}
	},

	// allow overriding how to find the list for rare usage scenarios (#7715)
	_getList: function() {
		return this.tablist || this.element.find( "ol,ul" ).eq( 0 );
	},

	_createPanel: function( id ) {
		return $( "<div>" )
			.attr( "id", id )
			.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
			.data( "ui-tabs-destroy", true );
	},

	_setupDisabled: function( disabled ) {
		if ( $.isArray( disabled ) ) {
			if ( !disabled.length ) {
				disabled = false;
			} else if ( disabled.length === this.anchors.length ) {
				disabled = true;
			}
		}

		// disable tabs
		for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) {
			if ( disabled === true || $.inArray( i, disabled ) !== -1 ) {
				$( li )
					.addClass( "ui-state-disabled" )
					.attr( "aria-disabled", "true" );
			} else {
				$( li )
					.removeClass( "ui-state-disabled" )
					.removeAttr( "aria-disabled" );
			}
		}

		this.options.disabled = disabled;
	},

	_setupEvents: function( event ) {
		var events = {};
		if ( event ) {
			$.each( event.split(" "), function( index, eventName ) {
				events[ eventName ] = "_eventHandler";
			});
		}

		this._off( this.anchors.add( this.tabs ).add( this.panels ) );
		// Always prevent the default action, even when disabled
		this._on( true, this.anchors, {
			click: function( event ) {
				event.preventDefault();
			}
		});
		this._on( this.anchors, events );
		this._on( this.tabs, { keydown: "_tabKeydown" } );
		this._on( this.panels, { keydown: "_panelKeydown" } );

		this._focusable( this.tabs );
		this._hoverable( this.tabs );
	},

	_setupHeightStyle: function( heightStyle ) {
		var maxHeight,
			parent = this.element.parent();

		if ( heightStyle === "fill" ) {
			maxHeight = parent.height();
			maxHeight -= this.element.outerHeight() - this.element.height();

			this.element.siblings( ":visible" ).each(function() {
				var elem = $( this ),
					position = elem.css( "position" );

				if ( position === "absolute" || position === "fixed" ) {
					return;
				}
				maxHeight -= elem.outerHeight( true );
			});

			this.element.children().not( this.panels ).each(function() {
				maxHeight -= $( this ).outerHeight( true );
			});

			this.panels.each(function() {
				$( this ).height( Math.max( 0, maxHeight -
					$( this ).innerHeight() + $( this ).height() ) );
			})
			.css( "overflow", "auto" );
		} else if ( heightStyle === "auto" ) {
			maxHeight = 0;
			this.panels.each(function() {
				maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() );
			}).height( maxHeight );
		}
	},

	_eventHandler: function( event ) {
		var options = this.options,
			active = this.active,
			anchor = $( event.currentTarget ),
			tab = anchor.closest( "li" ),
			clickedIsActive = tab[ 0 ] === active[ 0 ],
			collapsing = clickedIsActive && options.collapsible,
			toShow = collapsing ? $() : this._getPanelForTab( tab ),
			toHide = !active.length ? $() : this._getPanelForTab( active ),
			eventData = {
				oldTab: active,
				oldPanel: toHide,
				newTab: collapsing ? $() : tab,
				newPanel: toShow
			};

		event.preventDefault();

		if ( tab.hasClass( "ui-state-disabled" ) ||
				// tab is already loading
				tab.hasClass( "ui-tabs-loading" ) ||
				// can't switch durning an animation
				this.running ||
				// click on active header, but not collapsible
				( clickedIsActive && !options.collapsible ) ||
				// allow canceling activation
				( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
			return;
		}

		options.active = collapsing ? false : this.tabs.index( tab );

		this.active = clickedIsActive ? $() : tab;
		if ( this.xhr ) {
			this.xhr.abort();
		}

		if ( !toHide.length && !toShow.length ) {
			$.error( "jQuery UI Tabs: Mismatching fragment identifier." );
		}

		if ( toShow.length ) {
			this.load( this.tabs.index( tab ), event );
		}
		this._toggle( event, eventData );
	},

	// handles show/hide for selecting tabs
	_toggle: function( event, eventData ) {
		var that = this,
			toShow = eventData.newPanel,
			toHide = eventData.oldPanel;

		this.running = true;

		function complete() {
			that.running = false;
			that._trigger( "activate", event, eventData );
		}

		function show() {
			eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" );

			if ( toShow.length && that.options.show ) {
				that._show( toShow, that.options.show, complete );
			} else {
				toShow.show();
				complete();
			}
		}

		// start out by hiding, then showing, then completing
		if ( toHide.length && this.options.hide ) {
			this._hide( toHide, this.options.hide, function() {
				eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
				show();
			});
		} else {
			eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
			toHide.hide();
			show();
		}

		toHide.attr( "aria-hidden", "true" );
		eventData.oldTab.attr({
			"aria-selected": "false",
			"aria-expanded": "false"
		});
		// If we're switching tabs, remove the old tab from the tab order.
		// If we're opening from collapsed state, remove the previous tab from the tab order.
		// If we're collapsing, then keep the collapsing tab in the tab order.
		if ( toShow.length && toHide.length ) {
			eventData.oldTab.attr( "tabIndex", -1 );
		} else if ( toShow.length ) {
			this.tabs.filter(function() {
				return $( this ).attr( "tabIndex" ) === 0;
			})
			.attr( "tabIndex", -1 );
		}

		toShow.attr( "aria-hidden", "false" );
		eventData.newTab.attr({
			"aria-selected": "true",
			"aria-expanded": "true",
			tabIndex: 0
		});
	},

	_activate: function( index ) {
		var anchor,
			active = this._findActive( index );

		// trying to activate the already active panel
		if ( active[ 0 ] === this.active[ 0 ] ) {
			return;
		}

		// trying to collapse, simulate a click on the current active header
		if ( !active.length ) {
			active = this.active;
		}

		anchor = active.find( ".ui-tabs-anchor" )[ 0 ];
		this._eventHandler({
			target: anchor,
			currentTarget: anchor,
			preventDefault: $.noop
		});
	},

	_findActive: function( index ) {
		return index === false ? $() : this.tabs.eq( index );
	},

	_getIndex: function( index ) {
		// meta-function to give users option to provide a href string instead of a numerical index.
		if ( typeof index === "string" ) {
			index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) );
		}

		return index;
	},

	_destroy: function() {
		if ( this.xhr ) {
			this.xhr.abort();
		}

		this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" );

		this.tablist
			.removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
			.removeAttr( "role" );

		this.anchors
			.removeClass( "ui-tabs-anchor" )
			.removeAttr( "role" )
			.removeAttr( "tabIndex" )
			.removeUniqueId();

		this.tablist.unbind( this.eventNamespace );

		this.tabs.add( this.panels ).each(function() {
			if ( $.data( this, "ui-tabs-destroy" ) ) {
				$( this ).remove();
			} else {
				$( this )
					.removeClass( "ui-state-default ui-state-active ui-state-disabled " +
						"ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" )
					.removeAttr( "tabIndex" )
					.removeAttr( "aria-live" )
					.removeAttr( "aria-busy" )
					.removeAttr( "aria-selected" )
					.removeAttr( "aria-labelledby" )
					.removeAttr( "aria-hidden" )
					.removeAttr( "aria-expanded" )
					.removeAttr( "role" );
			}
		});

		this.tabs.each(function() {
			var li = $( this ),
				prev = li.data( "ui-tabs-aria-controls" );
			if ( prev ) {
				li
					.attr( "aria-controls", prev )
					.removeData( "ui-tabs-aria-controls" );
			} else {
				li.removeAttr( "aria-controls" );
			}
		});

		this.panels.show();

		if ( this.options.heightStyle !== "content" ) {
			this.panels.css( "height", "" );
		}
	},

	enable: function( index ) {
		var disabled = this.options.disabled;
		if ( disabled === false ) {
			return;
		}

		if ( index === undefined ) {
			disabled = false;
		} else {
			index = this._getIndex( index );
			if ( $.isArray( disabled ) ) {
				disabled = $.map( disabled, function( num ) {
					return num !== index ? num : null;
				});
			} else {
				disabled = $.map( this.tabs, function( li, num ) {
					return num !== index ? num : null;
				});
			}
		}
		this._setupDisabled( disabled );
	},

	disable: function( index ) {
		var disabled = this.options.disabled;
		if ( disabled === true ) {
			return;
		}

		if ( index === undefined ) {
			disabled = true;
		} else {
			index = this._getIndex( index );
			if ( $.inArray( index, disabled ) !== -1 ) {
				return;
			}
			if ( $.isArray( disabled ) ) {
				disabled = $.merge( [ index ], disabled ).sort();
			} else {
				disabled = [ index ];
			}
		}
		this._setupDisabled( disabled );
	},

	load: function( index, event ) {
		index = this._getIndex( index );
		var that = this,
			tab = this.tabs.eq( index ),
			anchor = tab.find( ".ui-tabs-anchor" ),
			panel = this._getPanelForTab( tab ),
			eventData = {
				tab: tab,
				panel: panel
			},
			complete = function( jqXHR, status ) {
				if ( status === "abort" ) {
					that.panels.stop( false, true );
				}

				tab.removeClass( "ui-tabs-loading" );
				panel.removeAttr( "aria-busy" );

				if ( jqXHR === that.xhr ) {
					delete that.xhr;
				}
			};

		// not remote
		if ( this._isLocal( anchor[ 0 ] ) ) {
			return;
		}

		this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) );

		// support: jQuery <1.8
		// jQuery <1.8 returns false if the request is canceled in beforeSend,
		// but as of 1.8, $.ajax() always returns a jqXHR object.
		if ( this.xhr && this.xhr.statusText !== "canceled" ) {
			tab.addClass( "ui-tabs-loading" );
			panel.attr( "aria-busy", "true" );

			this.xhr
				.done(function( response, status, jqXHR ) {
					// support: jQuery <1.8
					// http://bugs.jquery.com/ticket/11778
					setTimeout(function() {
						panel.html( response );
						that._trigger( "load", event, eventData );

						complete( jqXHR, status );
					}, 1 );
				})
				.fail(function( jqXHR, status ) {
					// support: jQuery <1.8
					// http://bugs.jquery.com/ticket/11778
					setTimeout(function() {
						complete( jqXHR, status );
					}, 1 );
				});
		}
	},

	_ajaxSettings: function( anchor, event, eventData ) {
		var that = this;
		return {
			url: anchor.attr( "href" ),
			beforeSend: function( jqXHR, settings ) {
				return that._trigger( "beforeLoad", event,
					$.extend( { jqXHR: jqXHR, ajaxSettings: settings }, eventData ) );
			}
		};
	},

	_getPanelForTab: function( tab ) {
		var id = $( tab ).attr( "aria-controls" );
		return this.element.find( this._sanitizeSelector( "#" + id ) );
	}
});


/*!
 * jQuery UI Tooltip 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/tooltip/
 */


var tooltip = $.widget( "ui.tooltip", {
	version: "1.11.4",
	options: {
		content: function() {
			// support: IE<9, Opera in jQuery <1.7
			// .text() can't accept undefined, so coerce to a string
			var title = $( this ).attr( "title" ) || "";
			// Escape title, since we're going from an attribute to raw HTML
			return $( "<a>" ).text( title ).html();
		},
		hide: true,
		// Disabled elements have inconsistent behavior across browsers (#8661)
		items: "[title]:not([disabled])",
		position: {
			my: "left top+15",
			at: "left bottom",
			collision: "flipfit flip"
		},
		show: true,
		tooltipClass: null,
		track: false,

		// callbacks
		close: null,
		open: null
	},

	_addDescribedBy: function( elem, id ) {
		var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ );
		describedby.push( id );
		elem
			.data( "ui-tooltip-id", id )
			.attr( "aria-describedby", $.trim( describedby.join( " " ) ) );
	},

	_removeDescribedBy: function( elem ) {
		var id = elem.data( "ui-tooltip-id" ),
			describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ),
			index = $.inArray( id, describedby );

		if ( index !== -1 ) {
			describedby.splice( index, 1 );
		}

		elem.removeData( "ui-tooltip-id" );
		describedby = $.trim( describedby.join( " " ) );
		if ( describedby ) {
			elem.attr( "aria-describedby", describedby );
		} else {
			elem.removeAttr( "aria-describedby" );
		}
	},

	_create: function() {
		this._on({
			mouseover: "open",
			focusin: "open"
		});

		// IDs of generated tooltips, needed for destroy
		this.tooltips = {};

		// IDs of parent tooltips where we removed the title attribute
		this.parents = {};

		if ( this.options.disabled ) {
			this._disable();
		}

		// Append the aria-live region so tooltips announce correctly
		this.liveRegion = $( "<div>" )
			.attr({
				role: "log",
				"aria-live": "assertive",
				"aria-relevant": "additions"
			})
			.addClass( "ui-helper-hidden-accessible" )
			.appendTo( this.document[ 0 ].body );
	},

	_setOption: function( key, value ) {
		var that = this;

		if ( key === "disabled" ) {
			this[ value ? "_disable" : "_enable" ]();
			this.options[ key ] = value;
			// disable element style changes
			return;
		}

		this._super( key, value );

		if ( key === "content" ) {
			$.each( this.tooltips, function( id, tooltipData ) {
				that._updateContent( tooltipData.element );
			});
		}
	},

	_disable: function() {
		var that = this;

		// close open tooltips
		$.each( this.tooltips, function( id, tooltipData ) {
			var event = $.Event( "blur" );
			event.target = event.currentTarget = tooltipData.element[ 0 ];
			that.close( event, true );
		});

		// remove title attributes to prevent native tooltips
		this.element.find( this.options.items ).addBack().each(function() {
			var element = $( this );
			if ( element.is( "[title]" ) ) {
				element
					.data( "ui-tooltip-title", element.attr( "title" ) )
					.removeAttr( "title" );
			}
		});
	},

	_enable: function() {
		// restore title attributes
		this.element.find( this.options.items ).addBack().each(function() {
			var element = $( this );
			if ( element.data( "ui-tooltip-title" ) ) {
				element.attr( "title", element.data( "ui-tooltip-title" ) );
			}
		});
	},

	open: function( event ) {
		var that = this,
			target = $( event ? event.target : this.element )
				// we need closest here due to mouseover bubbling,
				// but always pointing at the same event target
				.closest( this.options.items );

		// No element to show a tooltip for or the tooltip is already open
		if ( !target.length || target.data( "ui-tooltip-id" ) ) {
			return;
		}

		if ( target.attr( "title" ) ) {
			target.data( "ui-tooltip-title", target.attr( "title" ) );
		}

		target.data( "ui-tooltip-open", true );

		// kill parent tooltips, custom or native, for hover
		if ( event && event.type === "mouseover" ) {
			target.parents().each(function() {
				var parent = $( this ),
					blurEvent;
				if ( parent.data( "ui-tooltip-open" ) ) {
					blurEvent = $.Event( "blur" );
					blurEvent.target = blurEvent.currentTarget = this;
					that.close( blurEvent, true );
				}
				if ( parent.attr( "title" ) ) {
					parent.uniqueId();
					that.parents[ this.id ] = {
						element: this,
						title: parent.attr( "title" )
					};
					parent.attr( "title", "" );
				}
			});
		}

		this._registerCloseHandlers( event, target );
		this._updateContent( target, event );
	},

	_updateContent: function( target, event ) {
		var content,
			contentOption = this.options.content,
			that = this,
			eventType = event ? event.type : null;

		if ( typeof contentOption === "string" ) {
			return this._open( event, target, contentOption );
		}

		content = contentOption.call( target[0], function( response ) {

			// IE may instantly serve a cached response for ajax requests
			// delay this call to _open so the other call to _open runs first
			that._delay(function() {

				// Ignore async response if tooltip was closed already
				if ( !target.data( "ui-tooltip-open" ) ) {
					return;
				}

				// jQuery creates a special event for focusin when it doesn't
				// exist natively. To improve performance, the native event
				// object is reused and the type is changed. Therefore, we can't
				// rely on the type being correct after the event finished
				// bubbling, so we set it back to the previous value. (#8740)
				if ( event ) {
					event.type = eventType;
				}
				this._open( event, target, response );
			});
		});
		if ( content ) {
			this._open( event, target, content );
		}
	},

	_open: function( event, target, content ) {
		var tooltipData, tooltip, delayedShow, a11yContent,
			positionOption = $.extend( {}, this.options.position );

		if ( !content ) {
			return;
		}

		// Content can be updated multiple times. If the tooltip already
		// exists, then just update the content and bail.
		tooltipData = this._find( target );
		if ( tooltipData ) {
			tooltipData.tooltip.find( ".ui-tooltip-content" ).html( content );
			return;
		}

		// if we have a title, clear it to prevent the native tooltip
		// we have to check first to avoid defining a title if none exists
		// (we don't want to cause an element to start matching [title])
		//
		// We use removeAttr only for key events, to allow IE to export the correct
		// accessible attributes. For mouse events, set to empty string to avoid
		// native tooltip showing up (happens only when removing inside mouseover).
		if ( target.is( "[title]" ) ) {
			if ( event && event.type === "mouseover" ) {
				target.attr( "title", "" );
			} else {
				target.removeAttr( "title" );
			}
		}

		tooltipData = this._tooltip( target );
		tooltip = tooltipData.tooltip;
		this._addDescribedBy( target, tooltip.attr( "id" ) );
		tooltip.find( ".ui-tooltip-content" ).html( content );

		// Support: Voiceover on OS X, JAWS on IE <= 9
		// JAWS announces deletions even when aria-relevant="additions"
		// Voiceover will sometimes re-read the entire log region's contents from the beginning
		this.liveRegion.children().hide();
		if ( content.clone ) {
			a11yContent = content.clone();
			a11yContent.removeAttr( "id" ).find( "[id]" ).removeAttr( "id" );
		} else {
			a11yContent = content;
		}
		$( "<div>" ).html( a11yContent ).appendTo( this.liveRegion );

		function position( event ) {
			positionOption.of = event;
			if ( tooltip.is( ":hidden" ) ) {
				return;
			}
			tooltip.position( positionOption );
		}
		if ( this.options.track && event && /^mouse/.test( event.type ) ) {
			this._on( this.document, {
				mousemove: position
			});
			// trigger once to override element-relative positioning
			position( event );
		} else {
			tooltip.position( $.extend({
				of: target
			}, this.options.position ) );
		}

		tooltip.hide();

		this._show( tooltip, this.options.show );
		// Handle tracking tooltips that are shown with a delay (#8644). As soon
		// as the tooltip is visible, position the tooltip using the most recent
		// event.
		if ( this.options.show && this.options.show.delay ) {
			delayedShow = this.delayedShow = setInterval(function() {
				if ( tooltip.is( ":visible" ) ) {
					position( positionOption.of );
					clearInterval( delayedShow );
				}
			}, $.fx.interval );
		}

		this._trigger( "open", event, { tooltip: tooltip } );
	},

	_registerCloseHandlers: function( event, target ) {
		var events = {
			keyup: function( event ) {
				if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
					var fakeEvent = $.Event(event);
					fakeEvent.currentTarget = target[0];
					this.close( fakeEvent, true );
				}
			}
		};

		// Only bind remove handler for delegated targets. Non-delegated
		// tooltips will handle this in destroy.
		if ( target[ 0 ] !== this.element[ 0 ] ) {
			events.remove = function() {
				this._removeTooltip( this._find( target ).tooltip );
			};
		}

		if ( !event || event.type === "mouseover" ) {
			events.mouseleave = "close";
		}
		if ( !event || event.type === "focusin" ) {
			events.focusout = "close";
		}
		this._on( true, target, events );
	},

	close: function( event ) {
		var tooltip,
			that = this,
			target = $( event ? event.currentTarget : this.element ),
			tooltipData = this._find( target );

		// The tooltip may already be closed
		if ( !tooltipData ) {

			// We set ui-tooltip-open immediately upon open (in open()), but only set the
			// additional data once there's actually content to show (in _open()). So even if the
			// tooltip doesn't have full data, we always remove ui-tooltip-open in case we're in
			// the period between open() and _open().
			target.removeData( "ui-tooltip-open" );
			return;
		}

		tooltip = tooltipData.tooltip;

		// disabling closes the tooltip, so we need to track when we're closing
		// to avoid an infinite loop in case the tooltip becomes disabled on close
		if ( tooltipData.closing ) {
			return;
		}

		// Clear the interval for delayed tracking tooltips
		clearInterval( this.delayedShow );

		// only set title if we had one before (see comment in _open())
		// If the title attribute has changed since open(), don't restore
		if ( target.data( "ui-tooltip-title" ) && !target.attr( "title" ) ) {
			target.attr( "title", target.data( "ui-tooltip-title" ) );
		}

		this._removeDescribedBy( target );

		tooltipData.hiding = true;
		tooltip.stop( true );
		this._hide( tooltip, this.options.hide, function() {
			that._removeTooltip( $( this ) );
		});

		target.removeData( "ui-tooltip-open" );
		this._off( target, "mouseleave focusout keyup" );

		// Remove 'remove' binding only on delegated targets
		if ( target[ 0 ] !== this.element[ 0 ] ) {
			this._off( target, "remove" );
		}
		this._off( this.document, "mousemove" );

		if ( event && event.type === "mouseleave" ) {
			$.each( this.parents, function( id, parent ) {
				$( parent.element ).attr( "title", parent.title );
				delete that.parents[ id ];
			});
		}

		tooltipData.closing = true;
		this._trigger( "close", event, { tooltip: tooltip } );
		if ( !tooltipData.hiding ) {
			tooltipData.closing = false;
		}
	},

	_tooltip: function( element ) {
		var tooltip = $( "<div>" )
				.attr( "role", "tooltip" )
				.addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " +
					( this.options.tooltipClass || "" ) ),
			id = tooltip.uniqueId().attr( "id" );

		$( "<div>" )
			.addClass( "ui-tooltip-content" )
			.appendTo( tooltip );

		tooltip.appendTo( this.document[0].body );

		return this.tooltips[ id ] = {
			element: element,
			tooltip: tooltip
		};
	},

	_find: function( target ) {
		var id = target.data( "ui-tooltip-id" );
		return id ? this.tooltips[ id ] : null;
	},

	_removeTooltip: function( tooltip ) {
		tooltip.remove();
		delete this.tooltips[ tooltip.attr( "id" ) ];
	},

	_destroy: function() {
		var that = this;

		// close open tooltips
		$.each( this.tooltips, function( id, tooltipData ) {
			// Delegate to close method to handle common cleanup
			var event = $.Event( "blur" ),
				element = tooltipData.element;
			event.target = event.currentTarget = element[ 0 ];
			that.close( event, true );

			// Remove immediately; destroying an open tooltip doesn't use the
			// hide animation
			$( "#" + id ).remove();

			// Restore the title
			if ( element.data( "ui-tooltip-title" ) ) {
				// If the title attribute has changed since open(), don't restore
				if ( !element.attr( "title" ) ) {
					element.attr( "title", element.data( "ui-tooltip-title" ) );
				}
				element.removeData( "ui-tooltip-title" );
			}
		});
		this.liveRegion.remove();
	}
});



}));/*!
 * jQuery UI Touch Punch 0.2.3
 *
 * Copyright 2011–2014, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Depends:
 *  jquery.ui.widget.js
 *  jquery.ui.mouse.js
 */
(function ($) {

  // Detect touch support
  $.support.touch = 'ontouchend' in document;

  // Ignore browsers without touch support
  if (!$.support.touch) {
    return;
  }

  var mouseProto = $.ui.mouse.prototype,
      _mouseInit = mouseProto._mouseInit,
      _mouseDestroy = mouseProto._mouseDestroy,
      touchHandled;

  /**
   * Simulate a mouse event based on a corresponding touch event
   * @param {Object} event A touch event
   * @param {String} simulatedType The corresponding mouse event
   */
  function simulateMouseEvent (event, simulatedType) {

    // Ignore multi-touch events
    if (event.originalEvent.touches.length > 1) {
      return;
    }

    event.preventDefault();

    var touch = event.originalEvent.changedTouches[0],
        simulatedEvent = document.createEvent('MouseEvents');
    
    // Initialize the simulated mouse event using the touch event's coordinates
    simulatedEvent.initMouseEvent(
      simulatedType,    // type
      true,             // bubbles                    
      true,             // cancelable                 
      window,           // view                       
      1,                // detail                     
      touch.screenX,    // screenX                    
      touch.screenY,    // screenY                    
      touch.clientX,    // clientX                    
      touch.clientY,    // clientY                    
      false,            // ctrlKey                    
      false,            // altKey                     
      false,            // shiftKey                   
      false,            // metaKey                    
      0,                // button                     
      null              // relatedTarget              
    );

    // Dispatch the simulated event to the target element
    event.target.dispatchEvent(simulatedEvent);
  }

  /**
   * Handle the jQuery UI widget's touchstart events
   * @param {Object} event The widget element's touchstart event
   */
  mouseProto._touchStart = function (event) {

    var self = this;

    // Ignore the event if another widget is already being handled
    if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
      return;
    }

    // Set the flag to prevent other widgets from inheriting the touch event
    touchHandled = true;

    // Track movement to determine if interaction was a click
    self._touchMoved = false;

    // Simulate the mouseover event
    simulateMouseEvent(event, 'mouseover');

    // Simulate the mousemove event
    simulateMouseEvent(event, 'mousemove');

    // Simulate the mousedown event
    simulateMouseEvent(event, 'mousedown');
  };

  /**
   * Handle the jQuery UI widget's touchmove events
   * @param {Object} event The document's touchmove event
   */
  mouseProto._touchMove = function (event) {

    // Ignore event if not handled
    if (!touchHandled) {
      return;
    }

    // Interaction was not a click
    this._touchMoved = true;

    // Simulate the mousemove event
    simulateMouseEvent(event, 'mousemove');
  };

  /**
   * Handle the jQuery UI widget's touchend events
   * @param {Object} event The document's touchend event
   */
  mouseProto._touchEnd = function (event) {

    // Ignore event if not handled
    if (!touchHandled) {
      return;
    }

    // Simulate the mouseup event
    simulateMouseEvent(event, 'mouseup');

    // Simulate the mouseout event
    simulateMouseEvent(event, 'mouseout');

    // If the touch interaction did not move, it should trigger a click
    if (!this._touchMoved) {

      // Simulate the click event
      simulateMouseEvent(event, 'click');
    }

    // Unset the flag to allow other widgets to inherit the touch event
    touchHandled = false;
  };

  /**
   * A duck punch of the $.ui.mouse _mouseInit method to support touch events.
   * This method extends the widget with bound touch event handlers that
   * translate touch events to mouse events and pass them to the widget's
   * original mouse event handling methods.
   */
  mouseProto._mouseInit = function () {
    
    var self = this;

    // Delegate the touch handlers to the widget's element
    self.element.bind({
      touchstart: $.proxy(self, '_touchStart'),
      touchmove: $.proxy(self, '_touchMove'),
      touchend: $.proxy(self, '_touchEnd')
    });

    // Call the original $.ui.mouse init method
    _mouseInit.call(self);
  };

  /**
   * Remove the touch event handlers
   */
  mouseProto._mouseDestroy = function () {
    
    var self = this;

    // Delegate the touch handlers to the widget's element
    self.element.unbind({
      touchstart: $.proxy(self, '_touchStart'),
      touchmove: $.proxy(self, '_touchMove'),
      touchend: $.proxy(self, '_touchEnd')
    });

    // Call the original $.ui.mouse destroy method
    _mouseDestroy.call(self);
  };

})(jQuery);/*
 * jQuery UI Widget 1.10.3+amd
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2013 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/jQuery.widget/
 */

(function(factory) {
  if (typeof define === "function" && define.amd) {
    // Register as an anonymous AMD module:
    define([ "jquery" ], factory);
  } else {
    // Browser globals:
    factory(jQuery);
  }
}(function($, undefined) {

  var uuid = 0, slice = Array.prototype.slice, _cleanData = $.cleanData;
  $.cleanData = function(elems) {
    for (var i = 0, elem; (elem = elems[i]) != null; i++) {
      try {
        $(elem).triggerHandler("remove");
        // http://bugs.jquery.com/ticket/8235
      } catch (e) {
      }
    }
    _cleanData(elems);
  };

  $.widget = function(name, base, prototype) {
    var fullName, existingConstructor, constructor, basePrototype,
    // proxiedPrototype allows the provided prototype to remain unmodified
    // so that it can be used as a mixin for multiple widgets (#8876)
    proxiedPrototype = {}, namespace = name.split(".")[0];

    name = name.split(".")[1];
    fullName = namespace + "-" + name;

    if (!prototype) {
      prototype = base;
      base = $.Widget;
    }

    // create selector for plugin
    $.expr[":"][fullName.toLowerCase()] = function(elem) {
      return !!$.data(elem, fullName);
    };

    $[namespace] = $[namespace] || {};
    existingConstructor = $[namespace][name];
    constructor = $[namespace][name] = function(options, element) {
      // allow instantiation without "new" keyword
      if (!this._createWidget) {
        return new constructor(options, element);
      }

      // allow instantiation without initializing for simple inheritance
      // must use "new" keyword (the code above always passes args)
      if (arguments.length) {
        this._createWidget(options, element);
      }
    };
    // extend with the existing constructor to carry over any static properties
    $.extend(constructor, existingConstructor, {
      version : prototype.version,
      // copy the object used to create the prototype in case we need to
      // redefine the widget later
      _proto : $.extend({}, prototype),
      // track widgets that inherit from this widget in case this widget is
      // redefined after a widget inherits from it
      _childConstructors : []
    });

    basePrototype = new base();
    // we need to make the options hash a property directly on the new instance
    // otherwise we'll modify the options hash on the prototype that we're
    // inheriting from
    basePrototype.options = $.widget.extend({}, basePrototype.options);
    $.each(prototype, function(prop, value) {
      if (!$.isFunction(value)) {
        proxiedPrototype[prop] = value;
        return;
      }
      proxiedPrototype[prop] = (function() {
        var _super = function() {
          return base.prototype[prop].apply(this, arguments);
        }, _superApply = function(args) {
          return base.prototype[prop].apply(this, args);
        };
        return function() {
          var __super = this._super, __superApply = this._superApply, returnValue;

          this._super = _super;
          this._superApply = _superApply;

          returnValue = value.apply(this, arguments);

          this._super = __super;
          this._superApply = __superApply;

          return returnValue;
        };
      })();
    });
    constructor.prototype = $.widget.extend(basePrototype, {
      // TODO: remove support for widgetEventPrefix
      // always use the name + a colon as the prefix, e.g., draggable:start
      // don't prefix for widgets that aren't DOM-based
      widgetEventPrefix : existingConstructor ? basePrototype.widgetEventPrefix : name
    }, proxiedPrototype, {
      constructor : constructor,
      namespace : namespace,
      widgetName : name,
      widgetFullName : fullName
    });

    // If this widget is being redefined then we need to find all widgets that
    // are inheriting from it and redefine all of them so that they inherit from
    // the new version of this widget. We're essentially trying to replace one
    // level in the prototype chain.
    if (existingConstructor) {
      $.each(existingConstructor._childConstructors, function(i, child) {
        var childPrototype = child.prototype;

        // redefine the child widget using the same prototype that was
        // originally used, but inherit from the new version of the base
        $.widget(childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto);
      });
      // remove the list of existing child constructors from the old constructor
      // so the old child constructors can be garbage collected
      delete existingConstructor._childConstructors;
    } else {
      base._childConstructors.push(constructor);
    }

    $.widget.bridge(name, constructor);
  };

  $.widget.extend = function(target) {
    var input = slice.call(arguments, 1), inputIndex = 0, inputLength = input.length, key, value;
    for (; inputIndex < inputLength; inputIndex++) {
      for (key in input[inputIndex]) {
        value = input[inputIndex][key];
        if (input[inputIndex].hasOwnProperty(key) && value !== undefined) {
          // Clone objects
          if ($.isPlainObject(value)) {
            target[key] = $.isPlainObject(target[key]) ? $.widget.extend({}, target[key], value) :
            // Don't extend strings, arrays, etc. with objects
            $.widget.extend({}, value);
            // Copy everything else by reference
          } else {
            target[key] = value;
          }
        }
      }
    }
    return target;
  };

  $.widget.bridge = function(name, object) {
    var fullName = object.prototype.widgetFullName || name;
    $.fn[name] = function(options) {
      var isMethodCall = typeof options === "string", args = slice.call(arguments, 1), returnValue = this;

      // allow multiple hashes to be passed on init
      options = !isMethodCall && args.length ? $.widget.extend.apply(null, [ options ].concat(args)) : options;

      if (isMethodCall) {
        this.each(function() {
          var methodValue, instance = $.data(this, fullName);
          if (!instance) {
            return $.error("cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'");
          }
          if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
            return $.error("no such method '" + options + "' for " + name + " widget instance");
          }
          methodValue = instance[options].apply(instance, args);
          if (methodValue !== instance && methodValue !== undefined) {
            returnValue = methodValue && methodValue.jquery ? returnValue.pushStack(methodValue.get()) : methodValue;
            return false;
          }
        });
      } else {
        this.each(function() {
          var instance = $.data(this, fullName);
          if (instance) {
            instance.option(options || {})._init();
          } else {
            $.data(this, fullName, new object(options, this));
          }
        });
      }

      return returnValue;
    };
  };

  $.Widget = function( /* options, element */) {
  };
  $.Widget._childConstructors = [];

  $.Widget.prototype = {
    widgetName : "widget",
    widgetEventPrefix : "",
    defaultElement : "<div>",
    options : {
      disabled : false,

      // callbacks
      create : null
    },
    _createWidget : function(options, element) {
      element = $(element || this.defaultElement || this)[0];
      this.element = $(element);
      this.uuid = uuid++;
      this.eventNamespace = "." + this.widgetName + this.uuid;
      this.options = $.widget.extend({}, this.options, this._getCreateOptions(), options);

      this.bindings = $();
      this.hoverable = $();
      this.focusable = $();

      if (element !== this) {
        $.data(element, this.widgetFullName, this);
        this._on(true, this.element, {
          remove : function(event) {
            if (event.target === element) {
              this.destroy();
            }
          }
        });
        this.document = $(element.style ?
        // element within the document
        element.ownerDocument :
        // element is window or document
        element.document || element);
        this.window = $(this.document[0].defaultView || this.document[0].parentWindow);
      }

      this._create();
      this._trigger("create", null, this._getCreateEventData());
      this._init();
    },
    _getCreateOptions : $.noop,
    _getCreateEventData : $.noop,
    _create : $.noop,
    _init : $.noop,

    destroy : function() {
      this._destroy();
      // we can probably remove the unbind calls in 2.0
      // all event bindings should go through this._on()
      this.element.unbind(this.eventNamespace)
      // 1.9 BC for #7810
      // TODO remove dual storage
      .removeData(this.widgetName).removeData(this.widgetFullName)
      // support: jquery <1.6.3
      // http://bugs.jquery.com/ticket/9413
      .removeData($.camelCase(this.widgetFullName));
      this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(
          this.widgetFullName + "-disabled " + "ui-state-disabled");

      // clean up events and states
      this.bindings.unbind(this.eventNamespace);
        this.hoverable.removeClass("ui-state-hover");
        this.focusable.removeClass("ui-state-focus");
    },
    _destroy : $.noop,

    widget : function() {
      return this.element;
    },

    option : function(key, value) {
      var options = key, parts, curOption, i;

      if (arguments.length === 0) {
        // don't return a reference to the internal hash
        return $.widget.extend({}, this.options);
      }

      if (typeof key === "string") {
        // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
        options = {};
        parts = key.split(".");
        key = parts.shift();
        if (parts.length) {
          curOption = options[key] = $.widget.extend({}, this.options[key]);
          for (i = 0; i < parts.length - 1; i++) {
            curOption[parts[i]] = curOption[parts[i]] || {};
            curOption = curOption[parts[i]];
          }
          key = parts.pop();
          if (value === undefined) {
            return curOption[key] === undefined ? null : curOption[key];
          }
          curOption[key] = value;
        } else {
          if (value === undefined) {
            return this.options[key] === undefined ? null : this.options[key];
          }
          options[key] = value;
        }
      }

      this._setOptions(options);

      return this;
    },
    _setOptions : function(options) {
      var key;

      for (key in options) {
        this._setOption(key, options[key]);
      }

      return this;
    },
    _setOption : function(key, value) {
      this.options[key] = value;

      if (key === "disabled") {
        this.widget().toggleClass(this.widgetFullName + "-disabled ui-state-disabled", !!value).attr("aria-disabled", value);
        if (this.hoverable) {
        this.hoverable.removeClass("ui-state-hover");
        }
        if (this.focusable) {
        this.focusable.removeClass("ui-state-focus");
        }
      }

      return this;
    },

    enable : function() {
      return this._setOption("disabled", false);
    },
    disable : function() {
      return this._setOption("disabled", true);
    },

    _on : function(suppressDisabledCheck, element, handlers) {
      var delegateElement, instance = this;

      // no suppressDisabledCheck flag, shuffle arguments
      if (typeof suppressDisabledCheck !== "boolean") {
        handlers = element;
        element = suppressDisabledCheck;
        suppressDisabledCheck = false;
      }

      // no element argument, shuffle and use this.element
      if (!handlers) {
        handlers = element;
        element = this.element;
        delegateElement = this.widget();
      } else {
        // accept selectors, DOM elements
        element = delegateElement = $(element);
        this.bindings = this.bindings.add(element);
      }

      $.each(handlers, function(event, handler) {
        function handlerProxy() {
          // allow widgets to customize the disabled handling
          // - disabled as an array instead of boolean
          // - disabled class as method for disabling individual parts
          if (!suppressDisabledCheck && (instance.options.disabled === true || $(this).hasClass("ui-state-disabled"))) {
            return;
          }
          return (typeof handler === "string" ? instance[handler] : handler).apply(instance, arguments);
        }

        // copy the guid so direct unbinding works
        if (typeof handler !== "string") {
          handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++;
        }

        var match = event.match(/^(\w+)\s*(.*)$/), eventName = match[1] + instance.eventNamespace, selector = match[2];
        if (selector) {
          delegateElement.delegate(selector, eventName, handlerProxy);
        } else {
          element.bind(eventName, handlerProxy);
        }
      });
    },

    _off : function(element, eventName) {
      eventName = (eventName || "").split(" ").join(this.eventNamespace + " ") + this.eventNamespace;
      element.unbind(eventName).undelegate(eventName);
    },

    _delay : function(handler, delay) {
      function handlerProxy() {
        return (typeof handler === "string" ? instance[handler] : handler).apply(instance, arguments);
      }
      var instance = this;
      return setTimeout(handlerProxy, delay || 0);
    },

    _hoverable : function(element) {
      this.hoverable = this.hoverable.add(element);
      this._on(element, {
        mouseenter : function(event) {
          $(event.currentTarget).addClass("ui-state-hover");
        },
        mouseleave : function(event) {
          $(event.currentTarget).removeClass("ui-state-hover");
        }
      });
    },

    _focusable : function(element) {
      this.focusable = this.focusable.add(element);
      this._on(element, {
        focusin : function(event) {
          $(event.currentTarget).addClass("ui-state-focus");
        },
        focusout : function(event) {
          $(event.currentTarget).removeClass("ui-state-focus");
        }
      });
    },

    _trigger : function(type, event, data) {
      var prop, orig, callback = this.options[type];

      data = data || {};
      event = $.Event(event);
      event.type = (type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type).toLowerCase();
      // the original event may come from any element
      // so we need to reset the target on the new event
      event.target = this.element[0];

      // copy original event properties over to the new event
      orig = event.originalEvent;
      if (orig) {
        for (prop in orig) {
          if (!(prop in event)) {
            event[prop] = orig[prop];
          }
        }
      }

      this.element.trigger(event, data);
      return !($.isFunction(callback) && callback.apply(this.element[0], [ event ].concat(data)) === false || event.isDefaultPrevented());
    }
  };

  $.each({
    show : "fadeIn",
    hide : "fadeOut"
  }, function(method, defaultEffect) {
    $.Widget.prototype["_" + method] = function(element, options, callback) {
      if (typeof options === "string") {
        options = {
          effect : options
        };
      }
      var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect
          || defaultEffect;
      options = options || {};
      if (typeof options === "number") {
        options = {
          duration : options
        };
      }
      hasOptions = !$.isEmptyObject(options);
      options.complete = callback;
      if (options.delay) {
        element.delay(options.delay);
      }
      if (hasOptions && $.effects && $.effects.effect[effectName]) {
        element[method](options);
      } else if (effectName !== method && element[effectName]) {
        element[effectName](options.duration, options.easing, callback);
      } else {
        element.queue(function(next) {
          $(this)[method]();
          if (callback) {
            callback.call(element[0]);
          }
          next();
        });
      }
    };
  });

}));
/*
 * jQuery File Upload Plugin 5.32.2
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window, document, location, File, Blob, FormData */

(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define([
            'jquery',
            'jquery.ui.widget'
        ], factory);
    } else {
        // Browser globals:
        factory(window.jQuery);
    }
}(function ($) {
    'use strict';

    // Detect file input support, based on
    // http://viljamis.com/blog/2012/file-upload-support-on-mobile/
    $.support.fileInput = !(new RegExp(
        // Handle devices which give false positives for the feature detection:
        '(Android (1\\.[0156]|2\\.[01]))' +
            '|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)' +
            '|(w(eb)?OSBrowser)|(webOS)' +
            '|(Kindle/(1\\.0|2\\.[05]|3\\.0))'
    ).test(window.navigator.userAgent) ||
        // Feature detection for all other devices:
        $('<input type="file">').prop('disabled'));

    // The FileReader API is not actually used, but works as feature detection,
    // as e.g. Safari supports XHR file uploads via the FormData API,
    // but not non-multipart XHR file uploads:
    $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader);
    $.support.xhrFormDataFileUpload = !!window.FormData;

    // Detect support for Blob slicing (required for chunked uploads):
    $.support.blobSlice = window.Blob && (Blob.prototype.slice ||
        Blob.prototype.webkitSlice || Blob.prototype.mozSlice);

    // The fileupload widget listens for change events on file input fields defined
    // via fileInput setting and paste or drop events of the given dropZone.
    // In addition to the default jQuery Widget methods, the fileupload widget
    // exposes the "add" and "send" methods, to add or directly send files using
    // the fileupload API.
    // By default, files added via file input selection, paste, drag & drop or
    // "add" method are uploaded immediately, but it is possible to override
    // the "add" callback option to queue file uploads.
    $.widget('blueimp.fileupload', {

        options: {
            // The drop target element(s), by the default the complete document.
            // Set to null to disable drag & drop support:
            dropZone: $(document),
            // The paste target element(s), by the default the complete document.
            // Set to null to disable paste support:
            pasteZone: $(document),
            // The file input field(s), that are listened to for change events.
            // If undefined, it is set to the file input fields inside
            // of the widget element on plugin initialization.
            // Set to null to disable the change listener.
            fileInput: undefined,
            // By default, the file input field is replaced with a clone after
            // each input field change event. This is required for iframe transport
            // queues and allows change events to be fired for the same file
            // selection, but can be disabled by setting the following option to false:
            replaceFileInput: true,
            // The parameter name for the file form data (the request argument name).
            // If undefined or empty, the name property of the file input field is
            // used, or "files[]" if the file input name property is also empty,
            // can be a string or an array of strings:
            paramName: undefined,
            // By default, each file of a selection is uploaded using an individual
            // request for XHR type uploads. Set to false to upload file
            // selections in one request each:
            singleFileUploads: true,
            // To limit the number of files uploaded with one XHR request,
            // set the following option to an integer greater than 0:
            limitMultiFileUploads: undefined,
            // Set the following option to true to issue all file upload requests
            // in a sequential order:
            sequentialUploads: false,
            // To limit the number of concurrent uploads,
            // set the following option to an integer greater than 0:
            limitConcurrentUploads: undefined,
            // Set the following option to true to force iframe transport uploads:
            forceIframeTransport: false,
            // Set the following option to the location of a redirect url on the
            // origin server, for cross-domain iframe transport uploads:
            redirect: undefined,
            // The parameter name for the redirect url, sent as part of the form
            // data and set to 'redirect' if this option is empty:
            redirectParamName: undefined,
            // Set the following option to the location of a postMessage window,
            // to enable postMessage transport uploads:
            postMessage: undefined,
            // By default, XHR file uploads are sent as multipart/form-data.
            // The iframe transport is always using multipart/form-data.
            // Set to false to enable non-multipart XHR uploads:
            multipart: true,
            // To upload large files in smaller chunks, set the following option
            // to a preferred maximum chunk size. If set to 0, null or undefined,
            // or the browser does not support the required Blob API, files will
            // be uploaded as a whole.
            maxChunkSize: undefined,
            // When a non-multipart upload or a chunked multipart upload has been
            // aborted, this option can be used to resume the upload by setting
            // it to the size of the already uploaded bytes. This option is most
            // useful when modifying the options object inside of the "add" or
            // "send" callbacks, as the options are cloned for each file upload.
            uploadedBytes: undefined,
            // By default, failed (abort or error) file uploads are removed from the
            // global progress calculation. Set the following option to false to
            // prevent recalculating the global progress data:
            recalculateProgress: true,
            // Interval in milliseconds to calculate and trigger progress events:
            progressInterval: 100,
            // Interval in milliseconds to calculate progress bitrate:
            bitrateInterval: 500,
            // By default, uploads are started automatically when adding files:
            autoUpload: true,

            // Error and info messages:
            messages: {
                uploadedBytes: 'Uploaded bytes exceed file size'
            },

            // Translation function, gets the message key to be translated
            // and an object with context specific data as arguments:
            i18n: function (message, context) {
                message = this.messages[message] || message.toString();
                if (context) {
                    $.each(context, function (key, value) {
                        message = message.replace('{' + key + '}', value);
                    });
                }
                return message;
            },

            // Additional form data to be sent along with the file uploads can be set
            // using this option, which accepts an array of objects with name and
            // value properties, a function returning such an array, a FormData
            // object (for XHR file uploads), or a simple object.
            // The form of the first fileInput is given as parameter to the function:
            formData: function (form) {
                return form.serializeArray();
            },

            // The add callback is invoked as soon as files are added to the fileupload
            // widget (via file input selection, drag & drop, paste or add API call).
            // If the singleFileUploads option is enabled, this callback will be
            // called once for each file in the selection for XHR file uploads, else
            // once for each file selection.
            //
            // The upload starts when the submit method is invoked on the data parameter.
            // The data object contains a files property holding the added files
            // and allows you to override plugin options as well as define ajax settings.
            //
            // Listeners for this callback can also be bound the following way:
            // .bind('fileuploadadd', func);
            //
            // data.submit() returns a Promise object and allows to attach additional
            // handlers using jQuery's Deferred callbacks:
            // data.submit().done(func).fail(func).always(func);
            add: function (e, data) {
                if (data.autoUpload || (data.autoUpload !== false &&
                        $(this).fileupload('option', 'autoUpload'))) {
                    data.process().done(function () {
                        data.submit();
                    });
                }
            },

            // Other callbacks:

            // Callback for the submit event of each file upload:
            // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);

            // Callback for the start of each file upload request:
            // send: function (e, data) {}, // .bind('fileuploadsend', func);

            // Callback for successful uploads:
            // done: function (e, data) {}, // .bind('fileuploaddone', func);

            // Callback for failed (abort or error) uploads:
            // fail: function (e, data) {}, // .bind('fileuploadfail', func);

            // Callback for completed (success, abort or error) requests:
            // always: function (e, data) {}, // .bind('fileuploadalways', func);

            // Callback for upload progress events:
            // progress: function (e, data) {}, // .bind('fileuploadprogress', func);

            // Callback for global upload progress events:
            // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);

            // Callback for uploads start, equivalent to the global ajaxStart event:
            // start: function (e) {}, // .bind('fileuploadstart', func);

            // Callback for uploads stop, equivalent to the global ajaxStop event:
            // stop: function (e) {}, // .bind('fileuploadstop', func);

            // Callback for change events of the fileInput(s):
            // change: function (e, data) {}, // .bind('fileuploadchange', func);

            // Callback for paste events to the pasteZone(s):
            // paste: function (e, data) {}, // .bind('fileuploadpaste', func);

            // Callback for drop events of the dropZone(s):
            // drop: function (e, data) {}, // .bind('fileuploaddrop', func);

            // Callback for dragover events of the dropZone(s):
            // dragover: function (e) {}, // .bind('fileuploaddragover', func);

            // Callback for the start of each chunk upload request:
            // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func);

            // Callback for successful chunk uploads:
            // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func);

            // Callback for failed (abort or error) chunk uploads:
            // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func);

            // Callback for completed (success, abort or error) chunk upload requests:
            // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func);

            // The plugin options are used as settings object for the ajax calls.
            // The following are jQuery ajax settings required for the file uploads:
            processData: false,
            contentType: false,
            cache: false
        },

        // A list of options that require reinitializing event listeners and/or
        // special initialization code:
        _specialOptions: [
            'fileInput',
            'dropZone',
            'pasteZone',
            'multipart',
            'forceIframeTransport'
        ],

        _blobSlice: $.support.blobSlice && function () {
            var slice = this.slice || this.webkitSlice || this.mozSlice;
            return slice.apply(this, arguments);
        },

        _BitrateTimer: function () {
            this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime());
            this.loaded = 0;
            this.bitrate = 0;
            this.getBitrate = function (now, loaded, interval) {
                var timeDiff = now - this.timestamp;
                if (!this.bitrate || !interval || timeDiff > interval) {
                    this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
                    this.loaded = loaded;
                    this.timestamp = now;
                }
                return this.bitrate;
            };
        },

        _isXHRUpload: function (options) {
            return !options.forceIframeTransport &&
                ((!options.multipart && $.support.xhrFileUpload) ||
                $.support.xhrFormDataFileUpload);
        },

        _getFormData: function (options) {
            var formData;
            if (typeof options.formData === 'function') {
                return options.formData(options.form);
            }
            if ($.isArray(options.formData)) {
                return options.formData;
            }
            if ($.type(options.formData) === 'object') {
                formData = [];
                $.each(options.formData, function (name, value) {
                    formData.push({name: name, value: value});
                });
                return formData;
            }
            return [];
        },

        _getTotal: function (files) {
            var total = 0;
            $.each(files, function (index, file) {
                total += file.size || 1;
            });
            return total;
        },

        _initProgressObject: function (obj) {
            var progress = {
                loaded: 0,
                total: 0,
                bitrate: 0
            };
            if (obj._progress) {
                $.extend(obj._progress, progress);
            } else {
                obj._progress = progress;
            }
        },

        _initResponseObject: function (obj) {
            var prop;
            if (obj._response) {
                for (prop in obj._response) {
                    if (obj._response.hasOwnProperty(prop)) {
                        delete obj._response[prop];
                    }
                }
            } else {
                obj._response = {};
            }
        },

        _onProgress: function (e, data) {
            if (e.lengthComputable) {
                var now = ((Date.now) ? Date.now() : (new Date()).getTime()),
                    loaded;
                if (data._time && data.progressInterval &&
                        (now - data._time < data.progressInterval) &&
                        e.loaded !== e.total) {
                    return;
                }
                data._time = now;
                loaded = Math.floor(
                    e.loaded / e.total * (data.chunkSize || data._progress.total)
                ) + (data.uploadedBytes || 0);
                // Add the difference from the previously loaded state
                // to the global loaded counter:
                this._progress.loaded += (loaded - data._progress.loaded);
                this._progress.bitrate = this._bitrateTimer.getBitrate(
                    now,
                    this._progress.loaded,
                    data.bitrateInterval
                );
                data._progress.loaded = data.loaded = loaded;
                data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate(
                    now,
                    loaded,
                    data.bitrateInterval
                );
                // Trigger a custom progress event with a total data property set
                // to the file size(s) of the current upload and a loaded data
                // property calculated accordingly:
                this._trigger('progress', e, data);
                // Trigger a global progress event for all current file uploads,
                // including ajax calls queued for sequential file uploads:
                this._trigger('progressall', e, this._progress);
            }
        },

        _initProgressListener: function (options) {
            var that = this,
                xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
            // Accesss to the native XHR object is required to add event listeners
            // for the upload progress event:
            if (xhr.upload) {
                $(xhr.upload).bind('progress', function (e) {
                    var oe = e.originalEvent;
                    // Make sure the progress event properties get copied over:
                    e.lengthComputable = oe.lengthComputable;
                    e.loaded = oe.loaded;
                    e.total = oe.total;
                    that._onProgress(e, options);
                });
                options.xhr = function () {
                    return xhr;
                };
            }
        },

        _isInstanceOf: function (type, obj) {
            // Cross-frame instanceof check
            return Object.prototype.toString.call(obj) === '[object ' + type + ']';
        },

        _initXHRData: function (options) {
            var that = this,
                formData,
                file = options.files[0],
                // Ignore non-multipart setting if not supported:
                multipart = options.multipart || !$.support.xhrFileUpload,
                paramName = options.paramName[0];
            options.headers = options.headers || {};
            if (options.contentRange) {
                options.headers['Content-Range'] = options.contentRange;
            }
            if (!multipart || options.blob || !this._isInstanceOf('File', file)) {
                options.headers['Content-Disposition'] = 'attachment; filename="' +
                    encodeURI(file.name) + '"';
            }
            if (!multipart) {
                options.contentType = file.type;
                options.data = options.blob || file;
            } else if ($.support.xhrFormDataFileUpload) {
                if (options.postMessage) {
                    // window.postMessage does not allow sending FormData
                    // objects, so we just add the File/Blob objects to
                    // the formData array and let the postMessage window
                    // create the FormData object out of this array:
                    formData = this._getFormData(options);
                    if (options.blob) {
                        formData.push({
                            name: paramName,
                            value: options.blob
                        });
                    } else {
                        $.each(options.files, function (index, file) {
                            formData.push({
                                name: options.paramName[index] || paramName,
                                value: file
                            });
                        });
                    }
                } else {
                    if (that._isInstanceOf('FormData', options.formData)) {
                        formData = options.formData;
                    } else {
                        formData = new FormData();
                        $.each(this._getFormData(options), function (index, field) {
                            formData.append(field.name, field.value);
                        });
                    }
                    if (options.blob) {
                        formData.append(paramName, options.blob, file.name);
                    } else {
                        $.each(options.files, function (index, file) {
                            // This check allows the tests to run with
                            // dummy objects:
                            if (that._isInstanceOf('File', file) ||
                                    that._isInstanceOf('Blob', file)) {
                                formData.append(
                                    options.paramName[index] || paramName,
                                    file,
                                    file.name
                                );
                            }
                        });
                    }
                }
                options.data = formData;
            }
            // Blob reference is not needed anymore, free memory:
            options.blob = null;
        },

        _initIframeSettings: function (options) {
            var targetHost = $('<a></a>').prop('href', options.url).prop('host');
            // Setting the dataType to iframe enables the iframe transport:
            options.dataType = 'iframe ' + (options.dataType || '');
            // The iframe transport accepts a serialized array as form data:
            options.formData = this._getFormData(options);
            // Add redirect url to form data on cross-domain uploads:
            if (options.redirect && targetHost && targetHost !== location.host) {
                options.formData.push({
                    name: options.redirectParamName || 'redirect',
                    value: options.redirect
                });
            }
        },

        _initDataSettings: function (options) {
            if (this._isXHRUpload(options)) {
                if (!this._chunkedUpload(options, true)) {
                    if (!options.data) {
                        this._initXHRData(options);
                    }
                    this._initProgressListener(options);
                }
                if (options.postMessage) {
                    // Setting the dataType to postmessage enables the
                    // postMessage transport:
                    options.dataType = 'postmessage ' + (options.dataType || '');
                }
            } else {
                this._initIframeSettings(options);
            }
        },

        _getParamName: function (options) {
            var fileInput = $(options.fileInput),
                paramName = options.paramName;
            if (!paramName) {
                paramName = [];
                fileInput.each(function () {
                    var input = $(this),
                        name = input.prop('name') || 'files[]',
                        i = (input.prop('files') || [1]).length;
                    while (i) {
                        paramName.push(name);
                        i -= 1;
                    }
                });
                if (!paramName.length) {
                    paramName = [fileInput.prop('name') || 'files[]'];
                }
            } else if (!$.isArray(paramName)) {
                paramName = [paramName];
            }
            return paramName;
        },

        _initFormSettings: function (options) {
            // Retrieve missing options from the input field and the
            // associated form, if available:
            if (!options.form || !options.form.length) {
                options.form = $(options.fileInput.prop('form'));
                // If the given file input doesn't have an associated form,
                // use the default widget file input's form:
                if (!options.form.length) {
                    options.form = $(this.options.fileInput.prop('form'));
                }
            }
            options.paramName = this._getParamName(options);
            if (!options.url) {
                options.url = options.form.prop('action') || location.href;
            }
            // The HTTP request method must be "POST" or "PUT":
            options.type = (options.type || options.form.prop('method') || '')
                .toUpperCase();
            if (options.type !== 'POST' && options.type !== 'PUT' &&
                    options.type !== 'PATCH') {
                options.type = 'POST';
            }
            if (!options.formAcceptCharset) {
                options.formAcceptCharset = options.form.attr('accept-charset');
            }
        },

        _getAJAXSettings: function (data) {
            var options = $.extend({}, this.options, data);
            this._initFormSettings(options);
            this._initDataSettings(options);
            return options;
        },

        // jQuery 1.6 doesn't provide .state(),
        // while jQuery 1.8+ removed .isRejected() and .isResolved():
        _getDeferredState: function (deferred) {
            if (deferred.state) {
                return deferred.state();
            }
            if (deferred.isResolved()) {
                return 'resolved';
            }
            if (deferred.isRejected()) {
                return 'rejected';
            }
            return 'pending';
        },

        // Maps jqXHR callbacks to the equivalent
        // methods of the given Promise object:
        _enhancePromise: function (promise) {
            promise.success = promise.done;
            promise.error = promise.fail;
            promise.complete = promise.always;
            return promise;
        },

        // Creates and returns a Promise object enhanced with
        // the jqXHR methods abort, success, error and complete:
        _getXHRPromise: function (resolveOrReject, context, args) {
            var dfd = $.Deferred(),
                promise = dfd.promise();
            context = context || this.options.context || promise;
            if (resolveOrReject === true) {
                dfd.resolveWith(context, args);
            } else if (resolveOrReject === false) {
                dfd.rejectWith(context, args);
            }
            promise.abort = dfd.promise;
            return this._enhancePromise(promise);
        },

        // Adds convenience methods to the data callback argument:
        _addConvenienceMethods: function (e, data) {
            var that = this,
                getPromise = function (data) {
                    return $.Deferred().resolveWith(that, [data]).promise();
                };
            data.process = function (resolveFunc, rejectFunc) {
                if (resolveFunc || rejectFunc) {
                    data._processQueue = this._processQueue =
                        (this._processQueue || getPromise(this))
                            .pipe(resolveFunc, rejectFunc);
                }
                return this._processQueue || getPromise(this);
            };
            data.submit = function () {
                if (this.state() !== 'pending') {
                    data.jqXHR = this.jqXHR =
                        (that._trigger('submit', e, this) !== false) &&
                        that._onSend(e, this);
                }
                return this.jqXHR || that._getXHRPromise();
            };
            data.abort = function () {
                if (this.jqXHR) {
                    return this.jqXHR.abort();
                }
                return that._getXHRPromise();
            };
            data.state = function () {
                if (this.jqXHR) {
                    return that._getDeferredState(this.jqXHR);
                }
                if (this._processQueue) {
                    return that._getDeferredState(this._processQueue);
                }
            };
            data.progress = function () {
                return this._progress;
            };
            data.response = function () {
                return this._response;
            };
        },

        // Parses the Range header from the server response
        // and returns the uploaded bytes:
        _getUploadedBytes: function (jqXHR) {
            var range = jqXHR.getResponseHeader('Range'),
                parts = range && range.split('-'),
                upperBytesPos = parts && parts.length > 1 &&
                    parseInt(parts[1], 10);
            return upperBytesPos && upperBytesPos + 1;
        },

        // Uploads a file in multiple, sequential requests
        // by splitting the file up in multiple blob chunks.
        // If the second parameter is true, only tests if the file
        // should be uploaded in chunks, but does not invoke any
        // upload requests:
        _chunkedUpload: function (options, testOnly) {
            options.uploadedBytes = options.uploadedBytes || 0;
            var that = this,
                file = options.files[0],
                fs = file.size,
                ub = options.uploadedBytes,
                mcs = options.maxChunkSize || fs,
                slice = this._blobSlice,
                dfd = $.Deferred(),
                promise = dfd.promise(),
                jqXHR,
                upload;
            if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
                    options.data) {
                return false;
            }
            if (testOnly) {
                return true;
            }
            if (ub >= fs) {
                file.error = options.i18n('uploadedBytes');
                return this._getXHRPromise(
                    false,
                    options.context,
                    [null, 'error', file.error]
                );
            }
            // The chunk upload method:
            upload = function () {
                // Clone the options object for each chunk upload:
                var o = $.extend({}, options),
                    currentLoaded = o._progress.loaded;
                o.blob = slice.call(
                    file,
                    ub,
                    ub + mcs,
                    file.type
                );
                // Store the current chunk size, as the blob itself
                // will be dereferenced after data processing:
                o.chunkSize = o.blob.size;
                // Expose the chunk bytes position range:
                o.contentRange = 'bytes ' + ub + '-' +
                    (ub + o.chunkSize - 1) + '/' + fs;
                // Process the upload data (the blob and potential form data):
                that._initXHRData(o);
                // Add progress listeners for this chunk upload:
                that._initProgressListener(o);
                jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
                        that._getXHRPromise(false, o.context))
                    .done(function (result, textStatus, jqXHR) {
                        ub = that._getUploadedBytes(jqXHR) ||
                            (ub + o.chunkSize);
                        // Create a progress event if no final progress event
                        // with loaded equaling total has been triggered
                        // for this chunk:
                        if (currentLoaded + o.chunkSize - o._progress.loaded) {
                            that._onProgress($.Event('progress', {
                                lengthComputable: true,
                                loaded: ub - o.uploadedBytes,
                                total: ub - o.uploadedBytes
                            }), o);
                        }
                        options.uploadedBytes = o.uploadedBytes = ub;
                        o.result = result;
                        o.textStatus = textStatus;
                        o.jqXHR = jqXHR;
                        that._trigger('chunkdone', null, o);
                        that._trigger('chunkalways', null, o);
                        if (ub < fs) {
                            // File upload not yet complete,
                            // continue with the next chunk:
                            upload();
                        } else {
                            dfd.resolveWith(
                                o.context,
                                [result, textStatus, jqXHR]
                            );
                        }
                    })
                    .fail(function (jqXHR, textStatus, errorThrown) {
                        o.jqXHR = jqXHR;
                        o.textStatus = textStatus;
                        o.errorThrown = errorThrown;
                        that._trigger('chunkfail', null, o);
                        that._trigger('chunkalways', null, o);
                        dfd.rejectWith(
                            o.context,
                            [jqXHR, textStatus, errorThrown]
                        );
                    });
            };
            this._enhancePromise(promise);
            promise.abort = function () {
                return jqXHR.abort();
            };
            upload();
            return promise;
        },

        _beforeSend: function (e, data) {
            if (this._active === 0) {
                // the start callback is triggered when an upload starts
                // and no other uploads are currently running,
                // equivalent to the global ajaxStart event:
                this._trigger('start');
                // Set timer for global bitrate progress calculation:
                this._bitrateTimer = new this._BitrateTimer();
                // Reset the global progress values:
                this._progress.loaded = this._progress.total = 0;
                this._progress.bitrate = 0;
            }
            // Make sure the container objects for the .response() and
            // .progress() methods on the data object are available
            // and reset to their initial state:
            this._initResponseObject(data);
            this._initProgressObject(data);
            data._progress.loaded = data.loaded = data.uploadedBytes || 0;
            data._progress.total = data.total = this._getTotal(data.files) || 1;
            data._progress.bitrate = data.bitrate = 0;
            this._active += 1;
            // Initialize the global progress values:
            this._progress.loaded += data.loaded;
            this._progress.total += data.total;
        },

        _onDone: function (result, textStatus, jqXHR, options) {
            var total = options._progress.total,
                response = options._response;
            if (options._progress.loaded < total) {
                // Create a progress event if no final progress event
                // with loaded equaling total has been triggered:
                this._onProgress($.Event('progress', {
                    lengthComputable: true,
                    loaded: total,
                    total: total
                }), options);
            }
            response.result = options.result = result;
            response.textStatus = options.textStatus = textStatus;
            response.jqXHR = options.jqXHR = jqXHR;
            this._trigger('done', null, options);
        },

        _onFail: function (jqXHR, textStatus, errorThrown, options) {
            var response = options._response;
            if (options.recalculateProgress) {
                // Remove the failed (error or abort) file upload from
                // the global progress calculation:
                this._progress.loaded -= options._progress.loaded;
                this._progress.total -= options._progress.total;
            }
            response.jqXHR = options.jqXHR = jqXHR;
            response.textStatus = options.textStatus = textStatus;
            response.errorThrown = options.errorThrown = errorThrown;
            this._trigger('fail', null, options);
        },

        _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
            // jqXHRorResult, textStatus and jqXHRorError are added to the
            // options object via done and fail callbacks
            this._trigger('always', null, options);
        },

        _onSend: function (e, data) {
            if (!data.submit) {
                this._addConvenienceMethods(e, data);
            }
            var that = this,
                jqXHR,
                aborted,
                slot,
                pipe,
                options = that._getAJAXSettings(data),
                send = function () {
                    that._sending += 1;
                    // Set timer for bitrate progress calculation:
                    options._bitrateTimer = new that._BitrateTimer();
                    jqXHR = jqXHR || (
                        ((aborted || that._trigger('send', e, options) === false) &&
                        that._getXHRPromise(false, options.context, aborted)) ||
                        that._chunkedUpload(options) || $.ajax(options)
                    ).done(function (result, textStatus, jqXHR) {
                        that._onDone(result, textStatus, jqXHR, options);
                    }).fail(function (jqXHR, textStatus, errorThrown) {
                        that._onFail(jqXHR, textStatus, errorThrown, options);
                    }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
                        that._onAlways(
                            jqXHRorResult,
                            textStatus,
                            jqXHRorError,
                            options
                        );
                        that._sending -= 1;
                        that._active -= 1;
                        if (options.limitConcurrentUploads &&
                                options.limitConcurrentUploads > that._sending) {
                            // Start the next queued upload,
                            // that has not been aborted:
                            var nextSlot = that._slots.shift();
                            while (nextSlot) {
                                if (that._getDeferredState(nextSlot) === 'pending') {
                                    nextSlot.resolve();
                                    break;
                                }
                                nextSlot = that._slots.shift();
                            }
                        }
                        if (that._active === 0) {
                            // The stop callback is triggered when all uploads have
                            // been completed, equivalent to the global ajaxStop event:
                            that._trigger('stop');
                        }
                    });
                    return jqXHR;
                };
            this._beforeSend(e, options);
            if (this.options.sequentialUploads ||
                    (this.options.limitConcurrentUploads &&
                    this.options.limitConcurrentUploads <= this._sending)) {
                if (this.options.limitConcurrentUploads > 1) {
                    slot = $.Deferred();
                    this._slots.push(slot);
                    pipe = slot.pipe(send);
                } else {
                    this._sequence = this._sequence.pipe(send, send);
                    pipe = this._sequence;
                }
                // Return the piped Promise object, enhanced with an abort method,
                // which is delegated to the jqXHR object of the current upload,
                // and jqXHR callbacks mapped to the equivalent Promise methods:
                pipe.abort = function () {
                    aborted = [undefined, 'abort', 'abort'];
                    if (!jqXHR) {
                        if (slot) {
                            slot.rejectWith(options.context, aborted);
                        }
                        return send();
                    }
                    return jqXHR.abort();
                };
                return this._enhancePromise(pipe);
            }
            return send();
        },

        _onAdd: function (e, data) {
            var that = this,
                result = true,
                options = $.extend({}, this.options, data),
                limit = options.limitMultiFileUploads,
                paramName = this._getParamName(options),
                paramNameSet,
                paramNameSlice,
                fileSet,
                i;
            if (!(options.singleFileUploads || limit) ||
                    !this._isXHRUpload(options)) {
                fileSet = [data.files];
                paramNameSet = [paramName];
            } else if (!options.singleFileUploads && limit) {
                fileSet = [];
                paramNameSet = [];
                for (i = 0; i < data.files.length; i += limit) {
                    fileSet.push(data.files.slice(i, i + limit));
                    paramNameSlice = paramName.slice(i, i + limit);
                    if (!paramNameSlice.length) {
                        paramNameSlice = paramName;
                    }
                    paramNameSet.push(paramNameSlice);
                }
            } else {
                paramNameSet = paramName;
            }
            data.originalFiles = data.files;
            $.each(fileSet || data.files, function (index, element) {
                var newData = $.extend({}, data);
                newData.files = fileSet ? element : [element];
                newData.paramName = paramNameSet[index];
                that._initResponseObject(newData);
                that._initProgressObject(newData);
                that._addConvenienceMethods(e, newData);
                result = that._trigger('add', e, newData);
                return result;
            });
            return result;
        },

        _replaceFileInput: function (input) {
            var inputClone = input.clone(true);
            $('<form></form>').append(inputClone)[0].reset();
            // Detaching allows to insert the fileInput on another form
            // without loosing the file input value:
            input.after(inputClone).detach();
            // Avoid memory leaks with the detached file input:
            $.cleanData(input.unbind('remove'));
            // Replace the original file input element in the fileInput
            // elements set with the clone, which has been copied including
            // event handlers:
            this.options.fileInput = this.options.fileInput.map(function (i, el) {
                if (el === input[0]) {
                    return inputClone[0];
                }
                return el;
            });
            // If the widget has been initialized on the file input itself,
            // override this.element with the file input clone:
            if (input[0] === this.element[0]) {
                this.element = inputClone;
            }
        },

        _handleFileTreeEntry: function (entry, path) {
            var that = this,
                dfd = $.Deferred(),
                errorHandler = function (e) {
                    if (e && !e.entry) {
                        e.entry = entry;
                    }
                    // Since $.when returns immediately if one
                    // Deferred is rejected, we use resolve instead.
                    // This allows valid files and invalid items
                    // to be returned together in one set:
                    dfd.resolve([e]);
                },
                dirReader;
            path = path || '';
            if (entry.isFile) {
                if (entry._file) {
                    // Workaround for Chrome bug #149735
                    entry._file.relativePath = path;
                    dfd.resolve(entry._file);
                } else {
                    entry.file(function (file) {
                        file.relativePath = path;
                        dfd.resolve(file);
                    }, errorHandler);
                }
            } else if (entry.isDirectory) {
                dirReader = entry.createReader();
                dirReader.readEntries(function (entries) {
                    that._handleFileTreeEntries(
                        entries,
                        path + entry.name + '/'
                    ).done(function (files) {
                        dfd.resolve(files);
                    }).fail(errorHandler);
                }, errorHandler);
            } else {
                // Return an empy list for file system items
                // other than files or directories:
                dfd.resolve([]);
            }
            return dfd.promise();
        },

        _handleFileTreeEntries: function (entries, path) {
            var that = this;
            return $.when.apply(
                $,
                $.map(entries, function (entry) {
                    return that._handleFileTreeEntry(entry, path);
                })
            ).pipe(function () {
                return Array.prototype.concat.apply(
                    [],
                    arguments
                );
            });
        },

        _getDroppedFiles: function (dataTransfer) {
            dataTransfer = dataTransfer || {};
            var items = dataTransfer.items;
            if (items && items.length && (items[0].webkitGetAsEntry ||
                    items[0].getAsEntry)) {
                return this._handleFileTreeEntries(
                    $.map(items, function (item) {
                        var entry;
                        if (item.webkitGetAsEntry) {
                            entry = item.webkitGetAsEntry();
                            if (entry) {
                                // Workaround for Chrome bug #149735:
                                entry._file = item.getAsFile();
                            }
                            return entry;
                        }
                        return item.getAsEntry();
                    })
                );
            }
            return $.Deferred().resolve(
                $.makeArray(dataTransfer.files)
            ).promise();
        },

        _getSingleFileInputFiles: function (fileInput) {
            fileInput = $(fileInput);
            var entries = fileInput.prop('webkitEntries') ||
                    fileInput.prop('entries'),
                files,
                value;
            if (entries && entries.length) {
                return this._handleFileTreeEntries(entries);
            }
            files = $.makeArray(fileInput.prop('files'));
            if (!files.length) {
                value = fileInput.prop('value');
                if (!value) {
                    return $.Deferred().resolve([]).promise();
                }
                // If the files property is not available, the browser does not
                // support the File API and we add a pseudo File object with
                // the input value as name with path information removed:
                files = [{name: value.replace(/^.*\\/, '')}];
            } else if (files[0].name === undefined && files[0].fileName) {
                // File normalization for Safari 4 and Firefox 3:
                $.each(files, function (index, file) {
                    file.name = file.fileName;
                    file.size = file.fileSize;
                });
            }
            return $.Deferred().resolve(files).promise();
        },

        _getFileInputFiles: function (fileInput) {
            if (!(fileInput instanceof $) || fileInput.length === 1) {
                return this._getSingleFileInputFiles(fileInput);
            }
            return $.when.apply(
                $,
                $.map(fileInput, this._getSingleFileInputFiles)
            ).pipe(function () {
                return Array.prototype.concat.apply(
                    [],
                    arguments
                );
            });
        },

        _onChange: function (e) {
            var that = this,
                data = {
                    fileInput: $(e.target),
                    form: $(e.target.form)
                };
            this._getFileInputFiles(data.fileInput).always(function (files) {
                data.files = files;
                if (that.options.replaceFileInput) {
                    that._replaceFileInput(data.fileInput);
                }
                if (that._trigger('change', e, data) !== false) {
                    that._onAdd(e, data);
                }
            });
        },

        _onPaste: function (e) {
            var items = e.originalEvent && e.originalEvent.clipboardData &&
                    e.originalEvent.clipboardData.items,
                data = {files: []};
            if (items && items.length) {
                $.each(items, function (index, item) {
                    var file = item.getAsFile && item.getAsFile();
                    if (file) {
                        data.files.push(file);
                    }
                });
                if (this._trigger('paste', e, data) === false ||
                        this._onAdd(e, data) === false) {
                    return false;
                }
            }
        },

        _onDrop: function (e) {
            e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
            var that = this,
                dataTransfer = e.dataTransfer,
                data = {};
            if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
                e.preventDefault();
                this._getDroppedFiles(dataTransfer).always(function (files) {
                    data.files = files;
                    if (that._trigger('drop', e, data) !== false) {
                        that._onAdd(e, data);
                    }
                });
            }
        },

        _onDragOver: function (e) {
            e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
            var dataTransfer = e.dataTransfer;
            if (dataTransfer) {
                if (this._trigger('dragover', e) === false) {
                    return false;
                }
                if ($.inArray('Files', dataTransfer.types) !== -1) {
                    dataTransfer.dropEffect = 'copy';
                    e.preventDefault();
                }
            }
        },

        _initEventHandlers: function () {
            if (this._isXHRUpload(this.options)) {
                this._on(this.options.dropZone, {
                    dragover: this._onDragOver,
                    drop: this._onDrop
                });
                this._on(this.options.pasteZone, {
                    paste: this._onPaste
                });
            }
            if ($.support.fileInput) {
                this._on(this.options.fileInput, {
                    change: this._onChange
                });
            }
        },

        _destroyEventHandlers: function () {
            this._off(this.options.dropZone, 'dragover drop');
            this._off(this.options.pasteZone, 'paste');
            this._off(this.options.fileInput, 'change');
        },

        _setOption: function (key, value) {
            var reinit = $.inArray(key, this._specialOptions) !== -1;
            if (reinit) {
                this._destroyEventHandlers();
            }
            this._super(key, value);
            if (reinit) {
                this._initSpecialOptions();
                this._initEventHandlers();
            }
        },

        _initSpecialOptions: function () {
            var options = this.options;
            if (options.fileInput === undefined) {
                options.fileInput = this.element.is('input[type="file"]') ?
                        this.element : this.element.find('input[type="file"]');
            } else if (!(options.fileInput instanceof $)) {
                options.fileInput = $(options.fileInput);
            }
            if (!(options.dropZone instanceof $)) {
                options.dropZone = $(options.dropZone);
            }
            if (!(options.pasteZone instanceof $)) {
                options.pasteZone = $(options.pasteZone);
            }
        },

        _getRegExp: function (str) {
            var parts = str.split('/'),
                modifiers = parts.pop();
            parts.shift();
            return new RegExp(parts.join('/'), modifiers);
        },

        _isRegExpOption: function (key, value) {
            return key !== 'url' && $.type(value) === 'string' &&
                /^\/.*\/[igm]{0,3}$/.test(value);
        },

        _initDataAttributes: function () {
            var that = this,
                options = this.options;
            // Initialize options set via HTML5 data-attributes:
            $.each(
                $(this.element[0].cloneNode(false)).data(),
                function (key, value) {
                    if (that._isRegExpOption(key, value)) {
                        value = that._getRegExp(value);
                    }
                    options[key] = value;
                }
            );
        },

        _create: function () {
            this._initDataAttributes();
            this._initSpecialOptions();
            this._slots = [];
            this._sequence = this._getXHRPromise(true);
            this._sending = this._active = 0;
            this._initProgressObject(this);
            this._initEventHandlers();
        },

        // This method is exposed to the widget API and allows to query
        // the number of active uploads:
        active: function () {
            return this._active;
        },

        // This method is exposed to the widget API and allows to query
        // the widget upload progress.
        // It returns an object with loaded, total and bitrate properties
        // for the running uploads:
        progress: function () {
            return this._progress;
        },

        // This method is exposed to the widget API and allows adding files
        // using the fileupload API. The data parameter accepts an object which
        // must have a files property and can contain additional options:
        // .fileupload('add', {files: filesList});
        add: function (data) {
            var that = this;
            if (!data || this.options.disabled) {
                return;
            }
            if (data.fileInput && !data.files) {
                this._getFileInputFiles(data.fileInput).always(function (files) {
                    data.files = files;
                    that._onAdd(null, data);
                });
            } else {
                data.files = $.makeArray(data.files);
                this._onAdd(null, data);
            }
        },

        // This method is exposed to the widget API and allows sending files
        // using the fileupload API. The data parameter accepts an object which
        // must have a files or fileInput property and can contain additional options:
        // .fileupload('send', {files: filesList});
        // The method returns a Promise object for the file upload call.
        send: function (data) {
            if (data && !this.options.disabled) {
                if (data.fileInput && !data.files) {
                    var that = this,
                        dfd = $.Deferred(),
                        promise = dfd.promise(),
                        jqXHR,
                        aborted;
                    promise.abort = function () {
                        aborted = true;
                        if (jqXHR) {
                            return jqXHR.abort();
                        }
                        dfd.reject(null, 'abort', 'abort');
                        return promise;
                    };
                    this._getFileInputFiles(data.fileInput).always(
                        function (files) {
                            if (aborted) {
                                return;
                            }
                            if (!files.length) {
                                dfd.reject();
                                return;
                            }
                            data.files = files;
                            jqXHR = that._onSend(null, data).then(
                                function (result, textStatus, jqXHR) {
                                    dfd.resolve(result, textStatus, jqXHR);
                                },
                                function (jqXHR, textStatus, errorThrown) {
                                    dfd.reject(jqXHR, textStatus, errorThrown);
                                }
                            );
                        }
                    );
                    return this._enhancePromise(promise);
                }
                data.files = $.makeArray(data.files);
                if (data.files.length) {
                    return this._onSend(null, data);
                }
            }
            return this._getXHRPromise(false, data && data.context);
        }

    });

}));
!function(a){"use strict";var b=function(a,c,d){var e,f,g=document.createElement("img");if(g.onerror=c,g.onload=function(){!f||d&&d.noRevoke||b.revokeObjectURL(f),c&&c(b.scale(g,d))},b.isInstanceOf("Blob",a)||b.isInstanceOf("File",a))e=f=b.createObjectURL(a),g._type=a.type;else{if("string"!=typeof a)return!1;e=a,d&&d.crossOrigin&&(g.crossOrigin=d.crossOrigin)}return e?(g.src=e,g):b.readFile(a,function(a){var b=a.target;b&&b.result?g.src=b.result:c&&c(a)})},c=window.createObjectURL&&window||window.URL&&URL.revokeObjectURL&&URL||window.webkitURL&&webkitURL;b.isInstanceOf=function(a,b){return Object.prototype.toString.call(b)==="[object "+a+"]"},b.transformCoordinates=function(){},b.getTransformedOptions=function(a,b){var c,d,e,f,g=b.aspectRatio;if(!g)return b;c={};for(d in b)b.hasOwnProperty(d)&&(c[d]=b[d]);return c.crop=!0,e=a.naturalWidth||a.width,f=a.naturalHeight||a.height,e/f>g?(c.maxWidth=f*g,c.maxHeight=f):(c.maxWidth=e,c.maxHeight=e/g),c},b.renderImageToCanvas=function(a,b,c,d,e,f,g,h,i,j){return a.getContext("2d").drawImage(b,c,d,e,f,g,h,i,j),a},b.hasCanvasOption=function(a){return a.canvas||a.crop||a.aspectRatio},b.scale=function(a,c){c=c||{};var d,e,f,g,h,i,j,k,l,m=document.createElement("canvas"),n=a.getContext||b.hasCanvasOption(c)&&m.getContext,o=a.naturalWidth||a.width,p=a.naturalHeight||a.height,q=o,r=p,s=function(){var a=Math.max((f||q)/q,(g||r)/r);a>1&&(q*=a,r*=a)},t=function(){var a=Math.min((d||q)/q,(e||r)/r);1>a&&(q*=a,r*=a)};return n&&(c=b.getTransformedOptions(a,c),j=c.left||0,k=c.top||0,c.sourceWidth?(h=c.sourceWidth,void 0!==c.right&&void 0===c.left&&(j=o-h-c.right)):h=o-j-(c.right||0),c.sourceHeight?(i=c.sourceHeight,void 0!==c.bottom&&void 0===c.top&&(k=p-i-c.bottom)):i=p-k-(c.bottom||0),q=h,r=i),d=c.maxWidth,e=c.maxHeight,f=c.minWidth,g=c.minHeight,n&&d&&e&&c.crop?(q=d,r=e,l=h/i-d/e,0>l?(i=e*h/d,void 0===c.top&&void 0===c.bottom&&(k=(p-i)/2)):l>0&&(h=d*i/e,void 0===c.left&&void 0===c.right&&(j=(o-h)/2))):((c.contain||c.cover)&&(f=d=d||f,g=e=e||g),c.cover?(t(),s()):(s(),t())),n?(m.width=q,m.height=r,b.transformCoordinates(m,c),b.renderImageToCanvas(m,a,j,k,h,i,0,0,q,r)):(a.width=q,a.height=r,a)},b.createObjectURL=function(a){return c?c.createObjectURL(a):!1},b.revokeObjectURL=function(a){return c?c.revokeObjectURL(a):!1},b.readFile=function(a,b,c){if(window.FileReader){var d=new FileReader;if(d.onload=d.onerror=b,c=c||"readAsDataURL",d[c])return d[c](a),d}return!1},"function"==typeof define&&define.amd?define(function(){return b}):a.loadImage=b}(this),function(a){"use strict";"function"==typeof define&&define.amd?define(["load-image"],a):a(window.loadImage)}(function(a){"use strict";if(window.navigator&&window.navigator.platform&&/iP(hone|od|ad)/.test(window.navigator.platform)){var b=a.renderImageToCanvas;a.detectSubsampling=function(a){var b,c;return a.width*a.height>1048576?(b=document.createElement("canvas"),b.width=b.height=1,c=b.getContext("2d"),c.drawImage(a,-a.width+1,0),0===c.getImageData(0,0,1,1).data[3]):!1},a.detectVerticalSquash=function(a,b){var c,d,e,f,g,h=a.naturalHeight||a.height,i=document.createElement("canvas"),j=i.getContext("2d");for(b&&(h/=2),i.width=1,i.height=h,j.drawImage(a,0,0),c=j.getImageData(0,0,1,h).data,d=0,e=h,f=h;f>d;)g=c[4*(f-1)+3],0===g?e=f:d=f,f=e+d>>1;return f/h||1},a.renderImageToCanvas=function(c,d,e,f,g,h,i,j,k,l){if("image/jpeg"===d._type){var m,n,o,p,q=c.getContext("2d"),r=document.createElement("canvas"),s=1024,t=r.getContext("2d");if(r.width=s,r.height=s,q.save(),m=a.detectSubsampling(d),m&&(e/=2,f/=2,g/=2,h/=2),n=a.detectVerticalSquash(d,m),m||1!==n){for(f*=n,k=Math.ceil(s*k/g),l=Math.ceil(s*l/h/n),j=0,p=0;h>p;){for(i=0,o=0;g>o;)t.clearRect(0,0,s,s),t.drawImage(d,e,f,g,h,-o,-p,g,h),q.drawImage(r,0,0,s,s,i,j,k,l),o+=s,i+=k;p+=s,j+=l}return q.restore(),c}}return b(c,d,e,f,g,h,i,j,k,l)}}}),function(a){"use strict";"function"==typeof define&&define.amd?define(["load-image"],a):a(window.loadImage)}(function(a){"use strict";var b=a.hasCanvasOption,c=a.transformCoordinates,d=a.getTransformedOptions;a.hasCanvasOption=function(c){return b.call(a,c)||c.orientation},a.transformCoordinates=function(b,d){c.call(a,b,d);var e=b.getContext("2d"),f=b.width,g=b.height,h=d.orientation;if(h&&!(h>8))switch(h>4&&(b.width=g,b.height=f),h){case 2:e.translate(f,0),e.scale(-1,1);break;case 3:e.translate(f,g),e.rotate(Math.PI);break;case 4:e.translate(0,g),e.scale(1,-1);break;case 5:e.rotate(.5*Math.PI),e.scale(1,-1);break;case 6:e.rotate(.5*Math.PI),e.translate(0,-g);break;case 7:e.rotate(.5*Math.PI),e.translate(f,-g),e.scale(-1,1);break;case 8:e.rotate(-.5*Math.PI),e.translate(-f,0)}},a.getTransformedOptions=function(b,c){var e,f,g=d.call(a,b,c),h=g.orientation;if(!h||h>8||1===h)return g;e={};for(f in g)g.hasOwnProperty(f)&&(e[f]=g[f]);switch(g.orientation){case 2:e.left=g.right,e.right=g.left;break;case 3:e.left=g.right,e.top=g.bottom,e.right=g.left,e.bottom=g.top;break;case 4:e.top=g.bottom,e.bottom=g.top;break;case 5:e.left=g.top,e.top=g.left,e.right=g.bottom,e.bottom=g.right;break;case 6:e.left=g.top,e.top=g.right,e.right=g.bottom,e.bottom=g.left;break;case 7:e.left=g.bottom,e.top=g.right,e.right=g.top,e.bottom=g.left;break;case 8:e.left=g.bottom,e.top=g.left,e.right=g.top,e.bottom=g.right}return g.orientation>4&&(e.maxWidth=g.maxHeight,e.maxHeight=g.maxWidth,e.minWidth=g.minHeight,e.minHeight=g.minWidth,e.sourceWidth=g.sourceHeight,e.sourceHeight=g.sourceWidth),e}}),function(a){"use strict";"function"==typeof define&&define.amd?define(["load-image"],a):a(window.loadImage)}(function(a){"use strict";var b=window.Blob&&(Blob.prototype.slice||Blob.prototype.webkitSlice||Blob.prototype.mozSlice);a.blobSlice=b&&function(){var a=this.slice||this.webkitSlice||this.mozSlice;return a.apply(this,arguments)},a.metaDataParsers={jpeg:{65505:[]}},a.parseMetaData=function(b,c,d){d=d||{};var e=this,f=d.maxMetaDataSize||262144,g={},h=!(window.DataView&&b&&b.size>=12&&"image/jpeg"===b.type&&a.blobSlice);(h||!a.readFile(a.blobSlice.call(b,0,f),function(b){if(b.target.error)return console.log(b.target.error),void c(g);var f,h,i,j,k=b.target.result,l=new DataView(k),m=2,n=l.byteLength-4,o=m;if(65496===l.getUint16(0)){for(;n>m&&(f=l.getUint16(m),f>=65504&&65519>=f||65534===f);){if(h=l.getUint16(m+2)+2,m+h>l.byteLength){console.log("Invalid meta data: Invalid segment size.");break}if(i=a.metaDataParsers.jpeg[f])for(j=0;j<i.length;j+=1)i[j].call(e,l,m,h,g,d);m+=h,o=m}!d.disableImageHead&&o>6&&(g.imageHead=k.slice?k.slice(0,o):new Uint8Array(k).subarray(0,o))}else console.log("Invalid JPEG file: Missing JPEG marker.");c(g)},"readAsArrayBuffer"))&&c(g)}}),function(a){"use strict";"function"==typeof define&&define.amd?define(["load-image","load-image-meta"],a):a(window.loadImage)}(function(a){"use strict";a.ExifMap=function(){return this},a.ExifMap.prototype.map={Orientation:274},a.ExifMap.prototype.get=function(a){return this[a]||this[this.map[a]]},a.getExifThumbnail=function(a,b,c){var d,e,f;if(!c||b+c>a.byteLength)return void console.log("Invalid Exif data: Invalid thumbnail data.");for(d=[],e=0;c>e;e+=1)f=a.getUint8(b+e),d.push((16>f?"0":"")+f.toString(16));return"data:image/jpeg,%"+d.join("%")},a.exifTagTypes={1:{getValue:function(a,b){return a.getUint8(b)},size:1},2:{getValue:function(a,b){return String.fromCharCode(a.getUint8(b))},size:1,ascii:!0},3:{getValue:function(a,b,c){return a.getUint16(b,c)},size:2},4:{getValue:function(a,b,c){return a.getUint32(b,c)},size:4},5:{getValue:function(a,b,c){return a.getUint32(b,c)/a.getUint32(b+4,c)},size:8},9:{getValue:function(a,b,c){return a.getInt32(b,c)},size:4},10:{getValue:function(a,b,c){return a.getInt32(b,c)/a.getInt32(b+4,c)},size:8}},a.exifTagTypes[7]=a.exifTagTypes[1],a.getExifValue=function(b,c,d,e,f,g){var h,i,j,k,l,m,n=a.exifTagTypes[e];if(!n)return void console.log("Invalid Exif data: Invalid tag type.");if(h=n.size*f,i=h>4?c+b.getUint32(d+8,g):d+8,i+h>b.byteLength)return void console.log("Invalid Exif data: Invalid data offset.");if(1===f)return n.getValue(b,i,g);for(j=[],k=0;f>k;k+=1)j[k]=n.getValue(b,i+k*n.size,g);if(n.ascii){for(l="",k=0;k<j.length&&(m=j[k],"\x00"!==m);k+=1)l+=m;return l}return j},a.parseExifTag=function(b,c,d,e,f){var g=b.getUint16(d,e);f.exif[g]=a.getExifValue(b,c,d,b.getUint16(d+2,e),b.getUint32(d+4,e),e)},a.parseExifTags=function(a,b,c,d,e){var f,g,h;if(c+6>a.byteLength)return void console.log("Invalid Exif data: Invalid directory offset.");if(f=a.getUint16(c,d),g=c+2+12*f,g+4>a.byteLength)return void console.log("Invalid Exif data: Invalid directory size.");for(h=0;f>h;h+=1)this.parseExifTag(a,b,c+2+12*h,d,e);return a.getUint32(g,d)},a.parseExifData=function(b,c,d,e,f){if(!f.disableExif){var g,h,i,j=c+10;if(1165519206===b.getUint32(c+4)){if(j+8>b.byteLength)return void console.log("Invalid Exif data: Invalid segment size.");if(0!==b.getUint16(c+8))return void console.log("Invalid Exif data: Missing byte alignment offset.");switch(b.getUint16(j)){case 18761:g=!0;break;case 19789:g=!1;break;default:return void console.log("Invalid Exif data: Invalid byte alignment marker.")}if(42!==b.getUint16(j+2,g))return void console.log("Invalid Exif data: Missing TIFF marker.");h=b.getUint32(j+4,g),e.exif=new a.ExifMap,h=a.parseExifTags(b,j,j+h,g,e),h&&!f.disableExifThumbnail&&(i={exif:{}},h=a.parseExifTags(b,j,j+h,g,i),i.exif[513]&&(e.exif.Thumbnail=a.getExifThumbnail(b,j+i.exif[513],i.exif[514]))),e.exif[34665]&&!f.disableExifSub&&a.parseExifTags(b,j,j+e.exif[34665],g,e),e.exif[34853]&&!f.disableExifGps&&a.parseExifTags(b,j,j+e.exif[34853],g,e)}}},a.metaDataParsers.jpeg[65505].push(a.parseExifData)}),function(a){"use strict";"function"==typeof define&&define.amd?define(["load-image","load-image-exif"],a):a(window.loadImage)}(function(a){"use strict";a.ExifMap.prototype.tags={256:"ImageWidth",257:"ImageHeight",34665:"ExifIFDPointer",34853:"GPSInfoIFDPointer",40965:"InteroperabilityIFDPointer",258:"BitsPerSample",259:"Compression",262:"PhotometricInterpretation",274:"Orientation",277:"SamplesPerPixel",284:"PlanarConfiguration",530:"YCbCrSubSampling",531:"YCbCrPositioning",282:"XResolution",283:"YResolution",296:"ResolutionUnit",273:"StripOffsets",278:"RowsPerStrip",279:"StripByteCounts",513:"JPEGInterchangeFormat",514:"JPEGInterchangeFormatLength",301:"TransferFunction",318:"WhitePoint",319:"PrimaryChromaticities",529:"YCbCrCoefficients",532:"ReferenceBlackWhite",306:"DateTime",270:"ImageDescription",271:"Make",272:"Model",305:"Software",315:"Artist",33432:"Copyright",36864:"ExifVersion",40960:"FlashpixVersion",40961:"ColorSpace",40962:"PixelXDimension",40963:"PixelYDimension",42240:"Gamma",37121:"ComponentsConfiguration",37122:"CompressedBitsPerPixel",37500:"MakerNote",37510:"UserComment",40964:"RelatedSoundFile",36867:"DateTimeOriginal",36868:"DateTimeDigitized",37520:"SubSecTime",37521:"SubSecTimeOriginal",37522:"SubSecTimeDigitized",33434:"ExposureTime",33437:"FNumber",34850:"ExposureProgram",34852:"SpectralSensitivity",34855:"PhotographicSensitivity",34856:"OECF",34864:"SensitivityType",34865:"StandardOutputSensitivity",34866:"RecommendedExposureIndex",34867:"ISOSpeed",34868:"ISOSpeedLatitudeyyy",34869:"ISOSpeedLatitudezzz",37377:"ShutterSpeedValue",37378:"ApertureValue",37379:"BrightnessValue",37380:"ExposureBias",37381:"MaxApertureValue",37382:"SubjectDistance",37383:"MeteringMode",37384:"LightSource",37385:"Flash",37396:"SubjectArea",37386:"FocalLength",41483:"FlashEnergy",41484:"SpatialFrequencyResponse",41486:"FocalPlaneXResolution",41487:"FocalPlaneYResolution",41488:"FocalPlaneResolutionUnit",41492:"SubjectLocation",41493:"ExposureIndex",41495:"SensingMethod",41728:"FileSource",41729:"SceneType",41730:"CFAPattern",41985:"CustomRendered",41986:"ExposureMode",41987:"WhiteBalance",41988:"DigitalZoomRatio",41989:"FocalLengthIn35mmFilm",41990:"SceneCaptureType",41991:"GainControl",41992:"Contrast",41993:"Saturation",41994:"Sharpness",41995:"DeviceSettingDescription",41996:"SubjectDistanceRange",42016:"ImageUniqueID",42032:"CameraOwnerName",42033:"BodySerialNumber",42034:"LensSpecification",42035:"LensMake",42036:"LensModel",42037:"LensSerialNumber",0:"GPSVersionID",1:"GPSLatitudeRef",2:"GPSLatitude",3:"GPSLongitudeRef",4:"GPSLongitude",5:"GPSAltitudeRef",6:"GPSAltitude",7:"GPSTimeStamp",8:"GPSSatellites",9:"GPSStatus",10:"GPSMeasureMode",11:"GPSDOP",12:"GPSSpeedRef",13:"GPSSpeed",14:"GPSTrackRef",15:"GPSTrack",16:"GPSImgDirectionRef",17:"GPSImgDirection",18:"GPSMapDatum",19:"GPSDestLatitudeRef",20:"GPSDestLatitude",21:"GPSDestLongitudeRef",22:"GPSDestLongitude",23:"GPSDestBearingRef",24:"GPSDestBearing",25:"GPSDestDistanceRef",26:"GPSDestDistance",27:"GPSProcessingMethod",28:"GPSAreaInformation",29:"GPSDateStamp",30:"GPSDifferential",31:"GPSHPositioningError"},a.ExifMap.prototype.stringValues={ExposureProgram:{0:"Undefined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"},MeteringMode:{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"},LightSource:{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"},Flash:{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"},SensingMethod:{1:"Undefined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"},SceneCaptureType:{0:"Standard",1:"Landscape",2:"Portrait",3:"Night scene"},SceneType:{1:"Directly photographed"},CustomRendered:{0:"Normal process",1:"Custom process"},WhiteBalance:{0:"Auto white balance",1:"Manual white balance"},GainControl:{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"},Contrast:{0:"Normal",1:"Soft",2:"Hard"},Saturation:{0:"Normal",1:"Low saturation",2:"High saturation"},Sharpness:{0:"Normal",1:"Soft",2:"Hard"},SubjectDistanceRange:{0:"Unknown",1:"Macro",2:"Close view",3:"Distant view"},FileSource:{3:"DSC"},ComponentsConfiguration:{0:"",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"},Orientation:{1:"top-left",2:"top-right",3:"bottom-right",4:"bottom-left",5:"left-top",6:"right-top",7:"right-bottom",8:"left-bottom"}},a.ExifMap.prototype.getText=function(a){var b=this.get(a);switch(a){case"LightSource":case"Flash":case"MeteringMode":case"ExposureProgram":case"SensingMethod":case"SceneCaptureType":case"SceneType":case"CustomRendered":case"WhiteBalance":case"GainControl":case"Contrast":case"Saturation":case"Sharpness":case"SubjectDistanceRange":case"FileSource":case"Orientation":return this.stringValues[a][b];case"ExifVersion":case"FlashpixVersion":return String.fromCharCode(b[0],b[1],b[2],b[3]);case"ComponentsConfiguration":return this.stringValues[a][b[0]]+this.stringValues[a][b[1]]+this.stringValues[a][b[2]]+this.stringValues[a][b[3]];case"GPSVersionID":return b[0]+"."+b[1]+"."+b[2]+"."+b[3]}return String(b)},function(a){var b,c=a.tags,d=a.map;for(b in c)c.hasOwnProperty(b)&&(d[c[b]]=b)}(a.ExifMap.prototype),a.ExifMap.prototype.getAll=function(){var a,b,c={};for(a in this)this.hasOwnProperty(a)&&(b=this.tags[a],b&&(c[b]=this.getText(b)));return c}});/*
    json2.js
    2012-10-08

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html


    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.


    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/

/*jslint evil: true, regexp: true */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (typeof JSON !== 'object') {
    JSON = {};
}

(function () {
    'use strict';

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf())
                ? this.getUTCFullYear()     + '-' +
                    f(this.getUTCMonth() + 1) + '-' +
                    f(this.getUTCDate())      + 'T' +
                    f(this.getUTCHours())     + ':' +
                    f(this.getUTCMinutes())   + ':' +
                    f(this.getUTCSeconds())   + 'Z'
                : null;
        };

        String.prototype.toJSON      =
            Number.prototype.toJSON  =
            Boolean.prototype.toJSON = function (key) {
                return this.valueOf();
            };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string'
                ? c
                : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' : '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0
                    ? '[]'
                    : gap
                    ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
                    : '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    if (typeof rep[i] === 'string') {
                        k = rep[i];
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.prototype.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0
                ? '{}'
                : gap
                ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
                : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                    typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/
                    .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                        .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function'
                    ? walk({'': j}, '')
                    : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:vars, curly:true, browser:false, indent:2, maxerr:50, quotmark:single */
/*global window:false, $:false, console:false*/
/* $Id: ClientToServerLogger.js 154194 2013-12-09 12:25:35Z hcremer $ */

/**
 * A js class to send log statements to the server log.
 * You can use the 'info', 'warn' and 'error' functions so send logging by hand. If the 'autoLogErrors' option is enabled, every
 * 'console.error' statement and any uncaught exception will be logged to the server.
 *
 * slConfig:
 * - 'clientId' the client id for this logger. Must match the enum in de.cewecolor.ips.web.actions.logging.Client!
 * - 'url' the url to the logToServer.do action
 * - 'autoLogErrors' if true, every console.error or uncaught exception is logged to the server.
 *
 * Requirements:
 * - jQuery
 * - json2.js
 *
 * Author: Holger Cremer
 */

var de = de || {};
de.cewecolor = de.cewecolor || {};
de.cewecolor.ClientToServerLogger = function (slConfig) {
  'use strict';

  // after this amount of log types, the logger will be disabled for this type
  var MAX_CONSOLE_ERRORS = 10;
  var MAX_UNCAUGHT_EXCP = 10;

  var consoleErrorCount = 0, uncaughtExcpCount = 0;

  function log(level, msg, data) {
    if (!slConfig.clientId) {
      return;
    }

    msg = msg || '-';
    data = data || {};

    var logString = msg + ': ';

    // we expect a map for data, but repair any other input
    if (typeof data !== 'object') {
      data = { '0': data };
    }
    if ($.isArray(data)) {
      var argsAsMap = {};
      $.each(data, function (index, item) {
        argsAsMap[index] = item;
      });
      data = argsAsMap;
    }


    logString += JSON.stringify(data);

    $.post(slConfig.url, {
      client: slConfig.clientId,
      logLevel: level,
      logMessage: logString,
      stack: ''
    });
  }

  function floodCheck(current, max, type)  {
    if (current <= max) {
      return false;
    }

    if (current === max + 1) {
      log('warn', 'to many logging events. Logger is disabled for this log type.', { logType: type} );
    }

    return true;
  }



  this.info = function (msg, data) {
    log('info', msg, data);
  };
  this.warn = function (msg, data) {
    log('warn', msg, data);
  };
  this.error = function (msg, data) {
    log('error', msg, data);
  };

  // init
  if (slConfig.autoLogErrors) {
    if (console) {
      var consoleErrorFn = console.error;
      console.error = function (arg1, arg2, arg3) {
        // try to call the original error function
        try {
          if (typeof consoleErrorFn === 'function') {
            // FF & Chrome & IE10
            consoleErrorFn.apply(console, arguments);
          } else if (typeof consoleErrorFn === 'object') {
            // old IEs
            consoleErrorFn(arg1, arg2, arg3);
          }
        } catch (e) {
          // ignore
        }

        consoleErrorCount++;
        if (floodCheck(consoleErrorCount, MAX_CONSOLE_ERRORS, 'consoleError')) {
          return;
        }

        // create a real array from the arguments
        var args = $.map(arguments, function (item, index) {
          return item;
        });

        log('error', 'console.error', args);
      };
    }

    window.onerror = function (msg, url, line) {
      uncaughtExcpCount++;
      if (floodCheck(uncaughtExcpCount, MAX_UNCAUGHT_EXCP, 'uncaught')) {
        return false;
      }

      log('error', 'Uncaught exception', {
        msg: msg,
        url: url,
        line: line
      });

      // Just let default handler run.
      return false;
    };
  }
};
/*! SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/

var swfobject = function() {
	
	var UNDEF = "undefined",
		OBJECT = "object",
		SHOCKWAVE_FLASH = "Shockwave Flash",
		SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
		FLASH_MIME_TYPE = "application/x-shockwave-flash",
		EXPRESS_INSTALL_ID = "SWFObjectExprInst",
		
		win = window,
		doc = document,
		nav = navigator,
		
		domLoadFnArr = [],
		regObjArr = [],
		objIdArr = [],
		listenersArr = [],
		script,
		timer = null,
		storedAltContent = null,
		storedAltContentId = null,
		isDomLoaded = false,
		isExpressInstallActive = false;
	
	/* Centralized function for browser feature detection
		- Proprietary feature detection (conditional compiling) is used to detect Internet Explorer's features
		- User agent string detection is only used when no alternative is possible
		- Is executed directly for optimal performance
	*/	
	var ua = function() {
		var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
			playerVersion = [0,0,0],
			d = null;
		if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
			d = nav.plugins[SHOCKWAVE_FLASH].description;
			if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
				d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
				playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
				playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
				playerVersion[2] = /r/.test(d) ? parseInt(d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
			}
		}
		else if (typeof win.ActiveXObject != UNDEF) {
			var a = null, fp6Crash = false;
			try {
				a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".7");
			}
			catch(e) {
				try { 
					a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".6");
					playerVersion = [6,0,21];
					a.AllowScriptAccess = "always";	 // Introduced in fp6.0.47
				}
				catch(e) {
					if (playerVersion[0] == 6) {
						fp6Crash = true;
					}
				}
				if (!fp6Crash) {
					try {
						a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
					}
					catch(e) {}
				}
			}
			if (!fp6Crash && a) { // a will return null when ActiveX is disabled
				try {
					d = a.GetVariable("$version");	// Will crash fp6.0.21/23/29
					if (d) {
						d = d.split(" ")[1].split(",");
						playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
					}
				}
				catch(e) {}
			}
		}
		var u = nav.userAgent.toLowerCase(),
			p = nav.platform.toLowerCase(),
			webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
			ie = false,
			windows = p ? /win/.test(p) : /win/.test(u),
			mac = p ? /mac/.test(p) : /mac/.test(u);
		/*@cc_on
			ie = true;
			@if (@_win32)
				windows = true;
			@elif (@_mac)
				mac = true;
			@end
		@*/
		return { w3cdom:w3cdom, pv:playerVersion, webkit:webkit, ie:ie, win:windows, mac:mac };
	}();

	/* Cross-browser onDomLoad
		- Based on Dean Edwards' solution: http://dean.edwards.name/weblog/2006/06/again/
		- Will fire an event as soon as the DOM of a page is loaded (supported by Gecko based browsers - like Firefox -, IE, Opera9+, Safari)
	*/ 
	var onDomLoad = function() {
		if (!ua.w3cdom) {
			return;
		}
		addDomLoadEvent(main);
		if (ua.ie && ua.win) {
			try {	 // Avoid a possible Operation Aborted error
				doc.write("<scr" + "ipt id=__ie_ondomload defer=true src=//:></scr" + "ipt>"); // String is split into pieces to avoid Norton AV to add code that can cause errors 
				script = getElementById("__ie_ondomload");
				if (script) {
					addListener(script, "onreadystatechange", checkReadyState);
				}
			}
			catch(e) {}
		}
		if (ua.webkit && typeof doc.readyState != UNDEF) {
			timer = setInterval(function() { if (/loaded|complete/.test(doc.readyState)) { callDomLoadFunctions(); }}, 10);
		}
		if (typeof doc.addEventListener != UNDEF) {
			doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, null);
		}
		addLoadEvent(callDomLoadFunctions);
	}();
	
	function checkReadyState() {
		if (script.readyState == "complete") {
			script.parentNode.removeChild(script);
			callDomLoadFunctions();
		}
	}
	
	function callDomLoadFunctions() {
		if (isDomLoaded) {
			return;
		}
		if (ua.ie && ua.win) { // Test if we can really add elements to the DOM; we don't want to fire it too early
			var s = createElement("span");
			try { // Avoid a possible Operation Aborted error
				var t = doc.getElementsByTagName("body")[0].appendChild(s);
				t.parentNode.removeChild(t);
			}
			catch (e) {
				return;
			}
		}
		isDomLoaded = true;
		if (timer) {
			clearInterval(timer);
			timer = null;
		}
		var dl = domLoadFnArr.length;
		for (var i = 0; i < dl; i++) {
			domLoadFnArr[i]();
		}
	}
	
	function addDomLoadEvent(fn) {
		if (isDomLoaded) {
			fn();
		}
		else { 
			domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
		}
	}
	
	/* Cross-browser onload
		- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
		- Will fire an event as soon as a web page including all of its assets are loaded 
	 */
	function addLoadEvent(fn) {
		if (typeof win.addEventListener != UNDEF) {
			win.addEventListener("load", fn, false);
		}
		else if (typeof doc.addEventListener != UNDEF) {
			doc.addEventListener("load", fn, false);
		}
		else if (typeof win.attachEvent != UNDEF) {
			addListener(win, "onload", fn);
		}
		else if (typeof win.onload == "function") {
			var fnOld = win.onload;
			win.onload = function() {
				fnOld();
				fn();
			};
		}
		else {
			win.onload = fn;
		}
	}
	
	/* Main function
		- Will preferably execute onDomLoad, otherwise onload (as a fallback)
	*/
	function main() { // Static publishing only
		var rl = regObjArr.length;
		for (var i = 0; i < rl; i++) { // For each registered object element
			var id = regObjArr[i].id;
			if (ua.pv[0] > 0) {
				var obj = getElementById(id);
				if (obj) {
					regObjArr[i].width = obj.getAttribute("width") ? obj.getAttribute("width") : "0";
					regObjArr[i].height = obj.getAttribute("height") ? obj.getAttribute("height") : "0";
					if (hasPlayerVersion(regObjArr[i].swfVersion)) { // Flash plug-in version >= Flash content version: Houston, we have a match!
						if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements
							fixParams(obj);
						}
						setVisibility(id, true);
					}
					else if (regObjArr[i].expressInstall && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) { // Show the Adobe Express Install dialog if set by the web page author and if supported (fp6.0.65+ on Win/Mac OS only)
						showExpressInstall(regObjArr[i]);
					}
					else { // Flash plug-in and Flash content version mismatch: display alternative content instead of Flash content
						displayAltContent(obj);
					}
				}
			}
			else {	// If no fp is installed, we let the object element do its job (show alternative content)
				setVisibility(id, true);
			}
		}
	}
	
	/* Fix nested param elements, which are ignored by older webkit engines
		- This includes Safari up to and including version 1.2.2 on Mac OS 10.3
		- Fall back to the proprietary embed element
	*/
	function fixParams(obj) {
		var nestedObj = obj.getElementsByTagName(OBJECT)[0];
		if (nestedObj) {
			var e = createElement("embed"), a = nestedObj.attributes;
			if (a) {
				var al = a.length;
				for (var i = 0; i < al; i++) {
					if (a[i].nodeName == "DATA") {
						e.setAttribute("src", a[i].nodeValue);
					}
					else {
						e.setAttribute(a[i].nodeName, a[i].nodeValue);
					}
				}
			}
			var c = nestedObj.childNodes;
			if (c) {
				var cl = c.length;
				for (var j = 0; j < cl; j++) {
					if (c[j].nodeType == 1 && c[j].nodeName == "PARAM") {
						e.setAttribute(c[j].getAttribute("name"), c[j].getAttribute("value"));
					}
				}
			}
			obj.parentNode.replaceChild(e, obj);
		}
	}
	
	/* Show the Adobe Express Install dialog
		- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
	*/
	function showExpressInstall(regObj) {
		isExpressInstallActive = true;
		var obj = getElementById(regObj.id);
		if (obj) {
			if (regObj.altContentId) {
				var ac = getElementById(regObj.altContentId);
				if (ac) {
					storedAltContent = ac;
					storedAltContentId = regObj.altContentId;
				}
			}
			else {
				storedAltContent = abstractAltContent(obj);
			}
			if (!(/%$/.test(regObj.width)) && parseInt(regObj.width, 10) < 310) {
				regObj.width = "310";
			}
			if (!(/%$/.test(regObj.height)) && parseInt(regObj.height, 10) < 137) {
				regObj.height = "137";
			}
			doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
			var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
				dt = doc.title,
				fv = "MMredirectURL=" + win.location + "&MMplayerType=" + pt + "&MMdoctitle=" + dt,
				replaceId = regObj.id;
			// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
			// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			if (ua.ie && ua.win && obj.readyState != 4) {
				var newObj = createElement("div");
				replaceId += "SWFObjectNew";
				newObj.setAttribute("id", replaceId);
				obj.parentNode.insertBefore(newObj, obj); // Insert placeholder div that will be replaced by the object element that loads expressinstall.swf
				obj.style.display = "none";
				var fn = function() {
					obj.parentNode.removeChild(obj);
				};
				addListener(win, "onload", fn);
			}
			createSWF({ data:regObj.expressInstall, id:EXPRESS_INSTALL_ID, width:regObj.width, height:regObj.height }, { flashvars:fv }, replaceId);
		}
	}
	
	/* Functions to abstract and display alternative content
	*/
	function displayAltContent(obj) {
		if (ua.ie && ua.win && obj.readyState != 4) {
			// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
			// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			var el = createElement("div");
			obj.parentNode.insertBefore(el, obj); // Insert placeholder div that will be replaced by the alternative content
			el.parentNode.replaceChild(abstractAltContent(obj), el);
			obj.style.display = "none";
			var fn = function() {
				obj.parentNode.removeChild(obj);
			};
			addListener(win, "onload", fn);
		}
		else {
			obj.parentNode.replaceChild(abstractAltContent(obj), obj);
		}
	} 

	function abstractAltContent(obj) {
		var ac = createElement("div");
		if (ua.win && ua.ie) {
			ac.innerHTML = obj.innerHTML;
		}
		else {
			var nestedObj = obj.getElementsByTagName(OBJECT)[0];
			if (nestedObj) {
				var c = nestedObj.childNodes;
				if (c) {
					var cl = c.length;
					for (var i = 0; i < cl; i++) {
						if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
							ac.appendChild(c[i].cloneNode(true));
						}
					}
				}
			}
		}
		return ac;
	}
	
	/* Cross-browser dynamic SWF creation
	*/
	function createSWF(attObj, parObj, id) {
		var r, el = getElementById(id);
		if (el) {
			if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
				attObj.id = id;
			}
			if (ua.ie && ua.win) { // IE, the object element and W3C DOM methods do not combine: fall back to outerHTML
				var att = "";
				for (var i in attObj) {
					if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries, like Object.prototype.toJSONString = function() {}
						if (i.toLowerCase() == "data") {
							parObj.movie = attObj[i];
						}
						else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							att += ' class="' + attObj[i] + '"';
						}
						else if (i.toLowerCase() != "classid") {
							att += ' ' + i + '="' + attObj[i] + '"';
						}
					}
				}
				var par = "";
				for (var j in parObj) {
					if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
						par += '<param name="' + j + '" value="' + parObj[j] + '" />';
					}
				}
				el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
				objIdArr[objIdArr.length] = attObj.id; // Stored to fix object 'leaks' on unload (dynamic publishing only)
				r = getElementById(attObj.id);	
			}
			else if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements: fall back to the proprietary embed element
				var e = createElement("embed");
				e.setAttribute("type", FLASH_MIME_TYPE);
				for (var k in attObj) {
					if (attObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
						if (k.toLowerCase() == "data") {
							e.setAttribute("src", attObj[k]);
						}
						else if (k.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							e.setAttribute("class", attObj[k]);
						}
						else if (k.toLowerCase() != "classid") { // Filter out IE specific attribute
							e.setAttribute(k, attObj[k]);
						}
					}
				}
				for (var l in parObj) {
					if (parObj[l] != Object.prototype[l]) { // Filter out prototype additions from other potential libraries
						if (l.toLowerCase() != "movie") { // Filter out IE specific param element
							e.setAttribute(l, parObj[l]);
						}
					}
				}
				el.parentNode.replaceChild(e, el);
				r = e;
			}
			else { // Well-behaving browsers
				var o = createElement(OBJECT);
				o.setAttribute("type", FLASH_MIME_TYPE);
				for (var m in attObj) {
					if (attObj[m] != Object.prototype[m]) { // Filter out prototype additions from other potential libraries
						if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							o.setAttribute("class", attObj[m]);
						}
						else if (m.toLowerCase() != "classid") { // Filter out IE specific attribute
							o.setAttribute(m, attObj[m]);
						}
					}
				}
				for (var n in parObj) {
					if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // Filter out prototype additions from other potential libraries and IE specific param element
						createObjParam(o, n, parObj[n]);
					}
				}
				el.parentNode.replaceChild(o, el);
				r = o;
			}
		}
		return r;
	}
	
	function createObjParam(el, pName, pValue) {
		var p = createElement("param");
		p.setAttribute("name", pName);	
		p.setAttribute("value", pValue);
		el.appendChild(p);
	}
	
	/* Cross-browser SWF removal
		- Especially needed to safely and completely remove a SWF in Internet Explorer
	*/
	function removeSWF(id) {
		var obj = getElementById(id);
		if (obj && (obj.nodeName == "OBJECT" || obj.nodeName == "EMBED")) {
			if (ua.ie && ua.win) {
				if (obj.readyState == 4) {
					removeObjectInIE(id);
				}
				else {
					win.attachEvent("onload", function() {
						removeObjectInIE(id);
					});
				}
			}
			else {
				obj.parentNode.removeChild(obj);
			}
		}
	}
	
	function removeObjectInIE(id) {
		var obj = getElementById(id);
		if (obj) {
			for (var i in obj) {
				if (typeof obj[i] == "function") {
					obj[i] = null;
				}
			}
			obj.parentNode.removeChild(obj);
		}
	}
	
	/* Functions to optimize JavaScript compression
	*/
	function getElementById(id) {
		var el = null;
		try {
			el = doc.getElementById(id);
		}
		catch (e) {}
		return el;
	}
	
	function createElement(el) {
		return doc.createElement(el);
	}
	
	/* Updated attachEvent function for Internet Explorer
		- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
	*/	
	function addListener(target, eventType, fn) {
		target.attachEvent(eventType, fn);
		listenersArr[listenersArr.length] = [target, eventType, fn];
	}
	
	/* Flash Player and SWF content version matching
	*/
	function hasPlayerVersion(rv) {
		var pv = ua.pv, v = rv.split(".");
		v[0] = parseInt(v[0], 10);
		v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
		v[2] = parseInt(v[2], 10) || 0;
		return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
	}
	
	/* Cross-browser dynamic CSS creation
		- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
	*/	
	function createCSS(sel, decl) {
		if (ua.ie && ua.mac) {
			return;
		}
		var h = doc.getElementsByTagName("head")[0], s = createElement("style");
		s.setAttribute("type", "text/css");
		s.setAttribute("media", "screen");
		if (!(ua.ie && ua.win) && typeof doc.createTextNode != UNDEF) {
			s.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
		}
		h.appendChild(s);
		if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
			var ls = doc.styleSheets[doc.styleSheets.length - 1];
			if (typeof ls.addRule == OBJECT) {
				ls.addRule(sel, decl);
			}
		}
	}
	
	function setVisibility(id, isVisible) {
		var v = isVisible ? "visible" : "hidden";
		if (isDomLoaded && getElementById(id)) {
			getElementById(id).style.visibility = v;
		}
		else {
			createCSS("#" + id, "visibility:" + v);
		}
	}

	/* Filter to avoid XSS attacks 
	*/
	function urlEncodeIfNecessary(s) {
		var regex = /[\\\"<>\.;]/;
		var hasBadChars = regex.exec(s) != null;
		return hasBadChars ? encodeURIComponent(s) : s;
	}
	
	/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
	*/
	var cleanup = function() {
		if (ua.ie && ua.win) {
			window.attachEvent("onunload", function() {
				// remove listeners to avoid memory leaks
				var ll = listenersArr.length;
				for (var i = 0; i < ll; i++) {
					listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
				}
				// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
				var il = objIdArr.length;
				for (var j = 0; j < il; j++) {
					removeSWF(objIdArr[j]);
				}
				// cleanup library's main closures to avoid memory leaks
				for (var k in ua) {
					ua[k] = null;
				}
				ua = null;
				for (var l in swfobject) {
					swfobject[l] = null;
				}
				swfobject = null;
			});
		}
	}();
	
	
	return {
		/* Public API
			- Reference: http://code.google.com/p/swfobject/wiki/SWFObject_2_0_documentation
		*/ 
		registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr) {
			if (!ua.w3cdom || !objectIdStr || !swfVersionStr) {
				return;
			}
			var regObj = {};
			regObj.id = objectIdStr;
			regObj.swfVersion = swfVersionStr;
			regObj.expressInstall = xiSwfUrlStr ? xiSwfUrlStr : false;
			regObjArr[regObjArr.length] = regObj;
			setVisibility(objectIdStr, false);
		},
		
		getObjectById: function(objectIdStr) {
			var r = null;
			if (ua.w3cdom) {
				var o = getElementById(objectIdStr);
				if (o) {
					var n = o.getElementsByTagName(OBJECT)[0];
					if (!n || (n && typeof o.SetVariable != UNDEF)) {
							r = o;
					}
					else if (typeof n.SetVariable != UNDEF) {
						r = n;
					}
				}
			}
			return r;
		},
		
		embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj) {
			if (!ua.w3cdom || !swfUrlStr || !replaceElemIdStr || !widthStr || !heightStr || !swfVersionStr) {
				return;
			}
			widthStr += ""; // Auto-convert to string
			heightStr += "";
			if (hasPlayerVersion(swfVersionStr)) {
				setVisibility(replaceElemIdStr, false);
				var att = {};
				if (attObj && typeof attObj === OBJECT) {
					for (var i in attObj) {
						if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries
							att[i] = attObj[i];
						}
					}
				}
				att.data = swfUrlStr;
				att.width = widthStr;
				att.height = heightStr;
				var par = {}; 
				if (parObj && typeof parObj === OBJECT) {
					for (var j in parObj) {
						if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
							par[j] = parObj[j];
						}
					}
				}
				if (flashvarsObj && typeof flashvarsObj === OBJECT) {
					for (var k in flashvarsObj) {
						if (flashvarsObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
							if (typeof par.flashvars != UNDEF) {
								par.flashvars += "&" + k + "=" + flashvarsObj[k];
							}
							else {
								par.flashvars = k + "=" + flashvarsObj[k];
							}
						}
					}
				}
				addDomLoadEvent(function() {
					createSWF(att, par, replaceElemIdStr);
					if (att.id == replaceElemIdStr) {
						setVisibility(replaceElemIdStr, true);
					}
				});
			}
			else if (xiSwfUrlStr && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) {
				isExpressInstallActive = true; // deferred execution
				setVisibility(replaceElemIdStr, false);
				addDomLoadEvent(function() {
					var regObj = {};
					regObj.id = regObj.altContentId = replaceElemIdStr;
					regObj.width = widthStr;
					regObj.height = heightStr;
					regObj.expressInstall = xiSwfUrlStr;
					showExpressInstall(regObj);
				});
			}
		},
		
		getFlashPlayerVersion: function() {
			return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
		},
		
		hasFlashPlayerVersion: hasPlayerVersion,
		
		createSWF: function(attObj, parObj, replaceElemIdStr) {
			if (ua.w3cdom) {
				return createSWF(attObj, parObj, replaceElemIdStr);
			}
			else {
				return undefined;
			}
		},
		
		removeSWF: function(objElemIdStr) {
			if (ua.w3cdom) {
				removeSWF(objElemIdStr);
			}
		},
		
		createCSS: function(sel, decl) {
			if (ua.w3cdom) {
				createCSS(sel, decl);
			}
		},
		
		addDomLoadEvent: addDomLoadEvent,
		
		addLoadEvent: addLoadEvent,
		
		getQueryParamValue: function(param) {
			var q = doc.location.search || doc.location.hash;
			if (param == null) {
				return urlEncodeIfNecessary(q);
			}
			if (q) {
				var pairs = q.substring(1).split("&");
				for (var i = 0; i < pairs.length; i++) {
					if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
						return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
					}
				}
			}
			return "";
		},
		
		// For internal usage only
		expressInstallCallback: function() {
			if (isExpressInstallActive && storedAltContent) {
				var obj = getElementById(EXPRESS_INSTALL_ID);
				if (obj) {
					obj.parentNode.replaceChild(storedAltContent, obj);
					if (storedAltContentId) {
						setVisibility(storedAltContentId, true);
						if (ua.ie && ua.win) {
							storedAltContent.style.display = "block";
						}
					}
					storedAltContent = null;
					storedAltContentId = null;
					isExpressInstallActive = false;
				}
			} 
		}
	};
}();
/**
 * @license AngularJS v1.4.3
 * (c) 2010-2015 Google, Inc. http://angularjs.org
 * License: MIT
 */
(function(window, document, undefined) {'use strict';

/**
 * @description
 *
 * This object provides a utility for producing rich Error messages within
 * Angular. It can be called as follows:
 *
 * var exampleMinErr = minErr('example');
 * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
 *
 * The above creates an instance of minErr in the example namespace. The
 * resulting error will have a namespaced error code of example.one.  The
 * resulting error will replace {0} with the value of foo, and {1} with the
 * value of bar. The object is not restricted in the number of arguments it can
 * take.
 *
 * If fewer arguments are specified than necessary for interpolation, the extra
 * interpolation markers will be preserved in the final string.
 *
 * Since data will be parsed statically during a build step, some restrictions
 * are applied with respect to how minErr instances are created and called.
 * Instances should have names of the form namespaceMinErr for a minErr created
 * using minErr('namespace') . Error codes, namespaces and template strings
 * should all be static strings, not variables or general expressions.
 *
 * @param {string} module The namespace to use for the new minErr instance.
 * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
 *   error from returned function, for cases when a particular type of error is useful.
 * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
 */

function minErr(module, ErrorConstructor) {
  ErrorConstructor = ErrorConstructor || Error;
  return function() {
    var SKIP_INDEXES = 2;

    var templateArgs = arguments,
      code = templateArgs[0],
      message = '[' + (module ? module + ':' : '') + code + '] ',
      template = templateArgs[1],
      paramPrefix, i;

    message += template.replace(/\{\d+\}/g, function(match) {
      var index = +match.slice(1, -1),
        shiftedIndex = index + SKIP_INDEXES;

      if (shiftedIndex < templateArgs.length) {
        return toDebugString(templateArgs[shiftedIndex]);
      }

      return match;
    });

    message += '\nhttp://errors.angularjs.org/1.4.3/' +
      (module ? module + '/' : '') + code;

    for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
      message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
        encodeURIComponent(toDebugString(templateArgs[i]));
    }

    return new ErrorConstructor(message);
  };
}

/* We need to tell jshint what variables are being exported */
/* global angular: true,
  msie: true,
  jqLite: true,
  jQuery: true,
  slice: true,
  splice: true,
  push: true,
  toString: true,
  ngMinErr: true,
  angularModule: true,
  uid: true,
  REGEX_STRING_REGEXP: true,
  VALIDITY_STATE_PROPERTY: true,

  lowercase: true,
  uppercase: true,
  manualLowercase: true,
  manualUppercase: true,
  nodeName_: true,
  isArrayLike: true,
  forEach: true,
  forEachSorted: true,
  reverseParams: true,
  nextUid: true,
  setHashKey: true,
  extend: true,
  toInt: true,
  inherit: true,
  merge: true,
  noop: true,
  identity: true,
  valueFn: true,
  isUndefined: true,
  isDefined: true,
  isObject: true,
  isBlankObject: true,
  isString: true,
  isNumber: true,
  isDate: true,
  isArray: true,
  isFunction: true,
  isRegExp: true,
  isWindow: true,
  isScope: true,
  isFile: true,
  isFormData: true,
  isBlob: true,
  isBoolean: true,
  isPromiseLike: true,
  trim: true,
  escapeForRegexp: true,
  isElement: true,
  makeMap: true,
  includes: true,
  arrayRemove: true,
  copy: true,
  shallowCopy: true,
  equals: true,
  csp: true,
  jq: true,
  concat: true,
  sliceArgs: true,
  bind: true,
  toJsonReplacer: true,
  toJson: true,
  fromJson: true,
  convertTimezoneToLocal: true,
  timezoneToOffset: true,
  startingTag: true,
  tryDecodeURIComponent: true,
  parseKeyValue: true,
  toKeyValue: true,
  encodeUriSegment: true,
  encodeUriQuery: true,
  angularInit: true,
  bootstrap: true,
  getTestability: true,
  snake_case: true,
  bindJQuery: true,
  assertArg: true,
  assertArgFn: true,
  assertNotHasOwnProperty: true,
  getter: true,
  getBlockNodes: true,
  hasOwnProperty: true,
  createMap: true,

  NODE_TYPE_ELEMENT: true,
  NODE_TYPE_ATTRIBUTE: true,
  NODE_TYPE_TEXT: true,
  NODE_TYPE_COMMENT: true,
  NODE_TYPE_DOCUMENT: true,
  NODE_TYPE_DOCUMENT_FRAGMENT: true,
*/

////////////////////////////////////

/**
 * @ngdoc module
 * @name ng
 * @module ng
 * @description
 *
 * # ng (core module)
 * The ng module is loaded by default when an AngularJS application is started. The module itself
 * contains the essential components for an AngularJS application to function. The table below
 * lists a high level breakdown of each of the services/factories, filters, directives and testing
 * components available within this core module.
 *
 * <div doc-module-components="ng"></div>
 */

var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;

// The name of a form control's ValidityState property.
// This is used so that it's possible for internal tests to create mock ValidityStates.
var VALIDITY_STATE_PROPERTY = 'validity';

/**
 * @ngdoc function
 * @name angular.lowercase
 * @module ng
 * @kind function
 *
 * @description Converts the specified string to lowercase.
 * @param {string} string String to be converted to lowercase.
 * @returns {string} Lowercased string.
 */
var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
var hasOwnProperty = Object.prototype.hasOwnProperty;

/**
 * @ngdoc function
 * @name angular.uppercase
 * @module ng
 * @kind function
 *
 * @description Converts the specified string to uppercase.
 * @param {string} string String to be converted to uppercase.
 * @returns {string} Uppercased string.
 */
var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};


var manualLowercase = function(s) {
  /* jshint bitwise: false */
  return isString(s)
      ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
      : s;
};
var manualUppercase = function(s) {
  /* jshint bitwise: false */
  return isString(s)
      ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
      : s;
};


// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
  lowercase = manualLowercase;
  uppercase = manualUppercase;
}


var
    msie,             // holds major version number for IE, or NaN if UA is not IE.
    jqLite,           // delay binding since jQuery could be loaded after us.
    jQuery,           // delay binding
    slice             = [].slice,
    splice            = [].splice,
    push              = [].push,
    toString          = Object.prototype.toString,
    getPrototypeOf    = Object.getPrototypeOf,
    ngMinErr          = minErr('ng'),

    /** @name angular */
    angular           = window.angular || (window.angular = {}),
    angularModule,
    uid               = 0;

/**
 * documentMode is an IE-only property
 * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
 */
msie = document.documentMode;


/**
 * @private
 * @param {*} obj
 * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
 *                   String ...)
 */
function isArrayLike(obj) {
  if (obj == null || isWindow(obj)) {
    return false;
  }

  // Support: iOS 8.2 (not reproducible in simulator)
  // "length" in obj used to prevent JIT error (gh-11508)
  var length = "length" in Object(obj) && obj.length;

  if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
    return true;
  }

  return isString(obj) || isArray(obj) || length === 0 ||
         typeof length === 'number' && length > 0 && (length - 1) in obj;
}

/**
 * @ngdoc function
 * @name angular.forEach
 * @module ng
 * @kind function
 *
 * @description
 * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
 * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
 * is the value of an object property or an array element, `key` is the object property key or
 * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
 *
 * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
 * using the `hasOwnProperty` method.
 *
 * Unlike ES262's
 * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
 * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
 * return the value provided.
 *
   ```js
     var values = {name: 'misko', gender: 'male'};
     var log = [];
     angular.forEach(values, function(value, key) {
       this.push(key + ': ' + value);
     }, log);
     expect(log).toEqual(['name: misko', 'gender: male']);
   ```
 *
 * @param {Object|Array} obj Object to iterate over.
 * @param {Function} iterator Iterator function.
 * @param {Object=} context Object to become context (`this`) for the iterator function.
 * @returns {Object|Array} Reference to `obj`.
 */

function forEach(obj, iterator, context) {
  var key, length;
  if (obj) {
    if (isFunction(obj)) {
      for (key in obj) {
        // Need to check if hasOwnProperty exists,
        // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
        if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
          iterator.call(context, obj[key], key, obj);
        }
      }
    } else if (isArray(obj) || isArrayLike(obj)) {
      var isPrimitive = typeof obj !== 'object';
      for (key = 0, length = obj.length; key < length; key++) {
        if (isPrimitive || key in obj) {
          iterator.call(context, obj[key], key, obj);
        }
      }
    } else if (obj.forEach && obj.forEach !== forEach) {
        obj.forEach(iterator, context, obj);
    } else if (isBlankObject(obj)) {
      // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
      for (key in obj) {
        iterator.call(context, obj[key], key, obj);
      }
    } else if (typeof obj.hasOwnProperty === 'function') {
      // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
      for (key in obj) {
        if (obj.hasOwnProperty(key)) {
          iterator.call(context, obj[key], key, obj);
        }
      }
    } else {
      // Slow path for objects which do not have a method `hasOwnProperty`
      for (key in obj) {
        if (hasOwnProperty.call(obj, key)) {
          iterator.call(context, obj[key], key, obj);
        }
      }
    }
  }
  return obj;
}

function forEachSorted(obj, iterator, context) {
  var keys = Object.keys(obj).sort();
  for (var i = 0; i < keys.length; i++) {
    iterator.call(context, obj[keys[i]], keys[i]);
  }
  return keys;
}


/**
 * when using forEach the params are value, key, but it is often useful to have key, value.
 * @param {function(string, *)} iteratorFn
 * @returns {function(*, string)}
 */
function reverseParams(iteratorFn) {
  return function(value, key) { iteratorFn(key, value); };
}

/**
 * A consistent way of creating unique IDs in angular.
 *
 * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
 * we hit number precision issues in JavaScript.
 *
 * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
 *
 * @returns {number} an unique alpha-numeric string
 */
function nextUid() {
  return ++uid;
}


/**
 * Set or clear the hashkey for an object.
 * @param obj object
 * @param h the hashkey (!truthy to delete the hashkey)
 */
function setHashKey(obj, h) {
  if (h) {
    obj.$$hashKey = h;
  } else {
    delete obj.$$hashKey;
  }
}


function baseExtend(dst, objs, deep) {
  var h = dst.$$hashKey;

  for (var i = 0, ii = objs.length; i < ii; ++i) {
    var obj = objs[i];
    if (!isObject(obj) && !isFunction(obj)) continue;
    var keys = Object.keys(obj);
    for (var j = 0, jj = keys.length; j < jj; j++) {
      var key = keys[j];
      var src = obj[key];

      if (deep && isObject(src)) {
        if (isDate(src)) {
          dst[key] = new Date(src.valueOf());
        } else {
          if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
          baseExtend(dst[key], [src], true);
        }
      } else {
        dst[key] = src;
      }
    }
  }

  setHashKey(dst, h);
  return dst;
}

/**
 * @ngdoc function
 * @name angular.extend
 * @module ng
 * @kind function
 *
 * @description
 * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
 * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
 * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
 *
 * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
 * {@link angular.merge} for this.
 *
 * @param {Object} dst Destination object.
 * @param {...Object} src Source object(s).
 * @returns {Object} Reference to `dst`.
 */
function extend(dst) {
  return baseExtend(dst, slice.call(arguments, 1), false);
}


/**
* @ngdoc function
* @name angular.merge
* @module ng
* @kind function
*
* @description
* Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
* by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
*
* Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
* objects, performing a deep copy.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*/
function merge(dst) {
  return baseExtend(dst, slice.call(arguments, 1), true);
}



function toInt(str) {
  return parseInt(str, 10);
}


function inherit(parent, extra) {
  return extend(Object.create(parent), extra);
}

/**
 * @ngdoc function
 * @name angular.noop
 * @module ng
 * @kind function
 *
 * @description
 * A function that performs no operations. This function can be useful when writing code in the
 * functional style.
   ```js
     function foo(callback) {
       var result = calculateResult();
       (callback || angular.noop)(result);
     }
   ```
 */
function noop() {}
noop.$inject = [];


/**
 * @ngdoc function
 * @name angular.identity
 * @module ng
 * @kind function
 *
 * @description
 * A function that returns its first argument. This function is useful when writing code in the
 * functional style.
 *
   ```js
     function transformer(transformationFn, value) {
       return (transformationFn || angular.identity)(value);
     };
   ```
  * @param {*} value to be returned.
  * @returns {*} the value passed in.
 */
function identity($) {return $;}
identity.$inject = [];


function valueFn(value) {return function() {return value;};}

function hasCustomToString(obj) {
  return isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
}


/**
 * @ngdoc function
 * @name angular.isUndefined
 * @module ng
 * @kind function
 *
 * @description
 * Determines if a reference is undefined.
 *
 * @param {*} value Reference to check.
 * @returns {boolean} True if `value` is undefined.
 */
function isUndefined(value) {return typeof value === 'undefined';}


/**
 * @ngdoc function
 * @name angular.isDefined
 * @module ng
 * @kind function
 *
 * @description
 * Determines if a reference is defined.
 *
 * @param {*} value Reference to check.
 * @returns {boolean} True if `value` is defined.
 */
function isDefined(value) {return typeof value !== 'undefined';}


/**
 * @ngdoc function
 * @name angular.isObject
 * @module ng
 * @kind function
 *
 * @description
 * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
 * considered to be objects. Note that JavaScript arrays are objects.
 *
 * @param {*} value Reference to check.
 * @returns {boolean} True if `value` is an `Object` but not `null`.
 */
function isObject(value) {
  // http://jsperf.com/isobject4
  return value !== null && typeof value === 'object';
}


/**
 * Determine if a value is an object with a null prototype
 *
 * @returns {boolean} True if `value` is an `Object` with a null prototype
 */
function isBlankObject(value) {
  return value !== null && typeof value === 'object' && !getPrototypeOf(value);
}


/**
 * @ngdoc function
 * @name angular.isString
 * @module ng
 * @kind function
 *
 * @description
 * Determines if a reference is a `String`.
 *
 * @param {*} value Reference to check.
 * @returns {boolean} True if `value` is a `String`.
 */
function isString(value) {return typeof value === 'string';}


/**
 * @ngdoc function
 * @name angular.isNumber
 * @module ng
 * @kind function
 *
 * @description
 * Determines if a reference is a `Number`.
 *
 * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
 *
 * If you wish to exclude these then you can use the native
 * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
 * method.
 *
 * @param {*} value Reference to check.
 * @returns {boolean} True if `value` is a `Number`.
 */
function isNumber(value) {return typeof value === 'number';}


/**
 * @ngdoc function
 * @name angular.isDate
 * @module ng
 * @kind function
 *
 * @description
 * Determines if a value is a date.
 *
 * @param {*} value Reference to check.
 * @returns {boolean} True if `value` is a `Date`.
 */
function isDate(value) {
  return toString.call(value) === '[object Date]';
}


/**
 * @ngdoc function
 * @name angular.isArray
 * @module ng
 * @kind function
 *
 * @description
 * Determines if a reference is an `Array`.
 *
 * @param {*} value Reference to check.
 * @returns {boolean} True if `value` is an `Array`.
 */
var isArray = Array.isArray;

/**
 * @ngdoc function
 * @name angular.isFunction
 * @module ng
 * @kind function
 *
 * @description
 * Determines if a reference is a `Function`.
 *
 * @param {*} value Reference to check.
 * @returns {boolean} True if `value` is a `Function`.
 */
function isFunction(value) {return typeof value === 'function';}


/**
 * Determines if a value is a regular expression object.
 *
 * @private
 * @param {*} value Reference to check.
 * @returns {boolean} True if `value` is a `RegExp`.
 */
function isRegExp(value) {
  return toString.call(value) === '[object RegExp]';
}


/**
 * Checks if `obj` is a window object.
 *
 * @private
 * @param {*} obj Object to check
 * @returns {boolean} True if `obj` is a window obj.
 */
function isWindow(obj) {
  return obj && obj.window === obj;
}


function isScope(obj) {
  return obj && obj.$evalAsync && obj.$watch;
}


function isFile(obj) {
  return toString.call(obj) === '[object File]';
}


function isFormData(obj) {
  return toString.call(obj) === '[object FormData]';
}


function isBlob(obj) {
  return toString.call(obj) === '[object Blob]';
}


function isBoolean(value) {
  return typeof value === 'boolean';
}


function isPromiseLike(obj) {
  return obj && isFunction(obj.then);
}


var TYPED_ARRAY_REGEXP = /^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/;
function isTypedArray(value) {
  return TYPED_ARRAY_REGEXP.test(toString.call(value));
}


var trim = function(value) {
  return isString(value) ? value.trim() : value;
};

// Copied from:
// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
// Prereq: s is a string.
var escapeForRegexp = function(s) {
  return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
           replace(/\x08/g, '\\x08');
};


/**
 * @ngdoc function
 * @name angular.isElement
 * @module ng
 * @kind function
 *
 * @description
 * Determines if a reference is a DOM element (or wrapped jQuery element).
 *
 * @param {*} value Reference to check.
 * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
 */
function isElement(node) {
  return !!(node &&
    (node.nodeName  // we are a direct element
    || (node.prop && node.attr && node.find)));  // we have an on and find method part of jQuery API
}

/**
 * @param str 'key1,key2,...'
 * @returns {object} in the form of {key1:true, key2:true, ...}
 */
function makeMap(str) {
  var obj = {}, items = str.split(","), i;
  for (i = 0; i < items.length; i++) {
    obj[items[i]] = true;
  }
  return obj;
}


function nodeName_(element) {
  return lowercase(element.nodeName || (element[0] && element[0].nodeName));
}

function includes(array, obj) {
  return Array.prototype.indexOf.call(array, obj) != -1;
}

function arrayRemove(array, value) {
  var index = array.indexOf(value);
  if (index >= 0) {
    array.splice(index, 1);
  }
  return index;
}

/**
 * @ngdoc function
 * @name angular.copy
 * @module ng
 * @kind function
 *
 * @description
 * Creates a deep copy of `source`, which should be an object or an array.
 *
 * * If no destination is supplied, a copy of the object or array is created.
 * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
 *   are deleted and then all elements/properties from the source are copied to it.
 * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
 * * If `source` is identical to 'destination' an exception will be thrown.
 *
 * @param {*} source The source that will be used to make a copy.
 *                   Can be any type, including primitives, `null`, and `undefined`.
 * @param {(Object|Array)=} destination Destination into which the source is copied. If
 *     provided, must be of the same type as `source`.
 * @returns {*} The copy or updated `destination`, if `destination` was specified.
 *
 * @example
 <example module="copyExample">
 <file name="index.html">
 <div ng-controller="ExampleController">
 <form novalidate class="simple-form">
 Name: <input type="text" ng-model="user.name" /><br />
 E-mail: <input type="email" ng-model="user.email" /><br />
 Gender: <input type="radio" ng-model="user.gender" value="male" />male
 <input type="radio" ng-model="user.gender" value="female" />female<br />
 <button ng-click="reset()">RESET</button>
 <button ng-click="update(user)">SAVE</button>
 </form>
 <pre>form = {{user | json}}</pre>
 <pre>master = {{master | json}}</pre>
 </div>

 <script>
  angular.module('copyExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.master= {};

      $scope.update = function(user) {
        // Example with 1 argument
        $scope.master= angular.copy(user);
      };

      $scope.reset = function() {
        // Example with 2 arguments
        angular.copy($scope.master, $scope.user);
      };

      $scope.reset();
    }]);
 </script>
 </file>
 </example>
 */
function copy(source, destination, stackSource, stackDest) {
  if (isWindow(source) || isScope(source)) {
    throw ngMinErr('cpws',
      "Can't copy! Making copies of Window or Scope instances is not supported.");
  }
  if (isTypedArray(destination)) {
    throw ngMinErr('cpta',
      "Can't copy! TypedArray destination cannot be mutated.");
  }

  if (!destination) {
    destination = source;
    if (isObject(source)) {
      var index;
      if (stackSource && (index = stackSource.indexOf(source)) !== -1) {
        return stackDest[index];
      }

      // TypedArray, Date and RegExp have specific copy functionality and must be
      // pushed onto the stack before returning.
      // Array and other objects create the base object and recurse to copy child
      // objects. The array/object will be pushed onto the stack when recursed.
      if (isArray(source)) {
        return copy(source, [], stackSource, stackDest);
      } else if (isTypedArray(source)) {
        destination = new source.constructor(source);
      } else if (isDate(source)) {
        destination = new Date(source.getTime());
      } else if (isRegExp(source)) {
        destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
        destination.lastIndex = source.lastIndex;
      } else {
        var emptyObject = Object.create(getPrototypeOf(source));
        return copy(source, emptyObject, stackSource, stackDest);
      }

      if (stackDest) {
        stackSource.push(source);
        stackDest.push(destination);
      }
    }
  } else {
    if (source === destination) throw ngMinErr('cpi',
      "Can't copy! Source and destination are identical.");

    stackSource = stackSource || [];
    stackDest = stackDest || [];

    if (isObject(source)) {
      stackSource.push(source);
      stackDest.push(destination);
    }

    var result, key;
    if (isArray(source)) {
      destination.length = 0;
      for (var i = 0; i < source.length; i++) {
        destination.push(copy(source[i], null, stackSource, stackDest));
      }
    } else {
      var h = destination.$$hashKey;
      if (isArray(destination)) {
        destination.length = 0;
      } else {
        forEach(destination, function(value, key) {
          delete destination[key];
        });
      }
      if (isBlankObject(source)) {
        // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
        for (key in source) {
          destination[key] = copy(source[key], null, stackSource, stackDest);
        }
      } else if (source && typeof source.hasOwnProperty === 'function') {
        // Slow path, which must rely on hasOwnProperty
        for (key in source) {
          if (source.hasOwnProperty(key)) {
            destination[key] = copy(source[key], null, stackSource, stackDest);
          }
        }
      } else {
        // Slowest path --- hasOwnProperty can't be called as a method
        for (key in source) {
          if (hasOwnProperty.call(source, key)) {
            destination[key] = copy(source[key], null, stackSource, stackDest);
          }
        }
      }
      setHashKey(destination,h);
    }
  }
  return destination;
}

/**
 * Creates a shallow copy of an object, an array or a primitive.
 *
 * Assumes that there are no proto properties for objects.
 */
function shallowCopy(src, dst) {
  if (isArray(src)) {
    dst = dst || [];

    for (var i = 0, ii = src.length; i < ii; i++) {
      dst[i] = src[i];
    }
  } else if (isObject(src)) {
    dst = dst || {};

    for (var key in src) {
      if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
        dst[key] = src[key];
      }
    }
  }

  return dst || src;
}


/**
 * @ngdoc function
 * @name angular.equals
 * @module ng
 * @kind function
 *
 * @description
 * Determines if two objects or two values are equivalent. Supports value types, regular
 * expressions, arrays and objects.
 *
 * Two objects or values are considered equivalent if at least one of the following is true:
 *
 * * Both objects or values pass `===` comparison.
 * * Both objects or values are of the same type and all of their properties are equal by
 *   comparing them with `angular.equals`.
 * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
 * * Both values represent the same regular expression (In JavaScript,
 *   /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
 *   representation matches).
 *
 * During a property comparison, properties of `function` type and properties with names
 * that begin with `$` are ignored.
 *
 * Scope and DOMWindow objects are being compared only by identify (`===`).
 *
 * @param {*} o1 Object or value to compare.
 * @param {*} o2 Object or value to compare.
 * @returns {boolean} True if arguments are equal.
 */
function equals(o1, o2) {
  if (o1 === o2) return true;
  if (o1 === null || o2 === null) return false;
  if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  if (t1 == t2) {
    if (t1 == 'object') {
      if (isArray(o1)) {
        if (!isArray(o2)) return false;
        if ((length = o1.length) == o2.length) {
          for (key = 0; key < length; key++) {
            if (!equals(o1[key], o2[key])) return false;
          }
          return true;
        }
      } else if (isDate(o1)) {
        if (!isDate(o2)) return false;
        return equals(o1.getTime(), o2.getTime());
      } else if (isRegExp(o1)) {
        return isRegExp(o2) ? o1.toString() == o2.toString() : false;
      } else {
        if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
          isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
        keySet = createMap();
        for (key in o1) {
          if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
          if (!equals(o1[key], o2[key])) return false;
          keySet[key] = true;
        }
        for (key in o2) {
          if (!(key in keySet) &&
              key.charAt(0) !== '$' &&
              o2[key] !== undefined &&
              !isFunction(o2[key])) return false;
        }
        return true;
      }
    }
  }
  return false;
}

var csp = function() {
  if (isDefined(csp.isActive_)) return csp.isActive_;

  var active = !!(document.querySelector('[ng-csp]') ||
                  document.querySelector('[data-ng-csp]'));

  if (!active) {
    try {
      /* jshint -W031, -W054 */
      new Function('');
      /* jshint +W031, +W054 */
    } catch (e) {
      active = true;
    }
  }

  return (csp.isActive_ = active);
};

/**
 * @ngdoc directive
 * @module ng
 * @name ngJq
 *
 * @element ANY
 * @param {string=} ngJq the name of the library available under `window`
 * to be used for angular.element
 * @description
 * Use this directive to force the angular.element library.  This should be
 * used to force either jqLite by leaving ng-jq blank or setting the name of
 * the jquery variable under window (eg. jQuery).
 *
 * Since angular looks for this directive when it is loaded (doesn't wait for the
 * DOMContentLoaded event), it must be placed on an element that comes before the script
 * which loads angular. Also, only the first instance of `ng-jq` will be used and all
 * others ignored.
 *
 * @example
 * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
 ```html
 <!doctype html>
 <html ng-app ng-jq>
 ...
 ...
 </html>
 ```
 * @example
 * This example shows how to use a jQuery based library of a different name.
 * The library name must be available at the top most 'window'.
 ```html
 <!doctype html>
 <html ng-app ng-jq="jQueryLib">
 ...
 ...
 </html>
 ```
 */
var jq = function() {
  if (isDefined(jq.name_)) return jq.name_;
  var el;
  var i, ii = ngAttrPrefixes.length, prefix, name;
  for (i = 0; i < ii; ++i) {
    prefix = ngAttrPrefixes[i];
    if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
      name = el.getAttribute(prefix + 'jq');
      break;
    }
  }

  return (jq.name_ = name);
};

function concat(array1, array2, index) {
  return array1.concat(slice.call(array2, index));
}

function sliceArgs(args, startIndex) {
  return slice.call(args, startIndex || 0);
}


/* jshint -W101 */
/**
 * @ngdoc function
 * @name angular.bind
 * @module ng
 * @kind function
 *
 * @description
 * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
 * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
 * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
 * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
 *
 * @param {Object} self Context which `fn` should be evaluated in.
 * @param {function()} fn Function to be bound.
 * @param {...*} args Optional arguments to be prebound to the `fn` function call.
 * @returns {function()} Function that wraps the `fn` with all the specified bindings.
 */
/* jshint +W101 */
function bind(self, fn) {
  var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  if (isFunction(fn) && !(fn instanceof RegExp)) {
    return curryArgs.length
      ? function() {
          return arguments.length
            ? fn.apply(self, concat(curryArgs, arguments, 0))
            : fn.apply(self, curryArgs);
        }
      : function() {
          return arguments.length
            ? fn.apply(self, arguments)
            : fn.call(self);
        };
  } else {
    // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
    return fn;
  }
}


function toJsonReplacer(key, value) {
  var val = value;

  if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
    val = undefined;
  } else if (isWindow(value)) {
    val = '$WINDOW';
  } else if (value &&  document === value) {
    val = '$DOCUMENT';
  } else if (isScope(value)) {
    val = '$SCOPE';
  }

  return val;
}


/**
 * @ngdoc function
 * @name angular.toJson
 * @module ng
 * @kind function
 *
 * @description
 * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
 * stripped since angular uses this notation internally.
 *
 * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
 * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
 *    If set to an integer, the JSON output will contain that many spaces per indentation.
 * @returns {string|undefined} JSON-ified string representing `obj`.
 */
function toJson(obj, pretty) {
  if (typeof obj === 'undefined') return undefined;
  if (!isNumber(pretty)) {
    pretty = pretty ? 2 : null;
  }
  return JSON.stringify(obj, toJsonReplacer, pretty);
}


/**
 * @ngdoc function
 * @name angular.fromJson
 * @module ng
 * @kind function
 *
 * @description
 * Deserializes a JSON string.
 *
 * @param {string} json JSON string to deserialize.
 * @returns {Object|Array|string|number} Deserialized JSON string.
 */
function fromJson(json) {
  return isString(json)
      ? JSON.parse(json)
      : json;
}


function timezoneToOffset(timezone, fallback) {
  var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
}


function addDateMinutes(date, minutes) {
  date = new Date(date.getTime());
  date.setMinutes(date.getMinutes() + minutes);
  return date;
}


function convertTimezoneToLocal(date, timezone, reverse) {
  reverse = reverse ? -1 : 1;
  var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
}


/**
 * @returns {string} Returns the string representation of the element.
 */
function startingTag(element) {
  element = jqLite(element).clone();
  try {
    // turns out IE does not let you set .html() on elements which
    // are not allowed to have children. So we just ignore it.
    element.empty();
  } catch (e) {}
  var elemHtml = jqLite('<div>').append(element).html();
  try {
    return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
        elemHtml.
          match(/^(<[^>]+>)/)[1].
          replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  } catch (e) {
    return lowercase(elemHtml);
  }

}


/////////////////////////////////////////////////

/**
 * Tries to decode the URI component without throwing an exception.
 *
 * @private
 * @param str value potential URI component to check.
 * @returns {boolean} True if `value` can be decoded
 * with the decodeURIComponent function.
 */
function tryDecodeURIComponent(value) {
  try {
    return decodeURIComponent(value);
  } catch (e) {
    // Ignore any invalid uri component
  }
}


/**
 * Parses an escaped url query string into key-value pairs.
 * @returns {Object.<string,boolean|Array>}
 */
function parseKeyValue(/**string*/keyValue) {
  var obj = {}, key_value, key;
  forEach((keyValue || "").split('&'), function(keyValue) {
    if (keyValue) {
      key_value = keyValue.replace(/\+/g,'%20').split('=');
      key = tryDecodeURIComponent(key_value[0]);
      if (isDefined(key)) {
        var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
        if (!hasOwnProperty.call(obj, key)) {
          obj[key] = val;
        } else if (isArray(obj[key])) {
          obj[key].push(val);
        } else {
          obj[key] = [obj[key],val];
        }
      }
    }
  });
  return obj;
}

function toKeyValue(obj) {
  var parts = [];
  forEach(obj, function(value, key) {
    if (isArray(value)) {
      forEach(value, function(arrayValue) {
        parts.push(encodeUriQuery(key, true) +
                   (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
      });
    } else {
    parts.push(encodeUriQuery(key, true) +
               (value === true ? '' : '=' + encodeUriQuery(value, true)));
    }
  });
  return parts.length ? parts.join('&') : '';
}


/**
 * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
 * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
 * segments:
 *    segment       = *pchar
 *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
 *    pct-encoded   = "%" HEXDIG HEXDIG
 *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
 *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
 *                     / "*" / "+" / "," / ";" / "="
 */
function encodeUriSegment(val) {
  return encodeUriQuery(val, true).
             replace(/%26/gi, '&').
             replace(/%3D/gi, '=').
             replace(/%2B/gi, '+');
}


/**
 * This method is intended for encoding *key* or *value* parts of query component. We need a custom
 * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
 * encoded per http://tools.ietf.org/html/rfc3986:
 *    query       = *( pchar / "/" / "?" )
 *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
 *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
 *    pct-encoded   = "%" HEXDIG HEXDIG
 *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
 *                     / "*" / "+" / "," / ";" / "="
 */
function encodeUriQuery(val, pctEncodeSpaces) {
  return encodeURIComponent(val).
             replace(/%40/gi, '@').
             replace(/%3A/gi, ':').
             replace(/%24/g, '$').
             replace(/%2C/gi, ',').
             replace(/%3B/gi, ';').
             replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}

var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];

function getNgAttribute(element, ngAttr) {
  var attr, i, ii = ngAttrPrefixes.length;
  for (i = 0; i < ii; ++i) {
    attr = ngAttrPrefixes[i] + ngAttr;
    if (isString(attr = element.getAttribute(attr))) {
      return attr;
    }
  }
  return null;
}

/**
 * @ngdoc directive
 * @name ngApp
 * @module ng
 *
 * @element ANY
 * @param {angular.Module} ngApp an optional application
 *   {@link angular.module module} name to load.
 * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
 *   created in "strict-di" mode. This means that the application will fail to invoke functions which
 *   do not use explicit function annotation (and are thus unsuitable for minification), as described
 *   in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
 *   tracking down the root of these bugs.
 *
 * @description
 *
 * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
 * designates the **root element** of the application and is typically placed near the root element
 * of the page - e.g. on the `<body>` or `<html>` tags.
 *
 * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
 * found in the document will be used to define the root element to auto-bootstrap as an
 * application. To run multiple applications in an HTML document you must manually bootstrap them using
 * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
 *
 * You can specify an **AngularJS module** to be used as the root module for the application.  This
 * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
 * should contain the application code needed or have dependencies on other modules that will
 * contain the code. See {@link angular.module} for more information.
 *
 * In the example below if the `ngApp` directive were not placed on the `html` element then the
 * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
 * would not be resolved to `3`.
 *
 * `ngApp` is the easiest, and most common way to bootstrap an application.
 *
 <example module="ngAppDemo">
   <file name="index.html">
   <div ng-controller="ngAppDemoController">
     I can add: {{a}} + {{b}} =  {{ a+b }}
   </div>
   </file>
   <file name="script.js">
   angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
     $scope.a = 1;
     $scope.b = 2;
   });
   </file>
 </example>
 *
 * Using `ngStrictDi`, you would see something like this:
 *
 <example ng-app-included="true">
   <file name="index.html">
   <div ng-app="ngAppStrictDemo" ng-strict-di>
       <div ng-controller="GoodController1">
           I can add: {{a}} + {{b}} =  {{ a+b }}

           <p>This renders because the controller does not fail to
              instantiate, by using explicit annotation style (see
              script.js for details)
           </p>
       </div>

       <div ng-controller="GoodController2">
           Name: <input ng-model="name"><br />
           Hello, {{name}}!

           <p>This renders because the controller does not fail to
              instantiate, by using explicit annotation style
              (see script.js for details)
           </p>
       </div>

       <div ng-controller="BadController">
           I can add: {{a}} + {{b}} =  {{ a+b }}

           <p>The controller could not be instantiated, due to relying
              on automatic function annotations (which are disabled in
              strict mode). As such, the content of this section is not
              interpolated, and there should be an error in your web console.
           </p>
       </div>
   </div>
   </file>
   <file name="script.js">
   angular.module('ngAppStrictDemo', [])
     // BadController will fail to instantiate, due to relying on automatic function annotation,
     // rather than an explicit annotation
     .controller('BadController', function($scope) {
       $scope.a = 1;
       $scope.b = 2;
     })
     // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
     // due to using explicit annotations using the array style and $inject property, respectively.
     .controller('GoodController1', ['$scope', function($scope) {
       $scope.a = 1;
       $scope.b = 2;
     }])
     .controller('GoodController2', GoodController2);
     function GoodController2($scope) {
       $scope.name = "World";
     }
     GoodController2.$inject = ['$scope'];
   </file>
   <file name="style.css">
   div[ng-controller] {
       margin-bottom: 1em;
       -webkit-border-radius: 4px;
       border-radius: 4px;
       border: 1px solid;
       padding: .5em;
   }
   div[ng-controller^=Good] {
       border-color: #d6e9c6;
       background-color: #dff0d8;
       color: #3c763d;
   }
   div[ng-controller^=Bad] {
       border-color: #ebccd1;
       background-color: #f2dede;
       color: #a94442;
       margin-bottom: 0;
   }
   </file>
 </example>
 */
function angularInit(element, bootstrap) {
  var appElement,
      module,
      config = {};

  // The element `element` has priority over any other element
  forEach(ngAttrPrefixes, function(prefix) {
    var name = prefix + 'app';

    if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
      appElement = element;
      module = element.getAttribute(name);
    }
  });
  forEach(ngAttrPrefixes, function(prefix) {
    var name = prefix + 'app';
    var candidate;

    if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
      appElement = candidate;
      module = candidate.getAttribute(name);
    }
  });
  if (appElement) {
    config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
    bootstrap(appElement, module ? [module] : [], config);
  }
}

/**
 * @ngdoc function
 * @name angular.bootstrap
 * @module ng
 * @description
 * Use this function to manually start up angular application.
 *
 * See: {@link guide/bootstrap Bootstrap}
 *
 * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
 * They must use {@link ng.directive:ngApp ngApp}.
 *
 * Angular will detect if it has been loaded into the browser more than once and only allow the
 * first loaded script to be bootstrapped and will report a warning to the browser console for
 * each of the subsequent scripts. This prevents strange results in applications, where otherwise
 * multiple instances of Angular try to work on the DOM.
 *
 * ```html
 * <!doctype html>
 * <html>
 * <body>
 * <div ng-controller="WelcomeController">
 *   {{greeting}}
 * </div>
 *
 * <script src="angular.js"></script>
 * <script>
 *   var app = angular.module('demo', [])
 *   .controller('WelcomeController', function($scope) {
 *       $scope.greeting = 'Welcome!';
 *   });
 *   angular.bootstrap(document, ['demo']);
 * </script>
 * </body>
 * </html>
 * ```
 *
 * @param {DOMElement} element DOM element which is the root of angular application.
 * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
 *     Each item in the array should be the name of a predefined module or a (DI annotated)
 *     function that will be invoked by the injector as a `config` block.
 *     See: {@link angular.module modules}
 * @param {Object=} config an object for defining configuration options for the application. The
 *     following keys are supported:
 *
 * * `strictDi` - disable automatic function annotation for the application. This is meant to
 *   assist in finding bugs which break minified code. Defaults to `false`.
 *
 * @returns {auto.$injector} Returns the newly created injector for this app.
 */
function bootstrap(element, modules, config) {
  if (!isObject(config)) config = {};
  var defaultConfig = {
    strictDi: false
  };
  config = extend(defaultConfig, config);
  var doBootstrap = function() {
    element = jqLite(element);

    if (element.injector()) {
      var tag = (element[0] === document) ? 'document' : startingTag(element);
      //Encode angle brackets to prevent input from being sanitized to empty string #8683
      throw ngMinErr(
          'btstrpd',
          "App Already Bootstrapped with this Element '{0}'",
          tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
    }

    modules = modules || [];
    modules.unshift(['$provide', function($provide) {
      $provide.value('$rootElement', element);
    }]);

    if (config.debugInfoEnabled) {
      // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
      modules.push(['$compileProvider', function($compileProvider) {
        $compileProvider.debugInfoEnabled(true);
      }]);
    }

    modules.unshift('ng');
    var injector = createInjector(modules, config.strictDi);
    injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
       function bootstrapApply(scope, element, compile, injector) {
        scope.$apply(function() {
          element.data('$injector', injector);
          compile(element)(scope);
        });
      }]
    );
    return injector;
  };

  var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;

  if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
    config.debugInfoEnabled = true;
    window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  }

  if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
    return doBootstrap();
  }

  window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  angular.resumeBootstrap = function(extraModules) {
    forEach(extraModules, function(module) {
      modules.push(module);
    });
    return doBootstrap();
  };

  if (isFunction(angular.resumeDeferredBootstrap)) {
    angular.resumeDeferredBootstrap();
  }
}

/**
 * @ngdoc function
 * @name angular.reloadWithDebugInfo
 * @module ng
 * @description
 * Use this function to reload the current application with debug information turned on.
 * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
 *
 * See {@link ng.$compileProvider#debugInfoEnabled} for more.
 */
function reloadWithDebugInfo() {
  window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  window.location.reload();
}

/**
 * @name angular.getTestability
 * @module ng
 * @description
 * Get the testability service for the instance of Angular on the given
 * element.
 * @param {DOMElement} element DOM element which is the root of angular application.
 */
function getTestability(rootElement) {
  var injector = angular.element(rootElement).injector();
  if (!injector) {
    throw ngMinErr('test',
      'no injector found for element argument to getTestability');
  }
  return injector.get('$$testability');
}

var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator) {
  separator = separator || '_';
  return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
    return (pos ? separator : '') + letter.toLowerCase();
  });
}

var bindJQueryFired = false;
var skipDestroyOnNextJQueryCleanData;
function bindJQuery() {
  var originalCleanData;

  if (bindJQueryFired) {
    return;
  }

  // bind to jQuery if present;
  var jqName = jq();
  jQuery = window.jQuery; // use default jQuery.
  if (isDefined(jqName)) { // `ngJq` present
    jQuery = jqName === null ? undefined : window[jqName]; // if empty; use jqLite. if not empty, use jQuery specified by `ngJq`.
  }

  // Use jQuery if it exists with proper functionality, otherwise default to us.
  // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  // versions. It will not work for sure with jQuery <1.7, though.
  if (jQuery && jQuery.fn.on) {
    jqLite = jQuery;
    extend(jQuery.fn, {
      scope: JQLitePrototype.scope,
      isolateScope: JQLitePrototype.isolateScope,
      controller: JQLitePrototype.controller,
      injector: JQLitePrototype.injector,
      inheritedData: JQLitePrototype.inheritedData
    });

    // All nodes removed from the DOM via various jQuery APIs like .remove()
    // are passed through jQuery.cleanData. Monkey-patch this method to fire
    // the $destroy event on all removed nodes.
    originalCleanData = jQuery.cleanData;
    jQuery.cleanData = function(elems) {
      var events;
      if (!skipDestroyOnNextJQueryCleanData) {
        for (var i = 0, elem; (elem = elems[i]) != null; i++) {
          events = jQuery._data(elem, "events");
          if (events && events.$destroy) {
            jQuery(elem).triggerHandler('$destroy');
          }
        }
      } else {
        skipDestroyOnNextJQueryCleanData = false;
      }
      originalCleanData(elems);
    };
  } else {
    jqLite = JQLite;
  }

  angular.element = jqLite;

  // Prevent double-proxying.
  bindJQueryFired = true;
}

/**
 * throw error if the argument is falsy.
 */
function assertArg(arg, name, reason) {
  if (!arg) {
    throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  }
  return arg;
}

function assertArgFn(arg, name, acceptArrayAnnotation) {
  if (acceptArrayAnnotation && isArray(arg)) {
      arg = arg[arg.length - 1];
  }

  assertArg(isFunction(arg), name, 'not a function, got ' +
      (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  return arg;
}

/**
 * throw error if the name given is hasOwnProperty
 * @param  {String} name    the name to test
 * @param  {String} context the context in which the name is used, such as module or directive
 */
function assertNotHasOwnProperty(name, context) {
  if (name === 'hasOwnProperty') {
    throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  }
}

/**
 * Return the value accessible from the object by path. Any undefined traversals are ignored
 * @param {Object} obj starting object
 * @param {String} path path to traverse
 * @param {boolean} [bindFnToScope=true]
 * @returns {Object} value as accessible by path
 */
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
  if (!path) return obj;
  var keys = path.split('.');
  var key;
  var lastInstance = obj;
  var len = keys.length;

  for (var i = 0; i < len; i++) {
    key = keys[i];
    if (obj) {
      obj = (lastInstance = obj)[key];
    }
  }
  if (!bindFnToScope && isFunction(obj)) {
    return bind(lastInstance, obj);
  }
  return obj;
}

/**
 * Return the DOM siblings between the first and last node in the given array.
 * @param {Array} array like object
 * @returns {jqLite} jqLite collection containing the nodes
 */
function getBlockNodes(nodes) {
  // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
  //             collection, otherwise update the original collection.
  var node = nodes[0];
  var endNode = nodes[nodes.length - 1];
  var blockNodes = [node];

  do {
    node = node.nextSibling;
    if (!node) break;
    blockNodes.push(node);
  } while (node !== endNode);

  return jqLite(blockNodes);
}


/**
 * Creates a new object without a prototype. This object is useful for lookup without having to
 * guard against prototypically inherited properties via hasOwnProperty.
 *
 * Related micro-benchmarks:
 * - http://jsperf.com/object-create2
 * - http://jsperf.com/proto-map-lookup/2
 * - http://jsperf.com/for-in-vs-object-keys2
 *
 * @returns {Object}
 */
function createMap() {
  return Object.create(null);
}

var NODE_TYPE_ELEMENT = 1;
var NODE_TYPE_ATTRIBUTE = 2;
var NODE_TYPE_TEXT = 3;
var NODE_TYPE_COMMENT = 8;
var NODE_TYPE_DOCUMENT = 9;
var NODE_TYPE_DOCUMENT_FRAGMENT = 11;

/**
 * @ngdoc type
 * @name angular.Module
 * @module ng
 * @description
 *
 * Interface for configuring angular {@link angular.module modules}.
 */

function setupModuleLoader(window) {

  var $injectorMinErr = minErr('$injector');
  var ngMinErr = minErr('ng');

  function ensure(obj, name, factory) {
    return obj[name] || (obj[name] = factory());
  }

  var angular = ensure(window, 'angular', Object);

  // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  angular.$$minErr = angular.$$minErr || minErr;

  return ensure(angular, 'module', function() {
    /** @type {Object.<string, angular.Module>} */
    var modules = {};

    /**
     * @ngdoc function
     * @name angular.module
     * @module ng
     * @description
     *
     * The `angular.module` is a global place for creating, registering and retrieving Angular
     * modules.
     * All modules (angular core or 3rd party) that should be available to an application must be
     * registered using this mechanism.
     *
     * When passed two or more arguments, a new module is created.  If passed only one argument, an
     * existing module (the name passed as the first argument to `module`) is retrieved.
     *
     *
     * # Module
     *
     * A module is a collection of services, directives, controllers, filters, and configuration information.
     * `angular.module` is used to configure the {@link auto.$injector $injector}.
     *
     * ```js
     * // Create a new module
     * var myModule = angular.module('myModule', []);
     *
     * // register a new service
     * myModule.value('appName', 'MyCoolApp');
     *
     * // configure existing services inside initialization blocks.
     * myModule.config(['$locationProvider', function($locationProvider) {
     *   // Configure existing providers
     *   $locationProvider.hashPrefix('!');
     * }]);
     * ```
     *
     * Then you can create an injector and load your modules like this:
     *
     * ```js
     * var injector = angular.injector(['ng', 'myModule'])
     * ```
     *
     * However it's more likely that you'll just use
     * {@link ng.directive:ngApp ngApp} or
     * {@link angular.bootstrap} to simplify this process for you.
     *
     * @param {!string} name The name of the module to create or retrieve.
     * @param {!Array.<string>=} requires If specified then new module is being created. If
     *        unspecified then the module is being retrieved for further configuration.
     * @param {Function=} configFn Optional configuration function for the module. Same as
     *        {@link angular.Module#config Module#config()}.
     * @returns {module} new module with the {@link angular.Module} api.
     */
    return function module(name, requires, configFn) {
      var assertNotHasOwnProperty = function(name, context) {
        if (name === 'hasOwnProperty') {
          throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
        }
      };

      assertNotHasOwnProperty(name, 'module');
      if (requires && modules.hasOwnProperty(name)) {
        modules[name] = null;
      }
      return ensure(modules, name, function() {
        if (!requires) {
          throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
             "the module name or forgot to load it. If registering a module ensure that you " +
             "specify the dependencies as the second argument.", name);
        }

        /** @type {!Array.<Array.<*>>} */
        var invokeQueue = [];

        /** @type {!Array.<Function>} */
        var configBlocks = [];

        /** @type {!Array.<Function>} */
        var runBlocks = [];

        var config = invokeLater('$injector', 'invoke', 'push', configBlocks);

        /** @type {angular.Module} */
        var moduleInstance = {
          // Private state
          _invokeQueue: invokeQueue,
          _configBlocks: configBlocks,
          _runBlocks: runBlocks,

          /**
           * @ngdoc property
           * @name angular.Module#requires
           * @module ng
           *
           * @description
           * Holds the list of modules which the injector will load before the current module is
           * loaded.
           */
          requires: requires,

          /**
           * @ngdoc property
           * @name angular.Module#name
           * @module ng
           *
           * @description
           * Name of the module.
           */
          name: name,


          /**
           * @ngdoc method
           * @name angular.Module#provider
           * @module ng
           * @param {string} name service name
           * @param {Function} providerType Construction function for creating new instance of the
           *                                service.
           * @description
           * See {@link auto.$provide#provider $provide.provider()}.
           */
          provider: invokeLaterAndSetModuleName('$provide', 'provider'),

          /**
           * @ngdoc method
           * @name angular.Module#factory
           * @module ng
           * @param {string} name service name
           * @param {Function} providerFunction Function for creating new instance of the service.
           * @description
           * See {@link auto.$provide#factory $provide.factory()}.
           */
          factory: invokeLaterAndSetModuleName('$provide', 'factory'),

          /**
           * @ngdoc method
           * @name angular.Module#service
           * @module ng
           * @param {string} name service name
           * @param {Function} constructor A constructor function that will be instantiated.
           * @description
           * See {@link auto.$provide#service $provide.service()}.
           */
          service: invokeLaterAndSetModuleName('$provide', 'service'),

          /**
           * @ngdoc method
           * @name angular.Module#value
           * @module ng
           * @param {string} name service name
           * @param {*} object Service instance object.
           * @description
           * See {@link auto.$provide#value $provide.value()}.
           */
          value: invokeLater('$provide', 'value'),

          /**
           * @ngdoc method
           * @name angular.Module#constant
           * @module ng
           * @param {string} name constant name
           * @param {*} object Constant value.
           * @description
           * Because the constant are fixed, they get applied before other provide methods.
           * See {@link auto.$provide#constant $provide.constant()}.
           */
          constant: invokeLater('$provide', 'constant', 'unshift'),

           /**
           * @ngdoc method
           * @name angular.Module#decorator
           * @module ng
           * @param {string} The name of the service to decorate.
           * @param {Function} This function will be invoked when the service needs to be
           *                                    instantiated and should return the decorated service instance.
           * @description
           * See {@link auto.$provide#decorator $provide.decorator()}.
           */
          decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),

          /**
           * @ngdoc method
           * @name angular.Module#animation
           * @module ng
           * @param {string} name animation name
           * @param {Function} animationFactory Factory function for creating new instance of an
           *                                    animation.
           * @description
           *
           * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
           *
           *
           * Defines an animation hook that can be later used with
           * {@link $animate $animate} service and directives that use this service.
           *
           * ```js
           * module.animation('.animation-name', function($inject1, $inject2) {
           *   return {
           *     eventName : function(element, done) {
           *       //code to run the animation
           *       //once complete, then run done()
           *       return function cancellationFunction(element) {
           *         //code to cancel the animation
           *       }
           *     }
           *   }
           * })
           * ```
           *
           * See {@link ng.$animateProvider#register $animateProvider.register()} and
           * {@link ngAnimate ngAnimate module} for more information.
           */
          animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),

          /**
           * @ngdoc method
           * @name angular.Module#filter
           * @module ng
           * @param {string} name Filter name - this must be a valid angular expression identifier
           * @param {Function} filterFactory Factory function for creating new instance of filter.
           * @description
           * See {@link ng.$filterProvider#register $filterProvider.register()}.
           *
           * <div class="alert alert-warning">
           * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
           * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
           * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
           * (`myapp_subsection_filterx`).
           * </div>
           */
          filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),

          /**
           * @ngdoc method
           * @name angular.Module#controller
           * @module ng
           * @param {string|Object} name Controller name, or an object map of controllers where the
           *    keys are the names and the values are the constructors.
           * @param {Function} constructor Controller constructor function.
           * @description
           * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
           */
          controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),

          /**
           * @ngdoc method
           * @name angular.Module#directive
           * @module ng
           * @param {string|Object} name Directive name, or an object map of directives where the
           *    keys are the names and the values are the factories.
           * @param {Function} directiveFactory Factory function for creating new instance of
           * directives.
           * @description
           * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
           */
          directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),

          /**
           * @ngdoc method
           * @name angular.Module#config
           * @module ng
           * @param {Function} configFn Execute this function on module load. Useful for service
           *    configuration.
           * @description
           * Use this method to register work which needs to be performed on module loading.
           * For more about how to configure services, see
           * {@link providers#provider-recipe Provider Recipe}.
           */
          config: config,

          /**
           * @ngdoc method
           * @name angular.Module#run
           * @module ng
           * @param {Function} initializationFn Execute this function after injector creation.
           *    Useful for application initialization.
           * @description
           * Use this method to register work which should be performed when the injector is done
           * loading all modules.
           */
          run: function(block) {
            runBlocks.push(block);
            return this;
          }
        };

        if (configFn) {
          config(configFn);
        }

        return moduleInstance;

        /**
         * @param {string} provider
         * @param {string} method
         * @param {String=} insertMethod
         * @returns {angular.Module}
         */
        function invokeLater(provider, method, insertMethod, queue) {
          if (!queue) queue = invokeQueue;
          return function() {
            queue[insertMethod || 'push']([provider, method, arguments]);
            return moduleInstance;
          };
        }

        /**
         * @param {string} provider
         * @param {string} method
         * @returns {angular.Module}
         */
        function invokeLaterAndSetModuleName(provider, method) {
          return function(recipeName, factoryFunction) {
            if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
            invokeQueue.push([provider, method, arguments]);
            return moduleInstance;
          };
        }
      });
    };
  });

}

/* global: toDebugString: true */

function serializeObject(obj) {
  var seen = [];

  return JSON.stringify(obj, function(key, val) {
    val = toJsonReplacer(key, val);
    if (isObject(val)) {

      if (seen.indexOf(val) >= 0) return '<<already seen>>';

      seen.push(val);
    }
    return val;
  });
}

function toDebugString(obj) {
  if (typeof obj === 'function') {
    return obj.toString().replace(/ \{[\s\S]*$/, '');
  } else if (typeof obj === 'undefined') {
    return 'undefined';
  } else if (typeof obj !== 'string') {
    return serializeObject(obj);
  }
  return obj;
}

/* global angularModule: true,
  version: true,

  $LocaleProvider,
  $CompileProvider,

  htmlAnchorDirective,
  inputDirective,
  inputDirective,
  formDirective,
  scriptDirective,
  selectDirective,
  styleDirective,
  optionDirective,
  ngBindDirective,
  ngBindHtmlDirective,
  ngBindTemplateDirective,
  ngClassDirective,
  ngClassEvenDirective,
  ngClassOddDirective,
  ngCspDirective,
  ngCloakDirective,
  ngControllerDirective,
  ngFormDirective,
  ngHideDirective,
  ngIfDirective,
  ngIncludeDirective,
  ngIncludeFillContentDirective,
  ngInitDirective,
  ngNonBindableDirective,
  ngPluralizeDirective,
  ngRepeatDirective,
  ngShowDirective,
  ngStyleDirective,
  ngSwitchDirective,
  ngSwitchWhenDirective,
  ngSwitchDefaultDirective,
  ngOptionsDirective,
  ngTranscludeDirective,
  ngModelDirective,
  ngListDirective,
  ngChangeDirective,
  patternDirective,
  patternDirective,
  requiredDirective,
  requiredDirective,
  minlengthDirective,
  minlengthDirective,
  maxlengthDirective,
  maxlengthDirective,
  ngValueDirective,
  ngModelOptionsDirective,
  ngAttributeAliasDirectives,
  ngEventDirectives,

  $AnchorScrollProvider,
  $AnimateProvider,
  $$CoreAnimateQueueProvider,
  $$CoreAnimateRunnerProvider,
  $BrowserProvider,
  $CacheFactoryProvider,
  $ControllerProvider,
  $DocumentProvider,
  $ExceptionHandlerProvider,
  $FilterProvider,
  $InterpolateProvider,
  $IntervalProvider,
  $$HashMapProvider,
  $HttpProvider,
  $HttpParamSerializerProvider,
  $HttpParamSerializerJQLikeProvider,
  $HttpBackendProvider,
  $LocationProvider,
  $LogProvider,
  $ParseProvider,
  $RootScopeProvider,
  $QProvider,
  $$QProvider,
  $$SanitizeUriProvider,
  $SceProvider,
  $SceDelegateProvider,
  $SnifferProvider,
  $TemplateCacheProvider,
  $TemplateRequestProvider,
  $$TestabilityProvider,
  $TimeoutProvider,
  $$RAFProvider,
  $WindowProvider,
  $$jqLiteProvider,
  $$CookieReaderProvider
*/


/**
 * @ngdoc object
 * @name angular.version
 * @module ng
 * @description
 * An object that contains information about the current AngularJS version. This object has the
 * following properties:
 *
 * - `full` – `{string}` – Full version string, such as "0.9.18".
 * - `major` – `{number}` – Major version number, such as "0".
 * - `minor` – `{number}` – Minor version number, such as "9".
 * - `dot` – `{number}` – Dot version number, such as "18".
 * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
 */
var version = {
  full: '1.4.3',    // all of these placeholder strings will be replaced by grunt's
  major: 1,    // package task
  minor: 4,
  dot: 3,
  codeName: 'foam-acceleration'
};


function publishExternalAPI(angular) {
  extend(angular, {
    'bootstrap': bootstrap,
    'copy': copy,
    'extend': extend,
    'merge': merge,
    'equals': equals,
    'element': jqLite,
    'forEach': forEach,
    'injector': createInjector,
    'noop': noop,
    'bind': bind,
    'toJson': toJson,
    'fromJson': fromJson,
    'identity': identity,
    'isUndefined': isUndefined,
    'isDefined': isDefined,
    'isString': isString,
    'isFunction': isFunction,
    'isObject': isObject,
    'isNumber': isNumber,
    'isElement': isElement,
    'isArray': isArray,
    'version': version,
    'isDate': isDate,
    'lowercase': lowercase,
    'uppercase': uppercase,
    'callbacks': {counter: 0},
    'getTestability': getTestability,
    '$$minErr': minErr,
    '$$csp': csp,
    'reloadWithDebugInfo': reloadWithDebugInfo
  });

  angularModule = setupModuleLoader(window);
  try {
    angularModule('ngLocale');
  } catch (e) {
    angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  }

  angularModule('ng', ['ngLocale'], ['$provide',
    function ngModule($provide) {
      // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
      $provide.provider({
        $$sanitizeUri: $$SanitizeUriProvider
      });
      $provide.provider('$compile', $CompileProvider).
        directive({
            a: htmlAnchorDirective,
            input: inputDirective,
            textarea: inputDirective,
            form: formDirective,
            script: scriptDirective,
            select: selectDirective,
            style: styleDirective,
            option: optionDirective,
            ngBind: ngBindDirective,
            ngBindHtml: ngBindHtmlDirective,
            ngBindTemplate: ngBindTemplateDirective,
            ngClass: ngClassDirective,
            ngClassEven: ngClassEvenDirective,
            ngClassOdd: ngClassOddDirective,
            ngCloak: ngCloakDirective,
            ngController: ngControllerDirective,
            ngForm: ngFormDirective,
            ngHide: ngHideDirective,
            ngIf: ngIfDirective,
            ngInclude: ngIncludeDirective,
            ngInit: ngInitDirective,
            ngNonBindable: ngNonBindableDirective,
            ngPluralize: ngPluralizeDirective,
            ngRepeat: ngRepeatDirective,
            ngShow: ngShowDirective,
            ngStyle: ngStyleDirective,
            ngSwitch: ngSwitchDirective,
            ngSwitchWhen: ngSwitchWhenDirective,
            ngSwitchDefault: ngSwitchDefaultDirective,
            ngOptions: ngOptionsDirective,
            ngTransclude: ngTranscludeDirective,
            ngModel: ngModelDirective,
            ngList: ngListDirective,
            ngChange: ngChangeDirective,
            pattern: patternDirective,
            ngPattern: patternDirective,
            required: requiredDirective,
            ngRequired: requiredDirective,
            minlength: minlengthDirective,
            ngMinlength: minlengthDirective,
            maxlength: maxlengthDirective,
            ngMaxlength: maxlengthDirective,
            ngValue: ngValueDirective,
            ngModelOptions: ngModelOptionsDirective
        }).
        directive({
          ngInclude: ngIncludeFillContentDirective
        }).
        directive(ngAttributeAliasDirectives).
        directive(ngEventDirectives);
      $provide.provider({
        $anchorScroll: $AnchorScrollProvider,
        $animate: $AnimateProvider,
        $$animateQueue: $$CoreAnimateQueueProvider,
        $$AnimateRunner: $$CoreAnimateRunnerProvider,
        $browser: $BrowserProvider,
        $cacheFactory: $CacheFactoryProvider,
        $controller: $ControllerProvider,
        $document: $DocumentProvider,
        $exceptionHandler: $ExceptionHandlerProvider,
        $filter: $FilterProvider,
        $interpolate: $InterpolateProvider,
        $interval: $IntervalProvider,
        $http: $HttpProvider,
        $httpParamSerializer: $HttpParamSerializerProvider,
        $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
        $httpBackend: $HttpBackendProvider,
        $location: $LocationProvider,
        $log: $LogProvider,
        $parse: $ParseProvider,
        $rootScope: $RootScopeProvider,
        $q: $QProvider,
        $$q: $$QProvider,
        $sce: $SceProvider,
        $sceDelegate: $SceDelegateProvider,
        $sniffer: $SnifferProvider,
        $templateCache: $TemplateCacheProvider,
        $templateRequest: $TemplateRequestProvider,
        $$testability: $$TestabilityProvider,
        $timeout: $TimeoutProvider,
        $window: $WindowProvider,
        $$rAF: $$RAFProvider,
        $$jqLite: $$jqLiteProvider,
        $$HashMap: $$HashMapProvider,
        $$cookieReader: $$CookieReaderProvider
      });
    }
  ]);
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *     Any commits to this file should be reviewed with security in mind.  *
 *   Changes to this file can potentially create security vulnerabilities. *
 *          An approval from 2 Core members with history of modifying      *
 *                         this file is required.                          *
 *                                                                         *
 *  Does the change somehow allow for arbitrary javascript to be executed? *
 *    Or allows for someone to change the prototype of built-in objects?   *
 *     Or gives undesired access to variables likes document or window?    *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/* global JQLitePrototype: true,
  addEventListenerFn: true,
  removeEventListenerFn: true,
  BOOLEAN_ATTR: true,
  ALIASED_ATTR: true,
*/

//////////////////////////////////
//JQLite
//////////////////////////////////

/**
 * @ngdoc function
 * @name angular.element
 * @module ng
 * @kind function
 *
 * @description
 * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
 *
 * If jQuery is available, `angular.element` is an alias for the
 * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
 * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
 *
 * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
 * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
 * commonly needed functionality with the goal of having a very small footprint.</div>
 *
 * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
 *
 * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
 * jqLite; they are never raw DOM references.</div>
 *
 * ## Angular's jqLite
 * jqLite provides only the following jQuery methods:
 *
 * - [`addClass()`](http://api.jquery.com/addClass/)
 * - [`after()`](http://api.jquery.com/after/)
 * - [`append()`](http://api.jquery.com/append/)
 * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
 * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
 * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
 * - [`clone()`](http://api.jquery.com/clone/)
 * - [`contents()`](http://api.jquery.com/contents/)
 * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
 * - [`data()`](http://api.jquery.com/data/)
 * - [`detach()`](http://api.jquery.com/detach/)
 * - [`empty()`](http://api.jquery.com/empty/)
 * - [`eq()`](http://api.jquery.com/eq/)
 * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
 * - [`hasClass()`](http://api.jquery.com/hasClass/)
 * - [`html()`](http://api.jquery.com/html/)
 * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
 * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
 * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
 * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
 * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
 * - [`prepend()`](http://api.jquery.com/prepend/)
 * - [`prop()`](http://api.jquery.com/prop/)
 * - [`ready()`](http://api.jquery.com/ready/)
 * - [`remove()`](http://api.jquery.com/remove/)
 * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
 * - [`removeClass()`](http://api.jquery.com/removeClass/)
 * - [`removeData()`](http://api.jquery.com/removeData/)
 * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
 * - [`text()`](http://api.jquery.com/text/)
 * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
 * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
 * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
 * - [`val()`](http://api.jquery.com/val/)
 * - [`wrap()`](http://api.jquery.com/wrap/)
 *
 * ## jQuery/jqLite Extras
 * Angular also provides the following additional methods and events to both jQuery and jqLite:
 *
 * ### Events
 * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
 *    on all DOM nodes being removed.  This can be used to clean up any 3rd party bindings to the DOM
 *    element before it is removed.
 *
 * ### Methods
 * - `controller(name)` - retrieves the controller of the current element or its parent. By default
 *   retrieves controller associated with the `ngController` directive. If `name` is provided as
 *   camelCase directive name, then the controller for this directive will be retrieved (e.g.
 *   `'ngModel'`).
 * - `injector()` - retrieves the injector of the current element or its parent.
 * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
 *   element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
 *   be enabled.
 * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
 *   current element. This getter should be used only on elements that contain a directive which starts a new isolate
 *   scope. Calling `scope()` on this element always returns the original non-isolate scope.
 *   Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
 * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
 *   parent element is reached.
 *
 * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
 * @returns {Object} jQuery object.
 */

JQLite.expando = 'ng339';

var jqCache = JQLite.cache = {},
    jqId = 1,
    addEventListenerFn = function(element, type, fn) {
      element.addEventListener(type, fn, false);
    },
    removeEventListenerFn = function(element, type, fn) {
      element.removeEventListener(type, fn, false);
    };

/*
 * !!! This is an undocumented "private" function !!!
 */
JQLite._data = function(node) {
  //jQuery always returns an object on cache miss
  return this.cache[node[this.expando]] || {};
};

function jqNextId() { return ++jqId; }


var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
var jqLiteMinErr = minErr('jqLite');

/**
 * Converts snake_case to camelCase.
 * Also there is special case for Moz prefix starting with upper case letter.
 * @param name Name to normalize
 */
function camelCase(name) {
  return name.
    replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
      return offset ? letter.toUpperCase() : letter;
    }).
    replace(MOZ_HACK_REGEXP, 'Moz$1');
}

var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
var HTML_REGEXP = /<|&#?\w+;/;
var TAG_NAME_REGEXP = /<([\w:]+)/;
var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;

var wrapMap = {
  '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, "", ""]
};

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


function jqLiteIsTextNode(html) {
  return !HTML_REGEXP.test(html);
}

function jqLiteAcceptsData(node) {
  // The window object can accept data but has no nodeType
  // Otherwise we are only interested in elements (1) and documents (9)
  var nodeType = node.nodeType;
  return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
}

function jqLiteHasData(node) {
  for (var key in jqCache[node.ng339]) {
    return true;
  }
  return false;
}

function jqLiteBuildFragment(html, context) {
  var tmp, tag, wrap,
      fragment = context.createDocumentFragment(),
      nodes = [], i;

  if (jqLiteIsTextNode(html)) {
    // Convert non-html into a text node
    nodes.push(context.createTextNode(html));
  } else {
    // Convert html into DOM nodes
    tmp = tmp || fragment.appendChild(context.createElement("div"));
    tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
    wrap = wrapMap[tag] || wrapMap._default;
    tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];

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

    nodes = concat(nodes, tmp.childNodes);

    tmp = fragment.firstChild;
    tmp.textContent = "";
  }

  // Remove wrapper from fragment
  fragment.textContent = "";
  fragment.innerHTML = ""; // Clear inner HTML
  forEach(nodes, function(node) {
    fragment.appendChild(node);
  });

  return fragment;
}

function jqLiteParseHTML(html, context) {
  context = context || document;
  var parsed;

  if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
    return [context.createElement(parsed[1])];
  }

  if ((parsed = jqLiteBuildFragment(html, context))) {
    return parsed.childNodes;
  }

  return [];
}

/////////////////////////////////////////////
function JQLite(element) {
  if (element instanceof JQLite) {
    return element;
  }

  var argIsString;

  if (isString(element)) {
    element = trim(element);
    argIsString = true;
  }
  if (!(this instanceof JQLite)) {
    if (argIsString && element.charAt(0) != '<') {
      throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
    }
    return new JQLite(element);
  }

  if (argIsString) {
    jqLiteAddNodes(this, jqLiteParseHTML(element));
  } else {
    jqLiteAddNodes(this, element);
  }
}

function jqLiteClone(element) {
  return element.cloneNode(true);
}

function jqLiteDealoc(element, onlyDescendants) {
  if (!onlyDescendants) jqLiteRemoveData(element);

  if (element.querySelectorAll) {
    var descendants = element.querySelectorAll('*');
    for (var i = 0, l = descendants.length; i < l; i++) {
      jqLiteRemoveData(descendants[i]);
    }
  }
}

function jqLiteOff(element, type, fn, unsupported) {
  if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');

  var expandoStore = jqLiteExpandoStore(element);
  var events = expandoStore && expandoStore.events;
  var handle = expandoStore && expandoStore.handle;

  if (!handle) return; //no listeners registered

  if (!type) {
    for (type in events) {
      if (type !== '$destroy') {
        removeEventListenerFn(element, type, handle);
      }
      delete events[type];
    }
  } else {
    forEach(type.split(' '), function(type) {
      if (isDefined(fn)) {
        var listenerFns = events[type];
        arrayRemove(listenerFns || [], fn);
        if (listenerFns && listenerFns.length > 0) {
          return;
        }
      }

      removeEventListenerFn(element, type, handle);
      delete events[type];
    });
  }
}

function jqLiteRemoveData(element, name) {
  var expandoId = element.ng339;
  var expandoStore = expandoId && jqCache[expandoId];

  if (expandoStore) {
    if (name) {
      delete expandoStore.data[name];
      return;
    }

    if (expandoStore.handle) {
      if (expandoStore.events.$destroy) {
        expandoStore.handle({}, '$destroy');
      }
      jqLiteOff(element);
    }
    delete jqCache[expandoId];
    element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  }
}


function jqLiteExpandoStore(element, createIfNecessary) {
  var expandoId = element.ng339,
      expandoStore = expandoId && jqCache[expandoId];

  if (createIfNecessary && !expandoStore) {
    element.ng339 = expandoId = jqNextId();
    expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  }

  return expandoStore;
}


function jqLiteData(element, key, value) {
  if (jqLiteAcceptsData(element)) {

    var isSimpleSetter = isDefined(value);
    var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
    var massGetter = !key;
    var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
    var data = expandoStore && expandoStore.data;

    if (isSimpleSetter) { // data('key', value)
      data[key] = value;
    } else {
      if (massGetter) {  // data()
        return data;
      } else {
        if (isSimpleGetter) { // data('key')
          // don't force creation of expandoStore if it doesn't exist yet
          return data && data[key];
        } else { // mass-setter: data({key1: val1, key2: val2})
          extend(data, key);
        }
      }
    }
  }
}

function jqLiteHasClass(element, selector) {
  if (!element.getAttribute) return false;
  return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
      indexOf(" " + selector + " ") > -1);
}

function jqLiteRemoveClass(element, cssClasses) {
  if (cssClasses && element.setAttribute) {
    forEach(cssClasses.split(' '), function(cssClass) {
      element.setAttribute('class', trim(
          (" " + (element.getAttribute('class') || '') + " ")
          .replace(/[\n\t]/g, " ")
          .replace(" " + trim(cssClass) + " ", " "))
      );
    });
  }
}

function jqLiteAddClass(element, cssClasses) {
  if (cssClasses && element.setAttribute) {
    var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
                            .replace(/[\n\t]/g, " ");

    forEach(cssClasses.split(' '), function(cssClass) {
      cssClass = trim(cssClass);
      if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
        existingClasses += cssClass + ' ';
      }
    });

    element.setAttribute('class', trim(existingClasses));
  }
}


function jqLiteAddNodes(root, elements) {
  // THIS CODE IS VERY HOT. Don't make changes without benchmarking.

  if (elements) {

    // if a Node (the most common case)
    if (elements.nodeType) {
      root[root.length++] = elements;
    } else {
      var length = elements.length;

      // if an Array or NodeList and not a Window
      if (typeof length === 'number' && elements.window !== elements) {
        if (length) {
          for (var i = 0; i < length; i++) {
            root[root.length++] = elements[i];
          }
        }
      } else {
        root[root.length++] = elements;
      }
    }
  }
}


function jqLiteController(element, name) {
  return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
}

function jqLiteInheritedData(element, name, value) {
  // if element is the document object work with the html element instead
  // this makes $(document).scope() possible
  if (element.nodeType == NODE_TYPE_DOCUMENT) {
    element = element.documentElement;
  }
  var names = isArray(name) ? name : [name];

  while (element) {
    for (var i = 0, ii = names.length; i < ii; i++) {
      if ((value = jqLite.data(element, names[i])) !== undefined) return value;
    }

    // If dealing with a document fragment node with a host element, and no parent, use the host
    // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
    // to lookup parent controllers.
    element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  }
}

function jqLiteEmpty(element) {
  jqLiteDealoc(element, true);
  while (element.firstChild) {
    element.removeChild(element.firstChild);
  }
}

function jqLiteRemove(element, keepData) {
  if (!keepData) jqLiteDealoc(element);
  var parent = element.parentNode;
  if (parent) parent.removeChild(element);
}


function jqLiteDocumentLoaded(action, win) {
  win = win || window;
  if (win.document.readyState === 'complete') {
    // Force the action to be run async for consistent behaviour
    // from the action's point of view
    // i.e. it will definitely not be in a $apply
    win.setTimeout(action);
  } else {
    // No need to unbind this handler as load is only ever called once
    jqLite(win).on('load', action);
  }
}

//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
  ready: function(fn) {
    var fired = false;

    function trigger() {
      if (fired) return;
      fired = true;
      fn();
    }

    // check if document is already loaded
    if (document.readyState === 'complete') {
      setTimeout(trigger);
    } else {
      this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
      // we can not use jqLite since we are not done loading and jQuery could be loaded later.
      // jshint -W064
      JQLite(window).on('load', trigger); // fallback to window.onload for others
      // jshint +W064
    }
  },
  toString: function() {
    var value = [];
    forEach(this, function(e) { value.push('' + e);});
    return '[' + value.join(', ') + ']';
  },

  eq: function(index) {
      return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  },

  length: 0,
  push: push,
  sort: [].sort,
  splice: [].splice
};

//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  BOOLEAN_ELEMENTS[value] = true;
});
var ALIASED_ATTR = {
  'ngMinlength': 'minlength',
  'ngMaxlength': 'maxlength',
  'ngMin': 'min',
  'ngMax': 'max',
  'ngPattern': 'pattern'
};

function getBooleanAttrName(element, name) {
  // check dom last since we will most likely fail on name
  var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];

  // booleanAttr is here twice to minimize DOM access
  return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
}

function getAliasedAttrName(element, name) {
  var nodeName = element.nodeName;
  return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
}

forEach({
  data: jqLiteData,
  removeData: jqLiteRemoveData,
  hasData: jqLiteHasData
}, function(fn, name) {
  JQLite[name] = fn;
});

forEach({
  data: jqLiteData,
  inheritedData: jqLiteInheritedData,

  scope: function(element) {
    // Can't use jqLiteData here directly so we stay compatible with jQuery!
    return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  },

  isolateScope: function(element) {
    // Can't use jqLiteData here directly so we stay compatible with jQuery!
    return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  },

  controller: jqLiteController,

  injector: function(element) {
    return jqLiteInheritedData(element, '$injector');
  },

  removeAttr: function(element, name) {
    element.removeAttribute(name);
  },

  hasClass: jqLiteHasClass,

  css: function(element, name, value) {
    name = camelCase(name);

    if (isDefined(value)) {
      element.style[name] = value;
    } else {
      return element.style[name];
    }
  },

  attr: function(element, name, value) {
    var nodeType = element.nodeType;
    if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
      return;
    }
    var lowercasedName = lowercase(name);
    if (BOOLEAN_ATTR[lowercasedName]) {
      if (isDefined(value)) {
        if (!!value) {
          element[name] = true;
          element.setAttribute(name, lowercasedName);
        } else {
          element[name] = false;
          element.removeAttribute(lowercasedName);
        }
      } else {
        return (element[name] ||
                 (element.attributes.getNamedItem(name) || noop).specified)
               ? lowercasedName
               : undefined;
      }
    } else if (isDefined(value)) {
      element.setAttribute(name, value);
    } else if (element.getAttribute) {
      // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
      // some elements (e.g. Document) don't have get attribute, so return undefined
      var ret = element.getAttribute(name, 2);
      // normalize non-existing attributes to undefined (as jQuery)
      return ret === null ? undefined : ret;
    }
  },

  prop: function(element, name, value) {
    if (isDefined(value)) {
      element[name] = value;
    } else {
      return element[name];
    }
  },

  text: (function() {
    getText.$dv = '';
    return getText;

    function getText(element, value) {
      if (isUndefined(value)) {
        var nodeType = element.nodeType;
        return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
      }
      element.textContent = value;
    }
  })(),

  val: function(element, value) {
    if (isUndefined(value)) {
      if (element.multiple && nodeName_(element) === 'select') {
        var result = [];
        forEach(element.options, function(option) {
          if (option.selected) {
            result.push(option.value || option.text);
          }
        });
        return result.length === 0 ? null : result;
      }
      return element.value;
    }
    element.value = value;
  },

  html: function(element, value) {
    if (isUndefined(value)) {
      return element.innerHTML;
    }
    jqLiteDealoc(element, true);
    element.innerHTML = value;
  },

  empty: jqLiteEmpty
}, function(fn, name) {
  /**
   * Properties: writes return selection, reads return first value
   */
  JQLite.prototype[name] = function(arg1, arg2) {
    var i, key;
    var nodeCount = this.length;

    // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
    // in a way that survives minification.
    // jqLiteEmpty takes no arguments but is a setter.
    if (fn !== jqLiteEmpty &&
        (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
      if (isObject(arg1)) {

        // we are a write, but the object properties are the key/values
        for (i = 0; i < nodeCount; i++) {
          if (fn === jqLiteData) {
            // data() takes the whole object in jQuery
            fn(this[i], arg1);
          } else {
            for (key in arg1) {
              fn(this[i], key, arg1[key]);
            }
          }
        }
        // return self for chaining
        return this;
      } else {
        // we are a read, so read the first child.
        // TODO: do we still need this?
        var value = fn.$dv;
        // Only if we have $dv do we iterate over all, otherwise it is just the first element.
        var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
        for (var j = 0; j < jj; j++) {
          var nodeValue = fn(this[j], arg1, arg2);
          value = value ? value + nodeValue : nodeValue;
        }
        return value;
      }
    } else {
      // we are a write, so apply to all children
      for (i = 0; i < nodeCount; i++) {
        fn(this[i], arg1, arg2);
      }
      // return self for chaining
      return this;
    }
  };
});

function createEventHandler(element, events) {
  var eventHandler = function(event, type) {
    // jQuery specific api
    event.isDefaultPrevented = function() {
      return event.defaultPrevented;
    };

    var eventFns = events[type || event.type];
    var eventFnsLength = eventFns ? eventFns.length : 0;

    if (!eventFnsLength) return;

    if (isUndefined(event.immediatePropagationStopped)) {
      var originalStopImmediatePropagation = event.stopImmediatePropagation;
      event.stopImmediatePropagation = function() {
        event.immediatePropagationStopped = true;

        if (event.stopPropagation) {
          event.stopPropagation();
        }

        if (originalStopImmediatePropagation) {
          originalStopImmediatePropagation.call(event);
        }
      };
    }

    event.isImmediatePropagationStopped = function() {
      return event.immediatePropagationStopped === true;
    };

    // Copy event handlers in case event handlers array is modified during execution.
    if ((eventFnsLength > 1)) {
      eventFns = shallowCopy(eventFns);
    }

    for (var i = 0; i < eventFnsLength; i++) {
      if (!event.isImmediatePropagationStopped()) {
        eventFns[i].call(element, event);
      }
    }
  };

  // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  //       events on `element`
  eventHandler.elem = element;
  return eventHandler;
}

//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
  removeData: jqLiteRemoveData,

  on: function jqLiteOn(element, type, fn, unsupported) {
    if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');

    // Do not add event handlers to non-elements because they will not be cleaned up.
    if (!jqLiteAcceptsData(element)) {
      return;
    }

    var expandoStore = jqLiteExpandoStore(element, true);
    var events = expandoStore.events;
    var handle = expandoStore.handle;

    if (!handle) {
      handle = expandoStore.handle = createEventHandler(element, events);
    }

    // http://jsperf.com/string-indexof-vs-split
    var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
    var i = types.length;

    while (i--) {
      type = types[i];
      var eventFns = events[type];

      if (!eventFns) {
        events[type] = [];

        if (type === 'mouseenter' || type === 'mouseleave') {
          // Refer to jQuery's implementation of mouseenter & mouseleave
          // Read about mouseenter and mouseleave:
          // http://www.quirksmode.org/js/events_mouse.html#link8

          jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
            var target = this, related = event.relatedTarget;
            // For mousenter/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 && !target.contains(related))) {
              handle(event, type);
            }
          });

        } else {
          if (type !== '$destroy') {
            addEventListenerFn(element, type, handle);
          }
        }
        eventFns = events[type];
      }
      eventFns.push(fn);
    }
  },

  off: jqLiteOff,

  one: function(element, type, fn) {
    element = jqLite(element);

    //add the listener twice so that when it is called
    //you can remove the original function and still be
    //able to call element.off(ev, fn) normally
    element.on(type, function onFn() {
      element.off(type, fn);
      element.off(type, onFn);
    });
    element.on(type, fn);
  },

  replaceWith: function(element, replaceNode) {
    var index, parent = element.parentNode;
    jqLiteDealoc(element);
    forEach(new JQLite(replaceNode), function(node) {
      if (index) {
        parent.insertBefore(node, index.nextSibling);
      } else {
        parent.replaceChild(node, element);
      }
      index = node;
    });
  },

  children: function(element) {
    var children = [];
    forEach(element.childNodes, function(element) {
      if (element.nodeType === NODE_TYPE_ELEMENT) {
        children.push(element);
      }
    });
    return children;
  },

  contents: function(element) {
    return element.contentDocument || element.childNodes || [];
  },

  append: function(element, node) {
    var nodeType = element.nodeType;
    if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;

    node = new JQLite(node);

    for (var i = 0, ii = node.length; i < ii; i++) {
      var child = node[i];
      element.appendChild(child);
    }
  },

  prepend: function(element, node) {
    if (element.nodeType === NODE_TYPE_ELEMENT) {
      var index = element.firstChild;
      forEach(new JQLite(node), function(child) {
        element.insertBefore(child, index);
      });
    }
  },

  wrap: function(element, wrapNode) {
    wrapNode = jqLite(wrapNode).eq(0).clone()[0];
    var parent = element.parentNode;
    if (parent) {
      parent.replaceChild(wrapNode, element);
    }
    wrapNode.appendChild(element);
  },

  remove: jqLiteRemove,

  detach: function(element) {
    jqLiteRemove(element, true);
  },

  after: function(element, newElement) {
    var index = element, parent = element.parentNode;
    newElement = new JQLite(newElement);

    for (var i = 0, ii = newElement.length; i < ii; i++) {
      var node = newElement[i];
      parent.insertBefore(node, index.nextSibling);
      index = node;
    }
  },

  addClass: jqLiteAddClass,
  removeClass: jqLiteRemoveClass,

  toggleClass: function(element, selector, condition) {
    if (selector) {
      forEach(selector.split(' '), function(className) {
        var classCondition = condition;
        if (isUndefined(classCondition)) {
          classCondition = !jqLiteHasClass(element, className);
        }
        (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
      });
    }
  },

  parent: function(element) {
    var parent = element.parentNode;
    return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  },

  next: function(element) {
    return element.nextElementSibling;
  },

  find: function(element, selector) {
    if (element.getElementsByTagName) {
      return element.getElementsByTagName(selector);
    } else {
      return [];
    }
  },

  clone: jqLiteClone,

  triggerHandler: function(element, event, extraParameters) {

    var dummyEvent, eventFnsCopy, handlerArgs;
    var eventName = event.type || event;
    var expandoStore = jqLiteExpandoStore(element);
    var events = expandoStore && expandoStore.events;
    var eventFns = events && events[eventName];

    if (eventFns) {
      // Create a dummy event to pass to the handlers
      dummyEvent = {
        preventDefault: function() { this.defaultPrevented = true; },
        isDefaultPrevented: function() { return this.defaultPrevented === true; },
        stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
        isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
        stopPropagation: noop,
        type: eventName,
        target: element
      };

      // If a custom event was provided then extend our dummy event with it
      if (event.type) {
        dummyEvent = extend(dummyEvent, event);
      }

      // Copy event handlers in case event handlers array is modified during execution.
      eventFnsCopy = shallowCopy(eventFns);
      handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];

      forEach(eventFnsCopy, function(fn) {
        if (!dummyEvent.isImmediatePropagationStopped()) {
          fn.apply(element, handlerArgs);
        }
      });
    }
  }
}, function(fn, name) {
  /**
   * chaining functions
   */
  JQLite.prototype[name] = function(arg1, arg2, arg3) {
    var value;

    for (var i = 0, ii = this.length; i < ii; i++) {
      if (isUndefined(value)) {
        value = fn(this[i], arg1, arg2, arg3);
        if (isDefined(value)) {
          // any function which returns a value needs to be wrapped
          value = jqLite(value);
        }
      } else {
        jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
      }
    }
    return isDefined(value) ? value : this;
  };

  // bind legacy bind/unbind to on/off
  JQLite.prototype.bind = JQLite.prototype.on;
  JQLite.prototype.unbind = JQLite.prototype.off;
});


// Provider for private $$jqLite service
function $$jqLiteProvider() {
  this.$get = function $$jqLite() {
    return extend(JQLite, {
      hasClass: function(node, classes) {
        if (node.attr) node = node[0];
        return jqLiteHasClass(node, classes);
      },
      addClass: function(node, classes) {
        if (node.attr) node = node[0];
        return jqLiteAddClass(node, classes);
      },
      removeClass: function(node, classes) {
        if (node.attr) node = node[0];
        return jqLiteRemoveClass(node, classes);
      }
    });
  };
}

/**
 * Computes a hash of an 'obj'.
 * Hash of a:
 *  string is string
 *  number is number as string
 *  object is either result of calling $$hashKey function on the object or uniquely generated id,
 *         that is also assigned to the $$hashKey property of the object.
 *
 * @param obj
 * @returns {string} hash string such that the same input will have the same hash string.
 *         The resulting string key is in 'type:hashKey' format.
 */
function hashKey(obj, nextUidFn) {
  var key = obj && obj.$$hashKey;

  if (key) {
    if (typeof key === 'function') {
      key = obj.$$hashKey();
    }
    return key;
  }

  var objType = typeof obj;
  if (objType == 'function' || (objType == 'object' && obj !== null)) {
    key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  } else {
    key = objType + ':' + obj;
  }

  return key;
}

/**
 * HashMap which can use objects as keys
 */
function HashMap(array, isolatedUid) {
  if (isolatedUid) {
    var uid = 0;
    this.nextUid = function() {
      return ++uid;
    };
  }
  forEach(array, this.put, this);
}
HashMap.prototype = {
  /**
   * Store key value pair
   * @param key key to store can be any type
   * @param value value to store can be any type
   */
  put: function(key, value) {
    this[hashKey(key, this.nextUid)] = value;
  },

  /**
   * @param key
   * @returns {Object} the value for the key
   */
  get: function(key) {
    return this[hashKey(key, this.nextUid)];
  },

  /**
   * Remove the key/value pair
   * @param key
   */
  remove: function(key) {
    var value = this[key = hashKey(key, this.nextUid)];
    delete this[key];
    return value;
  }
};

var $$HashMapProvider = [function() {
  this.$get = [function() {
    return HashMap;
  }];
}];

/**
 * @ngdoc function
 * @module ng
 * @name angular.injector
 * @kind function
 *
 * @description
 * Creates an injector object that can be used for retrieving services as well as for
 * dependency injection (see {@link guide/di dependency injection}).
 *
 * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
 *     {@link angular.module}. The `ng` module must be explicitly added.
 * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
 *     disallows argument name annotation inference.
 * @returns {injector} Injector object. See {@link auto.$injector $injector}.
 *
 * @example
 * Typical usage
 * ```js
 *   // create an injector
 *   var $injector = angular.injector(['ng']);
 *
 *   // use the injector to kick off your application
 *   // use the type inference to auto inject arguments, or use implicit injection
 *   $injector.invoke(function($rootScope, $compile, $document) {
 *     $compile($document)($rootScope);
 *     $rootScope.$digest();
 *   });
 * ```
 *
 * Sometimes you want to get access to the injector of a currently running Angular app
 * from outside Angular. Perhaps, you want to inject and compile some markup after the
 * application has been bootstrapped. You can do this using the extra `injector()` added
 * to JQuery/jqLite elements. See {@link angular.element}.
 *
 * *This is fairly rare but could be the case if a third party library is injecting the
 * markup.*
 *
 * In the following example a new block of HTML containing a `ng-controller`
 * directive is added to the end of the document body by JQuery. We then compile and link
 * it into the current AngularJS scope.
 *
 * ```js
 * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
 * $(document.body).append($div);
 *
 * angular.element(document).injector().invoke(function($compile) {
 *   var scope = angular.element($div).scope();
 *   $compile($div)(scope);
 * });
 * ```
 */


/**
 * @ngdoc module
 * @name auto
 * @description
 *
 * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
 */

var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var $injectorMinErr = minErr('$injector');

function anonFn(fn) {
  // For anonymous functions, showing at the very least the function signature can help in
  // debugging.
  var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
      args = fnText.match(FN_ARGS);
  if (args) {
    return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  }
  return 'fn';
}

function annotate(fn, strictDi, name) {
  var $inject,
      fnText,
      argDecl,
      last;

  if (typeof fn === 'function') {
    if (!($inject = fn.$inject)) {
      $inject = [];
      if (fn.length) {
        if (strictDi) {
          if (!isString(name) || !name) {
            name = fn.name || anonFn(fn);
          }
          throw $injectorMinErr('strictdi',
            '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
        }
        fnText = fn.toString().replace(STRIP_COMMENTS, '');
        argDecl = fnText.match(FN_ARGS);
        forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
          arg.replace(FN_ARG, function(all, underscore, name) {
            $inject.push(name);
          });
        });
      }
      fn.$inject = $inject;
    }
  } else if (isArray(fn)) {
    last = fn.length - 1;
    assertArgFn(fn[last], 'fn');
    $inject = fn.slice(0, last);
  } else {
    assertArgFn(fn, 'fn', true);
  }
  return $inject;
}

///////////////////////////////////////

/**
 * @ngdoc service
 * @name $injector
 *
 * @description
 *
 * `$injector` is used to retrieve object instances as defined by
 * {@link auto.$provide provider}, instantiate types, invoke methods,
 * and load modules.
 *
 * The following always holds true:
 *
 * ```js
 *   var $injector = angular.injector();
 *   expect($injector.get('$injector')).toBe($injector);
 *   expect($injector.invoke(function($injector) {
 *     return $injector;
 *   })).toBe($injector);
 * ```
 *
 * # Injection Function Annotation
 *
 * JavaScript does not have annotations, and annotations are needed for dependency injection. The
 * following are all valid ways of annotating function with injection arguments and are equivalent.
 *
 * ```js
 *   // inferred (only works if code not minified/obfuscated)
 *   $injector.invoke(function(serviceA){});
 *
 *   // annotated
 *   function explicit(serviceA) {};
 *   explicit.$inject = ['serviceA'];
 *   $injector.invoke(explicit);
 *
 *   // inline
 *   $injector.invoke(['serviceA', function(serviceA){}]);
 * ```
 *
 * ## Inference
 *
 * In JavaScript calling `toString()` on a function returns the function definition. The definition
 * can then be parsed and the function arguments can be extracted. This method of discovering
 * annotations is disallowed when the injector is in strict mode.
 * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
 * argument names.
 *
 * ## `$inject` Annotation
 * By adding an `$inject` property onto a function the injection parameters can be specified.
 *
 * ## Inline
 * As an array of injection names, where the last item in the array is the function to call.
 */

/**
 * @ngdoc method
 * @name $injector#get
 *
 * @description
 * Return an instance of the service.
 *
 * @param {string} name The name of the instance to retrieve.
 * @param {string=} caller An optional string to provide the origin of the function call for error messages.
 * @return {*} The instance.
 */

/**
 * @ngdoc method
 * @name $injector#invoke
 *
 * @description
 * Invoke the method and supply the method arguments from the `$injector`.
 *
 * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
 *   injected according to the {@link guide/di $inject Annotation} rules.
 * @param {Object=} self The `this` for the invoked method.
 * @param {Object=} locals Optional object. If preset then any argument names are read from this
 *                         object first, before the `$injector` is consulted.
 * @returns {*} the value returned by the invoked `fn` function.
 */

/**
 * @ngdoc method
 * @name $injector#has
 *
 * @description
 * Allows the user to query if the particular service exists.
 *
 * @param {string} name Name of the service to query.
 * @returns {boolean} `true` if injector has given service.
 */

/**
 * @ngdoc method
 * @name $injector#instantiate
 * @description
 * Create a new instance of JS type. The method takes a constructor function, invokes the new
 * operator, and supplies all of the arguments to the constructor function as specified by the
 * constructor annotation.
 *
 * @param {Function} Type Annotated constructor function.
 * @param {Object=} locals Optional object. If preset then any argument names are read from this
 * object first, before the `$injector` is consulted.
 * @returns {Object} new instance of `Type`.
 */

/**
 * @ngdoc method
 * @name $injector#annotate
 *
 * @description
 * Returns an array of service names which the function is requesting for injection. This API is
 * used by the injector to determine which services need to be injected into the function when the
 * function is invoked. There are three ways in which the function can be annotated with the needed
 * dependencies.
 *
 * # Argument names
 *
 * The simplest form is to extract the dependencies from the arguments of the function. This is done
 * by converting the function into a string using `toString()` method and extracting the argument
 * names.
 * ```js
 *   // Given
 *   function MyController($scope, $route) {
 *     // ...
 *   }
 *
 *   // Then
 *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
 * ```
 *
 * You can disallow this method by using strict injection mode.
 *
 * This method does not work with code minification / obfuscation. For this reason the following
 * annotation strategies are supported.
 *
 * # The `$inject` property
 *
 * If a function has an `$inject` property and its value is an array of strings, then the strings
 * represent names of services to be injected into the function.
 * ```js
 *   // Given
 *   var MyController = function(obfuscatedScope, obfuscatedRoute) {
 *     // ...
 *   }
 *   // Define function dependencies
 *   MyController['$inject'] = ['$scope', '$route'];
 *
 *   // Then
 *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
 * ```
 *
 * # The array notation
 *
 * It is often desirable to inline Injected functions and that's when setting the `$inject` property
 * is very inconvenient. In these situations using the array notation to specify the dependencies in
 * a way that survives minification is a better choice:
 *
 * ```js
 *   // We wish to write this (not minification / obfuscation safe)
 *   injector.invoke(function($compile, $rootScope) {
 *     // ...
 *   });
 *
 *   // We are forced to write break inlining
 *   var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
 *     // ...
 *   };
 *   tmpFn.$inject = ['$compile', '$rootScope'];
 *   injector.invoke(tmpFn);
 *
 *   // To better support inline function the inline annotation is supported
 *   injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
 *     // ...
 *   }]);
 *
 *   // Therefore
 *   expect(injector.annotate(
 *      ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
 *    ).toEqual(['$compile', '$rootScope']);
 * ```
 *
 * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
 * be retrieved as described above.
 *
 * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
 *
 * @returns {Array.<string>} The names of the services which the function requires.
 */




/**
 * @ngdoc service
 * @name $provide
 *
 * @description
 *
 * The {@link auto.$provide $provide} service has a number of methods for registering components
 * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
 * {@link angular.Module}.
 *
 * An Angular **service** is a singleton object created by a **service factory**.  These **service
 * factories** are functions which, in turn, are created by a **service provider**.
 * The **service providers** are constructor functions. When instantiated they must contain a
 * property called `$get`, which holds the **service factory** function.
 *
 * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
 * correct **service provider**, instantiating it and then calling its `$get` **service factory**
 * function to get the instance of the **service**.
 *
 * Often services have no configuration options and there is no need to add methods to the service
 * provider.  The provider will be no more than a constructor function with a `$get` property. For
 * these cases the {@link auto.$provide $provide} service has additional helper methods to register
 * services without specifying a provider.
 *
 * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
 *     {@link auto.$injector $injector}
 * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
 *     providers and services.
 * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
 *     services, not providers.
 * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
 *     that will be wrapped in a **service provider** object, whose `$get` property will contain the
 *     given factory function.
 * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
 *     that will be wrapped in a **service provider** object, whose `$get` property will instantiate
 *      a new object using the given constructor function.
 *
 * See the individual methods for more information and examples.
 */

/**
 * @ngdoc method
 * @name $provide#provider
 * @description
 *
 * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
 * are constructor functions, whose instances are responsible for "providing" a factory for a
 * service.
 *
 * Service provider names start with the name of the service they provide followed by `Provider`.
 * For example, the {@link ng.$log $log} service has a provider called
 * {@link ng.$logProvider $logProvider}.
 *
 * Service provider objects can have additional methods which allow configuration of the provider
 * and its service. Importantly, you can configure what kind of service is created by the `$get`
 * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
 * method {@link ng.$logProvider#debugEnabled debugEnabled}
 * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
 * console or not.
 *
 * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
                        'Provider'` key.
 * @param {(Object|function())} provider If the provider is:
 *
 *   - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
 *     {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
 *   - `Constructor`: a new instance of the provider will be created using
 *     {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
 *
 * @returns {Object} registered provider instance

 * @example
 *
 * The following example shows how to create a simple event tracking service and register it using
 * {@link auto.$provide#provider $provide.provider()}.
 *
 * ```js
 *  // Define the eventTracker provider
 *  function EventTrackerProvider() {
 *    var trackingUrl = '/track';
 *
 *    // A provider method for configuring where the tracked events should been saved
 *    this.setTrackingUrl = function(url) {
 *      trackingUrl = url;
 *    };
 *
 *    // The service factory function
 *    this.$get = ['$http', function($http) {
 *      var trackedEvents = {};
 *      return {
 *        // Call this to track an event
 *        event: function(event) {
 *          var count = trackedEvents[event] || 0;
 *          count += 1;
 *          trackedEvents[event] = count;
 *          return count;
 *        },
 *        // Call this to save the tracked events to the trackingUrl
 *        save: function() {
 *          $http.post(trackingUrl, trackedEvents);
 *        }
 *      };
 *    }];
 *  }
 *
 *  describe('eventTracker', function() {
 *    var postSpy;
 *
 *    beforeEach(module(function($provide) {
 *      // Register the eventTracker provider
 *      $provide.provider('eventTracker', EventTrackerProvider);
 *    }));
 *
 *    beforeEach(module(function(eventTrackerProvider) {
 *      // Configure eventTracker provider
 *      eventTrackerProvider.setTrackingUrl('/custom-track');
 *    }));
 *
 *    it('tracks events', inject(function(eventTracker) {
 *      expect(eventTracker.event('login')).toEqual(1);
 *      expect(eventTracker.event('login')).toEqual(2);
 *    }));
 *
 *    it('saves to the tracking url', inject(function(eventTracker, $http) {
 *      postSpy = spyOn($http, 'post');
 *      eventTracker.event('login');
 *      eventTracker.save();
 *      expect(postSpy).toHaveBeenCalled();
 *      expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
 *      expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
 *      expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
 *    }));
 *  });
 * ```
 */

/**
 * @ngdoc method
 * @name $provide#factory
 * @description
 *
 * Register a **service factory**, which will be called to return the service instance.
 * This is short for registering a service where its provider consists of only a `$get` property,
 * which is the given service factory function.
 * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
 * configure your service in a provider.
 *
 * @param {string} name The name of the instance.
 * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
 *                      Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
 * @returns {Object} registered provider instance
 *
 * @example
 * Here is an example of registering a service
 * ```js
 *   $provide.factory('ping', ['$http', function($http) {
 *     return function ping() {
 *       return $http.send('/ping');
 *     };
 *   }]);
 * ```
 * You would then inject and use this service like this:
 * ```js
 *   someModule.controller('Ctrl', ['ping', function(ping) {
 *     ping();
 *   }]);
 * ```
 */


/**
 * @ngdoc method
 * @name $provide#service
 * @description
 *
 * Register a **service constructor**, which will be invoked with `new` to create the service
 * instance.
 * This is short for registering a service where its provider's `$get` property is the service
 * constructor function that will be used to instantiate the service instance.
 *
 * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
 * as a type/class.
 *
 * @param {string} name The name of the instance.
 * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
 *     that will be instantiated.
 * @returns {Object} registered provider instance
 *
 * @example
 * Here is an example of registering a service using
 * {@link auto.$provide#service $provide.service(class)}.
 * ```js
 *   var Ping = function($http) {
 *     this.$http = $http;
 *   };
 *
 *   Ping.$inject = ['$http'];
 *
 *   Ping.prototype.send = function() {
 *     return this.$http.get('/ping');
 *   };
 *   $provide.service('ping', Ping);
 * ```
 * You would then inject and use this service like this:
 * ```js
 *   someModule.controller('Ctrl', ['ping', function(ping) {
 *     ping.send();
 *   }]);
 * ```
 */


/**
 * @ngdoc method
 * @name $provide#value
 * @description
 *
 * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
 * number, an array, an object or a function.  This is short for registering a service where its
 * provider's `$get` property is a factory function that takes no arguments and returns the **value
 * service**.
 *
 * Value services are similar to constant services, except that they cannot be injected into a
 * module configuration function (see {@link angular.Module#config}) but they can be overridden by
 * an Angular
 * {@link auto.$provide#decorator decorator}.
 *
 * @param {string} name The name of the instance.
 * @param {*} value The value.
 * @returns {Object} registered provider instance
 *
 * @example
 * Here are some examples of creating value services.
 * ```js
 *   $provide.value('ADMIN_USER', 'admin');
 *
 *   $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
 *
 *   $provide.value('halfOf', function(value) {
 *     return value / 2;
 *   });
 * ```
 */


/**
 * @ngdoc method
 * @name $provide#constant
 * @description
 *
 * Register a **constant service**, such as a string, a number, an array, an object or a function,
 * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
 * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
 * be overridden by an Angular {@link auto.$provide#decorator decorator}.
 *
 * @param {string} name The name of the constant.
 * @param {*} value The constant value.
 * @returns {Object} registered instance
 *
 * @example
 * Here a some examples of creating constants:
 * ```js
 *   $provide.constant('SHARD_HEIGHT', 306);
 *
 *   $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
 *
 *   $provide.constant('double', function(value) {
 *     return value * 2;
 *   });
 * ```
 */


/**
 * @ngdoc method
 * @name $provide#decorator
 * @description
 *
 * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
 * intercepts the creation of a service, allowing it to override or modify the behaviour of the
 * service. The object returned by the decorator may be the original service, or a new service
 * object which replaces or wraps and delegates to the original service.
 *
 * @param {string} name The name of the service to decorate.
 * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
 *    instantiated and should return the decorated service instance. The function is called using
 *    the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
 *    Local injection arguments:
 *
 *    * `$delegate` - The original service instance, which can be monkey patched, configured,
 *      decorated or delegated to.
 *
 * @example
 * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
 * calls to {@link ng.$log#error $log.warn()}.
 * ```js
 *   $provide.decorator('$log', ['$delegate', function($delegate) {
 *     $delegate.warn = $delegate.error;
 *     return $delegate;
 *   }]);
 * ```
 */


function createInjector(modulesToLoad, strictDi) {
  strictDi = (strictDi === true);
  var INSTANTIATING = {},
      providerSuffix = 'Provider',
      path = [],
      loadedModules = new HashMap([], true),
      providerCache = {
        $provide: {
            provider: supportObject(provider),
            factory: supportObject(factory),
            service: supportObject(service),
            value: supportObject(value),
            constant: supportObject(constant),
            decorator: decorator
          }
      },
      providerInjector = (providerCache.$injector =
          createInternalInjector(providerCache, function(serviceName, caller) {
            if (angular.isString(caller)) {
              path.push(caller);
            }
            throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
          })),
      instanceCache = {},
      instanceInjector = (instanceCache.$injector =
          createInternalInjector(instanceCache, function(serviceName, caller) {
            var provider = providerInjector.get(serviceName + providerSuffix, caller);
            return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
          }));


  forEach(loadModules(modulesToLoad), function(fn) { if (fn) instanceInjector.invoke(fn); });

  return instanceInjector;

  ////////////////////////////////////
  // $provider
  ////////////////////////////////////

  function supportObject(delegate) {
    return function(key, value) {
      if (isObject(key)) {
        forEach(key, reverseParams(delegate));
      } else {
        return delegate(key, value);
      }
    };
  }

  function provider(name, provider_) {
    assertNotHasOwnProperty(name, 'service');
    if (isFunction(provider_) || isArray(provider_)) {
      provider_ = providerInjector.instantiate(provider_);
    }
    if (!provider_.$get) {
      throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
    }
    return providerCache[name + providerSuffix] = provider_;
  }

  function enforceReturnValue(name, factory) {
    return function enforcedReturnValue() {
      var result = instanceInjector.invoke(factory, this);
      if (isUndefined(result)) {
        throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
      }
      return result;
    };
  }

  function factory(name, factoryFn, enforce) {
    return provider(name, {
      $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
    });
  }

  function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
      return $injector.instantiate(constructor);
    }]);
  }

  function value(name, val) { return factory(name, valueFn(val), false); }

  function constant(name, value) {
    assertNotHasOwnProperty(name, 'constant');
    providerCache[name] = value;
    instanceCache[name] = value;
  }

  function decorator(serviceName, decorFn) {
    var origProvider = providerInjector.get(serviceName + providerSuffix),
        orig$get = origProvider.$get;

    origProvider.$get = function() {
      var origInstance = instanceInjector.invoke(orig$get, origProvider);
      return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
    };
  }

  ////////////////////////////////////
  // Module Loading
  ////////////////////////////////////
  function loadModules(modulesToLoad) {
    var runBlocks = [], moduleFn;
    forEach(modulesToLoad, function(module) {
      if (loadedModules.get(module)) return;
      loadedModules.put(module, true);

      function runInvokeQueue(queue) {
        var i, ii;
        for (i = 0, ii = queue.length; i < ii; i++) {
          var invokeArgs = queue[i],
              provider = providerInjector.get(invokeArgs[0]);

          provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
        }
      }

      try {
        if (isString(module)) {
          moduleFn = angularModule(module);
          runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
          runInvokeQueue(moduleFn._invokeQueue);
          runInvokeQueue(moduleFn._configBlocks);
        } else if (isFunction(module)) {
            runBlocks.push(providerInjector.invoke(module));
        } else if (isArray(module)) {
            runBlocks.push(providerInjector.invoke(module));
        } else {
          assertArgFn(module, 'module');
        }
      } catch (e) {
        if (isArray(module)) {
          module = module[module.length - 1];
        }
        if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
          // Safari & FF's stack traces don't contain error.message content
          // unlike those of Chrome and IE
          // So if stack doesn't contain message, we create a new string that contains both.
          // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
          /* jshint -W022 */
          e = e.message + '\n' + e.stack;
        }
        throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
                  module, e.stack || e.message || e);
      }
    });
    return runBlocks;
  }

  ////////////////////////////////////
  // internal Injector
  ////////////////////////////////////

  function createInternalInjector(cache, factory) {

    function getService(serviceName, caller) {
      if (cache.hasOwnProperty(serviceName)) {
        if (cache[serviceName] === INSTANTIATING) {
          throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
                    serviceName + ' <- ' + path.join(' <- '));
        }
        return cache[serviceName];
      } else {
        try {
          path.unshift(serviceName);
          cache[serviceName] = INSTANTIATING;
          return cache[serviceName] = factory(serviceName, caller);
        } catch (err) {
          if (cache[serviceName] === INSTANTIATING) {
            delete cache[serviceName];
          }
          throw err;
        } finally {
          path.shift();
        }
      }
    }

    function invoke(fn, self, locals, serviceName) {
      if (typeof locals === 'string') {
        serviceName = locals;
        locals = null;
      }

      var args = [],
          $inject = createInjector.$$annotate(fn, strictDi, serviceName),
          length, i,
          key;

      for (i = 0, length = $inject.length; i < length; i++) {
        key = $inject[i];
        if (typeof key !== 'string') {
          throw $injectorMinErr('itkn',
                  'Incorrect injection token! Expected service name as string, got {0}', key);
        }
        args.push(
          locals && locals.hasOwnProperty(key)
          ? locals[key]
          : getService(key, serviceName)
        );
      }
      if (isArray(fn)) {
        fn = fn[length];
      }

      // http://jsperf.com/angularjs-invoke-apply-vs-switch
      // #5388
      return fn.apply(self, args);
    }

    function instantiate(Type, locals, serviceName) {
      // Check if Type is annotated and use just the given function at n-1 as parameter
      // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
      // Object creation: http://jsperf.com/create-constructor/2
      var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
      var returnedValue = invoke(Type, instance, locals, serviceName);

      return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
    }

    return {
      invoke: invoke,
      instantiate: instantiate,
      get: getService,
      annotate: createInjector.$$annotate,
      has: function(name) {
        return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
      }
    };
  }
}

createInjector.$$annotate = annotate;

/**
 * @ngdoc provider
 * @name $anchorScrollProvider
 *
 * @description
 * Use `$anchorScrollProvider` to disable automatic scrolling whenever
 * {@link ng.$location#hash $location.hash()} changes.
 */
function $AnchorScrollProvider() {

  var autoScrollingEnabled = true;

  /**
   * @ngdoc method
   * @name $anchorScrollProvider#disableAutoScrolling
   *
   * @description
   * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
   * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
   * Use this method to disable automatic scrolling.
   *
   * If automatic scrolling is disabled, one must explicitly call
   * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
   * current hash.
   */
  this.disableAutoScrolling = function() {
    autoScrollingEnabled = false;
  };

  /**
   * @ngdoc service
   * @name $anchorScroll
   * @kind function
   * @requires $window
   * @requires $location
   * @requires $rootScope
   *
   * @description
   * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
   * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
   * in the
   * [HTML5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
   *
   * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
   * match any anchor whenever it changes. This can be disabled by calling
   * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
   *
   * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
   * vertical scroll-offset (either fixed or dynamic).
   *
   * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
   *                       {@link ng.$location#hash $location.hash()} will be used.
   *
   * @property {(number|function|jqLite)} yOffset
   * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
   * positioned elements at the top of the page, such as navbars, headers etc.
   *
   * `yOffset` can be specified in various ways:
   * - **number**: A fixed number of pixels to be used as offset.<br /><br />
   * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
   *   a number representing the offset (in pixels).<br /><br />
   * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
   *   the top of the page to the element's bottom will be used as offset.<br />
   *   **Note**: The element will be taken into account only as long as its `position` is set to
   *   `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
   *   their height and/or positioning according to the viewport's size.
   *
   * <br />
   * <div class="alert alert-warning">
   * In order for `yOffset` to work properly, scrolling should take place on the document's root and
   * not some child element.
   * </div>
   *
   * @example
     <example module="anchorScrollExample">
       <file name="index.html">
         <div id="scrollArea" ng-controller="ScrollController">
           <a ng-click="gotoBottom()">Go to bottom</a>
           <a id="bottom"></a> You're at the bottom!
         </div>
       </file>
       <file name="script.js">
         angular.module('anchorScrollExample', [])
           .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
             function ($scope, $location, $anchorScroll) {
               $scope.gotoBottom = function() {
                 // set the location.hash to the id of
                 // the element you wish to scroll to.
                 $location.hash('bottom');

                 // call $anchorScroll()
                 $anchorScroll();
               };
             }]);
       </file>
       <file name="style.css">
         #scrollArea {
           height: 280px;
           overflow: auto;
         }

         #bottom {
           display: block;
           margin-top: 2000px;
         }
       </file>
     </example>
   *
   * <hr />
   * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
   * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
   *
   * @example
     <example module="anchorScrollOffsetExample">
       <file name="index.html">
         <div class="fixed-header" ng-controller="headerCtrl">
           <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
             Go to anchor {{x}}
           </a>
         </div>
         <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
           Anchor {{x}} of 5
         </div>
       </file>
       <file name="script.js">
         angular.module('anchorScrollOffsetExample', [])
           .run(['$anchorScroll', function($anchorScroll) {
             $anchorScroll.yOffset = 50;   // always scroll by 50 extra pixels
           }])
           .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
             function ($anchorScroll, $location, $scope) {
               $scope.gotoAnchor = function(x) {
                 var newHash = 'anchor' + x;
                 if ($location.hash() !== newHash) {
                   // set the $location.hash to `newHash` and
                   // $anchorScroll will automatically scroll to it
                   $location.hash('anchor' + x);
                 } else {
                   // call $anchorScroll() explicitly,
                   // since $location.hash hasn't changed
                   $anchorScroll();
                 }
               };
             }
           ]);
       </file>
       <file name="style.css">
         body {
           padding-top: 50px;
         }

         .anchor {
           border: 2px dashed DarkOrchid;
           padding: 10px 10px 200px 10px;
         }

         .fixed-header {
           background-color: rgba(0, 0, 0, 0.2);
           height: 50px;
           position: fixed;
           top: 0; left: 0; right: 0;
         }

         .fixed-header > a {
           display: inline-block;
           margin: 5px 15px;
         }
       </file>
     </example>
   */
  this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
    var document = $window.document;

    // Helper function to get first anchor from a NodeList
    // (using `Array#some()` instead of `angular#forEach()` since it's more performant
    //  and working in all supported browsers.)
    function getFirstAnchor(list) {
      var result = null;
      Array.prototype.some.call(list, function(element) {
        if (nodeName_(element) === 'a') {
          result = element;
          return true;
        }
      });
      return result;
    }

    function getYOffset() {

      var offset = scroll.yOffset;

      if (isFunction(offset)) {
        offset = offset();
      } else if (isElement(offset)) {
        var elem = offset[0];
        var style = $window.getComputedStyle(elem);
        if (style.position !== 'fixed') {
          offset = 0;
        } else {
          offset = elem.getBoundingClientRect().bottom;
        }
      } else if (!isNumber(offset)) {
        offset = 0;
      }

      return offset;
    }

    function scrollTo(elem) {
      if (elem) {
        elem.scrollIntoView();

        var offset = getYOffset();

        if (offset) {
          // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
          // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
          // top of the viewport.
          //
          // IF the number of pixels from the top of `elem` to the end of the page's content is less
          // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
          // way down the page.
          //
          // This is often the case for elements near the bottom of the page.
          //
          // In such cases we do not need to scroll the whole `offset` up, just the difference between
          // the top of the element and the offset, which is enough to align the top of `elem` at the
          // desired position.
          var elemTop = elem.getBoundingClientRect().top;
          $window.scrollBy(0, elemTop - offset);
        }
      } else {
        $window.scrollTo(0, 0);
      }
    }

    function scroll(hash) {
      hash = isString(hash) ? hash : $location.hash();
      var elm;

      // empty hash, scroll to the top of the page
      if (!hash) scrollTo(null);

      // element with given id
      else if ((elm = document.getElementById(hash))) scrollTo(elm);

      // first anchor with given name :-D
      else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);

      // no element and hash == 'top', scroll to the top of the page
      else if (hash === 'top') scrollTo(null);
    }

    // does not scroll when user clicks on anchor link that is currently on
    // (no url change, no $location.hash() change), browser native does scroll
    if (autoScrollingEnabled) {
      $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
        function autoScrollWatchAction(newVal, oldVal) {
          // skip the initial scroll if $location.hash is empty
          if (newVal === oldVal && newVal === '') return;

          jqLiteDocumentLoaded(function() {
            $rootScope.$evalAsync(scroll);
          });
        });
    }

    return scroll;
  }];
}

var $animateMinErr = minErr('$animate');
var ELEMENT_NODE = 1;
var NG_ANIMATE_CLASSNAME = 'ng-animate';

function mergeClasses(a,b) {
  if (!a && !b) return '';
  if (!a) return b;
  if (!b) return a;
  if (isArray(a)) a = a.join(' ');
  if (isArray(b)) b = b.join(' ');
  return a + ' ' + b;
}

function extractElementNode(element) {
  for (var i = 0; i < element.length; i++) {
    var elm = element[i];
    if (elm.nodeType === ELEMENT_NODE) {
      return elm;
    }
  }
}

function splitClasses(classes) {
  if (isString(classes)) {
    classes = classes.split(' ');
  }

  // Use createMap() to prevent class assumptions involving property names in
  // Object.prototype
  var obj = createMap();
  forEach(classes, function(klass) {
    // sometimes the split leaves empty string values
    // incase extra spaces were applied to the options
    if (klass.length) {
      obj[klass] = true;
    }
  });
  return obj;
}

// if any other type of options value besides an Object value is
// passed into the $animate.method() animation then this helper code
// will be run which will ignore it. While this patch is not the
// greatest solution to this, a lot of existing plugins depend on
// $animate to either call the callback (< 1.2) or return a promise
// that can be changed. This helper function ensures that the options
// are wiped clean incase a callback function is provided.
function prepareAnimateOptions(options) {
  return isObject(options)
      ? options
      : {};
}

var $$CoreAnimateRunnerProvider = function() {
  this.$get = ['$q', '$$rAF', function($q, $$rAF) {
    function AnimateRunner() {}
    AnimateRunner.all = noop;
    AnimateRunner.chain = noop;
    AnimateRunner.prototype = {
      end: noop,
      cancel: noop,
      resume: noop,
      pause: noop,
      complete: noop,
      then: function(pass, fail) {
        return $q(function(resolve) {
          $$rAF(function() {
            resolve();
          });
        }).then(pass, fail);
      }
    };
    return AnimateRunner;
  }];
};

// this is prefixed with Core since it conflicts with
// the animateQueueProvider defined in ngAnimate/animateQueue.js
var $$CoreAnimateQueueProvider = function() {
  var postDigestQueue = new HashMap();
  var postDigestElements = [];

  this.$get = ['$$AnimateRunner', '$rootScope',
       function($$AnimateRunner,   $rootScope) {
    return {
      enabled: noop,
      on: noop,
      off: noop,
      pin: noop,

      push: function(element, event, options, domOperation) {
        domOperation        && domOperation();

        options = options || {};
        options.from        && element.css(options.from);
        options.to          && element.css(options.to);

        if (options.addClass || options.removeClass) {
          addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
        }

        return new $$AnimateRunner(); // jshint ignore:line
      }
    };

    function addRemoveClassesPostDigest(element, add, remove) {
      var data = postDigestQueue.get(element);
      var classVal;

      if (!data) {
        postDigestQueue.put(element, data = {});
        postDigestElements.push(element);
      }

      if (add) {
        forEach(add.split(' '), function(className) {
          if (className) {
            data[className] = true;
          }
        });
      }

      if (remove) {
        forEach(remove.split(' '), function(className) {
          if (className) {
            data[className] = false;
          }
        });
      }

      if (postDigestElements.length > 1) return;

      $rootScope.$$postDigest(function() {
        forEach(postDigestElements, function(element) {
          var data = postDigestQueue.get(element);
          if (data) {
            var existing = splitClasses(element.attr('class'));
            var toAdd = '';
            var toRemove = '';
            forEach(data, function(status, className) {
              var hasClass = !!existing[className];
              if (status !== hasClass) {
                if (status) {
                  toAdd += (toAdd.length ? ' ' : '') + className;
                } else {
                  toRemove += (toRemove.length ? ' ' : '') + className;
                }
              }
            });

            forEach(element, function(elm) {
              toAdd    && jqLiteAddClass(elm, toAdd);
              toRemove && jqLiteRemoveClass(elm, toRemove);
            });
            postDigestQueue.remove(element);
          }
        });

        postDigestElements.length = 0;
      });
    }
  }];
};

/**
 * @ngdoc provider
 * @name $animateProvider
 *
 * @description
 * Default implementation of $animate that doesn't perform any animations, instead just
 * synchronously performs DOM updates and resolves the returned runner promise.
 *
 * In order to enable animations the `ngAnimate` module has to be loaded.
 *
 * To see the functional implementation check out `src/ngAnimate/animate.js`.
 */
var $AnimateProvider = ['$provide', function($provide) {
  var provider = this;

  this.$$registeredAnimations = Object.create(null);

   /**
   * @ngdoc method
   * @name $animateProvider#register
   *
   * @description
   * Registers a new injectable animation factory function. The factory function produces the
   * animation object which contains callback functions for each event that is expected to be
   * animated.
   *
   *   * `eventFn`: `function(element, ... , doneFunction, options)`
   *   The element to animate, the `doneFunction` and the options fed into the animation. Depending
   *   on the type of animation additional arguments will be injected into the animation function. The
   *   list below explains the function signatures for the different animation methods:
   *
   *   - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
   *   - addClass: function(element, addedClasses, doneFunction, options)
   *   - removeClass: function(element, removedClasses, doneFunction, options)
   *   - enter, leave, move: function(element, doneFunction, options)
   *   - animate: function(element, fromStyles, toStyles, doneFunction, options)
   *
   *   Make sure to trigger the `doneFunction` once the animation is fully complete.
   *
   * ```js
   *   return {
   *     //enter, leave, move signature
   *     eventFn : function(element, done, options) {
   *       //code to run the animation
   *       //once complete, then run done()
   *       return function endFunction(wasCancelled) {
   *         //code to cancel the animation
   *       }
   *     }
   *   }
   * ```
   *
   * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
   * @param {Function} factory The factory function that will be executed to return the animation
   *                           object.
   */
  this.register = function(name, factory) {
    if (name && name.charAt(0) !== '.') {
      throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
    }

    var key = name + '-animation';
    provider.$$registeredAnimations[name.substr(1)] = key;
    $provide.factory(key, factory);
  };

  /**
   * @ngdoc method
   * @name $animateProvider#classNameFilter
   *
   * @description
   * Sets and/or returns the CSS class regular expression that is checked when performing
   * an animation. Upon bootstrap the classNameFilter value is not set at all and will
   * therefore enable $animate to attempt to perform an animation on any element that is triggered.
   * When setting the `classNameFilter` value, animations will only be performed on elements
   * that successfully match the filter expression. This in turn can boost performance
   * for low-powered devices as well as applications containing a lot of structural operations.
   * @param {RegExp=} expression The className expression which will be checked against all animations
   * @return {RegExp} The current CSS className expression value. If null then there is no expression value
   */
  this.classNameFilter = function(expression) {
    if (arguments.length === 1) {
      this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
      if (this.$$classNameFilter) {
        var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
        if (reservedRegex.test(this.$$classNameFilter.toString())) {
          throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);

        }
      }
    }
    return this.$$classNameFilter;
  };

  this.$get = ['$$animateQueue', function($$animateQueue) {
    function domInsert(element, parentElement, afterElement) {
      // if for some reason the previous element was removed
      // from the dom sometime before this code runs then let's
      // just stick to using the parent element as the anchor
      if (afterElement) {
        var afterNode = extractElementNode(afterElement);
        if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
          afterElement = null;
        }
      }
      afterElement ? afterElement.after(element) : parentElement.prepend(element);
    }

    /**
     * @ngdoc service
     * @name $animate
     * @description The $animate service exposes a series of DOM utility methods that provide support
     * for animation hooks. The default behavior is the application of DOM operations, however,
     * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
     * to ensure that animation runs with the triggered DOM operation.
     *
     * By default $animate doesn't trigger an animations. This is because the `ngAnimate` module isn't
     * included and only when it is active then the animation hooks that `$animate` triggers will be
     * functional. Once active then all structural `ng-` directives will trigger animations as they perform
     * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
     * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
     *
     * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
     *
     * To learn more about enabling animation support, click here to visit the
     * {@link ngAnimate ngAnimate module page}.
     */
    return {
      // we don't call it directly since non-existant arguments may
      // be interpreted as null within the sub enabled function

      /**
       *
       * @ngdoc method
       * @name $animate#on
       * @kind function
       * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
       *    has fired on the given element or among any of its children. Once the listener is fired, the provided callback
       *    is fired with the following params:
       *
       * ```js
       * $animate.on('enter', container,
       *    function callback(element, phase) {
       *      // cool we detected an enter animation within the container
       *    }
       * );
       * ```
       *
       * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
       * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
       *     as well as among its children
       * @param {Function} callback the callback function that will be fired when the listener is triggered
       *
       * The arguments present in the callback function are:
       * * `element` - The captured DOM element that the animation was fired on.
       * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
       */
      on: $$animateQueue.on,

      /**
       *
       * @ngdoc method
       * @name $animate#off
       * @kind function
       * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
       * can be used in three different ways depending on the arguments:
       *
       * ```js
       * // remove all the animation event listeners listening for `enter`
       * $animate.off('enter');
       *
       * // remove all the animation event listeners listening for `enter` on the given element and its children
       * $animate.off('enter', container);
       *
       * // remove the event listener function provided by `listenerFn` that is set
       * // to listen for `enter` on the given `element` as well as its children
       * $animate.off('enter', container, callback);
       * ```
       *
       * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
       * @param {DOMElement=} container the container element the event listener was placed on
       * @param {Function=} callback the callback function that was registered as the listener
       */
      off: $$animateQueue.off,

      /**
       * @ngdoc method
       * @name $animate#pin
       * @kind function
       * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
       *    outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
       *    element despite being outside the realm of the application or within another application. Say for example if the application
       *    was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
       *    as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
       *    that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
       *
       *    Note that this feature is only active when the `ngAnimate` module is used.
       *
       * @param {DOMElement} element the external element that will be pinned
       * @param {DOMElement} parentElement the host parent element that will be associated with the external element
       */
      pin: $$animateQueue.pin,

      /**
       *
       * @ngdoc method
       * @name $animate#enabled
       * @kind function
       * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
       * function can be called in four ways:
       *
       * ```js
       * // returns true or false
       * $animate.enabled();
       *
       * // changes the enabled state for all animations
       * $animate.enabled(false);
       * $animate.enabled(true);
       *
       * // returns true or false if animations are enabled for an element
       * $animate.enabled(element);
       *
       * // changes the enabled state for an element and its children
       * $animate.enabled(element, true);
       * $animate.enabled(element, false);
       * ```
       *
       * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
       * @param {boolean=} enabled whether or not the animations will be enabled for the element
       *
       * @return {boolean} whether or not animations are enabled
       */
      enabled: $$animateQueue.enabled,

      /**
       * @ngdoc method
       * @name $animate#cancel
       * @kind function
       * @description Cancels the provided animation.
       *
       * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
       */
      cancel: function(runner) {
        runner.end && runner.end();
      },

      /**
       *
       * @ngdoc method
       * @name $animate#enter
       * @kind function
       * @description Inserts the element into the DOM either after the `after` element (if provided) or
       *   as the first child within the `parent` element and then triggers an animation.
       *   A promise is returned that will be resolved during the next digest once the animation
       *   has completed.
       *
       * @param {DOMElement} element the element which will be inserted into the DOM
       * @param {DOMElement} parent the parent element which will append the element as
       *   a child (so long as the after element is not present)
       * @param {DOMElement=} after the sibling element after which the element will be appended
       * @param {object=} options an optional collection of options/styles that will be applied to the element
       *
       * @return {Promise} the animation callback promise
       */
      enter: function(element, parent, after, options) {
        parent = parent && jqLite(parent);
        after = after && jqLite(after);
        parent = parent || after.parent();
        domInsert(element, parent, after);
        return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
      },

      /**
       *
       * @ngdoc method
       * @name $animate#move
       * @kind function
       * @description Inserts (moves) the element into its new position in the DOM either after
       *   the `after` element (if provided) or as the first child within the `parent` element
       *   and then triggers an animation. A promise is returned that will be resolved
       *   during the next digest once the animation has completed.
       *
       * @param {DOMElement} element the element which will be moved into the new DOM position
       * @param {DOMElement} parent the parent element which will append the element as
       *   a child (so long as the after element is not present)
       * @param {DOMElement=} after the sibling element after which the element will be appended
       * @param {object=} options an optional collection of options/styles that will be applied to the element
       *
       * @return {Promise} the animation callback promise
       */
      move: function(element, parent, after, options) {
        parent = parent && jqLite(parent);
        after = after && jqLite(after);
        parent = parent || after.parent();
        domInsert(element, parent, after);
        return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
      },

      /**
       * @ngdoc method
       * @name $animate#leave
       * @kind function
       * @description Triggers an animation and then removes the element from the DOM.
       * When the function is called a promise is returned that will be resolved during the next
       * digest once the animation has completed.
       *
       * @param {DOMElement} element the element which will be removed from the DOM
       * @param {object=} options an optional collection of options/styles that will be applied to the element
       *
       * @return {Promise} the animation callback promise
       */
      leave: function(element, options) {
        return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
          element.remove();
        });
      },

      /**
       * @ngdoc method
       * @name $animate#addClass
       * @kind function
       *
       * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
       *   execution, the addClass operation will only be handled after the next digest and it will not trigger an
       *   animation if element already contains the CSS class or if the class is removed at a later step.
       *   Note that class-based animations are treated differently compared to structural animations
       *   (like enter, move and leave) since the CSS classes may be added/removed at different points
       *   depending if CSS or JavaScript animations are used.
       *
       * @param {DOMElement} element the element which the CSS classes will be applied to
       * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
       * @param {object=} options an optional collection of options/styles that will be applied to the element
       *
       * @return {Promise} the animation callback promise
       */
      addClass: function(element, className, options) {
        options = prepareAnimateOptions(options);
        options.addClass = mergeClasses(options.addclass, className);
        return $$animateQueue.push(element, 'addClass', options);
      },

      /**
       * @ngdoc method
       * @name $animate#removeClass
       * @kind function
       *
       * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
       *   execution, the removeClass operation will only be handled after the next digest and it will not trigger an
       *   animation if element does not contain the CSS class or if the class is added at a later step.
       *   Note that class-based animations are treated differently compared to structural animations
       *   (like enter, move and leave) since the CSS classes may be added/removed at different points
       *   depending if CSS or JavaScript animations are used.
       *
       * @param {DOMElement} element the element which the CSS classes will be applied to
       * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
       * @param {object=} options an optional collection of options/styles that will be applied to the element
       *
       * @return {Promise} the animation callback promise
       */
      removeClass: function(element, className, options) {
        options = prepareAnimateOptions(options);
        options.removeClass = mergeClasses(options.removeClass, className);
        return $$animateQueue.push(element, 'removeClass', options);
      },

      /**
       * @ngdoc method
       * @name $animate#setClass
       * @kind function
       *
       * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
       *    triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
       *    `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
       *    passed. Note that class-based animations are treated differently compared to structural animations
       *    (like enter, move and leave) since the CSS classes may be added/removed at different points
       *    depending if CSS or JavaScript animations are used.
       *
       * @param {DOMElement} element the element which the CSS classes will be applied to
       * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
       * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
       * @param {object=} options an optional collection of options/styles that will be applied to the element
       *
       * @return {Promise} the animation callback promise
       */
      setClass: function(element, add, remove, options) {
        options = prepareAnimateOptions(options);
        options.addClass = mergeClasses(options.addClass, add);
        options.removeClass = mergeClasses(options.removeClass, remove);
        return $$animateQueue.push(element, 'setClass', options);
      },

      /**
       * @ngdoc method
       * @name $animate#animate
       * @kind function
       *
       * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
       * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
       * on the provided styles. For example, if a transition animation is set for the given className then the provided from and
       * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
       * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
       *
       * @param {DOMElement} element the element which the CSS styles will be applied to
       * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
       * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
       * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
       *    this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
       *    (Note that if no animation is detected then this value will not be appplied to the element.)
       * @param {object=} options an optional collection of options/styles that will be applied to the element
       *
       * @return {Promise} the animation callback promise
       */
      animate: function(element, from, to, className, options) {
        options = prepareAnimateOptions(options);
        options.from = options.from ? extend(options.from, from) : from;
        options.to   = options.to   ? extend(options.to, to)     : to;

        className = className || 'ng-inline-animate';
        options.tempClasses = mergeClasses(options.tempClasses, className);
        return $$animateQueue.push(element, 'animate', options);
      }
    };
  }];
}];

function $$AsyncCallbackProvider() {
  this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
    return $$rAF.supported
      ? function(fn) { return $$rAF(fn); }
      : function(fn) {
        return $timeout(fn, 0, false);
      };
  }];
}

/* global stripHash: true */

/**
 * ! This is a private undocumented service !
 *
 * @name $browser
 * @requires $log
 * @description
 * This object has two goals:
 *
 * - hide all the global state in the browser caused by the window object
 * - abstract away all the browser specific features and inconsistencies
 *
 * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
 * service, which can be used for convenient testing of the application without the interaction with
 * the real browser apis.
 */
/**
 * @param {object} window The global window object.
 * @param {object} document jQuery wrapped document.
 * @param {object} $log window.console or an object with the same interface.
 * @param {object} $sniffer $sniffer service
 */
function Browser(window, document, $log, $sniffer) {
  var self = this,
      rawDocument = document[0],
      location = window.location,
      history = window.history,
      setTimeout = window.setTimeout,
      clearTimeout = window.clearTimeout,
      pendingDeferIds = {};

  self.isMock = false;

  var outstandingRequestCount = 0;
  var outstandingRequestCallbacks = [];

  // TODO(vojta): remove this temporary api
  self.$$completeOutstandingRequest = completeOutstandingRequest;
  self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };

  /**
   * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
   * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
   */
  function completeOutstandingRequest(fn) {
    try {
      fn.apply(null, sliceArgs(arguments, 1));
    } finally {
      outstandingRequestCount--;
      if (outstandingRequestCount === 0) {
        while (outstandingRequestCallbacks.length) {
          try {
            outstandingRequestCallbacks.pop()();
          } catch (e) {
            $log.error(e);
          }
        }
      }
    }
  }

  function getHash(url) {
    var index = url.indexOf('#');
    return index === -1 ? '' : url.substr(index);
  }

  /**
   * @private
   * Note: this method is used only by scenario runner
   * TODO(vojta): prefix this method with $$ ?
   * @param {function()} callback Function that will be called when no outstanding request
   */
  self.notifyWhenNoOutstandingRequests = function(callback) {
    if (outstandingRequestCount === 0) {
      callback();
    } else {
      outstandingRequestCallbacks.push(callback);
    }
  };

  //////////////////////////////////////////////////////////////
  // URL API
  //////////////////////////////////////////////////////////////

  var cachedState, lastHistoryState,
      lastBrowserUrl = location.href,
      baseElement = document.find('base'),
      reloadLocation = null;

  cacheState();
  lastHistoryState = cachedState;

  /**
   * @name $browser#url
   *
   * @description
   * GETTER:
   * Without any argument, this method just returns current value of location.href.
   *
   * SETTER:
   * With at least one argument, this method sets url to new value.
   * If html5 history api supported, pushState/replaceState is used, otherwise
   * location.href/location.replace is used.
   * Returns its own instance to allow chaining
   *
   * NOTE: this api is intended for use only by the $location service. Please use the
   * {@link ng.$location $location service} to change url.
   *
   * @param {string} url New url (when used as setter)
   * @param {boolean=} replace Should new url replace current history record?
   * @param {object=} state object to use with pushState/replaceState
   */
  self.url = function(url, replace, state) {
    // In modern browsers `history.state` is `null` by default; treating it separately
    // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
    // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
    if (isUndefined(state)) {
      state = null;
    }

    // Android Browser BFCache causes location, history reference to become stale.
    if (location !== window.location) location = window.location;
    if (history !== window.history) history = window.history;

    // setter
    if (url) {
      var sameState = lastHistoryState === state;

      // Don't change anything if previous and current URLs and states match. This also prevents
      // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
      // See https://github.com/angular/angular.js/commit/ffb2701
      if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
        return self;
      }
      var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
      lastBrowserUrl = url;
      lastHistoryState = state;
      // Don't use history API if only the hash changed
      // due to a bug in IE10/IE11 which leads
      // to not firing a `hashchange` nor `popstate` event
      // in some cases (see #9143).
      if ($sniffer.history && (!sameBase || !sameState)) {
        history[replace ? 'replaceState' : 'pushState'](state, '', url);
        cacheState();
        // Do the assignment again so that those two variables are referentially identical.
        lastHistoryState = cachedState;
      } else {
        if (!sameBase || reloadLocation) {
          reloadLocation = url;
        }
        if (replace) {
          location.replace(url);
        } else if (!sameBase) {
          location.href = url;
        } else {
          location.hash = getHash(url);
        }
      }
      return self;
    // getter
    } else {
      // - reloadLocation is needed as browsers don't allow to read out
      //   the new location.href if a reload happened.
      // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
      return reloadLocation || location.href.replace(/%27/g,"'");
    }
  };

  /**
   * @name $browser#state
   *
   * @description
   * This method is a getter.
   *
   * Return history.state or null if history.state is undefined.
   *
   * @returns {object} state
   */
  self.state = function() {
    return cachedState;
  };

  var urlChangeListeners = [],
      urlChangeInit = false;

  function cacheStateAndFireUrlChange() {
    cacheState();
    fireUrlChange();
  }

  function getCurrentState() {
    try {
      return history.state;
    } catch (e) {
      // MSIE can reportedly throw when there is no state (UNCONFIRMED).
    }
  }

  // This variable should be used *only* inside the cacheState function.
  var lastCachedState = null;
  function cacheState() {
    // This should be the only place in $browser where `history.state` is read.
    cachedState = getCurrentState();
    cachedState = isUndefined(cachedState) ? null : cachedState;

    // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
    if (equals(cachedState, lastCachedState)) {
      cachedState = lastCachedState;
    }
    lastCachedState = cachedState;
  }

  function fireUrlChange() {
    if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
      return;
    }

    lastBrowserUrl = self.url();
    lastHistoryState = cachedState;
    forEach(urlChangeListeners, function(listener) {
      listener(self.url(), cachedState);
    });
  }

  /**
   * @name $browser#onUrlChange
   *
   * @description
   * Register callback function that will be called, when url changes.
   *
   * It's only called when the url is changed from outside of angular:
   * - user types different url into address bar
   * - user clicks on history (forward/back) button
   * - user clicks on a link
   *
   * It's not called when url is changed by $browser.url() method
   *
   * The listener gets called with new url as parameter.
   *
   * NOTE: this api is intended for use only by the $location service. Please use the
   * {@link ng.$location $location service} to monitor url changes in angular apps.
   *
   * @param {function(string)} listener Listener function to be called when url changes.
   * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
   */
  self.onUrlChange = function(callback) {
    // TODO(vojta): refactor to use node's syntax for events
    if (!urlChangeInit) {
      // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
      // don't fire popstate when user change the address bar and don't fire hashchange when url
      // changed by push/replaceState

      // html5 history api - popstate event
      if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
      // hashchange event
      jqLite(window).on('hashchange', cacheStateAndFireUrlChange);

      urlChangeInit = true;
    }

    urlChangeListeners.push(callback);
    return callback;
  };

  /**
   * @private
   * Remove popstate and hashchange handler from window.
   *
   * NOTE: this api is intended for use only by $rootScope.
   */
  self.$$applicationDestroyed = function() {
    jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  };

  /**
   * Checks whether the url has changed outside of Angular.
   * Needs to be exported to be able to check for changes that have been done in sync,
   * as hashchange/popstate events fire in async.
   */
  self.$$checkUrlChange = fireUrlChange;

  //////////////////////////////////////////////////////////////
  // Misc API
  //////////////////////////////////////////////////////////////

  /**
   * @name $browser#baseHref
   *
   * @description
   * Returns current <base href>
   * (always relative - without domain)
   *
   * @returns {string} The current base href
   */
  self.baseHref = function() {
    var href = baseElement.attr('href');
    return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  };

  /**
   * @name $browser#defer
   * @param {function()} fn A function, who's execution should be deferred.
   * @param {number=} [delay=0] of milliseconds to defer the function execution.
   * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
   *
   * @description
   * Executes a fn asynchronously via `setTimeout(fn, delay)`.
   *
   * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
   * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
   * via `$browser.defer.flush()`.
   *
   */
  self.defer = function(fn, delay) {
    var timeoutId;
    outstandingRequestCount++;
    timeoutId = setTimeout(function() {
      delete pendingDeferIds[timeoutId];
      completeOutstandingRequest(fn);
    }, delay || 0);
    pendingDeferIds[timeoutId] = true;
    return timeoutId;
  };


  /**
   * @name $browser#defer.cancel
   *
   * @description
   * Cancels a deferred task identified with `deferId`.
   *
   * @param {*} deferId Token returned by the `$browser.defer` function.
   * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
   *                    canceled.
   */
  self.defer.cancel = function(deferId) {
    if (pendingDeferIds[deferId]) {
      delete pendingDeferIds[deferId];
      clearTimeout(deferId);
      completeOutstandingRequest(noop);
      return true;
    }
    return false;
  };

}

function $BrowserProvider() {
  this.$get = ['$window', '$log', '$sniffer', '$document',
      function($window, $log, $sniffer, $document) {
        return new Browser($window, $document, $log, $sniffer);
      }];
}

/**
 * @ngdoc service
 * @name $cacheFactory
 *
 * @description
 * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
 * them.
 *
 * ```js
 *
 *  var cache = $cacheFactory('cacheId');
 *  expect($cacheFactory.get('cacheId')).toBe(cache);
 *  expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
 *
 *  cache.put("key", "value");
 *  cache.put("another key", "another value");
 *
 *  // We've specified no options on creation
 *  expect(cache.info()).toEqual({id: 'cacheId', size: 2});
 *
 * ```
 *
 *
 * @param {string} cacheId Name or id of the newly created cache.
 * @param {object=} options Options object that specifies the cache behavior. Properties:
 *
 *   - `{number=}` `capacity` — turns the cache into LRU cache.
 *
 * @returns {object} Newly created cache object with the following set of methods:
 *
 * - `{object}` `info()` — Returns id, size, and options of cache.
 * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
 *   it.
 * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
 * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
 * - `{void}` `removeAll()` — Removes all cached values.
 * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
 *
 * @example
   <example module="cacheExampleApp">
     <file name="index.html">
       <div ng-controller="CacheController">
         <input ng-model="newCacheKey" placeholder="Key">
         <input ng-model="newCacheValue" placeholder="Value">
         <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>

         <p ng-if="keys.length">Cached Values</p>
         <div ng-repeat="key in keys">
           <span ng-bind="key"></span>
           <span>: </span>
           <b ng-bind="cache.get(key)"></b>
         </div>

         <p>Cache Info</p>
         <div ng-repeat="(key, value) in cache.info()">
           <span ng-bind="key"></span>
           <span>: </span>
           <b ng-bind="value"></b>
         </div>
       </div>
     </file>
     <file name="script.js">
       angular.module('cacheExampleApp', []).
         controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
           $scope.keys = [];
           $scope.cache = $cacheFactory('cacheId');
           $scope.put = function(key, value) {
             if ($scope.cache.get(key) === undefined) {
               $scope.keys.push(key);
             }
             $scope.cache.put(key, value === undefined ? null : value);
           };
         }]);
     </file>
     <file name="style.css">
       p {
         margin: 10px 0 3px;
       }
     </file>
   </example>
 */
function $CacheFactoryProvider() {

  this.$get = function() {
    var caches = {};

    function cacheFactory(cacheId, options) {
      if (cacheId in caches) {
        throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
      }

      var size = 0,
          stats = extend({}, options, {id: cacheId}),
          data = {},
          capacity = (options && options.capacity) || Number.MAX_VALUE,
          lruHash = {},
          freshEnd = null,
          staleEnd = null;

      /**
       * @ngdoc type
       * @name $cacheFactory.Cache
       *
       * @description
       * A cache object used to store and retrieve data, primarily used by
       * {@link $http $http} and the {@link ng.directive:script script} directive to cache
       * templates and other data.
       *
       * ```js
       *  angular.module('superCache')
       *    .factory('superCache', ['$cacheFactory', function($cacheFactory) {
       *      return $cacheFactory('super-cache');
       *    }]);
       * ```
       *
       * Example test:
       *
       * ```js
       *  it('should behave like a cache', inject(function(superCache) {
       *    superCache.put('key', 'value');
       *    superCache.put('another key', 'another value');
       *
       *    expect(superCache.info()).toEqual({
       *      id: 'super-cache',
       *      size: 2
       *    });
       *
       *    superCache.remove('another key');
       *    expect(superCache.get('another key')).toBeUndefined();
       *
       *    superCache.removeAll();
       *    expect(superCache.info()).toEqual({
       *      id: 'super-cache',
       *      size: 0
       *    });
       *  }));
       * ```
       */
      return caches[cacheId] = {

        /**
         * @ngdoc method
         * @name $cacheFactory.Cache#put
         * @kind function
         *
         * @description
         * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
         * retrieved later, and incrementing the size of the cache if the key was not already
         * present in the cache. If behaving like an LRU cache, it will also remove stale
         * entries from the set.
         *
         * It will not insert undefined values into the cache.
         *
         * @param {string} key the key under which the cached data is stored.
         * @param {*} value the value to store alongside the key. If it is undefined, the key
         *    will not be stored.
         * @returns {*} the value stored.
         */
        put: function(key, value) {
          if (isUndefined(value)) return;
          if (capacity < Number.MAX_VALUE) {
            var lruEntry = lruHash[key] || (lruHash[key] = {key: key});

            refresh(lruEntry);
          }

          if (!(key in data)) size++;
          data[key] = value;

          if (size > capacity) {
            this.remove(staleEnd.key);
          }

          return value;
        },

        /**
         * @ngdoc method
         * @name $cacheFactory.Cache#get
         * @kind function
         *
         * @description
         * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
         *
         * @param {string} key the key of the data to be retrieved
         * @returns {*} the value stored.
         */
        get: function(key) {
          if (capacity < Number.MAX_VALUE) {
            var lruEntry = lruHash[key];

            if (!lruEntry) return;

            refresh(lruEntry);
          }

          return data[key];
        },


        /**
         * @ngdoc method
         * @name $cacheFactory.Cache#remove
         * @kind function
         *
         * @description
         * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
         *
         * @param {string} key the key of the entry to be removed
         */
        remove: function(key) {
          if (capacity < Number.MAX_VALUE) {
            var lruEntry = lruHash[key];

            if (!lruEntry) return;

            if (lruEntry == freshEnd) freshEnd = lruEntry.p;
            if (lruEntry == staleEnd) staleEnd = lruEntry.n;
            link(lruEntry.n,lruEntry.p);

            delete lruHash[key];
          }

          delete data[key];
          size--;
        },


        /**
         * @ngdoc method
         * @name $cacheFactory.Cache#removeAll
         * @kind function
         *
         * @description
         * Clears the cache object of any entries.
         */
        removeAll: function() {
          data = {};
          size = 0;
          lruHash = {};
          freshEnd = staleEnd = null;
        },


        /**
         * @ngdoc method
         * @name $cacheFactory.Cache#destroy
         * @kind function
         *
         * @description
         * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
         * removing it from the {@link $cacheFactory $cacheFactory} set.
         */
        destroy: function() {
          data = null;
          stats = null;
          lruHash = null;
          delete caches[cacheId];
        },


        /**
         * @ngdoc method
         * @name $cacheFactory.Cache#info
         * @kind function
         *
         * @description
         * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
         *
         * @returns {object} an object with the following properties:
         *   <ul>
         *     <li>**id**: the id of the cache instance</li>
         *     <li>**size**: the number of entries kept in the cache instance</li>
         *     <li>**...**: any additional properties from the options object when creating the
         *       cache.</li>
         *   </ul>
         */
        info: function() {
          return extend({}, stats, {size: size});
        }
      };


      /**
       * makes the `entry` the freshEnd of the LRU linked list
       */
      function refresh(entry) {
        if (entry != freshEnd) {
          if (!staleEnd) {
            staleEnd = entry;
          } else if (staleEnd == entry) {
            staleEnd = entry.n;
          }

          link(entry.n, entry.p);
          link(entry, freshEnd);
          freshEnd = entry;
          freshEnd.n = null;
        }
      }


      /**
       * bidirectionally links two entries of the LRU linked list
       */
      function link(nextEntry, prevEntry) {
        if (nextEntry != prevEntry) {
          if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
          if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
        }
      }
    }


  /**
   * @ngdoc method
   * @name $cacheFactory#info
   *
   * @description
   * Get information about all the caches that have been created
   *
   * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
   */
    cacheFactory.info = function() {
      var info = {};
      forEach(caches, function(cache, cacheId) {
        info[cacheId] = cache.info();
      });
      return info;
    };


  /**
   * @ngdoc method
   * @name $cacheFactory#get
   *
   * @description
   * Get access to a cache object by the `cacheId` used when it was created.
   *
   * @param {string} cacheId Name or id of a cache to access.
   * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
   */
    cacheFactory.get = function(cacheId) {
      return caches[cacheId];
    };


    return cacheFactory;
  };
}

/**
 * @ngdoc service
 * @name $templateCache
 *
 * @description
 * The first time a template is used, it is loaded in the template cache for quick retrieval. You
 * can load templates directly into the cache in a `script` tag, or by consuming the
 * `$templateCache` service directly.
 *
 * Adding via the `script` tag:
 *
 * ```html
 *   <script type="text/ng-template" id="templateId.html">
 *     <p>This is the content of the template</p>
 *   </script>
 * ```
 *
 * **Note:** the `script` tag containing the template does not need to be included in the `head` of
 * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
 * element with ng-app attribute), otherwise the template will be ignored.
 *
 * Adding via the `$templateCache` service:
 *
 * ```js
 * var myApp = angular.module('myApp', []);
 * myApp.run(function($templateCache) {
 *   $templateCache.put('templateId.html', 'This is the content of the template');
 * });
 * ```
 *
 * To retrieve the template later, simply use it in your HTML:
 * ```html
 * <div ng-include=" 'templateId.html' "></div>
 * ```
 *
 * or get it via Javascript:
 * ```js
 * $templateCache.get('templateId.html')
 * ```
 *
 * See {@link ng.$cacheFactory $cacheFactory}.
 *
 */
function $TemplateCacheProvider() {
  this.$get = ['$cacheFactory', function($cacheFactory) {
    return $cacheFactory('templates');
  }];
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *     Any commits to this file should be reviewed with security in mind.  *
 *   Changes to this file can potentially create security vulnerabilities. *
 *          An approval from 2 Core members with history of modifying      *
 *                         this file is required.                          *
 *                                                                         *
 *  Does the change somehow allow for arbitrary javascript to be executed? *
 *    Or allows for someone to change the prototype of built-in objects?   *
 *     Or gives undesired access to variables likes document or window?    *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
 *
 * DOM-related variables:
 *
 * - "node" - DOM Node
 * - "element" - DOM Element or Node
 * - "$node" or "$element" - jqLite-wrapped node or element
 *
 *
 * Compiler related stuff:
 *
 * - "linkFn" - linking fn of a single directive
 * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
 * - "childLinkFn" -  function that aggregates all linking fns for child nodes of a particular node
 * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
 */


/**
 * @ngdoc service
 * @name $compile
 * @kind function
 *
 * @description
 * Compiles an HTML string or DOM into a template and produces a template function, which
 * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
 *
 * The compilation is a process of walking the DOM tree and matching DOM elements to
 * {@link ng.$compileProvider#directive directives}.
 *
 * <div class="alert alert-warning">
 * **Note:** This document is an in-depth reference of all directive options.
 * For a gentle introduction to directives with examples of common use cases,
 * see the {@link guide/directive directive guide}.
 * </div>
 *
 * ## Comprehensive Directive API
 *
 * There are many different options for a directive.
 *
 * The difference resides in the return value of the factory function.
 * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
 * or just the `postLink` function (all other properties will have the default values).
 *
 * <div class="alert alert-success">
 * **Best Practice:** It's recommended to use the "directive definition object" form.
 * </div>
 *
 * Here's an example directive declared with a Directive Definition Object:
 *
 * ```js
 *   var myModule = angular.module(...);
 *
 *   myModule.directive('directiveName', function factory(injectables) {
 *     var directiveDefinitionObject = {
 *       priority: 0,
 *       template: '<div></div>', // or // function(tElement, tAttrs) { ... },
 *       // or
 *       // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
 *       transclude: false,
 *       restrict: 'A',
 *       templateNamespace: 'html',
 *       scope: false,
 *       controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
 *       controllerAs: 'stringIdentifier',
 *       bindToController: false,
 *       require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
 *       compile: function compile(tElement, tAttrs, transclude) {
 *         return {
 *           pre: function preLink(scope, iElement, iAttrs, controller) { ... },
 *           post: function postLink(scope, iElement, iAttrs, controller) { ... }
 *         }
 *         // or
 *         // return function postLink( ... ) { ... }
 *       },
 *       // or
 *       // link: {
 *       //  pre: function preLink(scope, iElement, iAttrs, controller) { ... },
 *       //  post: function postLink(scope, iElement, iAttrs, controller) { ... }
 *       // }
 *       // or
 *       // link: function postLink( ... ) { ... }
 *     };
 *     return directiveDefinitionObject;
 *   });
 * ```
 *
 * <div class="alert alert-warning">
 * **Note:** Any unspecified options will use the default value. You can see the default values below.
 * </div>
 *
 * Therefore the above can be simplified as:
 *
 * ```js
 *   var myModule = angular.module(...);
 *
 *   myModule.directive('directiveName', function factory(injectables) {
 *     var directiveDefinitionObject = {
 *       link: function postLink(scope, iElement, iAttrs) { ... }
 *     };
 *     return directiveDefinitionObject;
 *     // or
 *     // return function postLink(scope, iElement, iAttrs) { ... }
 *   });
 * ```
 *
 *
 *
 * ### Directive Definition Object
 *
 * The directive definition object provides instructions to the {@link ng.$compile
 * compiler}. The attributes are:
 *
 * #### `multiElement`
 * When this property is set to true, the HTML compiler will collect DOM nodes between
 * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
 * together as the directive elements. It is recommended that this feature be used on directives
 * which are not strictly behavioural (such as {@link ngClick}), and which
 * do not manipulate or replace child nodes (such as {@link ngInclude}).
 *
 * #### `priority`
 * When there are multiple directives defined on a single DOM element, sometimes it
 * is necessary to specify the order in which the directives are applied. The `priority` is used
 * to sort the directives before their `compile` functions get called. Priority is defined as a
 * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
 * are also run in priority order, but post-link functions are run in reverse order. The order
 * of directives with the same priority is undefined. The default priority is `0`.
 *
 * #### `terminal`
 * If set to true then the current `priority` will be the last set of directives
 * which will execute (any directives at the current priority will still execute
 * as the order of execution on same `priority` is undefined). Note that expressions
 * and other directives used in the directive's template will also be excluded from execution.
 *
 * #### `scope`
 * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
 * same element request a new scope, only one new scope is created. The new scope rule does not
 * apply for the root of the template since the root of the template always gets a new scope.
 *
 * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
 * normal scope in that it does not prototypically inherit from the parent scope. This is useful
 * when creating reusable components, which should not accidentally read or modify data in the
 * parent scope.
 *
 * The 'isolate' scope takes an object hash which defines a set of local scope properties
 * derived from the parent scope. These local properties are useful for aliasing values for
 * templates. Locals definition is a hash of local scope property to its source:
 *
 * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
 *   always a string since DOM attributes are strings. If no `attr` name is specified  then the
 *   attribute name is assumed to be the same as the local name.
 *   Given `<widget my-attr="hello {{name}}">` and widget definition
 *   of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
 *   the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
 *   `localName` property on the widget scope. The `name` is read from the parent scope (not
 *   component scope).
 *
 * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
 *   parent scope property of name defined via the value of the `attr` attribute. If no `attr`
 *   name is specified then the attribute name is assumed to be the same as the local name.
 *   Given `<widget my-attr="parentModel">` and widget definition of
 *   `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
 *   value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
 *   in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
 *   scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
 *   can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
 *   you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
 *   `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
 *
 * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
 *   If no `attr` name is specified then the attribute name is assumed to be the same as the
 *   local name. Given `<widget my-attr="count = count + value">` and widget definition of
 *   `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
 *   a function wrapper for the `count = count + value` expression. Often it's desirable to
 *   pass data from the isolated scope via an expression to the parent scope, this can be
 *   done by passing a map of local variable names and values into the expression wrapper fn.
 *   For example, if the expression is `increment(amount)` then we can specify the amount value
 *   by calling the `localFn` as `localFn({amount: 22})`.
 *
 *
 * #### `bindToController`
 * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
 * allow a component to have its properties bound to the controller, rather than to scope. When the controller
 * is instantiated, the initial values of the isolate scope bindings are already available.
 *
 * #### `controller`
 * Controller constructor function. The controller is instantiated before the
 * pre-linking phase and it is shared with other directives (see
 * `require` attribute). This allows the directives to communicate with each other and augment
 * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
 *
 * * `$scope` - Current scope associated with the element
 * * `$element` - Current element
 * * `$attrs` - Current attributes object for the element
 * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
 *   `function([scope], cloneLinkingFn, futureParentElement)`.
 *    * `scope`: optional argument to override the scope.
 *    * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
 *    * `futureParentElement`:
 *        * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
 *        * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
 *        * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
 *          and when the `cloneLinkinFn` is passed,
 *          as those elements need to created and cloned in a special way when they are defined outside their
 *          usual containers (e.g. like `<svg>`).
 *        * See also the `directive.templateNamespace` property.
 *
 *
 * #### `require`
 * Require another directive and inject its controller as the fourth argument to the linking function. The
 * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
 * injected argument will be an array in corresponding order. If no such directive can be
 * found, or if the directive does not have a controller, then an error is raised (unless no link function
 * is specified, in which case error checking is skipped). The name can be prefixed with:
 *
 * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
 * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
 * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
 * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
 * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
 *   `null` to the `link` fn if not found.
 * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
 *   `null` to the `link` fn if not found.
 *
 *
 * #### `controllerAs`
 * Identifier name for a reference to the controller in the directive's scope.
 * This allows the controller to be referenced from the directive template. The directive
 * needs to define a scope for this configuration to be used. Useful in the case when
 * directive is used as component.
 *
 *
 * #### `restrict`
 * String of subset of `EACM` which restricts the directive to a specific directive
 * declaration style. If omitted, the defaults (elements and attributes) are used.
 *
 * * `E` - Element name (default): `<my-directive></my-directive>`
 * * `A` - Attribute (default): `<div my-directive="exp"></div>`
 * * `C` - Class: `<div class="my-directive: exp;"></div>`
 * * `M` - Comment: `<!-- directive: my-directive exp -->`
 *
 *
 * #### `templateNamespace`
 * String representing the document type used by the markup in the template.
 * AngularJS needs this information as those elements need to be created and cloned
 * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
 *
 * * `html` - All root nodes in the template are HTML. Root nodes may also be
 *   top-level elements such as `<svg>` or `<math>`.
 * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
 * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
 *
 * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
 *
 * #### `template`
 * HTML markup that may:
 * * Replace the contents of the directive's element (default).
 * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
 * * Wrap the contents of the directive's element (if `transclude` is true).
 *
 * Value may be:
 *
 * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
 * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
 *   function api below) and returns a string value.
 *
 *
 * #### `templateUrl`
 * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
 *
 * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
 * for later when the template has been resolved.  In the meantime it will continue to compile and link
 * sibling and parent elements as though this element had not contained any directives.
 *
 * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
 * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
 * case when only one deeply nested directive has `templateUrl`.
 *
 * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
 *
 * You can specify `templateUrl` as a string representing the URL or as a function which takes two
 * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
 * a string value representing the url.  In either case, the template URL is passed through {@link
 * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
 *
 *
 * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
 * specify what the template should replace. Defaults to `false`.
 *
 * * `true` - the template will replace the directive's element.
 * * `false` - the template will replace the contents of the directive's element.
 *
 * The replacement process migrates all of the attributes / classes from the old element to the new
 * one. See the {@link guide/directive#template-expanding-directive
 * Directives Guide} for an example.
 *
 * There are very few scenarios where element replacement is required for the application function,
 * the main one being reusable custom components that are used within SVG contexts
 * (because SVG doesn't work with custom elements in the DOM tree).
 *
 * #### `transclude`
 * Extract the contents of the element where the directive appears and make it available to the directive.
 * The contents are compiled and provided to the directive as a **transclusion function**. See the
 * {@link $compile#transclusion Transclusion} section below.
 *
 * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
 * directive's element or the entire element:
 *
 * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
 * * `'element'` - transclude the whole of the directive's element including any directives on this
 *   element that defined at a lower priority than this directive. When used, the `template`
 *   property is ignored.
 *
 *
 * #### `compile`
 *
 * ```js
 *   function compile(tElement, tAttrs, transclude) { ... }
 * ```
 *
 * The compile function deals with transforming the template DOM. Since most directives do not do
 * template transformation, it is not used often. The compile function takes the following arguments:
 *
 *   * `tElement` - template element - The element where the directive has been declared. It is
 *     safe to do template transformation on the element and child elements only.
 *
 *   * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
 *     between all directive compile functions.
 *
 *   * `transclude` -  [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
 *
 * <div class="alert alert-warning">
 * **Note:** The template instance and the link instance may be different objects if the template has
 * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
 * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
 * should be done in a linking function rather than in a compile function.
 * </div>

 * <div class="alert alert-warning">
 * **Note:** The compile function cannot handle directives that recursively use themselves in their
 * own templates or compile functions. Compiling these directives results in an infinite loop and a
 * stack overflow errors.
 *
 * This can be avoided by manually using $compile in the postLink function to imperatively compile
 * a directive's template instead of relying on automatic template compilation via `template` or
 * `templateUrl` declaration or manual compilation inside the compile function.
 * </div>
 *
 * <div class="alert alert-danger">
 * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
 *   e.g. does not know about the right outer scope. Please use the transclude function that is passed
 *   to the link function instead.
 * </div>

 * A compile function can have a return value which can be either a function or an object.
 *
 * * returning a (post-link) function - is equivalent to registering the linking function via the
 *   `link` property of the config object when the compile function is empty.
 *
 * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
 *   control when a linking function should be called during the linking phase. See info about
 *   pre-linking and post-linking functions below.
 *
 *
 * #### `link`
 * This property is used only if the `compile` property is not defined.
 *
 * ```js
 *   function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
 * ```
 *
 * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
 * executed after the template has been cloned. This is where most of the directive logic will be
 * put.
 *
 *   * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
 *     directive for registering {@link ng.$rootScope.Scope#$watch watches}.
 *
 *   * `iElement` - instance element - The element where the directive is to be used. It is safe to
 *     manipulate the children of the element only in `postLink` function since the children have
 *     already been linked.
 *
 *   * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
 *     between all directive linking functions.
 *
 *   * `controller` - the directive's required controller instance(s) - Instances are shared
 *     among all directives, which allows the directives to use the controllers as a communication
 *     channel. The exact value depends on the directive's `require` property:
 *       * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
 *       * `string`: the controller instance
 *       * `array`: array of controller instances
 *
 *     If a required controller cannot be found, and it is optional, the instance is `null`,
 *     otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
 *
 *     Note that you can also require the directive's own controller - it will be made available like
 *     like any other controller.
 *
 *   * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
 *     This is the same as the `$transclude`
 *     parameter of directive controllers, see there for details.
 *     `function([scope], cloneLinkingFn, futureParentElement)`.
 *
 * #### Pre-linking function
 *
 * Executed before the child elements are linked. Not safe to do DOM transformation since the
 * compiler linking function will fail to locate the correct elements for linking.
 *
 * #### Post-linking function
 *
 * Executed after the child elements are linked.
 *
 * Note that child elements that contain `templateUrl` directives will not have been compiled
 * and linked since they are waiting for their template to load asynchronously and their own
 * compilation and linking has been suspended until that occurs.
 *
 * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
 * for their async templates to be resolved.
 *
 *
 * ### Transclusion
 *
 * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
 * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
 * scope from where they were taken.
 *
 * Transclusion is used (often with {@link ngTransclude}) to insert the
 * original contents of a directive's element into a specified place in the template of the directive.
 * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
 * content has access to the properties on the scope from which it was taken, even if the directive
 * has isolated scope.
 * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
 *
 * This makes it possible for the widget to have private state for its template, while the transcluded
 * content has access to its originating scope.
 *
 * <div class="alert alert-warning">
 * **Note:** When testing an element transclude directive you must not place the directive at the root of the
 * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
 * Testing Transclusion Directives}.
 * </div>
 *
 * #### Transclusion Functions
 *
 * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
 * function** to the directive's `link` function and `controller`. This transclusion function is a special
 * **linking function** that will return the compiled contents linked to a new transclusion scope.
 *
 * <div class="alert alert-info">
 * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
 * ngTransclude will deal with it for us.
 * </div>
 *
 * If you want to manually control the insertion and removal of the transcluded content in your directive
 * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
 * object that contains the compiled DOM, which is linked to the correct transclusion scope.
 *
 * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
 * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
 * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
 *
 * <div class="alert alert-info">
 * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
 * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
 * </div>
 *
 * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
 * attach function**:
 *
 * ```js
 * var transcludedContent, transclusionScope;
 *
 * $transclude(function(clone, scope) {
 *   element.append(clone);
 *   transcludedContent = clone;
 *   transclusionScope = scope;
 * });
 * ```
 *
 * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
 * associated transclusion scope:
 *
 * ```js
 * transcludedContent.remove();
 * transclusionScope.$destroy();
 * ```
 *
 * <div class="alert alert-info">
 * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
 * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
 * then you are also responsible for calling `$destroy` on the transclusion scope.
 * </div>
 *
 * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
 * automatically destroy their transluded clones as necessary so you do not need to worry about this if
 * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
 *
 *
 * #### Transclusion Scopes
 *
 * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
 * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
 * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
 * was taken.
 *
 * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
 * like this:
 *
 * ```html
 * <div ng-app>
 *   <div isolate>
 *     <div transclusion>
 *     </div>
 *   </div>
 * </div>
 * ```
 *
 * The `$parent` scope hierarchy will look like this:
 *
 * ```
 * - $rootScope
 *   - isolate
 *     - transclusion
 * ```
 *
 * but the scopes will inherit prototypically from different scopes to their `$parent`.
 *
 * ```
 * - $rootScope
 *   - transclusion
 * - isolate
 * ```
 *
 *
 * ### Attributes
 *
 * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
 * `link()` or `compile()` functions. It has a variety of uses.
 *
 * accessing *Normalized attribute names:*
 * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
 * the attributes object allows for normalized access to
 *   the attributes.
 *
 * * *Directive inter-communication:* All directives share the same instance of the attributes
 *   object which allows the directives to use the attributes object as inter directive
 *   communication.
 *
 * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
 *   allowing other directives to read the interpolated value.
 *
 * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
 *   that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
 *   the only way to easily get the actual value because during the linking phase the interpolation
 *   hasn't been evaluated yet and so the value is at this time set to `undefined`.
 *
 * ```js
 * function linkingFn(scope, elm, attrs, ctrl) {
 *   // get the attribute value
 *   console.log(attrs.ngModel);
 *
 *   // change the attribute
 *   attrs.$set('ngModel', 'new value');
 *
 *   // observe changes to interpolated attribute
 *   attrs.$observe('ngModel', function(value) {
 *     console.log('ngModel has changed value to ' + value);
 *   });
 * }
 * ```
 *
 * ## Example
 *
 * <div class="alert alert-warning">
 * **Note**: Typically directives are registered with `module.directive`. The example below is
 * to illustrate how `$compile` works.
 * </div>
 *
 <example module="compileExample">
   <file name="index.html">
    <script>
      angular.module('compileExample', [], function($compileProvider) {
        // configure new 'compile' directive by passing a directive
        // factory function. The factory function injects the '$compile'
        $compileProvider.directive('compile', function($compile) {
          // directive factory creates a link function
          return function(scope, element, attrs) {
            scope.$watch(
              function(scope) {
                 // watch the 'compile' expression for changes
                return scope.$eval(attrs.compile);
              },
              function(value) {
                // when the 'compile' expression changes
                // assign it into the current DOM
                element.html(value);

                // compile the new DOM and link it to the current
                // scope.
                // NOTE: we only compile .childNodes so that
                // we don't get into infinite loop compiling ourselves
                $compile(element.contents())(scope);
              }
            );
          };
        });
      })
      .controller('GreeterController', ['$scope', function($scope) {
        $scope.name = 'Angular';
        $scope.html = 'Hello {{name}}';
      }]);
    </script>
    <div ng-controller="GreeterController">
      <input ng-model="name"> <br/>
      <textarea ng-model="html"></textarea> <br/>
      <div compile="html"></div>
    </div>
   </file>
   <file name="protractor.js" type="protractor">
     it('should auto compile', function() {
       var textarea = $('textarea');
       var output = $('div[compile]');
       // The initial state reads 'Hello Angular'.
       expect(output.getText()).toBe('Hello Angular');
       textarea.clear();
       textarea.sendKeys('{{name}}!');
       expect(output.getText()).toBe('Angular!');
     });
   </file>
 </example>

 *
 *
 * @param {string|DOMElement} element Element or HTML string to compile into a template function.
 * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
 *
 * <div class="alert alert-danger">
 * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
 *   e.g. will not use the right outer scope. Please pass the transclude function as a
 *   `parentBoundTranscludeFn` to the link function instead.
 * </div>
 *
 * @param {number} maxPriority only apply directives lower than given priority (Only effects the
 *                 root element(s), not their children)
 * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
 * (a DOM element/tree) to a scope. Where:
 *
 *  * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
 *  * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
 *  `template` and call the `cloneAttachFn` function allowing the caller to attach the
 *  cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
 *  called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
 *
 *      * `clonedElement` - is a clone of the original `element` passed into the compiler.
 *      * `scope` - is the current scope with which the linking function is working with.
 *
 *  * `options` - An optional object hash with linking options. If `options` is provided, then the following
 *  keys may be used to control linking behavior:
 *
 *      * `parentBoundTranscludeFn` - the transclude function made available to
 *        directives; if given, it will be passed through to the link functions of
 *        directives found in `element` during compilation.
 *      * `transcludeControllers` - an object hash with keys that map controller names
 *        to controller instances; if given, it will make the controllers
 *        available to directives.
 *      * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
 *        the cloned elements; only needed for transcludes that are allowed to contain non html
 *        elements (e.g. SVG elements). See also the directive.controller property.
 *
 * Calling the linking function returns the element of the template. It is either the original
 * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
 *
 * After linking the view is not updated until after a call to $digest which typically is done by
 * Angular automatically.
 *
 * If you need access to the bound view, there are two ways to do it:
 *
 * - If you are not asking the linking function to clone the template, create the DOM element(s)
 *   before you send them to the compiler and keep this reference around.
 *   ```js
 *     var element = $compile('<p>{{total}}</p>')(scope);
 *   ```
 *
 * - if on the other hand, you need the element to be cloned, the view reference from the original
 *   example would not point to the clone, but rather to the original template that was cloned. In
 *   this case, you can access the clone via the cloneAttachFn:
 *   ```js
 *     var templateElement = angular.element('<p>{{total}}</p>'),
 *         scope = ....;
 *
 *     var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
 *       //attach the clone to DOM document at the right place
 *     });
 *
 *     //now we have reference to the cloned DOM via `clonedElement`
 *   ```
 *
 *
 * For information on how the compiler works, see the
 * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
 */

var $compileMinErr = minErr('$compile');

/**
 * @ngdoc provider
 * @name $compileProvider
 *
 * @description
 */
$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
function $CompileProvider($provide, $$sanitizeUriProvider) {
  var hasDirectives = {},
      Suffix = 'Directive',
      COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
      CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
      ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
      REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;

  // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  // The assumption is that future DOM event attribute names will begin with
  // 'on' and be composed of only English letters.
  var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;

  function parseIsolateBindings(scope, directiveName, isController) {
    var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;

    var bindings = {};

    forEach(scope, function(definition, scopeName) {
      var match = definition.match(LOCAL_REGEXP);

      if (!match) {
        throw $compileMinErr('iscp',
            "Invalid {3} for directive '{0}'." +
            " Definition: {... {1}: '{2}' ...}",
            directiveName, scopeName, definition,
            (isController ? "controller bindings definition" :
            "isolate scope definition"));
      }

      bindings[scopeName] = {
        mode: match[1][0],
        collection: match[2] === '*',
        optional: match[3] === '?',
        attrName: match[4] || scopeName
      };
    });

    return bindings;
  }

  function parseDirectiveBindings(directive, directiveName) {
    var bindings = {
      isolateScope: null,
      bindToController: null
    };
    if (isObject(directive.scope)) {
      if (directive.bindToController === true) {
        bindings.bindToController = parseIsolateBindings(directive.scope,
                                                         directiveName, true);
        bindings.isolateScope = {};
      } else {
        bindings.isolateScope = parseIsolateBindings(directive.scope,
                                                     directiveName, false);
      }
    }
    if (isObject(directive.bindToController)) {
      bindings.bindToController =
          parseIsolateBindings(directive.bindToController, directiveName, true);
    }
    if (isObject(bindings.bindToController)) {
      var controller = directive.controller;
      var controllerAs = directive.controllerAs;
      if (!controller) {
        // There is no controller, there may or may not be a controllerAs property
        throw $compileMinErr('noctrl',
              "Cannot bind to controller without directive '{0}'s controller.",
              directiveName);
      } else if (!identifierForController(controller, controllerAs)) {
        // There is a controller, but no identifier or controllerAs property
        throw $compileMinErr('noident',
              "Cannot bind to controller without identifier for directive '{0}'.",
              directiveName);
      }
    }
    return bindings;
  }

  function assertValidDirectiveName(name) {
    var letter = name.charAt(0);
    if (!letter || letter !== lowercase(letter)) {
      throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
    }
    if (name !== name.trim()) {
      throw $compileMinErr('baddir',
            "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
            name);
    }
  }

  /**
   * @ngdoc method
   * @name $compileProvider#directive
   * @kind function
   *
   * @description
   * Register a new directive with the compiler.
   *
   * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
   *    will match as <code>ng-bind</code>), or an object map of directives where the keys are the
   *    names and the values are the factories.
   * @param {Function|Array} directiveFactory An injectable directive factory function. See
   *    {@link guide/directive} for more info.
   * @returns {ng.$compileProvider} Self for chaining.
   */
   this.directive = function registerDirective(name, directiveFactory) {
    assertNotHasOwnProperty(name, 'directive');
    if (isString(name)) {
      assertValidDirectiveName(name);
      assertArg(directiveFactory, 'directiveFactory');
      if (!hasDirectives.hasOwnProperty(name)) {
        hasDirectives[name] = [];
        $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
          function($injector, $exceptionHandler) {
            var directives = [];
            forEach(hasDirectives[name], function(directiveFactory, index) {
              try {
                var directive = $injector.invoke(directiveFactory);
                if (isFunction(directive)) {
                  directive = { compile: valueFn(directive) };
                } else if (!directive.compile && directive.link) {
                  directive.compile = valueFn(directive.link);
                }
                directive.priority = directive.priority || 0;
                directive.index = index;
                directive.name = directive.name || name;
                directive.require = directive.require || (directive.controller && directive.name);
                directive.restrict = directive.restrict || 'EA';
                var bindings = directive.$$bindings =
                    parseDirectiveBindings(directive, directive.name);
                if (isObject(bindings.isolateScope)) {
                  directive.$$isolateBindings = bindings.isolateScope;
                }
                directive.$$moduleName = directiveFactory.$$moduleName;
                directives.push(directive);
              } catch (e) {
                $exceptionHandler(e);
              }
            });
            return directives;
          }]);
      }
      hasDirectives[name].push(directiveFactory);
    } else {
      forEach(name, reverseParams(registerDirective));
    }
    return this;
  };


  /**
   * @ngdoc method
   * @name $compileProvider#aHrefSanitizationWhitelist
   * @kind function
   *
   * @description
   * Retrieves or overrides the default regular expression that is used for whitelisting of safe
   * urls during a[href] sanitization.
   *
   * The sanitization is a security measure aimed at preventing XSS attacks via html links.
   *
   * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
   * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
   * regular expression. If a match is found, the original url is written into the dom. Otherwise,
   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
   *
   * @param {RegExp=} regexp New regexp to whitelist urls with.
   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
   *    chaining otherwise.
   */
  this.aHrefSanitizationWhitelist = function(regexp) {
    if (isDefined(regexp)) {
      $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
      return this;
    } else {
      return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
    }
  };


  /**
   * @ngdoc method
   * @name $compileProvider#imgSrcSanitizationWhitelist
   * @kind function
   *
   * @description
   * Retrieves or overrides the default regular expression that is used for whitelisting of safe
   * urls during img[src] sanitization.
   *
   * The sanitization is a security measure aimed at prevent XSS attacks via html links.
   *
   * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
   * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
   * regular expression. If a match is found, the original url is written into the dom. Otherwise,
   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
   *
   * @param {RegExp=} regexp New regexp to whitelist urls with.
   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
   *    chaining otherwise.
   */
  this.imgSrcSanitizationWhitelist = function(regexp) {
    if (isDefined(regexp)) {
      $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
      return this;
    } else {
      return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
    }
  };

  /**
   * @ngdoc method
   * @name  $compileProvider#debugInfoEnabled
   *
   * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
   * current debugInfoEnabled state
   * @returns {*} current value if used as getter or itself (chaining) if used as setter
   *
   * @kind function
   *
   * @description
   * Call this method to enable/disable various debug runtime information in the compiler such as adding
   * binding information and a reference to the current scope on to DOM elements.
   * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
   * * `ng-binding` CSS class
   * * `$binding` data property containing an array of the binding expressions
   *
   * You may want to disable this in production for a significant performance boost. See
   * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
   *
   * The default value is true.
   */
  var debugInfoEnabled = true;
  this.debugInfoEnabled = function(enabled) {
    if (isDefined(enabled)) {
      debugInfoEnabled = enabled;
      return this;
    }
    return debugInfoEnabled;
  };

  this.$get = [
            '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
            '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
    function($injector,   $interpolate,   $exceptionHandler,   $templateRequest,   $parse,
             $controller,   $rootScope,   $document,   $sce,   $animate,   $$sanitizeUri) {

    var Attributes = function(element, attributesToCopy) {
      if (attributesToCopy) {
        var keys = Object.keys(attributesToCopy);
        var i, l, key;

        for (i = 0, l = keys.length; i < l; i++) {
          key = keys[i];
          this[key] = attributesToCopy[key];
        }
      } else {
        this.$attr = {};
      }

      this.$$element = element;
    };

    Attributes.prototype = {
      /**
       * @ngdoc method
       * @name $compile.directive.Attributes#$normalize
       * @kind function
       *
       * @description
       * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
       * `data-`) to its normalized, camelCase form.
       *
       * Also there is special case for Moz prefix starting with upper case letter.
       *
       * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
       *
       * @param {string} name Name to normalize
       */
      $normalize: directiveNormalize,


      /**
       * @ngdoc method
       * @name $compile.directive.Attributes#$addClass
       * @kind function
       *
       * @description
       * Adds the CSS class value specified by the classVal parameter to the element. If animations
       * are enabled then an animation will be triggered for the class addition.
       *
       * @param {string} classVal The className value that will be added to the element
       */
      $addClass: function(classVal) {
        if (classVal && classVal.length > 0) {
          $animate.addClass(this.$$element, classVal);
        }
      },

      /**
       * @ngdoc method
       * @name $compile.directive.Attributes#$removeClass
       * @kind function
       *
       * @description
       * Removes the CSS class value specified by the classVal parameter from the element. If
       * animations are enabled then an animation will be triggered for the class removal.
       *
       * @param {string} classVal The className value that will be removed from the element
       */
      $removeClass: function(classVal) {
        if (classVal && classVal.length > 0) {
          $animate.removeClass(this.$$element, classVal);
        }
      },

      /**
       * @ngdoc method
       * @name $compile.directive.Attributes#$updateClass
       * @kind function
       *
       * @description
       * Adds and removes the appropriate CSS class values to the element based on the difference
       * between the new and old CSS class values (specified as newClasses and oldClasses).
       *
       * @param {string} newClasses The current CSS className value
       * @param {string} oldClasses The former CSS className value
       */
      $updateClass: function(newClasses, oldClasses) {
        var toAdd = tokenDifference(newClasses, oldClasses);
        if (toAdd && toAdd.length) {
          $animate.addClass(this.$$element, toAdd);
        }

        var toRemove = tokenDifference(oldClasses, newClasses);
        if (toRemove && toRemove.length) {
          $animate.removeClass(this.$$element, toRemove);
        }
      },

      /**
       * Set a normalized attribute on the element in a way such that all directives
       * can share the attribute. This function properly handles boolean attributes.
       * @param {string} key Normalized key. (ie ngAttribute)
       * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
       * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
       *     Defaults to true.
       * @param {string=} attrName Optional none normalized name. Defaults to key.
       */
      $set: function(key, value, writeAttr, attrName) {
        // TODO: decide whether or not to throw an error if "class"
        //is set through this function since it may cause $updateClass to
        //become unstable.

        var node = this.$$element[0],
            booleanKey = getBooleanAttrName(node, key),
            aliasedKey = getAliasedAttrName(node, key),
            observer = key,
            nodeName;

        if (booleanKey) {
          this.$$element.prop(key, value);
          attrName = booleanKey;
        } else if (aliasedKey) {
          this[aliasedKey] = value;
          observer = aliasedKey;
        }

        this[key] = value;

        // translate normalized key to actual key
        if (attrName) {
          this.$attr[key] = attrName;
        } else {
          attrName = this.$attr[key];
          if (!attrName) {
            this.$attr[key] = attrName = snake_case(key, '-');
          }
        }

        nodeName = nodeName_(this.$$element);

        if ((nodeName === 'a' && key === 'href') ||
            (nodeName === 'img' && key === 'src')) {
          // sanitize a[href] and img[src] values
          this[key] = value = $$sanitizeUri(value, key === 'src');
        } else if (nodeName === 'img' && key === 'srcset') {
          // sanitize img[srcset] values
          var result = "";

          // first check if there are spaces because it's not the same pattern
          var trimmedSrcset = trim(value);
          //                (   999x   ,|   999w   ,|   ,|,   )
          var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
          var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;

          // split srcset into tuple of uri and descriptor except for the last item
          var rawUris = trimmedSrcset.split(pattern);

          // for each tuples
          var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
          for (var i = 0; i < nbrUrisWith2parts; i++) {
            var innerIdx = i * 2;
            // sanitize the uri
            result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
            // add the descriptor
            result += (" " + trim(rawUris[innerIdx + 1]));
          }

          // split the last item into uri and descriptor
          var lastTuple = trim(rawUris[i * 2]).split(/\s/);

          // sanitize the last uri
          result += $$sanitizeUri(trim(lastTuple[0]), true);

          // and add the last descriptor if any
          if (lastTuple.length === 2) {
            result += (" " + trim(lastTuple[1]));
          }
          this[key] = value = result;
        }

        if (writeAttr !== false) {
          if (value === null || value === undefined) {
            this.$$element.removeAttr(attrName);
          } else {
            this.$$element.attr(attrName, value);
          }
        }

        // fire observers
        var $$observers = this.$$observers;
        $$observers && forEach($$observers[observer], function(fn) {
          try {
            fn(value);
          } catch (e) {
            $exceptionHandler(e);
          }
        });
      },


      /**
       * @ngdoc method
       * @name $compile.directive.Attributes#$observe
       * @kind function
       *
       * @description
       * Observes an interpolated attribute.
       *
       * The observer function will be invoked once during the next `$digest` following
       * compilation. The observer is then invoked whenever the interpolated value
       * changes.
       *
       * @param {string} key Normalized key. (ie ngAttribute) .
       * @param {function(interpolatedValue)} fn Function that will be called whenever
                the interpolated value of the attribute changes.
       *        See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
       * @returns {function()} Returns a deregistration function for this observer.
       */
      $observe: function(key, fn) {
        var attrs = this,
            $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
            listeners = ($$observers[key] || ($$observers[key] = []));

        listeners.push(fn);
        $rootScope.$evalAsync(function() {
          if (!listeners.$$inter && attrs.hasOwnProperty(key)) {
            // no one registered attribute interpolation function, so lets call it manually
            fn(attrs[key]);
          }
        });

        return function() {
          arrayRemove(listeners, fn);
        };
      }
    };


    function safeAddClass($element, className) {
      try {
        $element.addClass(className);
      } catch (e) {
        // ignore, since it means that we are trying to set class on
        // SVG element, where class name is read-only.
      }
    }


    var startSymbol = $interpolate.startSymbol(),
        endSymbol = $interpolate.endSymbol(),
        denormalizeTemplate = (startSymbol == '{{' || endSymbol  == '}}')
            ? identity
            : function denormalizeTemplate(template) {
              return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
        },
        NG_ATTR_BINDING = /^ngAttr[A-Z]/;

    compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
      var bindings = $element.data('$binding') || [];

      if (isArray(binding)) {
        bindings = bindings.concat(binding);
      } else {
        bindings.push(binding);
      }

      $element.data('$binding', bindings);
    } : noop;

    compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
      safeAddClass($element, 'ng-binding');
    } : noop;

    compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
      var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
      $element.data(dataName, scope);
    } : noop;

    compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
      safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
    } : noop;

    return compile;

    //================================

    function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
                        previousCompileContext) {
      if (!($compileNodes instanceof jqLite)) {
        // jquery always rewraps, whereas we need to preserve the original selector so that we can
        // modify it.
        $compileNodes = jqLite($compileNodes);
      }
      // We can not compile top level text elements since text nodes can be merged and we will
      // not be able to attach scope data to them, so we will wrap them in <span>
      forEach($compileNodes, function(node, index) {
        if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
          $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
        }
      });
      var compositeLinkFn =
              compileNodes($compileNodes, transcludeFn, $compileNodes,
                           maxPriority, ignoreDirective, previousCompileContext);
      compile.$$addScopeClass($compileNodes);
      var namespace = null;
      return function publicLinkFn(scope, cloneConnectFn, options) {
        assertArg(scope, 'scope');

        options = options || {};
        var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
          transcludeControllers = options.transcludeControllers,
          futureParentElement = options.futureParentElement;

        // When `parentBoundTranscludeFn` is passed, it is a
        // `controllersBoundTransclude` function (it was previously passed
        // as `transclude` to directive.link) so we must unwrap it to get
        // its `boundTranscludeFn`
        if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
          parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
        }

        if (!namespace) {
          namespace = detectNamespaceForChildElements(futureParentElement);
        }
        var $linkNode;
        if (namespace !== 'html') {
          // When using a directive with replace:true and templateUrl the $compileNodes
          // (or a child element inside of them)
          // might change, so we need to recreate the namespace adapted compileNodes
          // for call to the link function.
          // Note: This will already clone the nodes...
          $linkNode = jqLite(
            wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
          );
        } else if (cloneConnectFn) {
          // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
          // and sometimes changes the structure of the DOM.
          $linkNode = JQLitePrototype.clone.call($compileNodes);
        } else {
          $linkNode = $compileNodes;
        }

        if (transcludeControllers) {
          for (var controllerName in transcludeControllers) {
            $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
          }
        }

        compile.$$addScopeInfo($linkNode, scope);

        if (cloneConnectFn) cloneConnectFn($linkNode, scope);
        if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
        return $linkNode;
      };
    }

    function detectNamespaceForChildElements(parentElement) {
      // TODO: Make this detect MathML as well...
      var node = parentElement && parentElement[0];
      if (!node) {
        return 'html';
      } else {
        return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
      }
    }

    /**
     * Compile function matches each node in nodeList against the directives. Once all directives
     * for a particular node are collected their compile functions are executed. The compile
     * functions return values - the linking functions - are combined into a composite linking
     * function, which is the a linking function for the node.
     *
     * @param {NodeList} nodeList an array of nodes or NodeList to compile
     * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
     *        scope argument is auto-generated to the new child of the transcluded parent scope.
     * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
     *        the rootElement must be set the jqLite collection of the compile root. This is
     *        needed so that the jqLite collection items can be replaced with widgets.
     * @param {number=} maxPriority Max directive priority.
     * @returns {Function} A composite linking function of all of the matched directives or null.
     */
    function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
                            previousCompileContext) {
      var linkFns = [],
          attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;

      for (var i = 0; i < nodeList.length; i++) {
        attrs = new Attributes();

        // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
        directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
                                        ignoreDirective);

        nodeLinkFn = (directives.length)
            ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
                                      null, [], [], previousCompileContext)
            : null;

        if (nodeLinkFn && nodeLinkFn.scope) {
          compile.$$addScopeClass(attrs.$$element);
        }

        childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
                      !(childNodes = nodeList[i].childNodes) ||
                      !childNodes.length)
            ? null
            : compileNodes(childNodes,
                 nodeLinkFn ? (
                  (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
                     && nodeLinkFn.transclude) : transcludeFn);

        if (nodeLinkFn || childLinkFn) {
          linkFns.push(i, nodeLinkFn, childLinkFn);
          linkFnFound = true;
          nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
        }

        //use the previous context only for the first element in the virtual group
        previousCompileContext = null;
      }

      // return a linking function if we have found anything, null otherwise
      return linkFnFound ? compositeLinkFn : null;

      function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
        var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
        var stableNodeList;


        if (nodeLinkFnFound) {
          // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
          // offsets don't get screwed up
          var nodeListLength = nodeList.length;
          stableNodeList = new Array(nodeListLength);

          // create a sparse array by only copying the elements which have a linkFn
          for (i = 0; i < linkFns.length; i+=3) {
            idx = linkFns[i];
            stableNodeList[idx] = nodeList[idx];
          }
        } else {
          stableNodeList = nodeList;
        }

        for (i = 0, ii = linkFns.length; i < ii;) {
          node = stableNodeList[linkFns[i++]];
          nodeLinkFn = linkFns[i++];
          childLinkFn = linkFns[i++];

          if (nodeLinkFn) {
            if (nodeLinkFn.scope) {
              childScope = scope.$new();
              compile.$$addScopeInfo(jqLite(node), childScope);
              var destroyBindings = nodeLinkFn.$$destroyBindings;
              if (destroyBindings) {
                nodeLinkFn.$$destroyBindings = null;
                childScope.$on('$destroyed', destroyBindings);
              }
            } else {
              childScope = scope;
            }

            if (nodeLinkFn.transcludeOnThisElement) {
              childBoundTranscludeFn = createBoundTranscludeFn(
                  scope, nodeLinkFn.transclude, parentBoundTranscludeFn);

            } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
              childBoundTranscludeFn = parentBoundTranscludeFn;

            } else if (!parentBoundTranscludeFn && transcludeFn) {
              childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);

            } else {
              childBoundTranscludeFn = null;
            }

            nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn,
                       nodeLinkFn);

          } else if (childLinkFn) {
            childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
          }
        }
      }
    }

    function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {

      var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {

        if (!transcludedScope) {
          transcludedScope = scope.$new(false, containingScope);
          transcludedScope.$$transcluded = true;
        }

        return transcludeFn(transcludedScope, cloneFn, {
          parentBoundTranscludeFn: previousBoundTranscludeFn,
          transcludeControllers: controllers,
          futureParentElement: futureParentElement
        });
      };

      return boundTranscludeFn;
    }

    /**
     * Looks for directives on the given node and adds them to the directive collection which is
     * sorted.
     *
     * @param node Node to search.
     * @param directives An array to which the directives are added to. This array is sorted before
     *        the function returns.
     * @param attrs The shared attrs object which is used to populate the normalized attributes.
     * @param {number=} maxPriority Max directive priority.
     */
    function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
      var nodeType = node.nodeType,
          attrsMap = attrs.$attr,
          match,
          className;

      switch (nodeType) {
        case NODE_TYPE_ELEMENT: /* Element */
          // use the node name: <directive>
          addDirective(directives,
              directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);

          // iterate over the attributes
          for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
                   j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
            var attrStartName = false;
            var attrEndName = false;

            attr = nAttrs[j];
            name = attr.name;
            value = trim(attr.value);

            // support ngAttr attribute binding
            ngAttrName = directiveNormalize(name);
            if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
              name = name.replace(PREFIX_REGEXP, '')
                .substr(8).replace(/_(.)/g, function(match, letter) {
                  return letter.toUpperCase();
                });
            }

            var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
            if (directiveIsMultiElement(directiveNName)) {
              if (ngAttrName === directiveNName + 'Start') {
                attrStartName = name;
                attrEndName = name.substr(0, name.length - 5) + 'end';
                name = name.substr(0, name.length - 6);
              }
            }

            nName = directiveNormalize(name.toLowerCase());
            attrsMap[nName] = name;
            if (isNgAttr || !attrs.hasOwnProperty(nName)) {
                attrs[nName] = value;
                if (getBooleanAttrName(node, nName)) {
                  attrs[nName] = true; // presence means true
                }
            }
            addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
            addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
                          attrEndName);
          }

          // use class as directive
          className = node.className;
          if (isObject(className)) {
              // Maybe SVGAnimatedString
              className = className.animVal;
          }
          if (isString(className) && className !== '') {
            while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
              nName = directiveNormalize(match[2]);
              if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
                attrs[nName] = trim(match[3]);
              }
              className = className.substr(match.index + match[0].length);
            }
          }
          break;
        case NODE_TYPE_TEXT: /* Text Node */
          if (msie === 11) {
            // Workaround for #11781
            while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
              node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
              node.parentNode.removeChild(node.nextSibling);
            }
          }
          addTextInterpolateDirective(directives, node.nodeValue);
          break;
        case NODE_TYPE_COMMENT: /* Comment */
          try {
            match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
            if (match) {
              nName = directiveNormalize(match[1]);
              if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
                attrs[nName] = trim(match[2]);
              }
            }
          } catch (e) {
            // turns out that under some circumstances IE9 throws errors when one attempts to read
            // comment's node value.
            // Just ignore it and continue. (Can't seem to reproduce in test case.)
          }
          break;
      }

      directives.sort(byPriority);
      return directives;
    }

    /**
     * Given a node with an directive-start it collects all of the siblings until it finds
     * directive-end.
     * @param node
     * @param attrStart
     * @param attrEnd
     * @returns {*}
     */
    function groupScan(node, attrStart, attrEnd) {
      var nodes = [];
      var depth = 0;
      if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
        do {
          if (!node) {
            throw $compileMinErr('uterdir',
                      "Unterminated attribute, found '{0}' but no matching '{1}' found.",
                      attrStart, attrEnd);
          }
          if (node.nodeType == NODE_TYPE_ELEMENT) {
            if (node.hasAttribute(attrStart)) depth++;
            if (node.hasAttribute(attrEnd)) depth--;
          }
          nodes.push(node);
          node = node.nextSibling;
        } while (depth > 0);
      } else {
        nodes.push(node);
      }

      return jqLite(nodes);
    }

    /**
     * Wrapper for linking function which converts normal linking function into a grouped
     * linking function.
     * @param linkFn
     * @param attrStart
     * @param attrEnd
     * @returns {Function}
     */
    function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
      return function(scope, element, attrs, controllers, transcludeFn) {
        element = groupScan(element[0], attrStart, attrEnd);
        return linkFn(scope, element, attrs, controllers, transcludeFn);
      };
    }

    /**
     * Once the directives have been collected, their compile functions are executed. This method
     * is responsible for inlining directive templates as well as terminating the application
     * of the directives if the terminal directive has been reached.
     *
     * @param {Array} directives Array of collected directives to execute their compile function.
     *        this needs to be pre-sorted by priority order.
     * @param {Node} compileNode The raw DOM node to apply the compile functions to
     * @param {Object} templateAttrs The shared attribute function
     * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
     *                                                  scope argument is auto-generated to the new
     *                                                  child of the transcluded parent scope.
     * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
     *                              argument has the root jqLite array so that we can replace nodes
     *                              on it.
     * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
     *                                           compiling the transclusion.
     * @param {Array.<Function>} preLinkFns
     * @param {Array.<Function>} postLinkFns
     * @param {Object} previousCompileContext Context used for previous compilation of the current
     *                                        node
     * @returns {Function} linkFn
     */
    function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
                                   jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
                                   previousCompileContext) {
      previousCompileContext = previousCompileContext || {};

      var terminalPriority = -Number.MAX_VALUE,
          newScopeDirective = previousCompileContext.newScopeDirective,
          controllerDirectives = previousCompileContext.controllerDirectives,
          newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
          templateDirective = previousCompileContext.templateDirective,
          nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
          hasTranscludeDirective = false,
          hasTemplate = false,
          hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
          $compileNode = templateAttrs.$$element = jqLite(compileNode),
          directive,
          directiveName,
          $template,
          replaceDirective = originalReplaceDirective,
          childTranscludeFn = transcludeFn,
          linkFn,
          directiveValue;

      // executes all directives on the current element
      for (var i = 0, ii = directives.length; i < ii; i++) {
        directive = directives[i];
        var attrStart = directive.$$start;
        var attrEnd = directive.$$end;

        // collect multiblock sections
        if (attrStart) {
          $compileNode = groupScan(compileNode, attrStart, attrEnd);
        }
        $template = undefined;

        if (terminalPriority > directive.priority) {
          break; // prevent further processing of directives
        }

        if (directiveValue = directive.scope) {

          // skip the check for directives with async templates, we'll check the derived sync
          // directive when the template arrives
          if (!directive.templateUrl) {
            if (isObject(directiveValue)) {
              // This directive is trying to add an isolated scope.
              // Check that there is no scope of any kind already
              assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
                                directive, $compileNode);
              newIsolateScopeDirective = directive;
            } else {
              // This directive is trying to add a child scope.
              // Check that there is no isolated scope already
              assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
                                $compileNode);
            }
          }

          newScopeDirective = newScopeDirective || directive;
        }

        directiveName = directive.name;

        if (!directive.templateUrl && directive.controller) {
          directiveValue = directive.controller;
          controllerDirectives = controllerDirectives || createMap();
          assertNoDuplicate("'" + directiveName + "' controller",
              controllerDirectives[directiveName], directive, $compileNode);
          controllerDirectives[directiveName] = directive;
        }

        if (directiveValue = directive.transclude) {
          hasTranscludeDirective = true;

          // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
          // This option should only be used by directives that know how to safely handle element transclusion,
          // where the transcluded nodes are added or replaced after linking.
          if (!directive.$$tlb) {
            assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
            nonTlbTranscludeDirective = directive;
          }

          if (directiveValue == 'element') {
            hasElementTranscludeDirective = true;
            terminalPriority = directive.priority;
            $template = $compileNode;
            $compileNode = templateAttrs.$$element =
                jqLite(document.createComment(' ' + directiveName + ': ' +
                                              templateAttrs[directiveName] + ' '));
            compileNode = $compileNode[0];
            replaceWith(jqCollection, sliceArgs($template), compileNode);

            childTranscludeFn = compile($template, transcludeFn, terminalPriority,
                                        replaceDirective && replaceDirective.name, {
                                          // Don't pass in:
                                          // - controllerDirectives - otherwise we'll create duplicates controllers
                                          // - newIsolateScopeDirective or templateDirective - combining templates with
                                          //   element transclusion doesn't make sense.
                                          //
                                          // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
                                          // on the same element more than once.
                                          nonTlbTranscludeDirective: nonTlbTranscludeDirective
                                        });
          } else {
            $template = jqLite(jqLiteClone(compileNode)).contents();
            $compileNode.empty(); // clear contents
            childTranscludeFn = compile($template, transcludeFn);
          }
        }

        if (directive.template) {
          hasTemplate = true;
          assertNoDuplicate('template', templateDirective, directive, $compileNode);
          templateDirective = directive;

          directiveValue = (isFunction(directive.template))
              ? directive.template($compileNode, templateAttrs)
              : directive.template;

          directiveValue = denormalizeTemplate(directiveValue);

          if (directive.replace) {
            replaceDirective = directive;
            if (jqLiteIsTextNode(directiveValue)) {
              $template = [];
            } else {
              $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
            }
            compileNode = $template[0];

            if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
              throw $compileMinErr('tplrt',
                  "Template for directive '{0}' must have exactly one root element. {1}",
                  directiveName, '');
            }

            replaceWith(jqCollection, $compileNode, compileNode);

            var newTemplateAttrs = {$attr: {}};

            // combine directives from the original node and from the template:
            // - take the array of directives for this element
            // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
            // - collect directives from the template and sort them by priority
            // - combine directives as: processed + template + unprocessed
            var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
            var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));

            if (newIsolateScopeDirective) {
              markDirectivesAsIsolate(templateDirectives);
            }
            directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
            mergeTemplateAttributes(templateAttrs, newTemplateAttrs);

            ii = directives.length;
          } else {
            $compileNode.html(directiveValue);
          }
        }

        if (directive.templateUrl) {
          hasTemplate = true;
          assertNoDuplicate('template', templateDirective, directive, $compileNode);
          templateDirective = directive;

          if (directive.replace) {
            replaceDirective = directive;
          }

          nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
              templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
                controllerDirectives: controllerDirectives,
                newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
                newIsolateScopeDirective: newIsolateScopeDirective,
                templateDirective: templateDirective,
                nonTlbTranscludeDirective: nonTlbTranscludeDirective
              });
          ii = directives.length;
        } else if (directive.compile) {
          try {
            linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
            if (isFunction(linkFn)) {
              addLinkFns(null, linkFn, attrStart, attrEnd);
            } else if (linkFn) {
              addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
            }
          } catch (e) {
            $exceptionHandler(e, startingTag($compileNode));
          }
        }

        if (directive.terminal) {
          nodeLinkFn.terminal = true;
          terminalPriority = Math.max(terminalPriority, directive.priority);
        }

      }

      nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
      nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
      nodeLinkFn.templateOnThisElement = hasTemplate;
      nodeLinkFn.transclude = childTranscludeFn;

      previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;

      // might be normal or delayed nodeLinkFn depending on if templateUrl is present
      return nodeLinkFn;

      ////////////////////

      function addLinkFns(pre, post, attrStart, attrEnd) {
        if (pre) {
          if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
          pre.require = directive.require;
          pre.directiveName = directiveName;
          if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
            pre = cloneAndAnnotateFn(pre, {isolateScope: true});
          }
          preLinkFns.push(pre);
        }
        if (post) {
          if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
          post.require = directive.require;
          post.directiveName = directiveName;
          if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
            post = cloneAndAnnotateFn(post, {isolateScope: true});
          }
          postLinkFns.push(post);
        }
      }


      function getControllers(directiveName, require, $element, elementControllers) {
        var value;

        if (isString(require)) {
          var match = require.match(REQUIRE_PREFIX_REGEXP);
          var name = require.substring(match[0].length);
          var inheritType = match[1] || match[3];
          var optional = match[2] === '?';

          //If only parents then start at the parent element
          if (inheritType === '^^') {
            $element = $element.parent();
          //Otherwise attempt getting the controller from elementControllers in case
          //the element is transcluded (and has no data) and to avoid .data if possible
          } else {
            value = elementControllers && elementControllers[name];
            value = value && value.instance;
          }

          if (!value) {
            var dataName = '$' + name + 'Controller';
            value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
          }

          if (!value && !optional) {
            throw $compileMinErr('ctreq',
                "Controller '{0}', required by directive '{1}', can't be found!",
                name, directiveName);
          }
        } else if (isArray(require)) {
          value = [];
          for (var i = 0, ii = require.length; i < ii; i++) {
            value[i] = getControllers(directiveName, require[i], $element, elementControllers);
          }
        }

        return value || null;
      }

      function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
        var elementControllers = createMap();
        for (var controllerKey in controllerDirectives) {
          var directive = controllerDirectives[controllerKey];
          var locals = {
            $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
            $element: $element,
            $attrs: attrs,
            $transclude: transcludeFn
          };

          var controller = directive.controller;
          if (controller == '@') {
            controller = attrs[directive.name];
          }

          var controllerInstance = $controller(controller, locals, true, directive.controllerAs);

          // For directives with element transclusion the element is a comment,
          // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
          // clean up (http://bugs.jquery.com/ticket/8335).
          // Instead, we save the controllers for the element in a local hash and attach to .data
          // later, once we have the actual element.
          elementControllers[directive.name] = controllerInstance;
          if (!hasElementTranscludeDirective) {
            $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
          }
        }
        return elementControllers;
      }

      function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn,
                          thisLinkFn) {
        var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
            attrs;

        if (compileNode === linkNode) {
          attrs = templateAttrs;
          $element = templateAttrs.$$element;
        } else {
          $element = jqLite(linkNode);
          attrs = new Attributes($element, templateAttrs);
        }

        if (newIsolateScopeDirective) {
          isolateScope = scope.$new(true);
        }

        if (boundTranscludeFn) {
          // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
          // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
          transcludeFn = controllersBoundTransclude;
          transcludeFn.$$boundTransclude = boundTranscludeFn;
        }

        if (controllerDirectives) {
          elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
        }

        if (newIsolateScopeDirective) {
          // Initialize isolate scope bindings for new isolate scope directive.
          compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
              templateDirective === newIsolateScopeDirective.$$originalDirective)));
          compile.$$addScopeClass($element, true);
          isolateScope.$$isolateBindings =
              newIsolateScopeDirective.$$isolateBindings;
          initializeDirectiveBindings(scope, attrs, isolateScope,
                                      isolateScope.$$isolateBindings,
                                      newIsolateScopeDirective, isolateScope);
        }
        if (elementControllers) {
          // Initialize bindToController bindings for new/isolate scopes
          var scopeDirective = newIsolateScopeDirective || newScopeDirective;
          var bindings;
          var controllerForBindings;
          if (scopeDirective && elementControllers[scopeDirective.name]) {
            bindings = scopeDirective.$$bindings.bindToController;
            controller = elementControllers[scopeDirective.name];

            if (controller && controller.identifier && bindings) {
              controllerForBindings = controller;
              thisLinkFn.$$destroyBindings =
                  initializeDirectiveBindings(scope, attrs, controller.instance,
                                              bindings, scopeDirective);
            }
          }
          for (i in elementControllers) {
            controller = elementControllers[i];
            var controllerResult = controller();

            if (controllerResult !== controller.instance) {
              // If the controller constructor has a return value, overwrite the instance
              // from setupControllers and update the element data
              controller.instance = controllerResult;
              $element.data('$' + i + 'Controller', controllerResult);
              if (controller === controllerForBindings) {
                // Remove and re-install bindToController bindings
                thisLinkFn.$$destroyBindings();
                thisLinkFn.$$destroyBindings =
                  initializeDirectiveBindings(scope, attrs, controllerResult, bindings, scopeDirective);
              }
            }
          }
        }

        // PRELINKING
        for (i = 0, ii = preLinkFns.length; i < ii; i++) {
          linkFn = preLinkFns[i];
          invokeLinkFn(linkFn,
              linkFn.isolateScope ? isolateScope : scope,
              $element,
              attrs,
              linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
              transcludeFn
          );
        }

        // RECURSION
        // We only pass the isolate scope, if the isolate directive has a template,
        // otherwise the child elements do not belong to the isolate directive.
        var scopeToChild = scope;
        if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
          scopeToChild = isolateScope;
        }
        childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);

        // POSTLINKING
        for (i = postLinkFns.length - 1; i >= 0; i--) {
          linkFn = postLinkFns[i];
          invokeLinkFn(linkFn,
              linkFn.isolateScope ? isolateScope : scope,
              $element,
              attrs,
              linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
              transcludeFn
          );
        }

        // This is the function that is injected as `$transclude`.
        // Note: all arguments are optional!
        function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
          var transcludeControllers;

          // No scope passed in:
          if (!isScope(scope)) {
            futureParentElement = cloneAttachFn;
            cloneAttachFn = scope;
            scope = undefined;
          }

          if (hasElementTranscludeDirective) {
            transcludeControllers = elementControllers;
          }
          if (!futureParentElement) {
            futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
          }
          return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
        }
      }
    }

    function markDirectivesAsIsolate(directives) {
      // mark all directives as needing isolate scope.
      for (var j = 0, jj = directives.length; j < jj; j++) {
        directives[j] = inherit(directives[j], {$$isolateScope: true});
      }
    }

    /**
     * looks up the directive and decorates it with exception handling and proper parameters. We
     * call this the boundDirective.
     *
     * @param {string} name name of the directive to look up.
     * @param {string} location The directive must be found in specific format.
     *   String containing any of theses characters:
     *
     *   * `E`: element name
     *   * `A': attribute
     *   * `C`: class
     *   * `M`: comment
     * @returns {boolean} true if directive was added.
     */
    function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
                          endAttrName) {
      if (name === ignoreDirective) return null;
      var match = null;
      if (hasDirectives.hasOwnProperty(name)) {
        for (var directive, directives = $injector.get(name + Suffix),
            i = 0, ii = directives.length; i < ii; i++) {
          try {
            directive = directives[i];
            if ((maxPriority === undefined || maxPriority > directive.priority) &&
                 directive.restrict.indexOf(location) != -1) {
              if (startAttrName) {
                directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
              }
              tDirectives.push(directive);
              match = directive;
            }
          } catch (e) { $exceptionHandler(e); }
        }
      }
      return match;
    }


    /**
     * looks up the directive and returns true if it is a multi-element directive,
     * and therefore requires DOM nodes between -start and -end markers to be grouped
     * together.
     *
     * @param {string} name name of the directive to look up.
     * @returns true if directive was registered as multi-element.
     */
    function directiveIsMultiElement(name) {
      if (hasDirectives.hasOwnProperty(name)) {
        for (var directive, directives = $injector.get(name + Suffix),
            i = 0, ii = directives.length; i < ii; i++) {
          directive = directives[i];
          if (directive.multiElement) {
            return true;
          }
        }
      }
      return false;
    }

    /**
     * When the element is replaced with HTML template then the new attributes
     * on the template need to be merged with the existing attributes in the DOM.
     * The desired effect is to have both of the attributes present.
     *
     * @param {object} dst destination attributes (original DOM)
     * @param {object} src source attributes (from the directive template)
     */
    function mergeTemplateAttributes(dst, src) {
      var srcAttr = src.$attr,
          dstAttr = dst.$attr,
          $element = dst.$$element;

      // reapply the old attributes to the new element
      forEach(dst, function(value, key) {
        if (key.charAt(0) != '$') {
          if (src[key] && src[key] !== value) {
            value += (key === 'style' ? ';' : ' ') + src[key];
          }
          dst.$set(key, value, true, srcAttr[key]);
        }
      });

      // copy the new attributes on the old attrs object
      forEach(src, function(value, key) {
        if (key == 'class') {
          safeAddClass($element, value);
          dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
        } else if (key == 'style') {
          $element.attr('style', $element.attr('style') + ';' + value);
          dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
          // `dst` will never contain hasOwnProperty as DOM parser won't let it.
          // You will get an "InvalidCharacterError: DOM Exception 5" error if you
          // have an attribute like "has-own-property" or "data-has-own-property", etc.
        } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
          dst[key] = value;
          dstAttr[key] = srcAttr[key];
        }
      });
    }


    function compileTemplateUrl(directives, $compileNode, tAttrs,
        $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
      var linkQueue = [],
          afterTemplateNodeLinkFn,
          afterTemplateChildLinkFn,
          beforeTemplateCompileNode = $compileNode[0],
          origAsyncDirective = directives.shift(),
          derivedSyncDirective = inherit(origAsyncDirective, {
            templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
          }),
          templateUrl = (isFunction(origAsyncDirective.templateUrl))
              ? origAsyncDirective.templateUrl($compileNode, tAttrs)
              : origAsyncDirective.templateUrl,
          templateNamespace = origAsyncDirective.templateNamespace;

      $compileNode.empty();

      $templateRequest(templateUrl)
        .then(function(content) {
          var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;

          content = denormalizeTemplate(content);

          if (origAsyncDirective.replace) {
            if (jqLiteIsTextNode(content)) {
              $template = [];
            } else {
              $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
            }
            compileNode = $template[0];

            if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
              throw $compileMinErr('tplrt',
                  "Template for directive '{0}' must have exactly one root element. {1}",
                  origAsyncDirective.name, templateUrl);
            }

            tempTemplateAttrs = {$attr: {}};
            replaceWith($rootElement, $compileNode, compileNode);
            var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);

            if (isObject(origAsyncDirective.scope)) {
              markDirectivesAsIsolate(templateDirectives);
            }
            directives = templateDirectives.concat(directives);
            mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
          } else {
            compileNode = beforeTemplateCompileNode;
            $compileNode.html(content);
          }

          directives.unshift(derivedSyncDirective);

          afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
              childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
              previousCompileContext);
          forEach($rootElement, function(node, i) {
            if (node == compileNode) {
              $rootElement[i] = $compileNode[0];
            }
          });
          afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);

          while (linkQueue.length) {
            var scope = linkQueue.shift(),
                beforeTemplateLinkNode = linkQueue.shift(),
                linkRootElement = linkQueue.shift(),
                boundTranscludeFn = linkQueue.shift(),
                linkNode = $compileNode[0];

            if (scope.$$destroyed) continue;

            if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
              var oldClasses = beforeTemplateLinkNode.className;

              if (!(previousCompileContext.hasElementTranscludeDirective &&
                  origAsyncDirective.replace)) {
                // it was cloned therefore we have to clone as well.
                linkNode = jqLiteClone(compileNode);
              }
              replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);

              // Copy in CSS classes from original node
              safeAddClass(jqLite(linkNode), oldClasses);
            }
            if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
              childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
            } else {
              childBoundTranscludeFn = boundTranscludeFn;
            }
            afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
              childBoundTranscludeFn, afterTemplateNodeLinkFn);
          }
          linkQueue = null;
        });

      return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
        var childBoundTranscludeFn = boundTranscludeFn;
        if (scope.$$destroyed) return;
        if (linkQueue) {
          linkQueue.push(scope,
                         node,
                         rootElement,
                         childBoundTranscludeFn);
        } else {
          if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
            childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
          }
          afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn,
                                  afterTemplateNodeLinkFn);
        }
      };
    }


    /**
     * Sorting function for bound directives.
     */
    function byPriority(a, b) {
      var diff = b.priority - a.priority;
      if (diff !== 0) return diff;
      if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
      return a.index - b.index;
    }

    function assertNoDuplicate(what, previousDirective, directive, element) {

      function wrapModuleNameIfDefined(moduleName) {
        return moduleName ?
          (' (module: ' + moduleName + ')') :
          '';
      }

      if (previousDirective) {
        throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
            previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
            directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
      }
    }


    function addTextInterpolateDirective(directives, text) {
      var interpolateFn = $interpolate(text, true);
      if (interpolateFn) {
        directives.push({
          priority: 0,
          compile: function textInterpolateCompileFn(templateNode) {
            var templateNodeParent = templateNode.parent(),
                hasCompileParent = !!templateNodeParent.length;

            // When transcluding a template that has bindings in the root
            // we don't have a parent and thus need to add the class during linking fn.
            if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);

            return function textInterpolateLinkFn(scope, node) {
              var parent = node.parent();
              if (!hasCompileParent) compile.$$addBindingClass(parent);
              compile.$$addBindingInfo(parent, interpolateFn.expressions);
              scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
                node[0].nodeValue = value;
              });
            };
          }
        });
      }
    }


    function wrapTemplate(type, template) {
      type = lowercase(type || 'html');
      switch (type) {
      case 'svg':
      case 'math':
        var wrapper = document.createElement('div');
        wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
        return wrapper.childNodes[0].childNodes;
      default:
        return template;
      }
    }


    function getTrustedContext(node, attrNormalizedName) {
      if (attrNormalizedName == "srcdoc") {
        return $sce.HTML;
      }
      var tag = nodeName_(node);
      // maction[xlink:href] can source SVG.  It's not limited to <maction>.
      if (attrNormalizedName == "xlinkHref" ||
          (tag == "form" && attrNormalizedName == "action") ||
          (tag != "img" && (attrNormalizedName == "src" ||
                            attrNormalizedName == "ngSrc"))) {
        return $sce.RESOURCE_URL;
      }
    }


    function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
      var trustedContext = getTrustedContext(node, name);
      allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;

      var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);

      // no interpolation found -> ignore
      if (!interpolateFn) return;


      if (name === "multiple" && nodeName_(node) === "select") {
        throw $compileMinErr("selmulti",
            "Binding to the 'multiple' attribute is not supported. Element: {0}",
            startingTag(node));
      }

      directives.push({
        priority: 100,
        compile: function() {
            return {
              pre: function attrInterpolatePreLinkFn(scope, element, attr) {
                var $$observers = (attr.$$observers || (attr.$$observers = {}));

                if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
                  throw $compileMinErr('nodomevents',
                      "Interpolations for HTML DOM event attributes are disallowed.  Please use the " +
                          "ng- versions (such as ng-click instead of onclick) instead.");
                }

                // If the attribute has changed since last $interpolate()ed
                var newValue = attr[name];
                if (newValue !== value) {
                  // we need to interpolate again since the attribute value has been updated
                  // (e.g. by another directive's compile function)
                  // ensure unset/empty values make interpolateFn falsy
                  interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
                  value = newValue;
                }

                // if attribute was updated so that there is no interpolation going on we don't want to
                // register any observers
                if (!interpolateFn) return;

                // initialize attr object so that it's ready in case we need the value for isolate
                // scope initialization, otherwise the value would not be available from isolate
                // directive's linking fn during linking phase
                attr[name] = interpolateFn(scope);

                ($$observers[name] || ($$observers[name] = [])).$$inter = true;
                (attr.$$observers && attr.$$observers[name].$$scope || scope).
                  $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
                    //special case for class attribute addition + removal
                    //so that class changes can tap into the animation
                    //hooks provided by the $animate service. Be sure to
                    //skip animations when the first digest occurs (when
                    //both the new and the old values are the same) since
                    //the CSS classes are the non-interpolated values
                    if (name === 'class' && newValue != oldValue) {
                      attr.$updateClass(newValue, oldValue);
                    } else {
                      attr.$set(name, newValue);
                    }
                  });
              }
            };
          }
      });
    }


    /**
     * This is a special jqLite.replaceWith, which can replace items which
     * have no parents, provided that the containing jqLite collection is provided.
     *
     * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
     *                               in the root of the tree.
     * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
     *                                  the shell, but replace its DOM node reference.
     * @param {Node} newNode The new DOM node.
     */
    function replaceWith($rootElement, elementsToRemove, newNode) {
      var firstElementToRemove = elementsToRemove[0],
          removeCount = elementsToRemove.length,
          parent = firstElementToRemove.parentNode,
          i, ii;

      if ($rootElement) {
        for (i = 0, ii = $rootElement.length; i < ii; i++) {
          if ($rootElement[i] == firstElementToRemove) {
            $rootElement[i++] = newNode;
            for (var j = i, j2 = j + removeCount - 1,
                     jj = $rootElement.length;
                 j < jj; j++, j2++) {
              if (j2 < jj) {
                $rootElement[j] = $rootElement[j2];
              } else {
                delete $rootElement[j];
              }
            }
            $rootElement.length -= removeCount - 1;

            // If the replaced element is also the jQuery .context then replace it
            // .context is a deprecated jQuery api, so we should set it only when jQuery set it
            // http://api.jquery.com/context/
            if ($rootElement.context === firstElementToRemove) {
              $rootElement.context = newNode;
            }
            break;
          }
        }
      }

      if (parent) {
        parent.replaceChild(newNode, firstElementToRemove);
      }

      // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
      var fragment = document.createDocumentFragment();
      fragment.appendChild(firstElementToRemove);

      if (jqLite.hasData(firstElementToRemove)) {
        // Copy over user data (that includes Angular's $scope etc.). Don't copy private
        // data here because there's no public interface in jQuery to do that and copying over
        // event listeners (which is the main use of private data) wouldn't work anyway.
        jqLite(newNode).data(jqLite(firstElementToRemove).data());

        // Remove data of the replaced element. We cannot just call .remove()
        // on the element it since that would deallocate scope that is needed
        // for the new node. Instead, remove the data "manually".
        if (!jQuery) {
          delete jqLite.cache[firstElementToRemove[jqLite.expando]];
        } else {
          // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
          // the replaced element. The cleanData version monkey-patched by Angular would cause
          // the scope to be trashed and we do need the very same scope to work with the new
          // element. However, we cannot just cache the non-patched version and use it here as
          // that would break if another library patches the method after Angular does (one
          // example is jQuery UI). Instead, set a flag indicating scope destroying should be
          // skipped this one time.
          skipDestroyOnNextJQueryCleanData = true;
          jQuery.cleanData([firstElementToRemove]);
        }
      }

      for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
        var element = elementsToRemove[k];
        jqLite(element).remove(); // must do this way to clean up expando
        fragment.appendChild(element);
        delete elementsToRemove[k];
      }

      elementsToRemove[0] = newNode;
      elementsToRemove.length = 1;
    }


    function cloneAndAnnotateFn(fn, annotation) {
      return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
    }


    function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
      try {
        linkFn(scope, $element, attrs, controllers, transcludeFn);
      } catch (e) {
        $exceptionHandler(e, startingTag($element));
      }
    }


    // Set up $watches for isolate scope and controller bindings. This process
    // only occurs for isolate scopes and new scopes with controllerAs.
    function initializeDirectiveBindings(scope, attrs, destination, bindings,
                                         directive, newScope) {
      var onNewScopeDestroyed;
      forEach(bindings, function(definition, scopeName) {
        var attrName = definition.attrName,
        optional = definition.optional,
        mode = definition.mode, // @, =, or &
        lastValue,
        parentGet, parentSet, compare;

        if (!hasOwnProperty.call(attrs, attrName)) {
          // In the case of user defined a binding with the same name as a method in Object.prototype but didn't set
          // the corresponding attribute. We need to make sure subsequent code won't access to the prototype function
          attrs[attrName] = undefined;
        }

        switch (mode) {

          case '@':
            if (!attrs[attrName] && !optional) {
              destination[scopeName] = undefined;
            }

            attrs.$observe(attrName, function(value) {
              destination[scopeName] = value;
            });
            attrs.$$observers[attrName].$$scope = scope;
            if (attrs[attrName]) {
              // If the attribute has been provided then we trigger an interpolation to ensure
              // the value is there for use in the link fn
              destination[scopeName] = $interpolate(attrs[attrName])(scope);
            }
            break;

          case '=':
            if (optional && !attrs[attrName]) {
              return;
            }
            parentGet = $parse(attrs[attrName]);

            if (parentGet.literal) {
              compare = equals;
            } else {
              compare = function(a, b) { return a === b || (a !== a && b !== b); };
            }
            parentSet = parentGet.assign || function() {
              // reset the change, or we will throw this exception on every $digest
              lastValue = destination[scopeName] = parentGet(scope);
              throw $compileMinErr('nonassign',
                  "Expression '{0}' used with directive '{1}' is non-assignable!",
                  attrs[attrName], directive.name);
            };
            lastValue = destination[scopeName] = parentGet(scope);
            var parentValueWatch = function parentValueWatch(parentValue) {
              if (!compare(parentValue, destination[scopeName])) {
                // we are out of sync and need to copy
                if (!compare(parentValue, lastValue)) {
                  // parent changed and it has precedence
                  destination[scopeName] = parentValue;
                } else {
                  // if the parent can be assigned then do so
                  parentSet(scope, parentValue = destination[scopeName]);
                }
              }
              return lastValue = parentValue;
            };
            parentValueWatch.$stateful = true;
            var unwatch;
            if (definition.collection) {
              unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
            } else {
              unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
            }
            onNewScopeDestroyed = (onNewScopeDestroyed || []);
            onNewScopeDestroyed.push(unwatch);
            break;

          case '&':
            parentGet = $parse(attrs[attrName]);

            // Don't assign noop to destination if expression is not valid
            if (parentGet === noop && optional) break;

            destination[scopeName] = function(locals) {
              return parentGet(scope, locals);
            };
            break;
        }
      });
      var destroyBindings = onNewScopeDestroyed ? function destroyBindings() {
        for (var i = 0, ii = onNewScopeDestroyed.length; i < ii; ++i) {
          onNewScopeDestroyed[i]();
        }
      } : noop;
      if (newScope && destroyBindings !== noop) {
        newScope.$on('$destroy', destroyBindings);
        return noop;
      }
      return destroyBindings;
    }
  }];
}

var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
/**
 * Converts all accepted directives format into proper directive name.
 * @param name Name to normalize
 */
function directiveNormalize(name) {
  return camelCase(name.replace(PREFIX_REGEXP, ''));
}

/**
 * @ngdoc type
 * @name $compile.directive.Attributes
 *
 * @description
 * A shared object between directive compile / linking functions which contains normalized DOM
 * element attributes. The values reflect current binding state `{{ }}`. The normalization is
 * needed since all of these are treated as equivalent in Angular:
 *
 * ```
 *    <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
 * ```
 */

/**
 * @ngdoc property
 * @name $compile.directive.Attributes#$attr
 *
 * @description
 * A map of DOM element attribute names to the normalized name. This is
 * needed to do reverse lookup from normalized name back to actual name.
 */


/**
 * @ngdoc method
 * @name $compile.directive.Attributes#$set
 * @kind function
 *
 * @description
 * Set DOM element attribute value.
 *
 *
 * @param {string} name Normalized element attribute name of the property to modify. The name is
 *          reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
 *          property to the original name.
 * @param {string} value Value to set the attribute to. The value can be an interpolated string.
 */



/**
 * Closure compiler type information
 */

function nodesetLinkingFn(
  /* angular.Scope */ scope,
  /* NodeList */ nodeList,
  /* Element */ rootElement,
  /* function(Function) */ boundTranscludeFn
) {}

function directiveLinkingFn(
  /* nodesetLinkingFn */ nodesetLinkingFn,
  /* angular.Scope */ scope,
  /* Node */ node,
  /* Element */ rootElement,
  /* function(Function) */ boundTranscludeFn
) {}

function tokenDifference(str1, str2) {
  var values = '',
      tokens1 = str1.split(/\s+/),
      tokens2 = str2.split(/\s+/);

  outer:
  for (var i = 0; i < tokens1.length; i++) {
    var token = tokens1[i];
    for (var j = 0; j < tokens2.length; j++) {
      if (token == tokens2[j]) continue outer;
    }
    values += (values.length > 0 ? ' ' : '') + token;
  }
  return values;
}

function removeComments(jqNodes) {
  jqNodes = jqLite(jqNodes);
  var i = jqNodes.length;

  if (i <= 1) {
    return jqNodes;
  }

  while (i--) {
    var node = jqNodes[i];
    if (node.nodeType === NODE_TYPE_COMMENT) {
      splice.call(jqNodes, i, 1);
    }
  }
  return jqNodes;
}

var $controllerMinErr = minErr('$controller');


var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
function identifierForController(controller, ident) {
  if (ident && isString(ident)) return ident;
  if (isString(controller)) {
    var match = CNTRL_REG.exec(controller);
    if (match) return match[3];
  }
}


/**
 * @ngdoc provider
 * @name $controllerProvider
 * @description
 * The {@link ng.$controller $controller service} is used by Angular to create new
 * controllers.
 *
 * This provider allows controller registration via the
 * {@link ng.$controllerProvider#register register} method.
 */
function $ControllerProvider() {
  var controllers = {},
      globals = false;

  /**
   * @ngdoc method
   * @name $controllerProvider#register
   * @param {string|Object} name Controller name, or an object map of controllers where the keys are
   *    the names and the values are the constructors.
   * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
   *    annotations in the array notation).
   */
  this.register = function(name, constructor) {
    assertNotHasOwnProperty(name, 'controller');
    if (isObject(name)) {
      extend(controllers, name);
    } else {
      controllers[name] = constructor;
    }
  };

  /**
   * @ngdoc method
   * @name $controllerProvider#allowGlobals
   * @description If called, allows `$controller` to find controller constructors on `window`
   */
  this.allowGlobals = function() {
    globals = true;
  };


  this.$get = ['$injector', '$window', function($injector, $window) {

    /**
     * @ngdoc service
     * @name $controller
     * @requires $injector
     *
     * @param {Function|string} constructor If called with a function then it's considered to be the
     *    controller constructor function. Otherwise it's considered to be a string which is used
     *    to retrieve the controller constructor using the following steps:
     *
     *    * check if a controller with given name is registered via `$controllerProvider`
     *    * check if evaluating the string on the current scope returns a constructor
     *    * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
     *      `window` object (not recommended)
     *
     *    The string can use the `controller as property` syntax, where the controller instance is published
     *    as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
     *    to work correctly.
     *
     * @param {Object} locals Injection locals for Controller.
     * @return {Object} Instance of given controller.
     *
     * @description
     * `$controller` service is responsible for instantiating controllers.
     *
     * It's just a simple call to {@link auto.$injector $injector}, but extracted into
     * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
     */
    return function(expression, locals, later, ident) {
      // PRIVATE API:
      //   param `later` --- indicates that the controller's constructor is invoked at a later time.
      //                     If true, $controller will allocate the object with the correct
      //                     prototype chain, but will not invoke the controller until a returned
      //                     callback is invoked.
      //   param `ident` --- An optional label which overrides the label parsed from the controller
      //                     expression, if any.
      var instance, match, constructor, identifier;
      later = later === true;
      if (ident && isString(ident)) {
        identifier = ident;
      }

      if (isString(expression)) {
        match = expression.match(CNTRL_REG);
        if (!match) {
          throw $controllerMinErr('ctrlfmt',
            "Badly formed controller string '{0}'. " +
            "Must match `__name__ as __id__` or `__name__`.", expression);
        }
        constructor = match[1],
        identifier = identifier || match[3];
        expression = controllers.hasOwnProperty(constructor)
            ? controllers[constructor]
            : getter(locals.$scope, constructor, true) ||
                (globals ? getter($window, constructor, true) : undefined);

        assertArgFn(expression, constructor, true);
      }

      if (later) {
        // Instantiate controller later:
        // This machinery is used to create an instance of the object before calling the
        // controller's constructor itself.
        //
        // This allows properties to be added to the controller before the constructor is
        // invoked. Primarily, this is used for isolate scope bindings in $compile.
        //
        // This feature is not intended for use by applications, and is thus not documented
        // publicly.
        // Object creation: http://jsperf.com/create-constructor/2
        var controllerPrototype = (isArray(expression) ?
          expression[expression.length - 1] : expression).prototype;
        instance = Object.create(controllerPrototype || null);

        if (identifier) {
          addIdentifier(locals, identifier, instance, constructor || expression.name);
        }

        var instantiate;
        return instantiate = extend(function() {
          var result = $injector.invoke(expression, instance, locals, constructor);
          if (result !== instance && (isObject(result) || isFunction(result))) {
            instance = result;
            if (identifier) {
              // If result changed, re-assign controllerAs value to scope.
              addIdentifier(locals, identifier, instance, constructor || expression.name);
            }
          }
          return instance;
        }, {
          instance: instance,
          identifier: identifier
        });
      }

      instance = $injector.instantiate(expression, locals, constructor);

      if (identifier) {
        addIdentifier(locals, identifier, instance, constructor || expression.name);
      }

      return instance;
    };

    function addIdentifier(locals, identifier, instance, name) {
      if (!(locals && isObject(locals.$scope))) {
        throw minErr('$controller')('noscp',
          "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
          name, identifier);
      }

      locals.$scope[identifier] = instance;
    }
  }];
}

/**
 * @ngdoc service
 * @name $document
 * @requires $window
 *
 * @description
 * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
 *
 * @example
   <example module="documentExample">
     <file name="index.html">
       <div ng-controller="ExampleController">
         <p>$document title: <b ng-bind="title"></b></p>
         <p>window.document title: <b ng-bind="windowTitle"></b></p>
       </div>
     </file>
     <file name="script.js">
       angular.module('documentExample', [])
         .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
           $scope.title = $document[0].title;
           $scope.windowTitle = angular.element(window.document)[0].title;
         }]);
     </file>
   </example>
 */
function $DocumentProvider() {
  this.$get = ['$window', function(window) {
    return jqLite(window.document);
  }];
}

/**
 * @ngdoc service
 * @name $exceptionHandler
 * @requires ng.$log
 *
 * @description
 * Any uncaught exception in angular expressions is delegated to this service.
 * The default implementation simply delegates to `$log.error` which logs it into
 * the browser console.
 *
 * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
 * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
 *
 * ## Example:
 *
 * ```js
 *   angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
 *     return function(exception, cause) {
 *       exception.message += ' (caused by "' + cause + '")';
 *       throw exception;
 *     };
 *   });
 * ```
 *
 * This example will override the normal action of `$exceptionHandler`, to make angular
 * exceptions fail hard when they happen, instead of just logging to the console.
 *
 * <hr />
 * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
 * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
 * (unless executed during a digest).
 *
 * If you wish, you can manually delegate exceptions, e.g.
 * `try { ... } catch(e) { $exceptionHandler(e); }`
 *
 * @param {Error} exception Exception associated with the error.
 * @param {string=} cause optional information about the context in which
 *       the error was thrown.
 *
 */
function $ExceptionHandlerProvider() {
  this.$get = ['$log', function($log) {
    return function(exception, cause) {
      $log.error.apply($log, arguments);
    };
  }];
}

var APPLICATION_JSON = 'application/json';
var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
var JSON_START = /^\[|^\{(?!\{)/;
var JSON_ENDS = {
  '[': /]$/,
  '{': /}$/
};
var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;

function serializeValue(v) {
  if (isObject(v)) {
    return isDate(v) ? v.toISOString() : toJson(v);
  }
  return v;
}


function $HttpParamSerializerProvider() {
  /**
   * @ngdoc service
   * @name $httpParamSerializer
   * @description
   *
   * Default {@link $http `$http`} params serializer that converts objects to strings
   * according to the following rules:
   *
   * * `{'foo': 'bar'}` results in `foo=bar`
   * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
   * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
   * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
   *
   * Note that serializer will sort the request parameters alphabetically.
   * */

  this.$get = function() {
    return function ngParamSerializer(params) {
      if (!params) return '';
      var parts = [];
      forEachSorted(params, function(value, key) {
        if (value === null || isUndefined(value)) return;
        if (isArray(value)) {
          forEach(value, function(v, k) {
            parts.push(encodeUriQuery(key)  + '=' + encodeUriQuery(serializeValue(v)));
          });
        } else {
          parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
        }
      });

      return parts.join('&');
    };
  };
}

function $HttpParamSerializerJQLikeProvider() {
  /**
   * @ngdoc service
   * @name $httpParamSerializerJQLike
   * @description
   *
   * Alternative {@link $http `$http`} params serializer that follows
   * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
   * The serializer will also sort the params alphabetically.
   *
   * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
   *
   * ```js
   * $http({
   *   url: myUrl,
   *   method: 'GET',
   *   params: myParams,
   *   paramSerializer: '$httpParamSerializerJQLike'
   * });
   * ```
   *
   * It is also possible to set it as the default `paramSerializer` in the
   * {@link $httpProvider#defaults `$httpProvider`}.
   *
   * Additionally, you can inject the serializer and use it explicitly, for example to serialize
   * form data for submission:
   *
   * ```js
   * .controller(function($http, $httpParamSerializerJQLike) {
   *   //...
   *
   *   $http({
   *     url: myUrl,
   *     method: 'POST',
   *     data: $httpParamSerializerJQLike(myData),
   *     headers: {
   *       'Content-Type': 'application/x-www-form-urlencoded'
   *     }
   *   });
   *
   * });
   * ```
   *
   * */
  this.$get = function() {
    return function jQueryLikeParamSerializer(params) {
      if (!params) return '';
      var parts = [];
      serialize(params, '', true);
      return parts.join('&');

      function serialize(toSerialize, prefix, topLevel) {
        if (toSerialize === null || isUndefined(toSerialize)) return;
        if (isArray(toSerialize)) {
          forEach(toSerialize, function(value) {
            serialize(value, prefix + '[]');
          });
        } else if (isObject(toSerialize) && !isDate(toSerialize)) {
          forEachSorted(toSerialize, function(value, key) {
            serialize(value, prefix +
                (topLevel ? '' : '[') +
                key +
                (topLevel ? '' : ']'));
          });
        } else {
          parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
        }
      }
    };
  };
}

function defaultHttpResponseTransform(data, headers) {
  if (isString(data)) {
    // Strip json vulnerability protection prefix and trim whitespace
    var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();

    if (tempData) {
      var contentType = headers('Content-Type');
      if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
        data = fromJson(tempData);
      }
    }
  }

  return data;
}

function isJsonLike(str) {
    var jsonStart = str.match(JSON_START);
    return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
}

/**
 * Parse headers into key value object
 *
 * @param {string} headers Raw headers as a string
 * @returns {Object} Parsed headers as key value object
 */
function parseHeaders(headers) {
  var parsed = createMap(), i;

  function fillInParsed(key, val) {
    if (key) {
      parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
    }
  }

  if (isString(headers)) {
    forEach(headers.split('\n'), function(line) {
      i = line.indexOf(':');
      fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
    });
  } else if (isObject(headers)) {
    forEach(headers, function(headerVal, headerKey) {
      fillInParsed(lowercase(headerKey), trim(headerVal));
    });
  }

  return parsed;
}


/**
 * Returns a function that provides access to parsed headers.
 *
 * Headers are lazy parsed when first requested.
 * @see parseHeaders
 *
 * @param {(string|Object)} headers Headers to provide access to.
 * @returns {function(string=)} Returns a getter function which if called with:
 *
 *   - if called with single an argument returns a single header value or null
 *   - if called with no arguments returns an object containing all headers.
 */
function headersGetter(headers) {
  var headersObj;

  return function(name) {
    if (!headersObj) headersObj =  parseHeaders(headers);

    if (name) {
      var value = headersObj[lowercase(name)];
      if (value === void 0) {
        value = null;
      }
      return value;
    }

    return headersObj;
  };
}


/**
 * Chain all given functions
 *
 * This function is used for both request and response transforming
 *
 * @param {*} data Data to transform.
 * @param {function(string=)} headers HTTP headers getter fn.
 * @param {number} status HTTP status code of the response.
 * @param {(Function|Array.<Function>)} fns Function or an array of functions.
 * @returns {*} Transformed data.
 */
function transformData(data, headers, status, fns) {
  if (isFunction(fns)) {
    return fns(data, headers, status);
  }

  forEach(fns, function(fn) {
    data = fn(data, headers, status);
  });

  return data;
}


function isSuccess(status) {
  return 200 <= status && status < 300;
}


/**
 * @ngdoc provider
 * @name $httpProvider
 * @description
 * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
 * */
function $HttpProvider() {
  /**
   * @ngdoc property
   * @name $httpProvider#defaults
   * @description
   *
   * Object containing default values for all {@link ng.$http $http} requests.
   *
   * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
   * that will provide the cache for all requests who set their `cache` property to `true`.
   * If you set the `defaults.cache = false` then only requests that specify their own custom
   * cache object will be cached. See {@link $http#caching $http Caching} for more information.
   *
   * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
   * Defaults value is `'XSRF-TOKEN'`.
   *
   * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
   * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
   *
   * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
   * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
   * setting default headers.
   *     - **`defaults.headers.common`**
   *     - **`defaults.headers.post`**
   *     - **`defaults.headers.put`**
   *     - **`defaults.headers.patch`**
   *
   *
   * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
   *  used to the prepare string representation of request parameters (specified as an object).
   *  If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
   *  Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
   *
   **/
  var defaults = this.defaults = {
    // transform incoming response data
    transformResponse: [defaultHttpResponseTransform],

    // transform outgoing request data
    transformRequest: [function(d) {
      return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
    }],

    // default headers
    headers: {
      common: {
        'Accept': 'application/json, text/plain, */*'
      },
      post:   shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
      put:    shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
      patch:  shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
    },

    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',

    paramSerializer: '$httpParamSerializer'
  };

  var useApplyAsync = false;
  /**
   * @ngdoc method
   * @name $httpProvider#useApplyAsync
   * @description
   *
   * Configure $http service to combine processing of multiple http responses received at around
   * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
   * significant performance improvement for bigger applications that make many HTTP requests
   * concurrently (common during application bootstrap).
   *
   * Defaults to false. If no value is specified, returns the current configured value.
   *
   * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
   *    "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
   *    to load and share the same digest cycle.
   *
   * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
   *    otherwise, returns the current configured value.
   **/
  this.useApplyAsync = function(value) {
    if (isDefined(value)) {
      useApplyAsync = !!value;
      return this;
    }
    return useApplyAsync;
  };

  /**
   * @ngdoc property
   * @name $httpProvider#interceptors
   * @description
   *
   * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
   * pre-processing of request or postprocessing of responses.
   *
   * These service factories are ordered by request, i.e. they are applied in the same order as the
   * array, on request, but reverse order, on response.
   *
   * {@link ng.$http#interceptors Interceptors detailed info}
   **/
  var interceptorFactories = this.interceptors = [];

  this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
      function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {

    var defaultCache = $cacheFactory('$http');

    /**
     * Make sure that default param serializer is exposed as a function
     */
    defaults.paramSerializer = isString(defaults.paramSerializer) ?
      $injector.get(defaults.paramSerializer) : defaults.paramSerializer;

    /**
     * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
     * The reversal is needed so that we can build up the interception chain around the
     * server request.
     */
    var reversedInterceptors = [];

    forEach(interceptorFactories, function(interceptorFactory) {
      reversedInterceptors.unshift(isString(interceptorFactory)
          ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
    });

    /**
     * @ngdoc service
     * @kind function
     * @name $http
     * @requires ng.$httpBackend
     * @requires $cacheFactory
     * @requires $rootScope
     * @requires $q
     * @requires $injector
     *
     * @description
     * The `$http` service is a core Angular service that facilitates communication with the remote
     * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
     * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
     *
     * For unit testing applications that use `$http` service, see
     * {@link ngMock.$httpBackend $httpBackend mock}.
     *
     * For a higher level of abstraction, please check out the {@link ngResource.$resource
     * $resource} service.
     *
     * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
     * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
     * it is important to familiarize yourself with these APIs and the guarantees they provide.
     *
     *
     * ## General usage
     * The `$http` service is a function which takes a single argument — a configuration object —
     * that is used to generate an HTTP request and returns  a {@link ng.$q promise}
     * with two $http specific methods: `success` and `error`.
     *
     * ```js
     *   // Simple GET request example :
     *   $http.get('/someUrl').
     *     success(function(data, status, headers, config) {
     *       // this callback will be called asynchronously
     *       // when the response is available
     *     }).
     *     error(function(data, status, headers, config) {
     *       // called asynchronously if an error occurs
     *       // or server returns response with an error status.
     *     });
     * ```
     *
     * ```js
     *   // Simple POST request example (passing data) :
     *   $http.post('/someUrl', {msg:'hello word!'}).
     *     success(function(data, status, headers, config) {
     *       // this callback will be called asynchronously
     *       // when the response is available
     *     }).
     *     error(function(data, status, headers, config) {
     *       // called asynchronously if an error occurs
     *       // or server returns response with an error status.
     *     });
     * ```
     *
     *
     * Since the returned value of calling the $http function is a `promise`, you can also use
     * the `then` method to register callbacks, and these callbacks will receive a single argument –
     * an object representing the response. See the API signature and type info below for more
     * details.
     *
     * A response status code between 200 and 299 is considered a success status and
     * will result in the success callback being called. Note that if the response is a redirect,
     * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
     * called for such responses.
     *
     * ## Writing Unit Tests that use $http
     * When unit testing (using {@link ngMock ngMock}), it is necessary to call
     * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
     * request using trained responses.
     *
     * ```
     * $httpBackend.expectGET(...);
     * $http.get(...);
     * $httpBackend.flush();
     * ```
     *
     * ## Shortcut methods
     *
     * Shortcut methods are also available. All shortcut methods require passing in the URL, and
     * request data must be passed in for POST/PUT requests.
     *
     * ```js
     *   $http.get('/someUrl').success(successCallback);
     *   $http.post('/someUrl', data).success(successCallback);
     * ```
     *
     * Complete list of shortcut methods:
     *
     * - {@link ng.$http#get $http.get}
     * - {@link ng.$http#head $http.head}
     * - {@link ng.$http#post $http.post}
     * - {@link ng.$http#put $http.put}
     * - {@link ng.$http#delete $http.delete}
     * - {@link ng.$http#jsonp $http.jsonp}
     * - {@link ng.$http#patch $http.patch}
     *
     *
     * ## Setting HTTP Headers
     *
     * The $http service will automatically add certain HTTP headers to all requests. These defaults
     * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
     * object, which currently contains this default configuration:
     *
     * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
     *   - `Accept: application/json, text/plain, * / *`
     * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
     *   - `Content-Type: application/json`
     * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
     *   - `Content-Type: application/json`
     *
     * To add or overwrite these defaults, simply add or remove a property from these configuration
     * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
     * with the lowercased HTTP method name as the key, e.g.
     * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
     *
     * The defaults can also be set at runtime via the `$http.defaults` object in the same
     * fashion. For example:
     *
     * ```
     * module.run(function($http) {
     *   $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
     * });
     * ```
     *
     * In addition, you can supply a `headers` property in the config object passed when
     * calling `$http(config)`, which overrides the defaults without changing them globally.
     *
     * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
     * Use the `headers` property, setting the desired header to `undefined`. For example:
     *
     * ```js
     * var req = {
     *  method: 'POST',
     *  url: 'http://example.com',
     *  headers: {
     *    'Content-Type': undefined
     *  },
     *  data: { test: 'test' }
     * }
     *
     * $http(req).success(function(){...}).error(function(){...});
     * ```
     *
     * ## Transforming Requests and Responses
     *
     * Both requests and responses can be transformed using transformation functions: `transformRequest`
     * and `transformResponse`. These properties can be a single function that returns
     * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
     * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
     *
     * ### Default Transformations
     *
     * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
     * `defaults.transformResponse` properties. If a request does not provide its own transformations
     * then these will be applied.
     *
     * You can augment or replace the default transformations by modifying these properties by adding to or
     * replacing the array.
     *
     * Angular provides the following default transformations:
     *
     * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
     *
     * - If the `data` property of the request configuration object contains an object, serialize it
     *   into JSON format.
     *
     * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
     *
     *  - If XSRF prefix is detected, strip it (see Security Considerations section below).
     *  - If JSON response is detected, deserialize it using a JSON parser.
     *
     *
     * ### Overriding the Default Transformations Per Request
     *
     * If you wish override the request/response transformations only for a single request then provide
     * `transformRequest` and/or `transformResponse` properties on the configuration object passed
     * into `$http`.
     *
     * Note that if you provide these properties on the config object the default transformations will be
     * overwritten. If you wish to augment the default transformations then you must include them in your
     * local transformation array.
     *
     * The following code demonstrates adding a new response transformation to be run after the default response
     * transformations have been run.
     *
     * ```js
     * function appendTransform(defaults, transform) {
     *
     *   // We can't guarantee that the default transformation is an array
     *   defaults = angular.isArray(defaults) ? defaults : [defaults];
     *
     *   // Append the new transformation to the defaults
     *   return defaults.concat(transform);
     * }
     *
     * $http({
     *   url: '...',
     *   method: 'GET',
     *   transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
     *     return doTransform(value);
     *   })
     * });
     * ```
     *
     *
     * ## Caching
     *
     * To enable caching, set the request configuration `cache` property to `true` (to use default
     * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
     * When the cache is enabled, `$http` stores the response from the server in the specified
     * cache. The next time the same request is made, the response is served from the cache without
     * sending a request to the server.
     *
     * Note that even if the response is served from cache, delivery of the data is asynchronous in
     * the same way that real requests are.
     *
     * If there are multiple GET requests for the same URL that should be cached using the same
     * cache, but the cache is not populated yet, only one request to the server will be made and
     * the remaining requests will be fulfilled using the response from the first request.
     *
     * You can change the default cache to a new object (built with
     * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
     * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
     * their `cache` property to `true` will now use this cache object.
     *
     * If you set the default cache to `false` then only requests that specify their own custom
     * cache object will be cached.
     *
     * ## Interceptors
     *
     * Before you start creating interceptors, be sure to understand the
     * {@link ng.$q $q and deferred/promise APIs}.
     *
     * For purposes of global error handling, authentication, or any kind of synchronous or
     * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
     * able to intercept requests before they are handed to the server and
     * responses before they are handed over to the application code that
     * initiated these requests. The interceptors leverage the {@link ng.$q
     * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
     *
     * The interceptors are service factories that are registered with the `$httpProvider` by
     * adding them to the `$httpProvider.interceptors` array. The factory is called and
     * injected with dependencies (if specified) and returns the interceptor.
     *
     * There are two kinds of interceptors (and two kinds of rejection interceptors):
     *
     *   * `request`: interceptors get called with a http `config` object. The function is free to
     *     modify the `config` object or create a new one. The function needs to return the `config`
     *     object directly, or a promise containing the `config` or a new `config` object.
     *   * `requestError`: interceptor gets called when a previous interceptor threw an error or
     *     resolved with a rejection.
     *   * `response`: interceptors get called with http `response` object. The function is free to
     *     modify the `response` object or create a new one. The function needs to return the `response`
     *     object directly, or as a promise containing the `response` or a new `response` object.
     *   * `responseError`: interceptor gets called when a previous interceptor threw an error or
     *     resolved with a rejection.
     *
     *
     * ```js
     *   // register the interceptor as a service
     *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
     *     return {
     *       // optional method
     *       'request': function(config) {
     *         // do something on success
     *         return config;
     *       },
     *
     *       // optional method
     *      'requestError': function(rejection) {
     *         // do something on error
     *         if (canRecover(rejection)) {
     *           return responseOrNewPromise
     *         }
     *         return $q.reject(rejection);
     *       },
     *
     *
     *
     *       // optional method
     *       'response': function(response) {
     *         // do something on success
     *         return response;
     *       },
     *
     *       // optional method
     *      'responseError': function(rejection) {
     *         // do something on error
     *         if (canRecover(rejection)) {
     *           return responseOrNewPromise
     *         }
     *         return $q.reject(rejection);
     *       }
     *     };
     *   });
     *
     *   $httpProvider.interceptors.push('myHttpInterceptor');
     *
     *
     *   // alternatively, register the interceptor via an anonymous factory
     *   $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
     *     return {
     *      'request': function(config) {
     *          // same as above
     *       },
     *
     *       'response': function(response) {
     *          // same as above
     *       }
     *     };
     *   });
     * ```
     *
     * ## Security Considerations
     *
     * When designing web applications, consider security threats from:
     *
     * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
     * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
     *
     * Both server and the client must cooperate in order to eliminate these threats. Angular comes
     * pre-configured with strategies that address these issues, but for this to work backend server
     * cooperation is required.
     *
     * ### JSON Vulnerability Protection
     *
     * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
     * allows third party website to turn your JSON resource URL into
     * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
     * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
     * Angular will automatically strip the prefix before processing it as JSON.
     *
     * For example if your server needs to return:
     * ```js
     * ['one','two']
     * ```
     *
     * which is vulnerable to attack, your server can return:
     * ```js
     * )]}',
     * ['one','two']
     * ```
     *
     * Angular will strip the prefix, before processing the JSON.
     *
     *
     * ### Cross Site Request Forgery (XSRF) Protection
     *
     * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
     * an unauthorized site can gain your user's private data. Angular provides a mechanism
     * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
     * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
     * JavaScript that runs on your domain could read the cookie, your server can be assured that
     * the XHR came from JavaScript running on your domain. The header will not be set for
     * cross-domain requests.
     *
     * To take advantage of this, your server needs to set a token in a JavaScript readable session
     * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
     * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
     * that only JavaScript running on your domain could have sent the request. The token must be
     * unique for each user and must be verifiable by the server (to prevent the JavaScript from
     * making up its own tokens). We recommend that the token is a digest of your site's
     * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
     * for added security.
     *
     * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
     * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
     * or the per-request config object.
     *
     * In order to prevent collisions in environments where multiple Angular apps share the
     * same domain or subdomain, we recommend that each application uses unique cookie name.
     *
     *
     * @param {object} config Object describing the request to be made and how it should be
     *    processed. The object has following properties:
     *
     *    - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
     *    - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
     *    - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
     *      with the `paramSerializer` and appended as GET parameters.
     *    - **data** – `{string|Object}` – Data to be sent as the request message data.
     *    - **headers** – `{Object}` – Map of strings or functions which return strings representing
     *      HTTP headers to send to the server. If the return value of a function is null, the
     *      header will not be sent. Functions accept a config object as an argument.
     *    - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
     *    - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
     *    - **transformRequest** –
     *      `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
     *      transform function or an array of such functions. The transform function takes the http
     *      request body and headers and returns its transformed (typically serialized) version.
     *      See {@link ng.$http#overriding-the-default-transformations-per-request
     *      Overriding the Default Transformations}
     *    - **transformResponse** –
     *      `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
     *      transform function or an array of such functions. The transform function takes the http
     *      response body, headers and status and returns its transformed (typically deserialized) version.
     *      See {@link ng.$http#overriding-the-default-transformations-per-request
     *      Overriding the Default TransformationjqLiks}
     *    - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
     *      prepare the string representation of request parameters (specified as an object).
     *      If specified as string, it is interpreted as function registered with the
     *      {@link $injector $injector}, which means you can create your own serializer
     *      by registering it as a {@link auto.$provide#service service}.
     *      The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
     *      alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
     *    - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
     *      GET request, otherwise if a cache instance built with
     *      {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
     *      caching.
     *    - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
     *      that should abort the request when resolved.
     *    - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
     *      XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
     *      for more information.
     *    - **responseType** - `{string}` - see
     *      [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
     *
     * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
     *   standard `then` method and two http specific methods: `success` and `error`. The `then`
     *   method takes two arguments a success and an error callback which will be called with a
     *   response object. The `success` and `error` methods take a single argument - a function that
     *   will be called when the request succeeds or fails respectively. The arguments passed into
     *   these functions are destructured representation of the response object passed into the
     *   `then` method. The response object has these properties:
     *
     *   - **data** – `{string|Object}` – The response body transformed with the transform
     *     functions.
     *   - **status** – `{number}` – HTTP status code of the response.
     *   - **headers** – `{function([headerName])}` – Header getter function.
     *   - **config** – `{Object}` – The configuration object that was used to generate the request.
     *   - **statusText** – `{string}` – HTTP status text of the response.
     *
     * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
     *   requests. This is primarily meant to be used for debugging purposes.
     *
     *
     * @example
<example module="httpExample">
<file name="index.html">
  <div ng-controller="FetchController">
    <select ng-model="method" aria-label="Request method">
      <option>GET</option>
      <option>JSONP</option>
    </select>
    <input type="text" ng-model="url" size="80" aria-label="URL" />
    <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
    <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
    <button id="samplejsonpbtn"
      ng-click="updateModel('JSONP',
                    'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
      Sample JSONP
    </button>
    <button id="invalidjsonpbtn"
      ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
        Invalid JSONP
      </button>
    <pre>http status code: {{status}}</pre>
    <pre>http response data: {{data}}</pre>
  </div>
</file>
<file name="script.js">
  angular.module('httpExample', [])
    .controller('FetchController', ['$scope', '$http', '$templateCache',
      function($scope, $http, $templateCache) {
        $scope.method = 'GET';
        $scope.url = 'http-hello.html';

        $scope.fetch = function() {
          $scope.code = null;
          $scope.response = null;

          $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
            success(function(data, status) {
              $scope.status = status;
              $scope.data = data;
            }).
            error(function(data, status) {
              $scope.data = data || "Request failed";
              $scope.status = status;
          });
        };

        $scope.updateModel = function(method, url) {
          $scope.method = method;
          $scope.url = url;
        };
      }]);
</file>
<file name="http-hello.html">
  Hello, $http!
</file>
<file name="protractor.js" type="protractor">
  var status = element(by.binding('status'));
  var data = element(by.binding('data'));
  var fetchBtn = element(by.id('fetchbtn'));
  var sampleGetBtn = element(by.id('samplegetbtn'));
  var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));

  it('should make an xhr GET request', function() {
    sampleGetBtn.click();
    fetchBtn.click();
    expect(status.getText()).toMatch('200');
    expect(data.getText()).toMatch(/Hello, \$http!/);
  });

// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
// it('should make a JSONP request to angularjs.org', function() {
//   sampleJsonpBtn.click();
//   fetchBtn.click();
//   expect(status.getText()).toMatch('200');
//   expect(data.getText()).toMatch(/Super Hero!/);
// });

  it('should make JSONP request to invalid URL and invoke the error handler',
      function() {
    invalidJsonpBtn.click();
    fetchBtn.click();
    expect(status.getText()).toMatch('0');
    expect(data.getText()).toMatch('Request failed');
  });
</file>
</example>
     */
    function $http(requestConfig) {

      if (!angular.isObject(requestConfig)) {
        throw minErr('$http')('badreq', 'Http request configuration must be an object.  Received: {0}', requestConfig);
      }

      var config = extend({
        method: 'get',
        transformRequest: defaults.transformRequest,
        transformResponse: defaults.transformResponse,
        paramSerializer: defaults.paramSerializer
      }, requestConfig);

      config.headers = mergeHeaders(requestConfig);
      config.method = uppercase(config.method);
      config.paramSerializer = isString(config.paramSerializer) ?
        $injector.get(config.paramSerializer) : config.paramSerializer;

      var serverRequest = function(config) {
        var headers = config.headers;
        var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);

        // strip content-type if data is undefined
        if (isUndefined(reqData)) {
          forEach(headers, function(value, header) {
            if (lowercase(header) === 'content-type') {
                delete headers[header];
            }
          });
        }

        if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
          config.withCredentials = defaults.withCredentials;
        }

        // send request
        return sendReq(config, reqData).then(transformResponse, transformResponse);
      };

      var chain = [serverRequest, undefined];
      var promise = $q.when(config);

      // apply interceptors
      forEach(reversedInterceptors, function(interceptor) {
        if (interceptor.request || interceptor.requestError) {
          chain.unshift(interceptor.request, interceptor.requestError);
        }
        if (interceptor.response || interceptor.responseError) {
          chain.push(interceptor.response, interceptor.responseError);
        }
      });

      while (chain.length) {
        var thenFn = chain.shift();
        var rejectFn = chain.shift();

        promise = promise.then(thenFn, rejectFn);
      }

      promise.success = function(fn) {
        assertArgFn(fn, 'fn');

        promise.then(function(response) {
          fn(response.data, response.status, response.headers, config);
        });
        return promise;
      };

      promise.error = function(fn) {
        assertArgFn(fn, 'fn');

        promise.then(null, function(response) {
          fn(response.data, response.status, response.headers, config);
        });
        return promise;
      };

      return promise;

      function transformResponse(response) {
        // make a copy since the response must be cacheable
        var resp = extend({}, response);
        if (!response.data) {
          resp.data = response.data;
        } else {
          resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
        }
        return (isSuccess(response.status))
          ? resp
          : $q.reject(resp);
      }

      function executeHeaderFns(headers, config) {
        var headerContent, processedHeaders = {};

        forEach(headers, function(headerFn, header) {
          if (isFunction(headerFn)) {
            headerContent = headerFn(config);
            if (headerContent != null) {
              processedHeaders[header] = headerContent;
            }
          } else {
            processedHeaders[header] = headerFn;
          }
        });

        return processedHeaders;
      }

      function mergeHeaders(config) {
        var defHeaders = defaults.headers,
            reqHeaders = extend({}, config.headers),
            defHeaderName, lowercaseDefHeaderName, reqHeaderName;

        defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);

        // using for-in instead of forEach to avoid unecessary iteration after header has been found
        defaultHeadersIteration:
        for (defHeaderName in defHeaders) {
          lowercaseDefHeaderName = lowercase(defHeaderName);

          for (reqHeaderName in reqHeaders) {
            if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
              continue defaultHeadersIteration;
            }
          }

          reqHeaders[defHeaderName] = defHeaders[defHeaderName];
        }

        // execute if header value is a function for merged headers
        return executeHeaderFns(reqHeaders, shallowCopy(config));
      }
    }

    $http.pendingRequests = [];

    /**
     * @ngdoc method
     * @name $http#get
     *
     * @description
     * Shortcut method to perform `GET` request.
     *
     * @param {string} url Relative or absolute URL specifying the destination of the request
     * @param {Object=} config Optional configuration object
     * @returns {HttpPromise} Future object
     */

    /**
     * @ngdoc method
     * @name $http#delete
     *
     * @description
     * Shortcut method to perform `DELETE` request.
     *
     * @param {string} url Relative or absolute URL specifying the destination of the request
     * @param {Object=} config Optional configuration object
     * @returns {HttpPromise} Future object
     */

    /**
     * @ngdoc method
     * @name $http#head
     *
     * @description
     * Shortcut method to perform `HEAD` request.
     *
     * @param {string} url Relative or absolute URL specifying the destination of the request
     * @param {Object=} config Optional configuration object
     * @returns {HttpPromise} Future object
     */

    /**
     * @ngdoc method
     * @name $http#jsonp
     *
     * @description
     * Shortcut method to perform `JSONP` request.
     *
     * @param {string} url Relative or absolute URL specifying the destination of the request.
     *                     The name of the callback should be the string `JSON_CALLBACK`.
     * @param {Object=} config Optional configuration object
     * @returns {HttpPromise} Future object
     */
    createShortMethods('get', 'delete', 'head', 'jsonp');

    /**
     * @ngdoc method
     * @name $http#post
     *
     * @description
     * Shortcut method to perform `POST` request.
     *
     * @param {string} url Relative or absolute URL specifying the destination of the request
     * @param {*} data Request content
     * @param {Object=} config Optional configuration object
     * @returns {HttpPromise} Future object
     */

    /**
     * @ngdoc method
     * @name $http#put
     *
     * @description
     * Shortcut method to perform `PUT` request.
     *
     * @param {string} url Relative or absolute URL specifying the destination of the request
     * @param {*} data Request content
     * @param {Object=} config Optional configuration object
     * @returns {HttpPromise} Future object
     */

     /**
      * @ngdoc method
      * @name $http#patch
      *
      * @description
      * Shortcut method to perform `PATCH` request.
      *
      * @param {string} url Relative or absolute URL specifying the destination of the request
      * @param {*} data Request content
      * @param {Object=} config Optional configuration object
      * @returns {HttpPromise} Future object
      */
    createShortMethodsWithData('post', 'put', 'patch');

        /**
         * @ngdoc property
         * @name $http#defaults
         *
         * @description
         * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
         * default headers, withCredentials as well as request and response transformations.
         *
         * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
         */
    $http.defaults = defaults;


    return $http;


    function createShortMethods(names) {
      forEach(arguments, function(name) {
        $http[name] = function(url, config) {
          return $http(extend({}, config || {}, {
            method: name,
            url: url
          }));
        };
      });
    }


    function createShortMethodsWithData(name) {
      forEach(arguments, function(name) {
        $http[name] = function(url, data, config) {
          return $http(extend({}, config || {}, {
            method: name,
            url: url,
            data: data
          }));
        };
      });
    }


    /**
     * Makes the request.
     *
     * !!! ACCESSES CLOSURE VARS:
     * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
     */
    function sendReq(config, reqData) {
      var deferred = $q.defer(),
          promise = deferred.promise,
          cache,
          cachedResp,
          reqHeaders = config.headers,
          url = buildUrl(config.url, config.paramSerializer(config.params));

      $http.pendingRequests.push(config);
      promise.then(removePendingReq, removePendingReq);


      if ((config.cache || defaults.cache) && config.cache !== false &&
          (config.method === 'GET' || config.method === 'JSONP')) {
        cache = isObject(config.cache) ? config.cache
              : isObject(defaults.cache) ? defaults.cache
              : defaultCache;
      }

      if (cache) {
        cachedResp = cache.get(url);
        if (isDefined(cachedResp)) {
          if (isPromiseLike(cachedResp)) {
            // cached request has already been sent, but there is no response yet
            cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
          } else {
            // serving from cache
            if (isArray(cachedResp)) {
              resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
            } else {
              resolvePromise(cachedResp, 200, {}, 'OK');
            }
          }
        } else {
          // put the promise for the non-transformed response into cache as a placeholder
          cache.put(url, promise);
        }
      }


      // if we won't have the response in cache, set the xsrf headers and
      // send the request to the backend
      if (isUndefined(cachedResp)) {
        var xsrfValue = urlIsSameOrigin(config.url)
            ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
            : undefined;
        if (xsrfValue) {
          reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
        }

        $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
            config.withCredentials, config.responseType);
      }

      return promise;


      /**
       * Callback registered to $httpBackend():
       *  - caches the response if desired
       *  - resolves the raw $http promise
       *  - calls $apply
       */
      function done(status, response, headersString, statusText) {
        if (cache) {
          if (isSuccess(status)) {
            cache.put(url, [status, response, parseHeaders(headersString), statusText]);
          } else {
            // remove promise from the cache
            cache.remove(url);
          }
        }

        function resolveHttpPromise() {
          resolvePromise(response, status, headersString, statusText);
        }

        if (useApplyAsync) {
          $rootScope.$applyAsync(resolveHttpPromise);
        } else {
          resolveHttpPromise();
          if (!$rootScope.$$phase) $rootScope.$apply();
        }
      }


      /**
       * Resolves the raw $http promise.
       */
      function resolvePromise(response, status, headers, statusText) {
        // normalize internal statuses to 0
        status = Math.max(status, 0);

        (isSuccess(status) ? deferred.resolve : deferred.reject)({
          data: response,
          status: status,
          headers: headersGetter(headers),
          config: config,
          statusText: statusText
        });
      }

      function resolvePromiseWithResult(result) {
        resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
      }

      function removePendingReq() {
        var idx = $http.pendingRequests.indexOf(config);
        if (idx !== -1) $http.pendingRequests.splice(idx, 1);
      }
    }


    function buildUrl(url, serializedParams) {
      if (serializedParams.length > 0) {
        url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
      }
      return url;
    }
  }];
}

function createXhr() {
    return new window.XMLHttpRequest();
}

/**
 * @ngdoc service
 * @name $httpBackend
 * @requires $window
 * @requires $document
 *
 * @description
 * HTTP backend used by the {@link ng.$http service} that delegates to
 * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
 *
 * You should never need to use this service directly, instead use the higher-level abstractions:
 * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
 *
 * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
 * $httpBackend} which can be trained with responses.
 */
function $HttpBackendProvider() {
  this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
    return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  }];
}

function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  // TODO(vojta): fix the signature
  return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
    $browser.$$incOutstandingRequestCount();
    url = url || $browser.url();

    if (lowercase(method) == 'jsonp') {
      var callbackId = '_' + (callbacks.counter++).toString(36);
      callbacks[callbackId] = function(data) {
        callbacks[callbackId].data = data;
        callbacks[callbackId].called = true;
      };

      var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
          callbackId, function(status, text) {
        completeRequest(callback, status, callbacks[callbackId].data, "", text);
        callbacks[callbackId] = noop;
      });
    } else {

      var xhr = createXhr();

      xhr.open(method, url, true);
      forEach(headers, function(value, key) {
        if (isDefined(value)) {
            xhr.setRequestHeader(key, value);
        }
      });

      xhr.onload = function requestLoaded() {
        var statusText = xhr.statusText || '';

        // responseText is the old-school way of retrieving response (supported by IE8 & 9)
        // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
        var response = ('response' in xhr) ? xhr.response : xhr.responseText;

        // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
        var status = xhr.status === 1223 ? 204 : xhr.status;

        // fix status code when it is 0 (0 status is undocumented).
        // Occurs when accessing file resources or on Android 4.1 stock browser
        // while retrieving files from application cache.
        if (status === 0) {
          status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
        }

        completeRequest(callback,
            status,
            response,
            xhr.getAllResponseHeaders(),
            statusText);
      };

      var requestError = function() {
        // The response is always empty
        // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
        completeRequest(callback, -1, null, null, '');
      };

      xhr.onerror = requestError;
      xhr.onabort = requestError;

      if (withCredentials) {
        xhr.withCredentials = true;
      }

      if (responseType) {
        try {
          xhr.responseType = responseType;
        } catch (e) {
          // WebKit added support for the json responseType value on 09/03/2013
          // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
          // known to throw when setting the value "json" as the response type. Other older
          // browsers implementing the responseType
          //
          // The json response type can be ignored if not supported, because JSON payloads are
          // parsed on the client-side regardless.
          if (responseType !== 'json') {
            throw e;
          }
        }
      }

      xhr.send(post);
    }

    if (timeout > 0) {
      var timeoutId = $browserDefer(timeoutRequest, timeout);
    } else if (isPromiseLike(timeout)) {
      timeout.then(timeoutRequest);
    }


    function timeoutRequest() {
      jsonpDone && jsonpDone();
      xhr && xhr.abort();
    }

    function completeRequest(callback, status, response, headersString, statusText) {
      // cancel timeout and subsequent timeout promise resolution
      if (timeoutId !== undefined) {
        $browserDefer.cancel(timeoutId);
      }
      jsonpDone = xhr = null;

      callback(status, response, headersString, statusText);
      $browser.$$completeOutstandingRequest(noop);
    }
  };

  function jsonpReq(url, callbackId, done) {
    // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
    // - fetches local scripts via XHR and evals them
    // - adds and immediately removes script elements from the document
    var script = rawDocument.createElement('script'), callback = null;
    script.type = "text/javascript";
    script.src = url;
    script.async = true;

    callback = function(event) {
      removeEventListenerFn(script, "load", callback);
      removeEventListenerFn(script, "error", callback);
      rawDocument.body.removeChild(script);
      script = null;
      var status = -1;
      var text = "unknown";

      if (event) {
        if (event.type === "load" && !callbacks[callbackId].called) {
          event = { type: "error" };
        }
        text = event.type;
        status = event.type === "error" ? 404 : 200;
      }

      if (done) {
        done(status, text);
      }
    };

    addEventListenerFn(script, "load", callback);
    addEventListenerFn(script, "error", callback);
    rawDocument.body.appendChild(script);
    return callback;
  }
}

var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
$interpolateMinErr.throwNoconcat = function(text) {
  throw $interpolateMinErr('noconcat',
      "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
      "interpolations that concatenate multiple expressions when a trusted value is " +
      "required.  See http://docs.angularjs.org/api/ng.$sce", text);
};

$interpolateMinErr.interr = function(text, err) {
  return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
};

/**
 * @ngdoc provider
 * @name $interpolateProvider
 *
 * @description
 *
 * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
 *
 * @example
<example module="customInterpolationApp">
<file name="index.html">
<script>
  var customInterpolationApp = angular.module('customInterpolationApp', []);

  customInterpolationApp.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('//');
    $interpolateProvider.endSymbol('//');
  });


  customInterpolationApp.controller('DemoController', function() {
      this.label = "This binding is brought you by // interpolation symbols.";
  });
</script>
<div ng-app="App" ng-controller="DemoController as demo">
    //demo.label//
</div>
</file>
<file name="protractor.js" type="protractor">
  it('should interpolate binding with custom symbols', function() {
    expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  });
</file>
</example>
 */
function $InterpolateProvider() {
  var startSymbol = '{{';
  var endSymbol = '}}';

  /**
   * @ngdoc method
   * @name $interpolateProvider#startSymbol
   * @description
   * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
   *
   * @param {string=} value new value to set the starting symbol to.
   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
   */
  this.startSymbol = function(value) {
    if (value) {
      startSymbol = value;
      return this;
    } else {
      return startSymbol;
    }
  };

  /**
   * @ngdoc method
   * @name $interpolateProvider#endSymbol
   * @description
   * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
   *
   * @param {string=} value new value to set the ending symbol to.
   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
   */
  this.endSymbol = function(value) {
    if (value) {
      endSymbol = value;
      return this;
    } else {
      return endSymbol;
    }
  };


  this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
    var startSymbolLength = startSymbol.length,
        endSymbolLength = endSymbol.length,
        escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
        escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');

    function escape(ch) {
      return '\\\\\\' + ch;
    }

    function unescapeText(text) {
      return text.replace(escapedStartRegexp, startSymbol).
        replace(escapedEndRegexp, endSymbol);
    }

    function stringify(value) {
      if (value == null) { // null || undefined
        return '';
      }
      switch (typeof value) {
        case 'string':
          break;
        case 'number':
          value = '' + value;
          break;
        default:
          value = toJson(value);
      }

      return value;
    }

    /**
     * @ngdoc service
     * @name $interpolate
     * @kind function
     *
     * @requires $parse
     * @requires $sce
     *
     * @description
     *
     * Compiles a string with markup into an interpolation function. This service is used by the
     * HTML {@link ng.$compile $compile} service for data binding. See
     * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
     * interpolation markup.
     *
     *
     * ```js
     *   var $interpolate = ...; // injected
     *   var exp = $interpolate('Hello {{name | uppercase}}!');
     *   expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
     * ```
     *
     * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
     * `true`, the interpolation function will return `undefined` unless all embedded expressions
     * evaluate to a value other than `undefined`.
     *
     * ```js
     *   var $interpolate = ...; // injected
     *   var context = {greeting: 'Hello', name: undefined };
     *
     *   // default "forgiving" mode
     *   var exp = $interpolate('{{greeting}} {{name}}!');
     *   expect(exp(context)).toEqual('Hello !');
     *
     *   // "allOrNothing" mode
     *   exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
     *   expect(exp(context)).toBeUndefined();
     *   context.name = 'Angular';
     *   expect(exp(context)).toEqual('Hello Angular!');
     * ```
     *
     * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
     *
     * ####Escaped Interpolation
     * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
     * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
     * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
     * or binding.
     *
     * This enables web-servers to prevent script injection attacks and defacing attacks, to some
     * degree, while also enabling code examples to work without relying on the
     * {@link ng.directive:ngNonBindable ngNonBindable} directive.
     *
     * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
     * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
     * interpolation start/end markers with their escaped counterparts.**
     *
     * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
     * output when the $interpolate service processes the text. So, for HTML elements interpolated
     * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
     * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
     * this is typically useful only when user-data is used in rendering a template from the server, or
     * when otherwise untrusted data is used by a directive.
     *
     * <example>
     *  <file name="index.html">
     *    <div ng-init="username='A user'">
     *      <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
     *        </p>
     *      <p><strong>{{username}}</strong> attempts to inject code which will deface the
     *        application, but fails to accomplish their task, because the server has correctly
     *        escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
     *        characters.</p>
     *      <p>Instead, the result of the attempted script injection is visible, and can be removed
     *        from the database by an administrator.</p>
     *    </div>
     *  </file>
     * </example>
     *
     * @param {string} text The text with markup to interpolate.
     * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
     *    embedded expression in order to return an interpolation function. Strings with no
     *    embedded expression will return null for the interpolation function.
     * @param {string=} trustedContext when provided, the returned function passes the interpolated
     *    result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
     *    trustedContext)} before returning it.  Refer to the {@link ng.$sce $sce} service that
     *    provides Strict Contextual Escaping for details.
     * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
     *    unless all embedded expressions evaluate to a value other than `undefined`.
     * @returns {function(context)} an interpolation function which is used to compute the
     *    interpolated string. The function has these parameters:
     *
     * - `context`: evaluation context for all expressions embedded in the interpolated text
     */
    function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
      allOrNothing = !!allOrNothing;
      var startIndex,
          endIndex,
          index = 0,
          expressions = [],
          parseFns = [],
          textLength = text.length,
          exp,
          concat = [],
          expressionPositions = [];

      while (index < textLength) {
        if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
             ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
          if (index !== startIndex) {
            concat.push(unescapeText(text.substring(index, startIndex)));
          }
          exp = text.substring(startIndex + startSymbolLength, endIndex);
          expressions.push(exp);
          parseFns.push($parse(exp, parseStringifyInterceptor));
          index = endIndex + endSymbolLength;
          expressionPositions.push(concat.length);
          concat.push('');
        } else {
          // we did not find an interpolation, so we have to add the remainder to the separators array
          if (index !== textLength) {
            concat.push(unescapeText(text.substring(index)));
          }
          break;
        }
      }

      // Concatenating expressions makes it hard to reason about whether some combination of
      // concatenated values are unsafe to use and could easily lead to XSS.  By requiring that a
      // single expression be used for iframe[src], object[src], etc., we ensure that the value
      // that's used is assigned or constructed by some JS code somewhere that is more testable or
      // make it obvious that you bound the value to some user controlled value.  This helps reduce
      // the load when auditing for XSS issues.
      if (trustedContext && concat.length > 1) {
          $interpolateMinErr.throwNoconcat(text);
      }

      if (!mustHaveExpression || expressions.length) {
        var compute = function(values) {
          for (var i = 0, ii = expressions.length; i < ii; i++) {
            if (allOrNothing && isUndefined(values[i])) return;
            concat[expressionPositions[i]] = values[i];
          }
          return concat.join('');
        };

        var getValue = function(value) {
          return trustedContext ?
            $sce.getTrusted(trustedContext, value) :
            $sce.valueOf(value);
        };

        return extend(function interpolationFn(context) {
            var i = 0;
            var ii = expressions.length;
            var values = new Array(ii);

            try {
              for (; i < ii; i++) {
                values[i] = parseFns[i](context);
              }

              return compute(values);
            } catch (err) {
              $exceptionHandler($interpolateMinErr.interr(text, err));
            }

          }, {
          // all of these properties are undocumented for now
          exp: text, //just for compatibility with regular watchers created via $watch
          expressions: expressions,
          $$watchDelegate: function(scope, listener) {
            var lastValue;
            return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
              var currValue = compute(values);
              if (isFunction(listener)) {
                listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
              }
              lastValue = currValue;
            });
          }
        });
      }

      function parseStringifyInterceptor(value) {
        try {
          value = getValue(value);
          return allOrNothing && !isDefined(value) ? value : stringify(value);
        } catch (err) {
          $exceptionHandler($interpolateMinErr.interr(text, err));
        }
      }
    }


    /**
     * @ngdoc method
     * @name $interpolate#startSymbol
     * @description
     * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
     *
     * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
     * the symbol.
     *
     * @returns {string} start symbol.
     */
    $interpolate.startSymbol = function() {
      return startSymbol;
    };


    /**
     * @ngdoc method
     * @name $interpolate#endSymbol
     * @description
     * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
     *
     * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
     * the symbol.
     *
     * @returns {string} end symbol.
     */
    $interpolate.endSymbol = function() {
      return endSymbol;
    };

    return $interpolate;
  }];
}

function $IntervalProvider() {
  this.$get = ['$rootScope', '$window', '$q', '$$q',
       function($rootScope,   $window,   $q,   $$q) {
    var intervals = {};


     /**
      * @ngdoc service
      * @name $interval
      *
      * @description
      * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
      * milliseconds.
      *
      * The return value of registering an interval function is a promise. This promise will be
      * notified upon each tick of the interval, and will be resolved after `count` iterations, or
      * run indefinitely if `count` is not defined. The value of the notification will be the
      * number of iterations that have run.
      * To cancel an interval, call `$interval.cancel(promise)`.
      *
      * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
      * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
      * time.
      *
      * <div class="alert alert-warning">
      * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
      * with them.  In particular they are not automatically destroyed when a controller's scope or a
      * directive's element are destroyed.
      * You should take this into consideration and make sure to always cancel the interval at the
      * appropriate moment.  See the example below for more details on how and when to do this.
      * </div>
      *
      * @param {function()} fn A function that should be called repeatedly.
      * @param {number} delay Number of milliseconds between each function call.
      * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
      *   indefinitely.
      * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
      *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
      * @param {...*=} Pass additional parameters to the executed function.
      * @returns {promise} A promise which will be notified on each iteration.
      *
      * @example
      * <example module="intervalExample">
      * <file name="index.html">
      *   <script>
      *     angular.module('intervalExample', [])
      *       .controller('ExampleController', ['$scope', '$interval',
      *         function($scope, $interval) {
      *           $scope.format = 'M/d/yy h:mm:ss a';
      *           $scope.blood_1 = 100;
      *           $scope.blood_2 = 120;
      *
      *           var stop;
      *           $scope.fight = function() {
      *             // Don't start a new fight if we are already fighting
      *             if ( angular.isDefined(stop) ) return;
      *
      *             stop = $interval(function() {
      *               if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
      *                 $scope.blood_1 = $scope.blood_1 - 3;
      *                 $scope.blood_2 = $scope.blood_2 - 4;
      *               } else {
      *                 $scope.stopFight();
      *               }
      *             }, 100);
      *           };
      *
      *           $scope.stopFight = function() {
      *             if (angular.isDefined(stop)) {
      *               $interval.cancel(stop);
      *               stop = undefined;
      *             }
      *           };
      *
      *           $scope.resetFight = function() {
      *             $scope.blood_1 = 100;
      *             $scope.blood_2 = 120;
      *           };
      *
      *           $scope.$on('$destroy', function() {
      *             // Make sure that the interval is destroyed too
      *             $scope.stopFight();
      *           });
      *         }])
      *       // Register the 'myCurrentTime' directive factory method.
      *       // We inject $interval and dateFilter service since the factory method is DI.
      *       .directive('myCurrentTime', ['$interval', 'dateFilter',
      *         function($interval, dateFilter) {
      *           // return the directive link function. (compile function not needed)
      *           return function(scope, element, attrs) {
      *             var format,  // date format
      *                 stopTime; // so that we can cancel the time updates
      *
      *             // used to update the UI
      *             function updateTime() {
      *               element.text(dateFilter(new Date(), format));
      *             }
      *
      *             // watch the expression, and update the UI on change.
      *             scope.$watch(attrs.myCurrentTime, function(value) {
      *               format = value;
      *               updateTime();
      *             });
      *
      *             stopTime = $interval(updateTime, 1000);
      *
      *             // listen on DOM destroy (removal) event, and cancel the next UI update
      *             // to prevent updating time after the DOM element was removed.
      *             element.on('$destroy', function() {
      *               $interval.cancel(stopTime);
      *             });
      *           }
      *         }]);
      *   </script>
      *
      *   <div>
      *     <div ng-controller="ExampleController">
      *       <label>Date format: <input ng-model="format"></label> <hr/>
      *       Current time is: <span my-current-time="format"></span>
      *       <hr/>
      *       Blood 1 : <font color='red'>{{blood_1}}</font>
      *       Blood 2 : <font color='red'>{{blood_2}}</font>
      *       <button type="button" data-ng-click="fight()">Fight</button>
      *       <button type="button" data-ng-click="stopFight()">StopFight</button>
      *       <button type="button" data-ng-click="resetFight()">resetFight</button>
      *     </div>
      *   </div>
      *
      * </file>
      * </example>
      */
    function interval(fn, delay, count, invokeApply) {
      var hasParams = arguments.length > 4,
          args = hasParams ? sliceArgs(arguments, 4) : [],
          setInterval = $window.setInterval,
          clearInterval = $window.clearInterval,
          iteration = 0,
          skipApply = (isDefined(invokeApply) && !invokeApply),
          deferred = (skipApply ? $$q : $q).defer(),
          promise = deferred.promise;

      count = isDefined(count) ? count : 0;

      promise.then(null, null, (!hasParams) ? fn : function() {
        fn.apply(null, args);
      });

      promise.$$intervalId = setInterval(function tick() {
        deferred.notify(iteration++);

        if (count > 0 && iteration >= count) {
          deferred.resolve(iteration);
          clearInterval(promise.$$intervalId);
          delete intervals[promise.$$intervalId];
        }

        if (!skipApply) $rootScope.$apply();

      }, delay);

      intervals[promise.$$intervalId] = deferred;

      return promise;
    }


     /**
      * @ngdoc method
      * @name $interval#cancel
      *
      * @description
      * Cancels a task associated with the `promise`.
      *
      * @param {promise} promise returned by the `$interval` function.
      * @returns {boolean} Returns `true` if the task was successfully canceled.
      */
    interval.cancel = function(promise) {
      if (promise && promise.$$intervalId in intervals) {
        intervals[promise.$$intervalId].reject('canceled');
        $window.clearInterval(promise.$$intervalId);
        delete intervals[promise.$$intervalId];
        return true;
      }
      return false;
    };

    return interval;
  }];
}

/**
 * @ngdoc service
 * @name $locale
 *
 * @description
 * $locale service provides localization rules for various Angular components. As of right now the
 * only public api is:
 *
 * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
 */
function $LocaleProvider() {
  this.$get = function() {
    return {
      id: 'en-us',

      NUMBER_FORMATS: {
        DECIMAL_SEP: '.',
        GROUP_SEP: ',',
        PATTERNS: [
          { // Decimal Pattern
            minInt: 1,
            minFrac: 0,
            maxFrac: 3,
            posPre: '',
            posSuf: '',
            negPre: '-',
            negSuf: '',
            gSize: 3,
            lgSize: 3
          },{ //Currency Pattern
            minInt: 1,
            minFrac: 2,
            maxFrac: 2,
            posPre: '\u00A4',
            posSuf: '',
            negPre: '(\u00A4',
            negSuf: ')',
            gSize: 3,
            lgSize: 3
          }
        ],
        CURRENCY_SYM: '$'
      },

      DATETIME_FORMATS: {
        MONTH:
            'January,February,March,April,May,June,July,August,September,October,November,December'
            .split(','),
        SHORTMONTH:  'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
        DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
        SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
        AMPMS: ['AM','PM'],
        medium: 'MMM d, y h:mm:ss a',
        'short': 'M/d/yy h:mm a',
        fullDate: 'EEEE, MMMM d, y',
        longDate: 'MMMM d, y',
        mediumDate: 'MMM d, y',
        shortDate: 'M/d/yy',
        mediumTime: 'h:mm:ss a',
        shortTime: 'h:mm a',
        ERANAMES: [
          "Before Christ",
          "Anno Domini"
        ],
        ERAS: [
          "BC",
          "AD"
        ]
      },

      pluralCat: function(num) {
        if (num === 1) {
          return 'one';
        }
        return 'other';
      }
    };
  };
}

var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
    DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
var $locationMinErr = minErr('$location');


/**
 * Encode path using encodeUriSegment, ignoring forward slashes
 *
 * @param {string} path Path to encode
 * @returns {string}
 */
function encodePath(path) {
  var segments = path.split('/'),
      i = segments.length;

  while (i--) {
    segments[i] = encodeUriSegment(segments[i]);
  }

  return segments.join('/');
}

function parseAbsoluteUrl(absoluteUrl, locationObj) {
  var parsedUrl = urlResolve(absoluteUrl);

  locationObj.$$protocol = parsedUrl.protocol;
  locationObj.$$host = parsedUrl.hostname;
  locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
}


function parseAppUrl(relativeUrl, locationObj) {
  var prefixed = (relativeUrl.charAt(0) !== '/');
  if (prefixed) {
    relativeUrl = '/' + relativeUrl;
  }
  var match = urlResolve(relativeUrl);
  locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
      match.pathname.substring(1) : match.pathname);
  locationObj.$$search = parseKeyValue(match.search);
  locationObj.$$hash = decodeURIComponent(match.hash);

  // make sure path starts with '/';
  if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
    locationObj.$$path = '/' + locationObj.$$path;
  }
}


/**
 *
 * @param {string} begin
 * @param {string} whole
 * @returns {string} returns text from whole after begin or undefined if it does not begin with
 *                   expected string.
 */
function beginsWith(begin, whole) {
  if (whole.indexOf(begin) === 0) {
    return whole.substr(begin.length);
  }
}


function stripHash(url) {
  var index = url.indexOf('#');
  return index == -1 ? url : url.substr(0, index);
}

function trimEmptyHash(url) {
  return url.replace(/(#.+)|#$/, '$1');
}


function stripFile(url) {
  return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
}

/* return the server only (scheme://host:port) */
function serverBase(url) {
  return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
}


/**
 * LocationHtml5Url represents an url
 * This object is exposed as $location service when HTML5 mode is enabled and supported
 *
 * @constructor
 * @param {string} appBase application base URL
 * @param {string} basePrefix url path prefix
 */
function LocationHtml5Url(appBase, basePrefix) {
  this.$$html5 = true;
  basePrefix = basePrefix || '';
  var appBaseNoFile = stripFile(appBase);
  parseAbsoluteUrl(appBase, this);


  /**
   * Parse given html5 (regular) url string into properties
   * @param {string} url HTML5 url
   * @private
   */
  this.$$parse = function(url) {
    var pathUrl = beginsWith(appBaseNoFile, url);
    if (!isString(pathUrl)) {
      throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
          appBaseNoFile);
    }

    parseAppUrl(pathUrl, this);

    if (!this.$$path) {
      this.$$path = '/';
    }

    this.$$compose();
  };

  /**
   * Compose url and update `absUrl` property
   * @private
   */
  this.$$compose = function() {
    var search = toKeyValue(this.$$search),
        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';

    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
    this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  };

  this.$$parseLinkUrl = function(url, relHref) {
    if (relHref && relHref[0] === '#') {
      // special case for links to hash fragments:
      // keep the old url and only replace the hash fragment
      this.hash(relHref.slice(1));
      return true;
    }
    var appUrl, prevAppUrl;
    var rewrittenUrl;

    if ((appUrl = beginsWith(appBase, url)) !== undefined) {
      prevAppUrl = appUrl;
      if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
        rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
      } else {
        rewrittenUrl = appBase + prevAppUrl;
      }
    } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
      rewrittenUrl = appBaseNoFile + appUrl;
    } else if (appBaseNoFile == url + '/') {
      rewrittenUrl = appBaseNoFile;
    }
    if (rewrittenUrl) {
      this.$$parse(rewrittenUrl);
    }
    return !!rewrittenUrl;
  };
}


/**
 * LocationHashbangUrl represents url
 * This object is exposed as $location service when developer doesn't opt into html5 mode.
 * It also serves as the base class for html5 mode fallback on legacy browsers.
 *
 * @constructor
 * @param {string} appBase application base URL
 * @param {string} hashPrefix hashbang prefix
 */
function LocationHashbangUrl(appBase, hashPrefix) {
  var appBaseNoFile = stripFile(appBase);

  parseAbsoluteUrl(appBase, this);


  /**
   * Parse given hashbang url into properties
   * @param {string} url Hashbang url
   * @private
   */
  this.$$parse = function(url) {
    var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
    var withoutHashUrl;

    if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {

      // The rest of the url starts with a hash so we have
      // got either a hashbang path or a plain hash fragment
      withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
      if (isUndefined(withoutHashUrl)) {
        // There was no hashbang prefix so we just have a hash fragment
        withoutHashUrl = withoutBaseUrl;
      }

    } else {
      // There was no hashbang path nor hash fragment:
      // If we are in HTML5 mode we use what is left as the path;
      // Otherwise we ignore what is left
      if (this.$$html5) {
        withoutHashUrl = withoutBaseUrl;
      } else {
        withoutHashUrl = '';
        if (isUndefined(withoutBaseUrl)) {
          appBase = url;
          this.replace();
        }
      }
    }

    parseAppUrl(withoutHashUrl, this);

    this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);

    this.$$compose();

    /*
     * In Windows, on an anchor node on documents loaded from
     * the filesystem, the browser will return a pathname
     * prefixed with the drive name ('/C:/path') when a
     * pathname without a drive is set:
     *  * a.setAttribute('href', '/foo')
     *   * a.pathname === '/C:/foo' //true
     *
     * Inside of Angular, we're always using pathnames that
     * do not include drive names for routing.
     */
    function removeWindowsDriveName(path, url, base) {
      /*
      Matches paths for file protocol on windows,
      such as /C:/foo/bar, and captures only /foo/bar.
      */
      var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;

      var firstPathSegmentMatch;

      //Get the relative path from the input URL.
      if (url.indexOf(base) === 0) {
        url = url.replace(base, '');
      }

      // The input URL intentionally contains a first path segment that ends with a colon.
      if (windowsFilePathExp.exec(url)) {
        return path;
      }

      firstPathSegmentMatch = windowsFilePathExp.exec(path);
      return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
    }
  };

  /**
   * Compose hashbang url and update `absUrl` property
   * @private
   */
  this.$$compose = function() {
    var search = toKeyValue(this.$$search),
        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';

    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
    this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  };

  this.$$parseLinkUrl = function(url, relHref) {
    if (stripHash(appBase) == stripHash(url)) {
      this.$$parse(url);
      return true;
    }
    return false;
  };
}


/**
 * LocationHashbangUrl represents url
 * This object is exposed as $location service when html5 history api is enabled but the browser
 * does not support it.
 *
 * @constructor
 * @param {string} appBase application base URL
 * @param {string} hashPrefix hashbang prefix
 */
function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  this.$$html5 = true;
  LocationHashbangUrl.apply(this, arguments);

  var appBaseNoFile = stripFile(appBase);

  this.$$parseLinkUrl = function(url, relHref) {
    if (relHref && relHref[0] === '#') {
      // special case for links to hash fragments:
      // keep the old url and only replace the hash fragment
      this.hash(relHref.slice(1));
      return true;
    }

    var rewrittenUrl;
    var appUrl;

    if (appBase == stripHash(url)) {
      rewrittenUrl = url;
    } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
      rewrittenUrl = appBase + hashPrefix + appUrl;
    } else if (appBaseNoFile === url + '/') {
      rewrittenUrl = appBaseNoFile;
    }
    if (rewrittenUrl) {
      this.$$parse(rewrittenUrl);
    }
    return !!rewrittenUrl;
  };

  this.$$compose = function() {
    var search = toKeyValue(this.$$search),
        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';

    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
    // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
    this.$$absUrl = appBase + hashPrefix + this.$$url;
  };

}


var locationPrototype = {

  /**
   * Are we in html5 mode?
   * @private
   */
  $$html5: false,

  /**
   * Has any change been replacing?
   * @private
   */
  $$replace: false,

  /**
   * @ngdoc method
   * @name $location#absUrl
   *
   * @description
   * This method is getter only.
   *
   * Return full url representation with all segments encoded according to rules specified in
   * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
   *
   *
   * ```js
   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
   * var absUrl = $location.absUrl();
   * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
   * ```
   *
   * @return {string} full url
   */
  absUrl: locationGetter('$$absUrl'),

  /**
   * @ngdoc method
   * @name $location#url
   *
   * @description
   * This method is getter / setter.
   *
   * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
   *
   * Change path, search and hash, when called with parameter and return `$location`.
   *
   *
   * ```js
   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
   * var url = $location.url();
   * // => "/some/path?foo=bar&baz=xoxo"
   * ```
   *
   * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
   * @return {string} url
   */
  url: function(url) {
    if (isUndefined(url)) {
      return this.$$url;
    }

    var match = PATH_MATCH.exec(url);
    if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
    if (match[2] || match[1] || url === '') this.search(match[3] || '');
    this.hash(match[5] || '');

    return this;
  },

  /**
   * @ngdoc method
   * @name $location#protocol
   *
   * @description
   * This method is getter only.
   *
   * Return protocol of current url.
   *
   *
   * ```js
   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
   * var protocol = $location.protocol();
   * // => "http"
   * ```
   *
   * @return {string} protocol of current url
   */
  protocol: locationGetter('$$protocol'),

  /**
   * @ngdoc method
   * @name $location#host
   *
   * @description
   * This method is getter only.
   *
   * Return host of current url.
   *
   * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
   *
   *
   * ```js
   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
   * var host = $location.host();
   * // => "example.com"
   *
   * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
   * host = $location.host();
   * // => "example.com"
   * host = location.host;
   * // => "example.com:8080"
   * ```
   *
   * @return {string} host of current url.
   */
  host: locationGetter('$$host'),

  /**
   * @ngdoc method
   * @name $location#port
   *
   * @description
   * This method is getter only.
   *
   * Return port of current url.
   *
   *
   * ```js
   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
   * var port = $location.port();
   * // => 80
   * ```
   *
   * @return {Number} port
   */
  port: locationGetter('$$port'),

  /**
   * @ngdoc method
   * @name $location#path
   *
   * @description
   * This method is getter / setter.
   *
   * Return path of current url when called without any parameter.
   *
   * Change path when called with parameter and return `$location`.
   *
   * Note: Path should always begin with forward slash (/), this method will add the forward slash
   * if it is missing.
   *
   *
   * ```js
   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
   * var path = $location.path();
   * // => "/some/path"
   * ```
   *
   * @param {(string|number)=} path New path
   * @return {string} path
   */
  path: locationGetterSetter('$$path', function(path) {
    path = path !== null ? path.toString() : '';
    return path.charAt(0) == '/' ? path : '/' + path;
  }),

  /**
   * @ngdoc method
   * @name $location#search
   *
   * @description
   * This method is getter / setter.
   *
   * Return search part (as object) of current url when called without any parameter.
   *
   * Change search part when called with parameter and return `$location`.
   *
   *
   * ```js
   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
   * var searchObject = $location.search();
   * // => {foo: 'bar', baz: 'xoxo'}
   *
   * // set foo to 'yipee'
   * $location.search('foo', 'yipee');
   * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
   * ```
   *
   * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
   * hash object.
   *
   * When called with a single argument the method acts as a setter, setting the `search` component
   * of `$location` to the specified value.
   *
   * If the argument is a hash object containing an array of values, these values will be encoded
   * as duplicate search parameters in the url.
   *
   * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
   * will override only a single search property.
   *
   * If `paramValue` is an array, it will override the property of the `search` component of
   * `$location` specified via the first argument.
   *
   * If `paramValue` is `null`, the property specified via the first argument will be deleted.
   *
   * If `paramValue` is `true`, the property specified via the first argument will be added with no
   * value nor trailing equal sign.
   *
   * @return {Object} If called with no arguments returns the parsed `search` object. If called with
   * one or more arguments returns `$location` object itself.
   */
  search: function(search, paramValue) {
    switch (arguments.length) {
      case 0:
        return this.$$search;
      case 1:
        if (isString(search) || isNumber(search)) {
          search = search.toString();
          this.$$search = parseKeyValue(search);
        } else if (isObject(search)) {
          search = copy(search, {});
          // remove object undefined or null properties
          forEach(search, function(value, key) {
            if (value == null) delete search[key];
          });

          this.$$search = search;
        } else {
          throw $locationMinErr('isrcharg',
              'The first argument of the `$location#search()` call must be a string or an object.');
        }
        break;
      default:
        if (isUndefined(paramValue) || paramValue === null) {
          delete this.$$search[search];
        } else {
          this.$$search[search] = paramValue;
        }
    }

    this.$$compose();
    return this;
  },

  /**
   * @ngdoc method
   * @name $location#hash
   *
   * @description
   * This method is getter / setter.
   *
   * Return hash fragment when called without any parameter.
   *
   * Change hash fragment when called with parameter and return `$location`.
   *
   *
   * ```js
   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
   * var hash = $location.hash();
   * // => "hashValue"
   * ```
   *
   * @param {(string|number)=} hash New hash fragment
   * @return {string} hash
   */
  hash: locationGetterSetter('$$hash', function(hash) {
    return hash !== null ? hash.toString() : '';
  }),

  /**
   * @ngdoc method
   * @name $location#replace
   *
   * @description
   * If called, all changes to $location during current `$digest` will be replacing current history
   * record, instead of adding new one.
   */
  replace: function() {
    this.$$replace = true;
    return this;
  }
};

forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  Location.prototype = Object.create(locationPrototype);

  /**
   * @ngdoc method
   * @name $location#state
   *
   * @description
   * This method is getter / setter.
   *
   * Return the history state object when called without any parameter.
   *
   * Change the history state object when called with one parameter and return `$location`.
   * The state object is later passed to `pushState` or `replaceState`.
   *
   * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
   * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
   * older browsers (like IE9 or Android < 4.0), don't use this method.
   *
   * @param {object=} state State object for pushState or replaceState
   * @return {object} state
   */
  Location.prototype.state = function(state) {
    if (!arguments.length) {
      return this.$$state;
    }

    if (Location !== LocationHtml5Url || !this.$$html5) {
      throw $locationMinErr('nostate', 'History API state support is available only ' +
        'in HTML5 mode and only in browsers supporting HTML5 History API');
    }
    // The user might modify `stateObject` after invoking `$location.state(stateObject)`
    // but we're changing the $$state reference to $browser.state() during the $digest
    // so the modification window is narrow.
    this.$$state = isUndefined(state) ? null : state;

    return this;
  };
});


function locationGetter(property) {
  return function() {
    return this[property];
  };
}


function locationGetterSetter(property, preprocess) {
  return function(value) {
    if (isUndefined(value)) {
      return this[property];
    }

    this[property] = preprocess(value);
    this.$$compose();

    return this;
  };
}


/**
 * @ngdoc service
 * @name $location
 *
 * @requires $rootElement
 *
 * @description
 * The $location service parses the URL in the browser address bar (based on the
 * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
 * available to your application. Changes to the URL in the address bar are reflected into
 * $location service and changes to $location are reflected into the browser address bar.
 *
 * **The $location service:**
 *
 * - Exposes the current URL in the browser address bar, so you can
 *   - Watch and observe the URL.
 *   - Change the URL.
 * - Synchronizes the URL with the browser when the user
 *   - Changes the address bar.
 *   - Clicks the back or forward button (or clicks a History link).
 *   - Clicks on a link.
 * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
 *
 * For more information see {@link guide/$location Developer Guide: Using $location}
 */

/**
 * @ngdoc provider
 * @name $locationProvider
 * @description
 * Use the `$locationProvider` to configure how the application deep linking paths are stored.
 */
function $LocationProvider() {
  var hashPrefix = '',
      html5Mode = {
        enabled: false,
        requireBase: true,
        rewriteLinks: true
      };

  /**
   * @ngdoc method
   * @name $locationProvider#hashPrefix
   * @description
   * @param {string=} prefix Prefix for hash part (containing path and search)
   * @returns {*} current value if used as getter or itself (chaining) if used as setter
   */
  this.hashPrefix = function(prefix) {
    if (isDefined(prefix)) {
      hashPrefix = prefix;
      return this;
    } else {
      return hashPrefix;
    }
  };

  /**
   * @ngdoc method
   * @name $locationProvider#html5Mode
   * @description
   * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
   *   If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
   *   properties:
   *   - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
   *     change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
   *     support `pushState`.
   *   - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
   *     whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
   *     true, and a base tag is not present, an error will be thrown when `$location` is injected.
   *     See the {@link guide/$location $location guide for more information}
   *   - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
   *     enables/disables url rewriting for relative links.
   *
   * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
   */
  this.html5Mode = function(mode) {
    if (isBoolean(mode)) {
      html5Mode.enabled = mode;
      return this;
    } else if (isObject(mode)) {

      if (isBoolean(mode.enabled)) {
        html5Mode.enabled = mode.enabled;
      }

      if (isBoolean(mode.requireBase)) {
        html5Mode.requireBase = mode.requireBase;
      }

      if (isBoolean(mode.rewriteLinks)) {
        html5Mode.rewriteLinks = mode.rewriteLinks;
      }

      return this;
    } else {
      return html5Mode;
    }
  };

  /**
   * @ngdoc event
   * @name $location#$locationChangeStart
   * @eventType broadcast on root scope
   * @description
   * Broadcasted before a URL will change.
   *
   * This change can be prevented by calling
   * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
   * details about event object. Upon successful change
   * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
   *
   * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
   * the browser supports the HTML5 History API.
   *
   * @param {Object} angularEvent Synthetic event object.
   * @param {string} newUrl New URL
   * @param {string=} oldUrl URL that was before it was changed.
   * @param {string=} newState New history state object
   * @param {string=} oldState History state object that was before it was changed.
   */

  /**
   * @ngdoc event
   * @name $location#$locationChangeSuccess
   * @eventType broadcast on root scope
   * @description
   * Broadcasted after a URL was changed.
   *
   * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
   * the browser supports the HTML5 History API.
   *
   * @param {Object} angularEvent Synthetic event object.
   * @param {string} newUrl New URL
   * @param {string=} oldUrl URL that was before it was changed.
   * @param {string=} newState New history state object
   * @param {string=} oldState History state object that was before it was changed.
   */

  this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
      function($rootScope, $browser, $sniffer, $rootElement, $window) {
    var $location,
        LocationMode,
        baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
        initialUrl = $browser.url(),
        appBase;

    if (html5Mode.enabled) {
      if (!baseHref && html5Mode.requireBase) {
        throw $locationMinErr('nobase',
          "$location in HTML5 mode requires a <base> tag to be present!");
      }
      appBase = serverBase(initialUrl) + (baseHref || '/');
      LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
    } else {
      appBase = stripHash(initialUrl);
      LocationMode = LocationHashbangUrl;
    }
    $location = new LocationMode(appBase, '#' + hashPrefix);
    $location.$$parseLinkUrl(initialUrl, initialUrl);

    $location.$$state = $browser.state();

    var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;

    function setBrowserUrlWithFallback(url, replace, state) {
      var oldUrl = $location.url();
      var oldState = $location.$$state;
      try {
        $browser.url(url, replace, state);

        // Make sure $location.state() returns referentially identical (not just deeply equal)
        // state object; this makes possible quick checking if the state changed in the digest
        // loop. Checking deep equality would be too expensive.
        $location.$$state = $browser.state();
      } catch (e) {
        // Restore old values if pushState fails
        $location.url(oldUrl);
        $location.$$state = oldState;

        throw e;
      }
    }

    $rootElement.on('click', function(event) {
      // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
      // currently we open nice url link and redirect then

      if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;

      var elm = jqLite(event.target);

      // traverse the DOM up to find first A tag
      while (nodeName_(elm[0]) !== 'a') {
        // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
        if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
      }

      var absHref = elm.prop('href');
      // get the actual href attribute - see
      // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
      var relHref = elm.attr('href') || elm.attr('xlink:href');

      if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
        // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
        // an animation.
        absHref = urlResolve(absHref.animVal).href;
      }

      // Ignore when url is started with javascript: or mailto:
      if (IGNORE_URI_REGEXP.test(absHref)) return;

      if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
        if ($location.$$parseLinkUrl(absHref, relHref)) {
          // We do a preventDefault for all urls that are part of the angular application,
          // in html5mode and also without, so that we are able to abort navigation without
          // getting double entries in the location history.
          event.preventDefault();
          // update location manually
          if ($location.absUrl() != $browser.url()) {
            $rootScope.$apply();
            // hack to work around FF6 bug 684208 when scenario runner clicks on links
            $window.angular['ff-684208-preventDefault'] = true;
          }
        }
      }
    });


    // rewrite hashbang url <> html5 url
    if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
      $browser.url($location.absUrl(), true);
    }

    var initializing = true;

    // update $location when $browser url changes
    $browser.onUrlChange(function(newUrl, newState) {
      $rootScope.$evalAsync(function() {
        var oldUrl = $location.absUrl();
        var oldState = $location.$$state;
        var defaultPrevented;

        $location.$$parse(newUrl);
        $location.$$state = newState;

        defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
            newState, oldState).defaultPrevented;

        // if the location was changed by a `$locationChangeStart` handler then stop
        // processing this location change
        if ($location.absUrl() !== newUrl) return;

        if (defaultPrevented) {
          $location.$$parse(oldUrl);
          $location.$$state = oldState;
          setBrowserUrlWithFallback(oldUrl, false, oldState);
        } else {
          initializing = false;
          afterLocationChange(oldUrl, oldState);
        }
      });
      if (!$rootScope.$$phase) $rootScope.$digest();
    });

    // update browser
    $rootScope.$watch(function $locationWatch() {
      var oldUrl = trimEmptyHash($browser.url());
      var newUrl = trimEmptyHash($location.absUrl());
      var oldState = $browser.state();
      var currentReplace = $location.$$replace;
      var urlOrStateChanged = oldUrl !== newUrl ||
        ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);

      if (initializing || urlOrStateChanged) {
        initializing = false;

        $rootScope.$evalAsync(function() {
          var newUrl = $location.absUrl();
          var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
              $location.$$state, oldState).defaultPrevented;

          // if the location was changed by a `$locationChangeStart` handler then stop
          // processing this location change
          if ($location.absUrl() !== newUrl) return;

          if (defaultPrevented) {
            $location.$$parse(oldUrl);
            $location.$$state = oldState;
          } else {
            if (urlOrStateChanged) {
              setBrowserUrlWithFallback(newUrl, currentReplace,
                                        oldState === $location.$$state ? null : $location.$$state);
            }
            afterLocationChange(oldUrl, oldState);
          }
        });
      }

      $location.$$replace = false;

      // we don't need to return anything because $evalAsync will make the digest loop dirty when
      // there is a change
    });

    return $location;

    function afterLocationChange(oldUrl, oldState) {
      $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
        $location.$$state, oldState);
    }
}];
}

/**
 * @ngdoc service
 * @name $log
 * @requires $window
 *
 * @description
 * Simple service for logging. Default implementation safely writes the message
 * into the browser's console (if present).
 *
 * The main purpose of this service is to simplify debugging and troubleshooting.
 *
 * The default is to log `debug` messages. You can use
 * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
 *
 * @example
   <example module="logExample">
     <file name="script.js">
       angular.module('logExample', [])
         .controller('LogController', ['$scope', '$log', function($scope, $log) {
           $scope.$log = $log;
           $scope.message = 'Hello World!';
         }]);
     </file>
     <file name="index.html">
       <div ng-controller="LogController">
         <p>Reload this page with open console, enter text and hit the log button...</p>
         <label>Message:
         <input type="text" ng-model="message" /></label>
         <button ng-click="$log.log(message)">log</button>
         <button ng-click="$log.warn(message)">warn</button>
         <button ng-click="$log.info(message)">info</button>
         <button ng-click="$log.error(message)">error</button>
         <button ng-click="$log.debug(message)">debug</button>
       </div>
     </file>
   </example>
 */

/**
 * @ngdoc provider
 * @name $logProvider
 * @description
 * Use the `$logProvider` to configure how the application logs messages
 */
function $LogProvider() {
  var debug = true,
      self = this;

  /**
   * @ngdoc method
   * @name $logProvider#debugEnabled
   * @description
   * @param {boolean=} flag enable or disable debug level messages
   * @returns {*} current value if used as getter or itself (chaining) if used as setter
   */
  this.debugEnabled = function(flag) {
    if (isDefined(flag)) {
      debug = flag;
    return this;
    } else {
      return debug;
    }
  };

  this.$get = ['$window', function($window) {
    return {
      /**
       * @ngdoc method
       * @name $log#log
       *
       * @description
       * Write a log message
       */
      log: consoleLog('log'),

      /**
       * @ngdoc method
       * @name $log#info
       *
       * @description
       * Write an information message
       */
      info: consoleLog('info'),

      /**
       * @ngdoc method
       * @name $log#warn
       *
       * @description
       * Write a warning message
       */
      warn: consoleLog('warn'),

      /**
       * @ngdoc method
       * @name $log#error
       *
       * @description
       * Write an error message
       */
      error: consoleLog('error'),

      /**
       * @ngdoc method
       * @name $log#debug
       *
       * @description
       * Write a debug message
       */
      debug: (function() {
        var fn = consoleLog('debug');

        return function() {
          if (debug) {
            fn.apply(self, arguments);
          }
        };
      }())
    };

    function formatError(arg) {
      if (arg instanceof Error) {
        if (arg.stack) {
          arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
              ? 'Error: ' + arg.message + '\n' + arg.stack
              : arg.stack;
        } else if (arg.sourceURL) {
          arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
        }
      }
      return arg;
    }

    function consoleLog(type) {
      var console = $window.console || {},
          logFn = console[type] || console.log || noop,
          hasApply = false;

      // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
      // The reason behind this is that console.log has type "object" in IE8...
      try {
        hasApply = !!logFn.apply;
      } catch (e) {}

      if (hasApply) {
        return function() {
          var args = [];
          forEach(arguments, function(arg) {
            args.push(formatError(arg));
          });
          return logFn.apply(console, args);
        };
      }

      // we are IE which either doesn't have window.console => this is noop and we do nothing,
      // or we are IE where console.log doesn't have apply so we log at least first 2 args
      return function(arg1, arg2) {
        logFn(arg1, arg2 == null ? '' : arg2);
      };
    }
  }];
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *     Any commits to this file should be reviewed with security in mind.  *
 *   Changes to this file can potentially create security vulnerabilities. *
 *          An approval from 2 Core members with history of modifying      *
 *                         this file is required.                          *
 *                                                                         *
 *  Does the change somehow allow for arbitrary javascript to be executed? *
 *    Or allows for someone to change the prototype of built-in objects?   *
 *     Or gives undesired access to variables likes document or window?    *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

var $parseMinErr = minErr('$parse');

// Sandboxing Angular Expressions
// ------------------------------
// Angular expressions are generally considered safe because these expressions only have direct
// access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
// obtaining a reference to native JS functions such as the Function constructor.
//
// As an example, consider the following Angular expression:
//
//   {}.toString.constructor('alert("evil JS code")')
//
// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
// against the expression language, but not to prevent exploits that were enabled by exposing
// sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
// practice and therefore we are not even trying to protect against interaction with an object
// explicitly exposed in this way.
//
// In general, it is not possible to access a Window object from an angular expression unless a
// window or some DOM object that has a reference to window is published onto a Scope.
// Similarly we prevent invocations of function known to be dangerous, as well as assignments to
// native objects.
//
// See https://docs.angularjs.org/guide/security


function ensureSafeMemberName(name, fullExpression) {
  if (name === "__defineGetter__" || name === "__defineSetter__"
      || name === "__lookupGetter__" || name === "__lookupSetter__"
      || name === "__proto__") {
    throw $parseMinErr('isecfld',
        'Attempting to access a disallowed field in Angular expressions! '
        + 'Expression: {0}', fullExpression);
  }
  return name;
}

function ensureSafeObject(obj, fullExpression) {
  // nifty check if obj is Function that is fast and works across iframes and other contexts
  if (obj) {
    if (obj.constructor === obj) {
      throw $parseMinErr('isecfn',
          'Referencing Function in Angular expressions is disallowed! Expression: {0}',
          fullExpression);
    } else if (// isWindow(obj)
        obj.window === obj) {
      throw $parseMinErr('isecwindow',
          'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
          fullExpression);
    } else if (// isElement(obj)
        obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
      throw $parseMinErr('isecdom',
          'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
          fullExpression);
    } else if (// block Object so that we can't get hold of dangerous Object.* methods
        obj === Object) {
      throw $parseMinErr('isecobj',
          'Referencing Object in Angular expressions is disallowed! Expression: {0}',
          fullExpression);
    }
  }
  return obj;
}

var CALL = Function.prototype.call;
var APPLY = Function.prototype.apply;
var BIND = Function.prototype.bind;

function ensureSafeFunction(obj, fullExpression) {
  if (obj) {
    if (obj.constructor === obj) {
      throw $parseMinErr('isecfn',
        'Referencing Function in Angular expressions is disallowed! Expression: {0}',
        fullExpression);
    } else if (obj === CALL || obj === APPLY || obj === BIND) {
      throw $parseMinErr('isecff',
        'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
        fullExpression);
    }
  }
}

var OPERATORS = createMap();
forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};


/////////////////////////////////////////


/**
 * @constructor
 */
var Lexer = function(options) {
  this.options = options;
};

Lexer.prototype = {
  constructor: Lexer,

  lex: function(text) {
    this.text = text;
    this.index = 0;
    this.tokens = [];

    while (this.index < this.text.length) {
      var ch = this.text.charAt(this.index);
      if (ch === '"' || ch === "'") {
        this.readString(ch);
      } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
        this.readNumber();
      } else if (this.isIdent(ch)) {
        this.readIdent();
      } else if (this.is(ch, '(){}[].,;:?')) {
        this.tokens.push({index: this.index, text: ch});
        this.index++;
      } else if (this.isWhitespace(ch)) {
        this.index++;
      } else {
        var ch2 = ch + this.peek();
        var ch3 = ch2 + this.peek(2);
        var op1 = OPERATORS[ch];
        var op2 = OPERATORS[ch2];
        var op3 = OPERATORS[ch3];
        if (op1 || op2 || op3) {
          var token = op3 ? ch3 : (op2 ? ch2 : ch);
          this.tokens.push({index: this.index, text: token, operator: true});
          this.index += token.length;
        } else {
          this.throwError('Unexpected next character ', this.index, this.index + 1);
        }
      }
    }
    return this.tokens;
  },

  is: function(ch, chars) {
    return chars.indexOf(ch) !== -1;
  },

  peek: function(i) {
    var num = i || 1;
    return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  },

  isNumber: function(ch) {
    return ('0' <= ch && ch <= '9') && typeof ch === "string";
  },

  isWhitespace: function(ch) {
    // IE treats non-breaking space as \u00A0
    return (ch === ' ' || ch === '\r' || ch === '\t' ||
            ch === '\n' || ch === '\v' || ch === '\u00A0');
  },

  isIdent: function(ch) {
    return ('a' <= ch && ch <= 'z' ||
            'A' <= ch && ch <= 'Z' ||
            '_' === ch || ch === '$');
  },

  isExpOperator: function(ch) {
    return (ch === '-' || ch === '+' || this.isNumber(ch));
  },

  throwError: function(error, start, end) {
    end = end || this.index;
    var colStr = (isDefined(start)
            ? 's ' + start +  '-' + this.index + ' [' + this.text.substring(start, end) + ']'
            : ' ' + end);
    throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
        error, colStr, this.text);
  },

  readNumber: function() {
    var number = '';
    var start = this.index;
    while (this.index < this.text.length) {
      var ch = lowercase(this.text.charAt(this.index));
      if (ch == '.' || this.isNumber(ch)) {
        number += ch;
      } else {
        var peekCh = this.peek();
        if (ch == 'e' && this.isExpOperator(peekCh)) {
          number += ch;
        } else if (this.isExpOperator(ch) &&
            peekCh && this.isNumber(peekCh) &&
            number.charAt(number.length - 1) == 'e') {
          number += ch;
        } else if (this.isExpOperator(ch) &&
            (!peekCh || !this.isNumber(peekCh)) &&
            number.charAt(number.length - 1) == 'e') {
          this.throwError('Invalid exponent');
        } else {
          break;
        }
      }
      this.index++;
    }
    this.tokens.push({
      index: start,
      text: number,
      constant: true,
      value: Number(number)
    });
  },

  readIdent: function() {
    var start = this.index;
    while (this.index < this.text.length) {
      var ch = this.text.charAt(this.index);
      if (!(this.isIdent(ch) || this.isNumber(ch))) {
        break;
      }
      this.index++;
    }
    this.tokens.push({
      index: start,
      text: this.text.slice(start, this.index),
      identifier: true
    });
  },

  readString: function(quote) {
    var start = this.index;
    this.index++;
    var string = '';
    var rawString = quote;
    var escape = false;
    while (this.index < this.text.length) {
      var ch = this.text.charAt(this.index);
      rawString += ch;
      if (escape) {
        if (ch === 'u') {
          var hex = this.text.substring(this.index + 1, this.index + 5);
          if (!hex.match(/[\da-f]{4}/i)) {
            this.throwError('Invalid unicode escape [\\u' + hex + ']');
          }
          this.index += 4;
          string += String.fromCharCode(parseInt(hex, 16));
        } else {
          var rep = ESCAPE[ch];
          string = string + (rep || ch);
        }
        escape = false;
      } else if (ch === '\\') {
        escape = true;
      } else if (ch === quote) {
        this.index++;
        this.tokens.push({
          index: start,
          text: rawString,
          constant: true,
          value: string
        });
        return;
      } else {
        string += ch;
      }
      this.index++;
    }
    this.throwError('Unterminated quote', start);
  }
};

var AST = function(lexer, options) {
  this.lexer = lexer;
  this.options = options;
};

AST.Program = 'Program';
AST.ExpressionStatement = 'ExpressionStatement';
AST.AssignmentExpression = 'AssignmentExpression';
AST.ConditionalExpression = 'ConditionalExpression';
AST.LogicalExpression = 'LogicalExpression';
AST.BinaryExpression = 'BinaryExpression';
AST.UnaryExpression = 'UnaryExpression';
AST.CallExpression = 'CallExpression';
AST.MemberExpression = 'MemberExpression';
AST.Identifier = 'Identifier';
AST.Literal = 'Literal';
AST.ArrayExpression = 'ArrayExpression';
AST.Property = 'Property';
AST.ObjectExpression = 'ObjectExpression';
AST.ThisExpression = 'ThisExpression';

// Internal use only
AST.NGValueParameter = 'NGValueParameter';

AST.prototype = {
  ast: function(text) {
    this.text = text;
    this.tokens = this.lexer.lex(text);

    var value = this.program();

    if (this.tokens.length !== 0) {
      this.throwError('is an unexpected token', this.tokens[0]);
    }

    return value;
  },

  program: function() {
    var body = [];
    while (true) {
      if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
        body.push(this.expressionStatement());
      if (!this.expect(';')) {
        return { type: AST.Program, body: body};
      }
    }
  },

  expressionStatement: function() {
    return { type: AST.ExpressionStatement, expression: this.filterChain() };
  },

  filterChain: function() {
    var left = this.expression();
    var token;
    while ((token = this.expect('|'))) {
      left = this.filter(left);
    }
    return left;
  },

  expression: function() {
    return this.assignment();
  },

  assignment: function() {
    var result = this.ternary();
    if (this.expect('=')) {
      result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
    }
    return result;
  },

  ternary: function() {
    var test = this.logicalOR();
    var alternate;
    var consequent;
    if (this.expect('?')) {
      alternate = this.expression();
      if (this.consume(':')) {
        consequent = this.expression();
        return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
      }
    }
    return test;
  },

  logicalOR: function() {
    var left = this.logicalAND();
    while (this.expect('||')) {
      left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
    }
    return left;
  },

  logicalAND: function() {
    var left = this.equality();
    while (this.expect('&&')) {
      left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
    }
    return left;
  },

  equality: function() {
    var left = this.relational();
    var token;
    while ((token = this.expect('==','!=','===','!=='))) {
      left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
    }
    return left;
  },

  relational: function() {
    var left = this.additive();
    var token;
    while ((token = this.expect('<', '>', '<=', '>='))) {
      left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
    }
    return left;
  },

  additive: function() {
    var left = this.multiplicative();
    var token;
    while ((token = this.expect('+','-'))) {
      left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
    }
    return left;
  },

  multiplicative: function() {
    var left = this.unary();
    var token;
    while ((token = this.expect('*','/','%'))) {
      left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
    }
    return left;
  },

  unary: function() {
    var token;
    if ((token = this.expect('+', '-', '!'))) {
      return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
    } else {
      return this.primary();
    }
  },

  primary: function() {
    var primary;
    if (this.expect('(')) {
      primary = this.filterChain();
      this.consume(')');
    } else if (this.expect('[')) {
      primary = this.arrayDeclaration();
    } else if (this.expect('{')) {
      primary = this.object();
    } else if (this.constants.hasOwnProperty(this.peek().text)) {
      primary = copy(this.constants[this.consume().text]);
    } else if (this.peek().identifier) {
      primary = this.identifier();
    } else if (this.peek().constant) {
      primary = this.constant();
    } else {
      this.throwError('not a primary expression', this.peek());
    }

    var next;
    while ((next = this.expect('(', '[', '.'))) {
      if (next.text === '(') {
        primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
        this.consume(')');
      } else if (next.text === '[') {
        primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
        this.consume(']');
      } else if (next.text === '.') {
        primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
      } else {
        this.throwError('IMPOSSIBLE');
      }
    }
    return primary;
  },

  filter: function(baseExpression) {
    var args = [baseExpression];
    var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};

    while (this.expect(':')) {
      args.push(this.expression());
    }

    return result;
  },

  parseArguments: function() {
    var args = [];
    if (this.peekToken().text !== ')') {
      do {
        args.push(this.expression());
      } while (this.expect(','));
    }
    return args;
  },

  identifier: function() {
    var token = this.consume();
    if (!token.identifier) {
      this.throwError('is not a valid identifier', token);
    }
    return { type: AST.Identifier, name: token.text };
  },

  constant: function() {
    // TODO check that it is a constant
    return { type: AST.Literal, value: this.consume().value };
  },

  arrayDeclaration: function() {
    var elements = [];
    if (this.peekToken().text !== ']') {
      do {
        if (this.peek(']')) {
          // Support trailing commas per ES5.1.
          break;
        }
        elements.push(this.expression());
      } while (this.expect(','));
    }
    this.consume(']');

    return { type: AST.ArrayExpression, elements: elements };
  },

  object: function() {
    var properties = [], property;
    if (this.peekToken().text !== '}') {
      do {
        if (this.peek('}')) {
          // Support trailing commas per ES5.1.
          break;
        }
        property = {type: AST.Property, kind: 'init'};
        if (this.peek().constant) {
          property.key = this.constant();
        } else if (this.peek().identifier) {
          property.key = this.identifier();
        } else {
          this.throwError("invalid key", this.peek());
        }
        this.consume(':');
        property.value = this.expression();
        properties.push(property);
      } while (this.expect(','));
    }
    this.consume('}');

    return {type: AST.ObjectExpression, properties: properties };
  },

  throwError: function(msg, token) {
    throw $parseMinErr('syntax',
        'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
          token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  },

  consume: function(e1) {
    if (this.tokens.length === 0) {
      throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
    }

    var token = this.expect(e1);
    if (!token) {
      this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
    }
    return token;
  },

  peekToken: function() {
    if (this.tokens.length === 0) {
      throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
    }
    return this.tokens[0];
  },

  peek: function(e1, e2, e3, e4) {
    return this.peekAhead(0, e1, e2, e3, e4);
  },

  peekAhead: function(i, e1, e2, e3, e4) {
    if (this.tokens.length > i) {
      var token = this.tokens[i];
      var t = token.text;
      if (t === e1 || t === e2 || t === e3 || t === e4 ||
          (!e1 && !e2 && !e3 && !e4)) {
        return token;
      }
    }
    return false;
  },

  expect: function(e1, e2, e3, e4) {
    var token = this.peek(e1, e2, e3, e4);
    if (token) {
      this.tokens.shift();
      return token;
    }
    return false;
  },


  /* `undefined` is not a constant, it is an identifier,
   * but using it as an identifier is not supported
   */
  constants: {
    'true': { type: AST.Literal, value: true },
    'false': { type: AST.Literal, value: false },
    'null': { type: AST.Literal, value: null },
    'undefined': {type: AST.Literal, value: undefined },
    'this': {type: AST.ThisExpression }
  }
};

function ifDefined(v, d) {
  return typeof v !== 'undefined' ? v : d;
}

function plusFn(l, r) {
  if (typeof l === 'undefined') return r;
  if (typeof r === 'undefined') return l;
  return l + r;
}

function isStateless($filter, filterName) {
  var fn = $filter(filterName);
  return !fn.$stateful;
}

function findConstantAndWatchExpressions(ast, $filter) {
  var allConstants;
  var argsToWatch;
  switch (ast.type) {
  case AST.Program:
    allConstants = true;
    forEach(ast.body, function(expr) {
      findConstantAndWatchExpressions(expr.expression, $filter);
      allConstants = allConstants && expr.expression.constant;
    });
    ast.constant = allConstants;
    break;
  case AST.Literal:
    ast.constant = true;
    ast.toWatch = [];
    break;
  case AST.UnaryExpression:
    findConstantAndWatchExpressions(ast.argument, $filter);
    ast.constant = ast.argument.constant;
    ast.toWatch = ast.argument.toWatch;
    break;
  case AST.BinaryExpression:
    findConstantAndWatchExpressions(ast.left, $filter);
    findConstantAndWatchExpressions(ast.right, $filter);
    ast.constant = ast.left.constant && ast.right.constant;
    ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
    break;
  case AST.LogicalExpression:
    findConstantAndWatchExpressions(ast.left, $filter);
    findConstantAndWatchExpressions(ast.right, $filter);
    ast.constant = ast.left.constant && ast.right.constant;
    ast.toWatch = ast.constant ? [] : [ast];
    break;
  case AST.ConditionalExpression:
    findConstantAndWatchExpressions(ast.test, $filter);
    findConstantAndWatchExpressions(ast.alternate, $filter);
    findConstantAndWatchExpressions(ast.consequent, $filter);
    ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
    ast.toWatch = ast.constant ? [] : [ast];
    break;
  case AST.Identifier:
    ast.constant = false;
    ast.toWatch = [ast];
    break;
  case AST.MemberExpression:
    findConstantAndWatchExpressions(ast.object, $filter);
    if (ast.computed) {
      findConstantAndWatchExpressions(ast.property, $filter);
    }
    ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
    ast.toWatch = [ast];
    break;
  case AST.CallExpression:
    allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
    argsToWatch = [];
    forEach(ast.arguments, function(expr) {
      findConstantAndWatchExpressions(expr, $filter);
      allConstants = allConstants && expr.constant;
      if (!expr.constant) {
        argsToWatch.push.apply(argsToWatch, expr.toWatch);
      }
    });
    ast.constant = allConstants;
    ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
    break;
  case AST.AssignmentExpression:
    findConstantAndWatchExpressions(ast.left, $filter);
    findConstantAndWatchExpressions(ast.right, $filter);
    ast.constant = ast.left.constant && ast.right.constant;
    ast.toWatch = [ast];
    break;
  case AST.ArrayExpression:
    allConstants = true;
    argsToWatch = [];
    forEach(ast.elements, function(expr) {
      findConstantAndWatchExpressions(expr, $filter);
      allConstants = allConstants && expr.constant;
      if (!expr.constant) {
        argsToWatch.push.apply(argsToWatch, expr.toWatch);
      }
    });
    ast.constant = allConstants;
    ast.toWatch = argsToWatch;
    break;
  case AST.ObjectExpression:
    allConstants = true;
    argsToWatch = [];
    forEach(ast.properties, function(property) {
      findConstantAndWatchExpressions(property.value, $filter);
      allConstants = allConstants && property.value.constant;
      if (!property.value.constant) {
        argsToWatch.push.apply(argsToWatch, property.value.toWatch);
      }
    });
    ast.constant = allConstants;
    ast.toWatch = argsToWatch;
    break;
  case AST.ThisExpression:
    ast.constant = false;
    ast.toWatch = [];
    break;
  }
}

function getInputs(body) {
  if (body.length != 1) return;
  var lastExpression = body[0].expression;
  var candidate = lastExpression.toWatch;
  if (candidate.length !== 1) return candidate;
  return candidate[0] !== lastExpression ? candidate : undefined;
}

function isAssignable(ast) {
  return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
}

function assignableAST(ast) {
  if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
    return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  }
}

function isLiteral(ast) {
  return ast.body.length === 0 ||
      ast.body.length === 1 && (
      ast.body[0].expression.type === AST.Literal ||
      ast.body[0].expression.type === AST.ArrayExpression ||
      ast.body[0].expression.type === AST.ObjectExpression);
}

function isConstant(ast) {
  return ast.constant;
}

function ASTCompiler(astBuilder, $filter) {
  this.astBuilder = astBuilder;
  this.$filter = $filter;
}

ASTCompiler.prototype = {
  compile: function(expression, expensiveChecks) {
    var self = this;
    var ast = this.astBuilder.ast(expression);
    this.state = {
      nextId: 0,
      filters: {},
      expensiveChecks: expensiveChecks,
      fn: {vars: [], body: [], own: {}},
      assign: {vars: [], body: [], own: {}},
      inputs: []
    };
    findConstantAndWatchExpressions(ast, self.$filter);
    var extra = '';
    var assignable;
    this.stage = 'assign';
    if ((assignable = assignableAST(ast))) {
      this.state.computing = 'assign';
      var result = this.nextId();
      this.recurse(assignable, result);
      extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
    }
    var toWatch = getInputs(ast.body);
    self.stage = 'inputs';
    forEach(toWatch, function(watch, key) {
      var fnKey = 'fn' + key;
      self.state[fnKey] = {vars: [], body: [], own: {}};
      self.state.computing = fnKey;
      var intoId = self.nextId();
      self.recurse(watch, intoId);
      self.return_(intoId);
      self.state.inputs.push(fnKey);
      watch.watchId = key;
    });
    this.state.computing = 'fn';
    this.stage = 'main';
    this.recurse(ast);
    var fnString =
      // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
      // This is a workaround for this until we do a better job at only removing the prefix only when we should.
      '"' + this.USE + ' ' + this.STRICT + '";\n' +
      this.filterPrefix() +
      'var fn=' + this.generateFunction('fn', 's,l,a,i') +
      extra +
      this.watchFns() +
      'return fn;';

    /* jshint -W054 */
    var fn = (new Function('$filter',
        'ensureSafeMemberName',
        'ensureSafeObject',
        'ensureSafeFunction',
        'ifDefined',
        'plus',
        'text',
        fnString))(
          this.$filter,
          ensureSafeMemberName,
          ensureSafeObject,
          ensureSafeFunction,
          ifDefined,
          plusFn,
          expression);
    /* jshint +W054 */
    this.state = this.stage = undefined;
    fn.literal = isLiteral(ast);
    fn.constant = isConstant(ast);
    return fn;
  },

  USE: 'use',

  STRICT: 'strict',

  watchFns: function() {
    var result = [];
    var fns = this.state.inputs;
    var self = this;
    forEach(fns, function(name) {
      result.push('var ' + name + '=' + self.generateFunction(name, 's'));
    });
    if (fns.length) {
      result.push('fn.inputs=[' + fns.join(',') + '];');
    }
    return result.join('');
  },

  generateFunction: function(name, params) {
    return 'function(' + params + '){' +
        this.varsPrefix(name) +
        this.body(name) +
        '};';
  },

  filterPrefix: function() {
    var parts = [];
    var self = this;
    forEach(this.state.filters, function(id, filter) {
      parts.push(id + '=$filter(' + self.escape(filter) + ')');
    });
    if (parts.length) return 'var ' + parts.join(',') + ';';
    return '';
  },

  varsPrefix: function(section) {
    return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  },

  body: function(section) {
    return this.state[section].body.join('');
  },

  recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
    var left, right, self = this, args, expression;
    recursionFn = recursionFn || noop;
    if (!skipWatchIdCheck && isDefined(ast.watchId)) {
      intoId = intoId || this.nextId();
      this.if_('i',
        this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
        this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
      );
      return;
    }
    switch (ast.type) {
    case AST.Program:
      forEach(ast.body, function(expression, pos) {
        self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
        if (pos !== ast.body.length - 1) {
          self.current().body.push(right, ';');
        } else {
          self.return_(right);
        }
      });
      break;
    case AST.Literal:
      expression = this.escape(ast.value);
      this.assign(intoId, expression);
      recursionFn(expression);
      break;
    case AST.UnaryExpression:
      this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
      expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
      this.assign(intoId, expression);
      recursionFn(expression);
      break;
    case AST.BinaryExpression:
      this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
      this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
      if (ast.operator === '+') {
        expression = this.plus(left, right);
      } else if (ast.operator === '-') {
        expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
      } else {
        expression = '(' + left + ')' + ast.operator + '(' + right + ')';
      }
      this.assign(intoId, expression);
      recursionFn(expression);
      break;
    case AST.LogicalExpression:
      intoId = intoId || this.nextId();
      self.recurse(ast.left, intoId);
      self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
      recursionFn(intoId);
      break;
    case AST.ConditionalExpression:
      intoId = intoId || this.nextId();
      self.recurse(ast.test, intoId);
      self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
      recursionFn(intoId);
      break;
    case AST.Identifier:
      intoId = intoId || this.nextId();
      if (nameId) {
        nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
        nameId.computed = false;
        nameId.name = ast.name;
      }
      ensureSafeMemberName(ast.name);
      self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
        function() {
          self.if_(self.stage === 'inputs' || 's', function() {
            if (create && create !== 1) {
              self.if_(
                self.not(self.nonComputedMember('s', ast.name)),
                self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
            }
            self.assign(intoId, self.nonComputedMember('s', ast.name));
          });
        }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
        );
      if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
        self.addEnsureSafeObject(intoId);
      }
      recursionFn(intoId);
      break;
    case AST.MemberExpression:
      left = nameId && (nameId.context = this.nextId()) || this.nextId();
      intoId = intoId || this.nextId();
      self.recurse(ast.object, left, undefined, function() {
        self.if_(self.notNull(left), function() {
          if (ast.computed) {
            right = self.nextId();
            self.recurse(ast.property, right);
            self.addEnsureSafeMemberName(right);
            if (create && create !== 1) {
              self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
            }
            expression = self.ensureSafeObject(self.computedMember(left, right));
            self.assign(intoId, expression);
            if (nameId) {
              nameId.computed = true;
              nameId.name = right;
            }
          } else {
            ensureSafeMemberName(ast.property.name);
            if (create && create !== 1) {
              self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
            }
            expression = self.nonComputedMember(left, ast.property.name);
            if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
              expression = self.ensureSafeObject(expression);
            }
            self.assign(intoId, expression);
            if (nameId) {
              nameId.computed = false;
              nameId.name = ast.property.name;
            }
          }
        }, function() {
          self.assign(intoId, 'undefined');
        });
        recursionFn(intoId);
      }, !!create);
      break;
    case AST.CallExpression:
      intoId = intoId || this.nextId();
      if (ast.filter) {
        right = self.filter(ast.callee.name);
        args = [];
        forEach(ast.arguments, function(expr) {
          var argument = self.nextId();
          self.recurse(expr, argument);
          args.push(argument);
        });
        expression = right + '(' + args.join(',') + ')';
        self.assign(intoId, expression);
        recursionFn(intoId);
      } else {
        right = self.nextId();
        left = {};
        args = [];
        self.recurse(ast.callee, right, left, function() {
          self.if_(self.notNull(right), function() {
            self.addEnsureSafeFunction(right);
            forEach(ast.arguments, function(expr) {
              self.recurse(expr, self.nextId(), undefined, function(argument) {
                args.push(self.ensureSafeObject(argument));
              });
            });
            if (left.name) {
              if (!self.state.expensiveChecks) {
                self.addEnsureSafeObject(left.context);
              }
              expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
            } else {
              expression = right + '(' + args.join(',') + ')';
            }
            expression = self.ensureSafeObject(expression);
            self.assign(intoId, expression);
          }, function() {
            self.assign(intoId, 'undefined');
          });
          recursionFn(intoId);
        });
      }
      break;
    case AST.AssignmentExpression:
      right = this.nextId();
      left = {};
      if (!isAssignable(ast.left)) {
        throw $parseMinErr('lval', 'Trying to assing a value to a non l-value');
      }
      this.recurse(ast.left, undefined, left, function() {
        self.if_(self.notNull(left.context), function() {
          self.recurse(ast.right, right);
          self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
          expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
          self.assign(intoId, expression);
          recursionFn(intoId || expression);
        });
      }, 1);
      break;
    case AST.ArrayExpression:
      args = [];
      forEach(ast.elements, function(expr) {
        self.recurse(expr, self.nextId(), undefined, function(argument) {
          args.push(argument);
        });
      });
      expression = '[' + args.join(',') + ']';
      this.assign(intoId, expression);
      recursionFn(expression);
      break;
    case AST.ObjectExpression:
      args = [];
      forEach(ast.properties, function(property) {
        self.recurse(property.value, self.nextId(), undefined, function(expr) {
          args.push(self.escape(
              property.key.type === AST.Identifier ? property.key.name :
                ('' + property.key.value)) +
              ':' + expr);
        });
      });
      expression = '{' + args.join(',') + '}';
      this.assign(intoId, expression);
      recursionFn(expression);
      break;
    case AST.ThisExpression:
      this.assign(intoId, 's');
      recursionFn('s');
      break;
    case AST.NGValueParameter:
      this.assign(intoId, 'v');
      recursionFn('v');
      break;
    }
  },

  getHasOwnProperty: function(element, property) {
    var key = element + '.' + property;
    var own = this.current().own;
    if (!own.hasOwnProperty(key)) {
      own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
    }
    return own[key];
  },

  assign: function(id, value) {
    if (!id) return;
    this.current().body.push(id, '=', value, ';');
    return id;
  },

  filter: function(filterName) {
    if (!this.state.filters.hasOwnProperty(filterName)) {
      this.state.filters[filterName] = this.nextId(true);
    }
    return this.state.filters[filterName];
  },

  ifDefined: function(id, defaultValue) {
    return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  },

  plus: function(left, right) {
    return 'plus(' + left + ',' + right + ')';
  },

  return_: function(id) {
    this.current().body.push('return ', id, ';');
  },

  if_: function(test, alternate, consequent) {
    if (test === true) {
      alternate();
    } else {
      var body = this.current().body;
      body.push('if(', test, '){');
      alternate();
      body.push('}');
      if (consequent) {
        body.push('else{');
        consequent();
        body.push('}');
      }
    }
  },

  not: function(expression) {
    return '!(' + expression + ')';
  },

  notNull: function(expression) {
    return expression + '!=null';
  },

  nonComputedMember: function(left, right) {
    return left + '.' + right;
  },

  computedMember: function(left, right) {
    return left + '[' + right + ']';
  },

  member: function(left, right, computed) {
    if (computed) return this.computedMember(left, right);
    return this.nonComputedMember(left, right);
  },

  addEnsureSafeObject: function(item) {
    this.current().body.push(this.ensureSafeObject(item), ';');
  },

  addEnsureSafeMemberName: function(item) {
    this.current().body.push(this.ensureSafeMemberName(item), ';');
  },

  addEnsureSafeFunction: function(item) {
    this.current().body.push(this.ensureSafeFunction(item), ';');
  },

  ensureSafeObject: function(item) {
    return 'ensureSafeObject(' + item + ',text)';
  },

  ensureSafeMemberName: function(item) {
    return 'ensureSafeMemberName(' + item + ',text)';
  },

  ensureSafeFunction: function(item) {
    return 'ensureSafeFunction(' + item + ',text)';
  },

  lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
    var self = this;
    return function() {
      self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
    };
  },

  lazyAssign: function(id, value) {
    var self = this;
    return function() {
      self.assign(id, value);
    };
  },

  stringEscapeRegex: /[^ a-zA-Z0-9]/g,

  stringEscapeFn: function(c) {
    return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  },

  escape: function(value) {
    if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
    if (isNumber(value)) return value.toString();
    if (value === true) return 'true';
    if (value === false) return 'false';
    if (value === null) return 'null';
    if (typeof value === 'undefined') return 'undefined';

    throw $parseMinErr('esc', 'IMPOSSIBLE');
  },

  nextId: function(skip, init) {
    var id = 'v' + (this.state.nextId++);
    if (!skip) {
      this.current().vars.push(id + (init ? '=' + init : ''));
    }
    return id;
  },

  current: function() {
    return this.state[this.state.computing];
  }
};


function ASTInterpreter(astBuilder, $filter) {
  this.astBuilder = astBuilder;
  this.$filter = $filter;
}

ASTInterpreter.prototype = {
  compile: function(expression, expensiveChecks) {
    var self = this;
    var ast = this.astBuilder.ast(expression);
    this.expression = expression;
    this.expensiveChecks = expensiveChecks;
    findConstantAndWatchExpressions(ast, self.$filter);
    var assignable;
    var assign;
    if ((assignable = assignableAST(ast))) {
      assign = this.recurse(assignable);
    }
    var toWatch = getInputs(ast.body);
    var inputs;
    if (toWatch) {
      inputs = [];
      forEach(toWatch, function(watch, key) {
        var input = self.recurse(watch);
        watch.input = input;
        inputs.push(input);
        watch.watchId = key;
      });
    }
    var expressions = [];
    forEach(ast.body, function(expression) {
      expressions.push(self.recurse(expression.expression));
    });
    var fn = ast.body.length === 0 ? function() {} :
             ast.body.length === 1 ? expressions[0] :
             function(scope, locals) {
               var lastValue;
               forEach(expressions, function(exp) {
                 lastValue = exp(scope, locals);
               });
               return lastValue;
             };
    if (assign) {
      fn.assign = function(scope, value, locals) {
        return assign(scope, locals, value);
      };
    }
    if (inputs) {
      fn.inputs = inputs;
    }
    fn.literal = isLiteral(ast);
    fn.constant = isConstant(ast);
    return fn;
  },

  recurse: function(ast, context, create) {
    var left, right, self = this, args, expression;
    if (ast.input) {
      return this.inputs(ast.input, ast.watchId);
    }
    switch (ast.type) {
    case AST.Literal:
      return this.value(ast.value, context);
    case AST.UnaryExpression:
      right = this.recurse(ast.argument);
      return this['unary' + ast.operator](right, context);
    case AST.BinaryExpression:
      left = this.recurse(ast.left);
      right = this.recurse(ast.right);
      return this['binary' + ast.operator](left, right, context);
    case AST.LogicalExpression:
      left = this.recurse(ast.left);
      right = this.recurse(ast.right);
      return this['binary' + ast.operator](left, right, context);
    case AST.ConditionalExpression:
      return this['ternary?:'](
        this.recurse(ast.test),
        this.recurse(ast.alternate),
        this.recurse(ast.consequent),
        context
      );
    case AST.Identifier:
      ensureSafeMemberName(ast.name, self.expression);
      return self.identifier(ast.name,
                             self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
                             context, create, self.expression);
    case AST.MemberExpression:
      left = this.recurse(ast.object, false, !!create);
      if (!ast.computed) {
        ensureSafeMemberName(ast.property.name, self.expression);
        right = ast.property.name;
      }
      if (ast.computed) right = this.recurse(ast.property);
      return ast.computed ?
        this.computedMember(left, right, context, create, self.expression) :
        this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
    case AST.CallExpression:
      args = [];
      forEach(ast.arguments, function(expr) {
        args.push(self.recurse(expr));
      });
      if (ast.filter) right = this.$filter(ast.callee.name);
      if (!ast.filter) right = this.recurse(ast.callee, true);
      return ast.filter ?
        function(scope, locals, assign, inputs) {
          var values = [];
          for (var i = 0; i < args.length; ++i) {
            values.push(args[i](scope, locals, assign, inputs));
          }
          var value = right.apply(undefined, values, inputs);
          return context ? {context: undefined, name: undefined, value: value} : value;
        } :
        function(scope, locals, assign, inputs) {
          var rhs = right(scope, locals, assign, inputs);
          var value;
          if (rhs.value != null) {
            ensureSafeObject(rhs.context, self.expression);
            ensureSafeFunction(rhs.value, self.expression);
            var values = [];
            for (var i = 0; i < args.length; ++i) {
              values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
            }
            value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
          }
          return context ? {value: value} : value;
        };
    case AST.AssignmentExpression:
      left = this.recurse(ast.left, true, 1);
      right = this.recurse(ast.right);
      return function(scope, locals, assign, inputs) {
        var lhs = left(scope, locals, assign, inputs);
        var rhs = right(scope, locals, assign, inputs);
        ensureSafeObject(lhs.value, self.expression);
        lhs.context[lhs.name] = rhs;
        return context ? {value: rhs} : rhs;
      };
    case AST.ArrayExpression:
      args = [];
      forEach(ast.elements, function(expr) {
        args.push(self.recurse(expr));
      });
      return function(scope, locals, assign, inputs) {
        var value = [];
        for (var i = 0; i < args.length; ++i) {
          value.push(args[i](scope, locals, assign, inputs));
        }
        return context ? {value: value} : value;
      };
    case AST.ObjectExpression:
      args = [];
      forEach(ast.properties, function(property) {
        args.push({key: property.key.type === AST.Identifier ?
                        property.key.name :
                        ('' + property.key.value),
                   value: self.recurse(property.value)
        });
      });
      return function(scope, locals, assign, inputs) {
        var value = {};
        for (var i = 0; i < args.length; ++i) {
          value[args[i].key] = args[i].value(scope, locals, assign, inputs);
        }
        return context ? {value: value} : value;
      };
    case AST.ThisExpression:
      return function(scope) {
        return context ? {value: scope} : scope;
      };
    case AST.NGValueParameter:
      return function(scope, locals, assign, inputs) {
        return context ? {value: assign} : assign;
      };
    }
  },

  'unary+': function(argument, context) {
    return function(scope, locals, assign, inputs) {
      var arg = argument(scope, locals, assign, inputs);
      if (isDefined(arg)) {
        arg = +arg;
      } else {
        arg = 0;
      }
      return context ? {value: arg} : arg;
    };
  },
  'unary-': function(argument, context) {
    return function(scope, locals, assign, inputs) {
      var arg = argument(scope, locals, assign, inputs);
      if (isDefined(arg)) {
        arg = -arg;
      } else {
        arg = 0;
      }
      return context ? {value: arg} : arg;
    };
  },
  'unary!': function(argument, context) {
    return function(scope, locals, assign, inputs) {
      var arg = !argument(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'binary+': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var lhs = left(scope, locals, assign, inputs);
      var rhs = right(scope, locals, assign, inputs);
      var arg = plusFn(lhs, rhs);
      return context ? {value: arg} : arg;
    };
  },
  'binary-': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var lhs = left(scope, locals, assign, inputs);
      var rhs = right(scope, locals, assign, inputs);
      var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
      return context ? {value: arg} : arg;
    };
  },
  'binary*': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'binary/': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'binary%': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'binary===': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'binary!==': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'binary==': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'binary!=': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'binary<': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'binary>': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'binary<=': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'binary>=': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'binary&&': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'binary||': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  'ternary?:': function(test, alternate, consequent, context) {
    return function(scope, locals, assign, inputs) {
      var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },
  value: function(value, context) {
    return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  },
  identifier: function(name, expensiveChecks, context, create, expression) {
    return function(scope, locals, assign, inputs) {
      var base = locals && (name in locals) ? locals : scope;
      if (create && create !== 1 && base && !(base[name])) {
        base[name] = {};
      }
      var value = base ? base[name] : undefined;
      if (expensiveChecks) {
        ensureSafeObject(value, expression);
      }
      if (context) {
        return {context: base, name: name, value: value};
      } else {
        return value;
      }
    };
  },
  computedMember: function(left, right, context, create, expression) {
    return function(scope, locals, assign, inputs) {
      var lhs = left(scope, locals, assign, inputs);
      var rhs;
      var value;
      if (lhs != null) {
        rhs = right(scope, locals, assign, inputs);
        ensureSafeMemberName(rhs, expression);
        if (create && create !== 1 && lhs && !(lhs[rhs])) {
          lhs[rhs] = {};
        }
        value = lhs[rhs];
        ensureSafeObject(value, expression);
      }
      if (context) {
        return {context: lhs, name: rhs, value: value};
      } else {
        return value;
      }
    };
  },
  nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
    return function(scope, locals, assign, inputs) {
      var lhs = left(scope, locals, assign, inputs);
      if (create && create !== 1 && lhs && !(lhs[right])) {
        lhs[right] = {};
      }
      var value = lhs != null ? lhs[right] : undefined;
      if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
        ensureSafeObject(value, expression);
      }
      if (context) {
        return {context: lhs, name: right, value: value};
      } else {
        return value;
      }
    };
  },
  inputs: function(input, watchId) {
    return function(scope, value, locals, inputs) {
      if (inputs) return inputs[watchId];
      return input(scope, value, locals);
    };
  }
};

/**
 * @constructor
 */
var Parser = function(lexer, $filter, options) {
  this.lexer = lexer;
  this.$filter = $filter;
  this.options = options;
  this.ast = new AST(this.lexer);
  this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
                                   new ASTCompiler(this.ast, $filter);
};

Parser.prototype = {
  constructor: Parser,

  parse: function(text) {
    return this.astCompiler.compile(text, this.options.expensiveChecks);
  }
};

//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////

function setter(obj, path, setValue, fullExp) {
  ensureSafeObject(obj, fullExp);

  var element = path.split('.'), key;
  for (var i = 0; element.length > 1; i++) {
    key = ensureSafeMemberName(element.shift(), fullExp);
    var propertyObj = ensureSafeObject(obj[key], fullExp);
    if (!propertyObj) {
      propertyObj = {};
      obj[key] = propertyObj;
    }
    obj = propertyObj;
  }
  key = ensureSafeMemberName(element.shift(), fullExp);
  ensureSafeObject(obj[key], fullExp);
  obj[key] = setValue;
  return setValue;
}

var getterFnCacheDefault = createMap();
var getterFnCacheExpensive = createMap();

function isPossiblyDangerousMemberName(name) {
  return name == 'constructor';
}

var objectValueOf = Object.prototype.valueOf;

function getValueOf(value) {
  return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
}

///////////////////////////////////

/**
 * @ngdoc service
 * @name $parse
 * @kind function
 *
 * @description
 *
 * Converts Angular {@link guide/expression expression} into a function.
 *
 * ```js
 *   var getter = $parse('user.name');
 *   var setter = getter.assign;
 *   var context = {user:{name:'angular'}};
 *   var locals = {user:{name:'local'}};
 *
 *   expect(getter(context)).toEqual('angular');
 *   setter(context, 'newValue');
 *   expect(context.user.name).toEqual('newValue');
 *   expect(getter(context, locals)).toEqual('local');
 * ```
 *
 *
 * @param {string} expression String expression to compile.
 * @returns {function(context, locals)} a function which represents the compiled expression:
 *
 *    * `context` – `{object}` – an object against which any expressions embedded in the strings
 *      are evaluated against (typically a scope object).
 *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
 *      `context`.
 *
 *    The returned function also has the following properties:
 *      * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
 *        literal.
 *      * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
 *        constant literals.
 *      * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
 *        set to a function to change its value on the given context.
 *
 */


/**
 * @ngdoc provider
 * @name $parseProvider
 *
 * @description
 * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
 *  service.
 */
function $ParseProvider() {
  var cacheDefault = createMap();
  var cacheExpensive = createMap();

  this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
    var $parseOptions = {
          csp: $sniffer.csp,
          expensiveChecks: false
        },
        $parseOptionsExpensive = {
          csp: $sniffer.csp,
          expensiveChecks: true
        };

    return function $parse(exp, interceptorFn, expensiveChecks) {
      var parsedExpression, oneTime, cacheKey;

      switch (typeof exp) {
        case 'string':
          exp = exp.trim();
          cacheKey = exp;

          var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
          parsedExpression = cache[cacheKey];

          if (!parsedExpression) {
            if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
              oneTime = true;
              exp = exp.substring(2);
            }
            var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
            var lexer = new Lexer(parseOptions);
            var parser = new Parser(lexer, $filter, parseOptions);
            parsedExpression = parser.parse(exp);
            if (parsedExpression.constant) {
              parsedExpression.$$watchDelegate = constantWatchDelegate;
            } else if (oneTime) {
              parsedExpression.$$watchDelegate = parsedExpression.literal ?
                  oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
            } else if (parsedExpression.inputs) {
              parsedExpression.$$watchDelegate = inputsWatchDelegate;
            }
            cache[cacheKey] = parsedExpression;
          }
          return addInterceptor(parsedExpression, interceptorFn);

        case 'function':
          return addInterceptor(exp, interceptorFn);

        default:
          return noop;
      }
    };

    function expressionInputDirtyCheck(newValue, oldValueOfValue) {

      if (newValue == null || oldValueOfValue == null) { // null/undefined
        return newValue === oldValueOfValue;
      }

      if (typeof newValue === 'object') {

        // attempt to convert the value to a primitive type
        // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
        //             be cheaply dirty-checked
        newValue = getValueOf(newValue);

        if (typeof newValue === 'object') {
          // objects/arrays are not supported - deep-watching them would be too expensive
          return false;
        }

        // fall-through to the primitive equality check
      }

      //Primitive or NaN
      return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
    }

    function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
      var inputExpressions = parsedExpression.inputs;
      var lastResult;

      if (inputExpressions.length === 1) {
        var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
        inputExpressions = inputExpressions[0];
        return scope.$watch(function expressionInputWatch(scope) {
          var newInputValue = inputExpressions(scope);
          if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
            lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
            oldInputValueOf = newInputValue && getValueOf(newInputValue);
          }
          return lastResult;
        }, listener, objectEquality, prettyPrintExpression);
      }

      var oldInputValueOfValues = [];
      var oldInputValues = [];
      for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
        oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
        oldInputValues[i] = null;
      }

      return scope.$watch(function expressionInputsWatch(scope) {
        var changed = false;

        for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
          var newInputValue = inputExpressions[i](scope);
          if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
            oldInputValues[i] = newInputValue;
            oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
          }
        }

        if (changed) {
          lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
        }

        return lastResult;
      }, listener, objectEquality, prettyPrintExpression);
    }

    function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
      var unwatch, lastValue;
      return unwatch = scope.$watch(function oneTimeWatch(scope) {
        return parsedExpression(scope);
      }, function oneTimeListener(value, old, scope) {
        lastValue = value;
        if (isFunction(listener)) {
          listener.apply(this, arguments);
        }
        if (isDefined(value)) {
          scope.$$postDigest(function() {
            if (isDefined(lastValue)) {
              unwatch();
            }
          });
        }
      }, objectEquality);
    }

    function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
      var unwatch, lastValue;
      return unwatch = scope.$watch(function oneTimeWatch(scope) {
        return parsedExpression(scope);
      }, function oneTimeListener(value, old, scope) {
        lastValue = value;
        if (isFunction(listener)) {
          listener.call(this, value, old, scope);
        }
        if (isAllDefined(value)) {
          scope.$$postDigest(function() {
            if (isAllDefined(lastValue)) unwatch();
          });
        }
      }, objectEquality);

      function isAllDefined(value) {
        var allDefined = true;
        forEach(value, function(val) {
          if (!isDefined(val)) allDefined = false;
        });
        return allDefined;
      }
    }

    function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
      var unwatch;
      return unwatch = scope.$watch(function constantWatch(scope) {
        return parsedExpression(scope);
      }, function constantListener(value, old, scope) {
        if (isFunction(listener)) {
          listener.apply(this, arguments);
        }
        unwatch();
      }, objectEquality);
    }

    function addInterceptor(parsedExpression, interceptorFn) {
      if (!interceptorFn) return parsedExpression;
      var watchDelegate = parsedExpression.$$watchDelegate;

      var regularWatch =
          watchDelegate !== oneTimeLiteralWatchDelegate &&
          watchDelegate !== oneTimeWatchDelegate;

      var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
        var value = parsedExpression(scope, locals, assign, inputs);
        return interceptorFn(value, scope, locals);
      } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
        var value = parsedExpression(scope, locals, assign, inputs);
        var result = interceptorFn(value, scope, locals);
        // we only return the interceptor's result if the
        // initial value is defined (for bind-once)
        return isDefined(value) ? result : value;
      };

      // Propagate $$watchDelegates other then inputsWatchDelegate
      if (parsedExpression.$$watchDelegate &&
          parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
        fn.$$watchDelegate = parsedExpression.$$watchDelegate;
      } else if (!interceptorFn.$stateful) {
        // If there is an interceptor, but no watchDelegate then treat the interceptor like
        // we treat filters - it is assumed to be a pure function unless flagged with $stateful
        fn.$$watchDelegate = inputsWatchDelegate;
        fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
      }

      return fn;
    }
  }];
}

/**
 * @ngdoc service
 * @name $q
 * @requires $rootScope
 *
 * @description
 * A service that helps you run functions asynchronously, and use their return values (or exceptions)
 * when they are done processing.
 *
 * This is an implementation of promises/deferred objects inspired by
 * [Kris Kowal's Q](https://github.com/kriskowal/q).
 *
 * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
 * implementations, and the other which resembles ES6 promises to some degree.
 *
 * # $q constructor
 *
 * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
 * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
 * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
 *
 * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
 * available yet.
 *
 * It can be used like so:
 *
 * ```js
 *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`
 *   // are available in the current lexical scope (they could have been injected or passed in).
 *
 *   function asyncGreet(name) {
 *     // perform some asynchronous operation, resolve or reject the promise when appropriate.
 *     return $q(function(resolve, reject) {
 *       setTimeout(function() {
 *         if (okToGreet(name)) {
 *           resolve('Hello, ' + name + '!');
 *         } else {
 *           reject('Greeting ' + name + ' is not allowed.');
 *         }
 *       }, 1000);
 *     });
 *   }
 *
 *   var promise = asyncGreet('Robin Hood');
 *   promise.then(function(greeting) {
 *     alert('Success: ' + greeting);
 *   }, function(reason) {
 *     alert('Failed: ' + reason);
 *   });
 * ```
 *
 * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
 *
 * However, the more traditional CommonJS-style usage is still available, and documented below.
 *
 * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
 * interface for interacting with an object that represents the result of an action that is
 * performed asynchronously, and may or may not be finished at any given point in time.
 *
 * From the perspective of dealing with error handling, deferred and promise APIs are to
 * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
 *
 * ```js
 *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`
 *   // are available in the current lexical scope (they could have been injected or passed in).
 *
 *   function asyncGreet(name) {
 *     var deferred = $q.defer();
 *
 *     setTimeout(function() {
 *       deferred.notify('About to greet ' + name + '.');
 *
 *       if (okToGreet(name)) {
 *         deferred.resolve('Hello, ' + name + '!');
 *       } else {
 *         deferred.reject('Greeting ' + name + ' is not allowed.');
 *       }
 *     }, 1000);
 *
 *     return deferred.promise;
 *   }
 *
 *   var promise = asyncGreet('Robin Hood');
 *   promise.then(function(greeting) {
 *     alert('Success: ' + greeting);
 *   }, function(reason) {
 *     alert('Failed: ' + reason);
 *   }, function(update) {
 *     alert('Got notification: ' + update);
 *   });
 * ```
 *
 * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
 * comes in the way of guarantees that promise and deferred APIs make, see
 * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
 *
 * Additionally the promise api allows for composition that is very hard to do with the
 * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
 * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
 * section on serial or parallel joining of promises.
 *
 * # The Deferred API
 *
 * A new instance of deferred is constructed by calling `$q.defer()`.
 *
 * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
 * that can be used for signaling the successful or unsuccessful completion, as well as the status
 * of the task.
 *
 * **Methods**
 *
 * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
 *   constructed via `$q.reject`, the promise will be rejected instead.
 * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
 *   resolving it with a rejection constructed via `$q.reject`.
 * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
 *   multiple times before the promise is either resolved or rejected.
 *
 * **Properties**
 *
 * - promise – `{Promise}` – promise object associated with this deferred.
 *
 *
 * # The Promise API
 *
 * A new promise instance is created when a deferred instance is created and can be retrieved by
 * calling `deferred.promise`.
 *
 * The purpose of the promise object is to allow for interested parties to get access to the result
 * of the deferred task when it completes.
 *
 * **Methods**
 *
 * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
 *   will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
 *   as soon as the result is available. The callbacks are called with a single argument: the result
 *   or rejection reason. Additionally, the notify callback may be called zero or more times to
 *   provide a progress indication, before the promise is resolved or rejected.
 *
 *   This method *returns a new promise* which is resolved or rejected via the return value of the
 *   `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
 *   with the value which is resolved in that promise using
 *   [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
 *   It also notifies via the return value of the `notifyCallback` method. The promise cannot be
 *   resolved or rejected from the notifyCallback method.
 *
 * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
 *
 * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
 *   but to do so without modifying the final value. This is useful to release resources or do some
 *   clean-up that needs to be done whether the promise was rejected or resolved. See the [full
 *   specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
 *   more information.
 *
 * # Chaining promises
 *
 * Because calling the `then` method of a promise returns a new derived promise, it is easily
 * possible to create a chain of promises:
 *
 * ```js
 *   promiseB = promiseA.then(function(result) {
 *     return result + 1;
 *   });
 *
 *   // promiseB will be resolved immediately after promiseA is resolved and its value
 *   // will be the result of promiseA incremented by 1
 * ```
 *
 * It is possible to create chains of any length and since a promise can be resolved with another
 * promise (which will defer its resolution further), it is possible to pause/defer resolution of
 * the promises at any point in the chain. This makes it possible to implement powerful APIs like
 * $http's response interceptors.
 *
 *
 * # Differences between Kris Kowal's Q and $q
 *
 *  There are two main differences:
 *
 * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
 *   mechanism in angular, which means faster propagation of resolution or rejection into your
 *   models and avoiding unnecessary browser repaints, which would result in flickering UI.
 * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
 *   all the important functionality needed for common async tasks.
 *
 *  # Testing
 *
 *  ```js
 *    it('should simulate promise', inject(function($q, $rootScope) {
 *      var deferred = $q.defer();
 *      var promise = deferred.promise;
 *      var resolvedValue;
 *
 *      promise.then(function(value) { resolvedValue = value; });
 *      expect(resolvedValue).toBeUndefined();
 *
 *      // Simulate resolving of promise
 *      deferred.resolve(123);
 *      // Note that the 'then' function does not get called synchronously.
 *      // This is because we want the promise API to always be async, whether or not
 *      // it got called synchronously or asynchronously.
 *      expect(resolvedValue).toBeUndefined();
 *
 *      // Propagate promise resolution to 'then' functions using $apply().
 *      $rootScope.$apply();
 *      expect(resolvedValue).toEqual(123);
 *    }));
 *  ```
 *
 * @param {function(function, function)} resolver Function which is responsible for resolving or
 *   rejecting the newly created promise. The first parameter is a function which resolves the
 *   promise, the second parameter is a function which rejects the promise.
 *
 * @returns {Promise} The newly created promise.
 */
function $QProvider() {

  this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
    return qFactory(function(callback) {
      $rootScope.$evalAsync(callback);
    }, $exceptionHandler);
  }];
}

function $$QProvider() {
  this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
    return qFactory(function(callback) {
      $browser.defer(callback);
    }, $exceptionHandler);
  }];
}

/**
 * Constructs a promise manager.
 *
 * @param {function(function)} nextTick Function for executing functions in the next turn.
 * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
 *     debugging purposes.
 * @returns {object} Promise manager.
 */
function qFactory(nextTick, exceptionHandler) {
  var $qMinErr = minErr('$q', TypeError);
  function callOnce(self, resolveFn, rejectFn) {
    var called = false;
    function wrap(fn) {
      return function(value) {
        if (called) return;
        called = true;
        fn.call(self, value);
      };
    }

    return [wrap(resolveFn), wrap(rejectFn)];
  }

  /**
   * @ngdoc method
   * @name ng.$q#defer
   * @kind function
   *
   * @description
   * Creates a `Deferred` object which represents a task which will finish in the future.
   *
   * @returns {Deferred} Returns a new instance of deferred.
   */
  var defer = function() {
    return new Deferred();
  };

  function Promise() {
    this.$$state = { status: 0 };
  }

  Promise.prototype = {
    then: function(onFulfilled, onRejected, progressBack) {
      var result = new Deferred();

      this.$$state.pending = this.$$state.pending || [];
      this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
      if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);

      return result.promise;
    },

    "catch": function(callback) {
      return this.then(null, callback);
    },

    "finally": function(callback, progressBack) {
      return this.then(function(value) {
        return handleCallback(value, true, callback);
      }, function(error) {
        return handleCallback(error, false, callback);
      }, progressBack);
    }
  };

  //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  function simpleBind(context, fn) {
    return function(value) {
      fn.call(context, value);
    };
  }

  function processQueue(state) {
    var fn, deferred, pending;

    pending = state.pending;
    state.processScheduled = false;
    state.pending = undefined;
    for (var i = 0, ii = pending.length; i < ii; ++i) {
      deferred = pending[i][0];
      fn = pending[i][state.status];
      try {
        if (isFunction(fn)) {
          deferred.resolve(fn(state.value));
        } else if (state.status === 1) {
          deferred.resolve(state.value);
        } else {
          deferred.reject(state.value);
        }
      } catch (e) {
        deferred.reject(e);
        exceptionHandler(e);
      }
    }
  }

  function scheduleProcessQueue(state) {
    if (state.processScheduled || !state.pending) return;
    state.processScheduled = true;
    nextTick(function() { processQueue(state); });
  }

  function Deferred() {
    this.promise = new Promise();
    //Necessary to support unbound execution :/
    this.resolve = simpleBind(this, this.resolve);
    this.reject = simpleBind(this, this.reject);
    this.notify = simpleBind(this, this.notify);
  }

  Deferred.prototype = {
    resolve: function(val) {
      if (this.promise.$$state.status) return;
      if (val === this.promise) {
        this.$$reject($qMinErr(
          'qcycle',
          "Expected promise to be resolved with value other than itself '{0}'",
          val));
      } else {
        this.$$resolve(val);
      }

    },

    $$resolve: function(val) {
      var then, fns;

      fns = callOnce(this, this.$$resolve, this.$$reject);
      try {
        if ((isObject(val) || isFunction(val))) then = val && val.then;
        if (isFunction(then)) {
          this.promise.$$state.status = -1;
          then.call(val, fns[0], fns[1], this.notify);
        } else {
          this.promise.$$state.value = val;
          this.promise.$$state.status = 1;
          scheduleProcessQueue(this.promise.$$state);
        }
      } catch (e) {
        fns[1](e);
        exceptionHandler(e);
      }
    },

    reject: function(reason) {
      if (this.promise.$$state.status) return;
      this.$$reject(reason);
    },

    $$reject: function(reason) {
      this.promise.$$state.value = reason;
      this.promise.$$state.status = 2;
      scheduleProcessQueue(this.promise.$$state);
    },

    notify: function(progress) {
      var callbacks = this.promise.$$state.pending;

      if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
        nextTick(function() {
          var callback, result;
          for (var i = 0, ii = callbacks.length; i < ii; i++) {
            result = callbacks[i][0];
            callback = callbacks[i][3];
            try {
              result.notify(isFunction(callback) ? callback(progress) : progress);
            } catch (e) {
              exceptionHandler(e);
            }
          }
        });
      }
    }
  };

  /**
   * @ngdoc method
   * @name $q#reject
   * @kind function
   *
   * @description
   * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
   * used to forward rejection in a chain of promises. If you are dealing with the last promise in
   * a promise chain, you don't need to worry about it.
   *
   * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
   * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
   * a promise error callback and you want to forward the error to the promise derived from the
   * current promise, you have to "rethrow" the error by returning a rejection constructed via
   * `reject`.
   *
   * ```js
   *   promiseB = promiseA.then(function(result) {
   *     // success: do something and resolve promiseB
   *     //          with the old or a new result
   *     return result;
   *   }, function(reason) {
   *     // error: handle the error if possible and
   *     //        resolve promiseB with newPromiseOrValue,
   *     //        otherwise forward the rejection to promiseB
   *     if (canHandle(reason)) {
   *      // handle the error and recover
   *      return newPromiseOrValue;
   *     }
   *     return $q.reject(reason);
   *   });
   * ```
   *
   * @param {*} reason Constant, message, exception or an object representing the rejection reason.
   * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
   */
  var reject = function(reason) {
    var result = new Deferred();
    result.reject(reason);
    return result.promise;
  };

  var makePromise = function makePromise(value, resolved) {
    var result = new Deferred();
    if (resolved) {
      result.resolve(value);
    } else {
      result.reject(value);
    }
    return result.promise;
  };

  var handleCallback = function handleCallback(value, isResolved, callback) {
    var callbackOutput = null;
    try {
      if (isFunction(callback)) callbackOutput = callback();
    } catch (e) {
      return makePromise(e, false);
    }
    if (isPromiseLike(callbackOutput)) {
      return callbackOutput.then(function() {
        return makePromise(value, isResolved);
      }, function(error) {
        return makePromise(error, false);
      });
    } else {
      return makePromise(value, isResolved);
    }
  };

  /**
   * @ngdoc method
   * @name $q#when
   * @kind function
   *
   * @description
   * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
   * This is useful when you are dealing with an object that might or might not be a promise, or if
   * the promise comes from a source that can't be trusted.
   *
   * @param {*} value Value or a promise
   * @returns {Promise} Returns a promise of the passed value or promise
   */


  var when = function(value, callback, errback, progressBack) {
    var result = new Deferred();
    result.resolve(value);
    return result.promise.then(callback, errback, progressBack);
  };

  /**
   * @ngdoc method
   * @name $q#resolve
   * @kind function
   *
   * @description
   * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
   *
   * @param {*} value Value or a promise
   * @returns {Promise} Returns a promise of the passed value or promise
   */
  var resolve = when;

  /**
   * @ngdoc method
   * @name $q#all
   * @kind function
   *
   * @description
   * Combines multiple promises into a single promise that is resolved when all of the input
   * promises are resolved.
   *
   * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
   * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
   *   each value corresponding to the promise at the same index/key in the `promises` array/hash.
   *   If any of the promises is resolved with a rejection, this resulting promise will be rejected
   *   with the same rejection value.
   */

  function all(promises) {
    var deferred = new Deferred(),
        counter = 0,
        results = isArray(promises) ? [] : {};

    forEach(promises, function(promise, key) {
      counter++;
      when(promise).then(function(value) {
        if (results.hasOwnProperty(key)) return;
        results[key] = value;
        if (!(--counter)) deferred.resolve(results);
      }, function(reason) {
        if (results.hasOwnProperty(key)) return;
        deferred.reject(reason);
      });
    });

    if (counter === 0) {
      deferred.resolve(results);
    }

    return deferred.promise;
  }

  var $Q = function Q(resolver) {
    if (!isFunction(resolver)) {
      throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
    }

    if (!(this instanceof Q)) {
      // More useful when $Q is the Promise itself.
      return new Q(resolver);
    }

    var deferred = new Deferred();

    function resolveFn(value) {
      deferred.resolve(value);
    }

    function rejectFn(reason) {
      deferred.reject(reason);
    }

    resolver(resolveFn, rejectFn);

    return deferred.promise;
  };

  $Q.defer = defer;
  $Q.reject = reject;
  $Q.when = when;
  $Q.resolve = resolve;
  $Q.all = all;

  return $Q;
}

function $$RAFProvider() { //rAF
  this.$get = ['$window', '$timeout', function($window, $timeout) {
    var requestAnimationFrame = $window.requestAnimationFrame ||
                                $window.webkitRequestAnimationFrame;

    var cancelAnimationFrame = $window.cancelAnimationFrame ||
                               $window.webkitCancelAnimationFrame ||
                               $window.webkitCancelRequestAnimationFrame;

    var rafSupported = !!requestAnimationFrame;
    var rafFn = rafSupported
      ? function(fn) {
          var id = requestAnimationFrame(fn);
          return function() {
            cancelAnimationFrame(id);
          };
        }
      : function(fn) {
          var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
          return function() {
            $timeout.cancel(timer);
          };
        };

    queueFn.supported = rafSupported;

    var cancelLastRAF;
    var taskCount = 0;
    var taskQueue = [];
    return queueFn;

    function flush() {
      for (var i = 0; i < taskQueue.length; i++) {
        var task = taskQueue[i];
        if (task) {
          taskQueue[i] = null;
          task();
        }
      }
      taskCount = taskQueue.length = 0;
    }

    function queueFn(asyncFn) {
      var index = taskQueue.length;

      taskCount++;
      taskQueue.push(asyncFn);

      if (index === 0) {
        cancelLastRAF = rafFn(flush);
      }

      return function cancelQueueFn() {
        if (index >= 0) {
          taskQueue[index] = null;
          index = null;

          if (--taskCount === 0 && cancelLastRAF) {
            cancelLastRAF();
            cancelLastRAF = null;
            taskQueue.length = 0;
          }
        }
      };
    }
  }];
}

/**
 * DESIGN NOTES
 *
 * The design decisions behind the scope are heavily favored for speed and memory consumption.
 *
 * The typical use of scope is to watch the expressions, which most of the time return the same
 * value as last time so we optimize the operation.
 *
 * Closures construction is expensive in terms of speed as well as memory:
 *   - No closures, instead use prototypical inheritance for API
 *   - Internal state needs to be stored on scope directly, which means that private state is
 *     exposed as $$____ properties
 *
 * Loop operations are optimized by using while(count--) { ... }
 *   - this means that in order to keep the same order of execution as addition we have to add
 *     items to the array at the beginning (unshift) instead of at the end (push)
 *
 * Child scopes are created and removed often
 *   - Using an array would be slow since inserts in middle are expensive so we use linked list
 *
 * There are few watches then a lot of observers. This is why you don't want the observer to be
 * implemented in the same way as watch. Watch requires return of initialization function which
 * are expensive to construct.
 */


/**
 * @ngdoc provider
 * @name $rootScopeProvider
 * @description
 *
 * Provider for the $rootScope service.
 */

/**
 * @ngdoc method
 * @name $rootScopeProvider#digestTtl
 * @description
 *
 * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
 * assuming that the model is unstable.
 *
 * The current default is 10 iterations.
 *
 * In complex applications it's possible that the dependencies between `$watch`s will result in
 * several digest iterations. However if an application needs more than the default 10 digest
 * iterations for its model to stabilize then you should investigate what is causing the model to
 * continuously change during the digest.
 *
 * Increasing the TTL could have performance implications, so you should not change it without
 * proper justification.
 *
 * @param {number} limit The number of digest iterations.
 */


/**
 * @ngdoc service
 * @name $rootScope
 * @description
 *
 * Every application has a single root {@link ng.$rootScope.Scope scope}.
 * All other scopes are descendant scopes of the root scope. Scopes provide separation
 * between the model and the view, via a mechanism for watching the model for changes.
 * They also provide an event emission/broadcast and subscription facility. See the
 * {@link guide/scope developer guide on scopes}.
 */
function $RootScopeProvider() {
  var TTL = 10;
  var $rootScopeMinErr = minErr('$rootScope');
  var lastDirtyWatch = null;
  var applyAsyncId = null;

  this.digestTtl = function(value) {
    if (arguments.length) {
      TTL = value;
    }
    return TTL;
  };

  function createChildScopeClass(parent) {
    function ChildScope() {
      this.$$watchers = this.$$nextSibling =
          this.$$childHead = this.$$childTail = null;
      this.$$listeners = {};
      this.$$listenerCount = {};
      this.$$watchersCount = 0;
      this.$id = nextUid();
      this.$$ChildScope = null;
    }
    ChildScope.prototype = parent;
    return ChildScope;
  }

  this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
      function($injector, $exceptionHandler, $parse, $browser) {

    function destroyChildScope($event) {
        $event.currentScope.$$destroyed = true;
    }

    /**
     * @ngdoc type
     * @name $rootScope.Scope
     *
     * @description
     * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
     * {@link auto.$injector $injector}. Child scopes are created using the
     * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
     * compiled HTML template is executed.)
     *
     * Here is a simple scope snippet to show how you can interact with the scope.
     * ```html
     * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
     * ```
     *
     * # Inheritance
     * A scope can inherit from a parent scope, as in this example:
     * ```js
         var parent = $rootScope;
         var child = parent.$new();

         parent.salutation = "Hello";
         expect(child.salutation).toEqual('Hello');

         child.salutation = "Welcome";
         expect(child.salutation).toEqual('Welcome');
         expect(parent.salutation).toEqual('Hello');
     * ```
     *
     * When interacting with `Scope` in tests, additional helper methods are available on the
     * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
     * details.
     *
     *
     * @param {Object.<string, function()>=} providers Map of service factory which need to be
     *                                       provided for the current scope. Defaults to {@link ng}.
     * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
     *                              append/override services provided by `providers`. This is handy
     *                              when unit-testing and having the need to override a default
     *                              service.
     * @returns {Object} Newly created scope.
     *
     */
    function Scope() {
      this.$id = nextUid();
      this.$$phase = this.$parent = this.$$watchers =
                     this.$$nextSibling = this.$$prevSibling =
                     this.$$childHead = this.$$childTail = null;
      this.$root = this;
      this.$$destroyed = false;
      this.$$listeners = {};
      this.$$listenerCount = {};
      this.$$watchersCount = 0;
      this.$$isolateBindings = null;
    }

    /**
     * @ngdoc property
     * @name $rootScope.Scope#$id
     *
     * @description
     * Unique scope ID (monotonically increasing) useful for debugging.
     */

     /**
      * @ngdoc property
      * @name $rootScope.Scope#$parent
      *
      * @description
      * Reference to the parent scope.
      */

      /**
       * @ngdoc property
       * @name $rootScope.Scope#$root
       *
       * @description
       * Reference to the root scope.
       */

    Scope.prototype = {
      constructor: Scope,
      /**
       * @ngdoc method
       * @name $rootScope.Scope#$new
       * @kind function
       *
       * @description
       * Creates a new child {@link ng.$rootScope.Scope scope}.
       *
       * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
       * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
       *
       * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
       * desired for the scope and its child scopes to be permanently detached from the parent and
       * thus stop participating in model change detection and listener notification by invoking.
       *
       * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
       *         parent scope. The scope is isolated, as it can not see parent scope properties.
       *         When creating widgets, it is useful for the widget to not accidentally read parent
       *         state.
       *
       * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
       *                              of the newly created scope. Defaults to `this` scope if not provided.
       *                              This is used when creating a transclude scope to correctly place it
       *                              in the scope hierarchy while maintaining the correct prototypical
       *                              inheritance.
       *
       * @returns {Object} The newly created child scope.
       *
       */
      $new: function(isolate, parent) {
        var child;

        parent = parent || this;

        if (isolate) {
          child = new Scope();
          child.$root = this.$root;
        } else {
          // Only create a child scope class if somebody asks for one,
          // but cache it to allow the VM to optimize lookups.
          if (!this.$$ChildScope) {
            this.$$ChildScope = createChildScopeClass(this);
          }
          child = new this.$$ChildScope();
        }
        child.$parent = parent;
        child.$$prevSibling = parent.$$childTail;
        if (parent.$$childHead) {
          parent.$$childTail.$$nextSibling = child;
          parent.$$childTail = child;
        } else {
          parent.$$childHead = parent.$$childTail = child;
        }

        // When the new scope is not isolated or we inherit from `this`, and
        // the parent scope is destroyed, the property `$$destroyed` is inherited
        // prototypically. In all other cases, this property needs to be set
        // when the parent scope is destroyed.
        // The listener needs to be added after the parent is set
        if (isolate || parent != this) child.$on('$destroy', destroyChildScope);

        return child;
      },

      /**
       * @ngdoc method
       * @name $rootScope.Scope#$watch
       * @kind function
       *
       * @description
       * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
       *
       * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
       *   $digest()} and should return the value that will be watched. (Since
       *   {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
       *   `watchExpression` can execute multiple times per
       *   {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
       * - The `listener` is called only when the value from the current `watchExpression` and the
       *   previous call to `watchExpression` are not equal (with the exception of the initial run,
       *   see below). Inequality is determined according to reference inequality,
       *   [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
       *    via the `!==` Javascript operator, unless `objectEquality == true`
       *   (see next point)
       * - When `objectEquality == true`, inequality of the `watchExpression` is determined
       *   according to the {@link angular.equals} function. To save the value of the object for
       *   later comparison, the {@link angular.copy} function is used. This therefore means that
       *   watching complex objects will have adverse memory and performance implications.
       * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
       *   This is achieved by rerunning the watchers until no changes are detected. The rerun
       *   iteration limit is 10 to prevent an infinite loop deadlock.
       *
       *
       * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
       * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
       * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
       * change is detected, be prepared for multiple calls to your listener.)
       *
       * After a watcher is registered with the scope, the `listener` fn is called asynchronously
       * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
       * watcher. In rare cases, this is undesirable because the listener is called when the result
       * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
       * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
       * listener was called due to initialization.
       *
       *
       *
       * # Example
       * ```js
           // let's assume that scope was dependency injected as the $rootScope
           var scope = $rootScope;
           scope.name = 'misko';
           scope.counter = 0;

           expect(scope.counter).toEqual(0);
           scope.$watch('name', function(newValue, oldValue) {
             scope.counter = scope.counter + 1;
           });
           expect(scope.counter).toEqual(0);

           scope.$digest();
           // the listener is always called during the first $digest loop after it was registered
           expect(scope.counter).toEqual(1);

           scope.$digest();
           // but now it will not be called unless the value changes
           expect(scope.counter).toEqual(1);

           scope.name = 'adam';
           scope.$digest();
           expect(scope.counter).toEqual(2);



           // Using a function as a watchExpression
           var food;
           scope.foodCounter = 0;
           expect(scope.foodCounter).toEqual(0);
           scope.$watch(
             // This function returns the value being watched. It is called for each turn of the $digest loop
             function() { return food; },
             // This is the change listener, called when the value returned from the above function changes
             function(newValue, oldValue) {
               if ( newValue !== oldValue ) {
                 // Only increment the counter if the value changed
                 scope.foodCounter = scope.foodCounter + 1;
               }
             }
           );
           // No digest has been run so the counter will be zero
           expect(scope.foodCounter).toEqual(0);

           // Run the digest but since food has not changed count will still be zero
           scope.$digest();
           expect(scope.foodCounter).toEqual(0);

           // Update food and run digest.  Now the counter will increment
           food = 'cheeseburger';
           scope.$digest();
           expect(scope.foodCounter).toEqual(1);

       * ```
       *
       *
       *
       * @param {(function()|string)} watchExpression Expression that is evaluated on each
       *    {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
       *    a call to the `listener`.
       *
       *    - `string`: Evaluated as {@link guide/expression expression}
       *    - `function(scope)`: called with current `scope` as a parameter.
       * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
       *    of `watchExpression` changes.
       *
       *    - `newVal` contains the current value of the `watchExpression`
       *    - `oldVal` contains the previous value of the `watchExpression`
       *    - `scope` refers to the current scope
       * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
       *     comparing for reference equality.
       * @returns {function()} Returns a deregistration function for this listener.
       */
      $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
        var get = $parse(watchExp);

        if (get.$$watchDelegate) {
          return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
        }
        var scope = this,
            array = scope.$$watchers,
            watcher = {
              fn: listener,
              last: initWatchVal,
              get: get,
              exp: prettyPrintExpression || watchExp,
              eq: !!objectEquality
            };

        lastDirtyWatch = null;

        if (!isFunction(listener)) {
          watcher.fn = noop;
        }

        if (!array) {
          array = scope.$$watchers = [];
        }
        // we use unshift since we use a while loop in $digest for speed.
        // the while loop reads in reverse order.
        array.unshift(watcher);
        incrementWatchersCount(this, 1);

        return function deregisterWatch() {
          if (arrayRemove(array, watcher) >= 0) {
            incrementWatchersCount(scope, -1);
          }
          lastDirtyWatch = null;
        };
      },

      /**
       * @ngdoc method
       * @name $rootScope.Scope#$watchGroup
       * @kind function
       *
       * @description
       * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
       * If any one expression in the collection changes the `listener` is executed.
       *
       * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
       *   call to $digest() to see if any items changes.
       * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
       *
       * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
       * watched using {@link ng.$rootScope.Scope#$watch $watch()}
       *
       * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
       *    expression in `watchExpressions` changes
       *    The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
       *    those of `watchExpression`
       *    and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
       *    those of `watchExpression`
       *    The `scope` refers to the current scope.
       * @returns {function()} Returns a de-registration function for all listeners.
       */
      $watchGroup: function(watchExpressions, listener) {
        var oldValues = new Array(watchExpressions.length);
        var newValues = new Array(watchExpressions.length);
        var deregisterFns = [];
        var self = this;
        var changeReactionScheduled = false;
        var firstRun = true;

        if (!watchExpressions.length) {
          // No expressions means we call the listener ASAP
          var shouldCall = true;
          self.$evalAsync(function() {
            if (shouldCall) listener(newValues, newValues, self);
          });
          return function deregisterWatchGroup() {
            shouldCall = false;
          };
        }

        if (watchExpressions.length === 1) {
          // Special case size of one
          return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
            newValues[0] = value;
            oldValues[0] = oldValue;
            listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
          });
        }

        forEach(watchExpressions, function(expr, i) {
          var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
            newValues[i] = value;
            oldValues[i] = oldValue;
            if (!changeReactionScheduled) {
              changeReactionScheduled = true;
              self.$evalAsync(watchGroupAction);
            }
          });
          deregisterFns.push(unwatchFn);
        });

        function watchGroupAction() {
          changeReactionScheduled = false;

          if (firstRun) {
            firstRun = false;
            listener(newValues, newValues, self);
          } else {
            listener(newValues, oldValues, self);
          }
        }

        return function deregisterWatchGroup() {
          while (deregisterFns.length) {
            deregisterFns.shift()();
          }
        };
      },


      /**
       * @ngdoc method
       * @name $rootScope.Scope#$watchCollection
       * @kind function
       *
       * @description
       * Shallow watches the properties of an object and fires whenever any of the properties change
       * (for arrays, this implies watching the array items; for object maps, this implies watching
       * the properties). If a change is detected, the `listener` callback is fired.
       *
       * - The `obj` collection is observed via standard $watch operation and is examined on every
       *   call to $digest() to see if any items have been added, removed, or moved.
       * - The `listener` is called whenever anything within the `obj` has changed. Examples include
       *   adding, removing, and moving items belonging to an object or array.
       *
       *
       * # Example
       * ```js
          $scope.names = ['igor', 'matias', 'misko', 'james'];
          $scope.dataCount = 4;

          $scope.$watchCollection('names', function(newNames, oldNames) {
            $scope.dataCount = newNames.length;
          });

          expect($scope.dataCount).toEqual(4);
          $scope.$digest();

          //still at 4 ... no changes
          expect($scope.dataCount).toEqual(4);

          $scope.names.pop();
          $scope.$digest();

          //now there's been a change
          expect($scope.dataCount).toEqual(3);
       * ```
       *
       *
       * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
       *    expression value should evaluate to an object or an array which is observed on each
       *    {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
       *    collection will trigger a call to the `listener`.
       *
       * @param {function(newCollection, oldCollection, scope)} listener a callback function called
       *    when a change is detected.
       *    - The `newCollection` object is the newly modified data obtained from the `obj` expression
       *    - The `oldCollection` object is a copy of the former collection data.
       *      Due to performance considerations, the`oldCollection` value is computed only if the
       *      `listener` function declares two or more arguments.
       *    - The `scope` argument refers to the current scope.
       *
       * @returns {function()} Returns a de-registration function for this listener. When the
       *    de-registration function is executed, the internal watch operation is terminated.
       */
      $watchCollection: function(obj, listener) {
        $watchCollectionInterceptor.$stateful = true;

        var self = this;
        // the current value, updated on each dirty-check run
        var newValue;
        // a shallow copy of the newValue from the last dirty-check run,
        // updated to match newValue during dirty-check run
        var oldValue;
        // a shallow copy of the newValue from when the last change happened
        var veryOldValue;
        // only track veryOldValue if the listener is asking for it
        var trackVeryOldValue = (listener.length > 1);
        var changeDetected = 0;
        var changeDetector = $parse(obj, $watchCollectionInterceptor);
        var internalArray = [];
        var internalObject = {};
        var initRun = true;
        var oldLength = 0;

        function $watchCollectionInterceptor(_value) {
          newValue = _value;
          var newLength, key, bothNaN, newItem, oldItem;

          // If the new value is undefined, then return undefined as the watch may be a one-time watch
          if (isUndefined(newValue)) return;

          if (!isObject(newValue)) { // if primitive
            if (oldValue !== newValue) {
              oldValue = newValue;
              changeDetected++;
            }
          } else if (isArrayLike(newValue)) {
            if (oldValue !== internalArray) {
              // we are transitioning from something which was not an array into array.
              oldValue = internalArray;
              oldLength = oldValue.length = 0;
              changeDetected++;
            }

            newLength = newValue.length;

            if (oldLength !== newLength) {
              // if lengths do not match we need to trigger change notification
              changeDetected++;
              oldValue.length = oldLength = newLength;
            }
            // copy the items to oldValue and look for changes.
            for (var i = 0; i < newLength; i++) {
              oldItem = oldValue[i];
              newItem = newValue[i];

              bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
              if (!bothNaN && (oldItem !== newItem)) {
                changeDetected++;
                oldValue[i] = newItem;
              }
            }
          } else {
            if (oldValue !== internalObject) {
              // we are transitioning from something which was not an object into object.
              oldValue = internalObject = {};
              oldLength = 0;
              changeDetected++;
            }
            // copy the items to oldValue and look for changes.
            newLength = 0;
            for (key in newValue) {
              if (newValue.hasOwnProperty(key)) {
                newLength++;
                newItem = newValue[key];
                oldItem = oldValue[key];

                if (key in oldValue) {
                  bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
                  if (!bothNaN && (oldItem !== newItem)) {
                    changeDetected++;
                    oldValue[key] = newItem;
                  }
                } else {
                  oldLength++;
                  oldValue[key] = newItem;
                  changeDetected++;
                }
              }
            }
            if (oldLength > newLength) {
              // we used to have more keys, need to find them and destroy them.
              changeDetected++;
              for (key in oldValue) {
                if (!newValue.hasOwnProperty(key)) {
                  oldLength--;
                  delete oldValue[key];
                }
              }
            }
          }
          return changeDetected;
        }

        function $watchCollectionAction() {
          if (initRun) {
            initRun = false;
            listener(newValue, newValue, self);
          } else {
            listener(newValue, veryOldValue, self);
          }

          // make a copy for the next time a collection is changed
          if (trackVeryOldValue) {
            if (!isObject(newValue)) {
              //primitive
              veryOldValue = newValue;
            } else if (isArrayLike(newValue)) {
              veryOldValue = new Array(newValue.length);
              for (var i = 0; i < newValue.length; i++) {
                veryOldValue[i] = newValue[i];
              }
            } else { // if object
              veryOldValue = {};
              for (var key in newValue) {
                if (hasOwnProperty.call(newValue, key)) {
                  veryOldValue[key] = newValue[key];
                }
              }
            }
          }
        }

        return this.$watch(changeDetector, $watchCollectionAction);
      },

      /**
       * @ngdoc method
       * @name $rootScope.Scope#$digest
       * @kind function
       *
       * @description
       * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
       * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
       * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
       * until no more listeners are firing. This means that it is possible to get into an infinite
       * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
       * iterations exceeds 10.
       *
       * Usually, you don't call `$digest()` directly in
       * {@link ng.directive:ngController controllers} or in
       * {@link ng.$compileProvider#directive directives}.
       * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
       * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
       *
       * If you want to be notified whenever `$digest()` is called,
       * you can register a `watchExpression` function with
       * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
       *
       * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
       *
       * # Example
       * ```js
           var scope = ...;
           scope.name = 'misko';
           scope.counter = 0;

           expect(scope.counter).toEqual(0);
           scope.$watch('name', function(newValue, oldValue) {
             scope.counter = scope.counter + 1;
           });
           expect(scope.counter).toEqual(0);

           scope.$digest();
           // the listener is always called during the first $digest loop after it was registered
           expect(scope.counter).toEqual(1);

           scope.$digest();
           // but now it will not be called unless the value changes
           expect(scope.counter).toEqual(1);

           scope.name = 'adam';
           scope.$digest();
           expect(scope.counter).toEqual(2);
       * ```
       *
       */
      $digest: function() {
        var watch, value, last,
            watchers,
            length,
            dirty, ttl = TTL,
            next, current, target = this,
            watchLog = [],
            logIdx, logMsg, asyncTask;

        beginPhase('$digest');
        // Check for changes to browser url that happened in sync before the call to $digest
        $browser.$$checkUrlChange();

        if (this === $rootScope && applyAsyncId !== null) {
          // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
          // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
          $browser.defer.cancel(applyAsyncId);
          flushApplyAsync();
        }

        lastDirtyWatch = null;

        do { // "while dirty" loop
          dirty = false;
          current = target;

          while (asyncQueue.length) {
            try {
              asyncTask = asyncQueue.shift();
              asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
            } catch (e) {
              $exceptionHandler(e);
            }
            lastDirtyWatch = null;
          }

          traverseScopesLoop:
          do { // "traverse the scopes" loop
            if ((watchers = current.$$watchers)) {
              // process our watches
              length = watchers.length;
              while (length--) {
                try {
                  watch = watchers[length];
                  // Most common watches are on primitives, in which case we can short
                  // circuit it with === operator, only when === fails do we use .equals
                  if (watch) {
                    if ((value = watch.get(current)) !== (last = watch.last) &&
                        !(watch.eq
                            ? equals(value, last)
                            : (typeof value === 'number' && typeof last === 'number'
                               && isNaN(value) && isNaN(last)))) {
                      dirty = true;
                      lastDirtyWatch = watch;
                      watch.last = watch.eq ? copy(value, null) : value;
                      watch.fn(value, ((last === initWatchVal) ? value : last), current);
                      if (ttl < 5) {
                        logIdx = 4 - ttl;
                        if (!watchLog[logIdx]) watchLog[logIdx] = [];
                        watchLog[logIdx].push({
                          msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
                          newVal: value,
                          oldVal: last
                        });
                      }
                    } else if (watch === lastDirtyWatch) {
                      // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
                      // have already been tested.
                      dirty = false;
                      break traverseScopesLoop;
                    }
                  }
                } catch (e) {
                  $exceptionHandler(e);
                }
              }
            }

            // Insanity Warning: scope depth-first traversal
            // yes, this code is a bit crazy, but it works and we have tests to prove it!
            // this piece should be kept in sync with the traversal in $broadcast
            if (!(next = ((current.$$watchersCount && current.$$childHead) ||
                (current !== target && current.$$nextSibling)))) {
              while (current !== target && !(next = current.$$nextSibling)) {
                current = current.$parent;
              }
            }
          } while ((current = next));

          // `break traverseScopesLoop;` takes us to here

          if ((dirty || asyncQueue.length) && !(ttl--)) {
            clearPhase();
            throw $rootScopeMinErr('infdig',
                '{0} $digest() iterations reached. Aborting!\n' +
                'Watchers fired in the last 5 iterations: {1}',
                TTL, watchLog);
          }

        } while (dirty || asyncQueue.length);

        clearPhase();

        while (postDigestQueue.length) {
          try {
            postDigestQueue.shift()();
          } catch (e) {
            $exceptionHandler(e);
          }
        }
      },


      /**
       * @ngdoc event
       * @name $rootScope.Scope#$destroy
       * @eventType broadcast on scope being destroyed
       *
       * @description
       * Broadcasted when a scope and its children are being destroyed.
       *
       * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
       * clean up DOM bindings before an element is removed from the DOM.
       */

      /**
       * @ngdoc method
       * @name $rootScope.Scope#$destroy
       * @kind function
       *
       * @description
       * Removes the current scope (and all of its children) from the parent scope. Removal implies
       * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
       * propagate to the current scope and its children. Removal also implies that the current
       * scope is eligible for garbage collection.
       *
       * The `$destroy()` is usually used by directives such as
       * {@link ng.directive:ngRepeat ngRepeat} for managing the
       * unrolling of the loop.
       *
       * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
       * Application code can register a `$destroy` event handler that will give it a chance to
       * perform any necessary cleanup.
       *
       * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
       * clean up DOM bindings before an element is removed from the DOM.
       */
      $destroy: function() {
        // We can't destroy a scope that has been already destroyed.
        if (this.$$destroyed) return;
        var parent = this.$parent;

        this.$broadcast('$destroy');
        this.$$destroyed = true;

        if (this === $rootScope) {
          //Remove handlers attached to window when $rootScope is removed
          $browser.$$applicationDestroyed();
        }

        incrementWatchersCount(this, -this.$$watchersCount);
        for (var eventName in this.$$listenerCount) {
          decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
        }

        // sever all the references to parent scopes (after this cleanup, the current scope should
        // not be retained by any of our references and should be eligible for garbage collection)
        if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
        if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
        if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
        if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;

        // Disable listeners, watchers and apply/digest methods
        this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
        this.$on = this.$watch = this.$watchGroup = function() { return noop; };
        this.$$listeners = {};

        // All of the code below is bogus code that works around V8's memory leak via optimized code
        // and inline caches.
        //
        // see:
        // - https://code.google.com/p/v8/issues/detail?id=2073#c26
        // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
        // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451

        this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
            this.$$childTail = this.$root = this.$$watchers = null;
      },

      /**
       * @ngdoc method
       * @name $rootScope.Scope#$eval
       * @kind function
       *
       * @description
       * Executes the `expression` on the current scope and returns the result. Any exceptions in
       * the expression are propagated (uncaught). This is useful when evaluating Angular
       * expressions.
       *
       * # Example
       * ```js
           var scope = ng.$rootScope.Scope();
           scope.a = 1;
           scope.b = 2;

           expect(scope.$eval('a+b')).toEqual(3);
           expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
       * ```
       *
       * @param {(string|function())=} expression An angular expression to be executed.
       *
       *    - `string`: execute using the rules as defined in  {@link guide/expression expression}.
       *    - `function(scope)`: execute the function with the current `scope` parameter.
       *
       * @param {(object)=} locals Local variables object, useful for overriding values in scope.
       * @returns {*} The result of evaluating the expression.
       */
      $eval: function(expr, locals) {
        return $parse(expr)(this, locals);
      },

      /**
       * @ngdoc method
       * @name $rootScope.Scope#$evalAsync
       * @kind function
       *
       * @description
       * Executes the expression on the current scope at a later point in time.
       *
       * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
       * that:
       *
       *   - it will execute after the function that scheduled the evaluation (preferably before DOM
       *     rendering).
       *   - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
       *     `expression` execution.
       *
       * Any exceptions from the execution of the expression are forwarded to the
       * {@link ng.$exceptionHandler $exceptionHandler} service.
       *
       * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
       * will be scheduled. However, it is encouraged to always call code that changes the model
       * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
       *
       * @param {(string|function())=} expression An angular expression to be executed.
       *
       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.
       *    - `function(scope)`: execute the function with the current `scope` parameter.
       *
       * @param {(object)=} locals Local variables object, useful for overriding values in scope.
       */
      $evalAsync: function(expr, locals) {
        // if we are outside of an $digest loop and this is the first time we are scheduling async
        // task also schedule async auto-flush
        if (!$rootScope.$$phase && !asyncQueue.length) {
          $browser.defer(function() {
            if (asyncQueue.length) {
              $rootScope.$digest();
            }
          });
        }

        asyncQueue.push({scope: this, expression: expr, locals: locals});
      },

      $$postDigest: function(fn) {
        postDigestQueue.push(fn);
      },

      /**
       * @ngdoc method
       * @name $rootScope.Scope#$apply
       * @kind function
       *
       * @description
       * `$apply()` is used to execute an expression in angular from outside of the angular
       * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
       * Because we are calling into the angular framework we need to perform proper scope life
       * cycle of {@link ng.$exceptionHandler exception handling},
       * {@link ng.$rootScope.Scope#$digest executing watches}.
       *
       * ## Life cycle
       *
       * # Pseudo-Code of `$apply()`
       * ```js
           function $apply(expr) {
             try {
               return $eval(expr);
             } catch (e) {
               $exceptionHandler(e);
             } finally {
               $root.$digest();
             }
           }
       * ```
       *
       *
       * Scope's `$apply()` method transitions through the following stages:
       *
       * 1. The {@link guide/expression expression} is executed using the
       *    {@link ng.$rootScope.Scope#$eval $eval()} method.
       * 2. Any exceptions from the execution of the expression are forwarded to the
       *    {@link ng.$exceptionHandler $exceptionHandler} service.
       * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
       *    expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
       *
       *
       * @param {(string|function())=} exp An angular expression to be executed.
       *
       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.
       *    - `function(scope)`: execute the function with current `scope` parameter.
       *
       * @returns {*} The result of evaluating the expression.
       */
      $apply: function(expr) {
        try {
          beginPhase('$apply');
          return this.$eval(expr);
        } catch (e) {
          $exceptionHandler(e);
        } finally {
          clearPhase();
          try {
            $rootScope.$digest();
          } catch (e) {
            $exceptionHandler(e);
            throw e;
          }
        }
      },

      /**
       * @ngdoc method
       * @name $rootScope.Scope#$applyAsync
       * @kind function
       *
       * @description
       * Schedule the invocation of $apply to occur at a later time. The actual time difference
       * varies across browsers, but is typically around ~10 milliseconds.
       *
       * This can be used to queue up multiple expressions which need to be evaluated in the same
       * digest.
       *
       * @param {(string|function())=} exp An angular expression to be executed.
       *
       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.
       *    - `function(scope)`: execute the function with current `scope` parameter.
       */
      $applyAsync: function(expr) {
        var scope = this;
        expr && applyAsyncQueue.push($applyAsyncExpression);
        scheduleApplyAsync();

        function $applyAsyncExpression() {
          scope.$eval(expr);
        }
      },

      /**
       * @ngdoc method
       * @name $rootScope.Scope#$on
       * @kind function
       *
       * @description
       * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
       * discussion of event life cycle.
       *
       * The event listener function format is: `function(event, args...)`. The `event` object
       * passed into the listener has the following attributes:
       *
       *   - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
       *     `$broadcast`-ed.
       *   - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
       *     event propagates through the scope hierarchy, this property is set to null.
       *   - `name` - `{string}`: name of the event.
       *   - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
       *     further event propagation (available only for events that were `$emit`-ed).
       *   - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
       *     to true.
       *   - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
       *
       * @param {string} name Event name to listen on.
       * @param {function(event, ...args)} listener Function to call when the event is emitted.
       * @returns {function()} Returns a deregistration function for this listener.
       */
      $on: function(name, listener) {
        var namedListeners = this.$$listeners[name];
        if (!namedListeners) {
          this.$$listeners[name] = namedListeners = [];
        }
        namedListeners.push(listener);

        var current = this;
        do {
          if (!current.$$listenerCount[name]) {
            current.$$listenerCount[name] = 0;
          }
          current.$$listenerCount[name]++;
        } while ((current = current.$parent));

        var self = this;
        return function() {
          var indexOfListener = namedListeners.indexOf(listener);
          if (indexOfListener !== -1) {
            namedListeners[indexOfListener] = null;
            decrementListenerCount(self, 1, name);
          }
        };
      },


      /**
       * @ngdoc method
       * @name $rootScope.Scope#$emit
       * @kind function
       *
       * @description
       * Dispatches an event `name` upwards through the scope hierarchy notifying the
       * registered {@link ng.$rootScope.Scope#$on} listeners.
       *
       * The event life cycle starts at the scope on which `$emit` was called. All
       * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
       * notified. Afterwards, the event traverses upwards toward the root scope and calls all
       * registered listeners along the way. The event will stop propagating if one of the listeners
       * cancels it.
       *
       * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
       * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
       *
       * @param {string} name Event name to emit.
       * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
       * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
       */
      $emit: function(name, args) {
        var empty = [],
            namedListeners,
            scope = this,
            stopPropagation = false,
            event = {
              name: name,
              targetScope: scope,
              stopPropagation: function() {stopPropagation = true;},
              preventDefault: function() {
                event.defaultPrevented = true;
              },
              defaultPrevented: false
            },
            listenerArgs = concat([event], arguments, 1),
            i, length;

        do {
          namedListeners = scope.$$listeners[name] || empty;
          event.currentScope = scope;
          for (i = 0, length = namedListeners.length; i < length; i++) {

            // if listeners were deregistered, defragment the array
            if (!namedListeners[i]) {
              namedListeners.splice(i, 1);
              i--;
              length--;
              continue;
            }
            try {
              //allow all listeners attached to the current scope to run
              namedListeners[i].apply(null, listenerArgs);
            } catch (e) {
              $exceptionHandler(e);
            }
          }
          //if any listener on the current scope stops propagation, prevent bubbling
          if (stopPropagation) {
            event.currentScope = null;
            return event;
          }
          //traverse upwards
          scope = scope.$parent;
        } while (scope);

        event.currentScope = null;

        return event;
      },


      /**
       * @ngdoc method
       * @name $rootScope.Scope#$broadcast
       * @kind function
       *
       * @description
       * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
       * registered {@link ng.$rootScope.Scope#$on} listeners.
       *
       * The event life cycle starts at the scope on which `$broadcast` was called. All
       * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
       * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
       * scope and calls all registered listeners along the way. The event cannot be canceled.
       *
       * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
       * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
       *
       * @param {string} name Event name to broadcast.
       * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
       * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
       */
      $broadcast: function(name, args) {
        var target = this,
            current = target,
            next = target,
            event = {
              name: name,
              targetScope: target,
              preventDefault: function() {
                event.defaultPrevented = true;
              },
              defaultPrevented: false
            };

        if (!target.$$listenerCount[name]) return event;

        var listenerArgs = concat([event], arguments, 1),
            listeners, i, length;

        //down while you can, then up and next sibling or up and next sibling until back at root
        while ((current = next)) {
          event.currentScope = current;
          listeners = current.$$listeners[name] || [];
          for (i = 0, length = listeners.length; i < length; i++) {
            // if listeners were deregistered, defragment the array
            if (!listeners[i]) {
              listeners.splice(i, 1);
              i--;
              length--;
              continue;
            }

            try {
              listeners[i].apply(null, listenerArgs);
            } catch (e) {
              $exceptionHandler(e);
            }
          }

          // Insanity Warning: scope depth-first traversal
          // yes, this code is a bit crazy, but it works and we have tests to prove it!
          // this piece should be kept in sync with the traversal in $digest
          // (though it differs due to having the extra check for $$listenerCount)
          if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
              (current !== target && current.$$nextSibling)))) {
            while (current !== target && !(next = current.$$nextSibling)) {
              current = current.$parent;
            }
          }
        }

        event.currentScope = null;
        return event;
      }
    };

    var $rootScope = new Scope();

    //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
    var asyncQueue = $rootScope.$$asyncQueue = [];
    var postDigestQueue = $rootScope.$$postDigestQueue = [];
    var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];

    return $rootScope;


    function beginPhase(phase) {
      if ($rootScope.$$phase) {
        throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
      }

      $rootScope.$$phase = phase;
    }

    function clearPhase() {
      $rootScope.$$phase = null;
    }

    function incrementWatchersCount(current, count) {
      do {
        current.$$watchersCount += count;
      } while ((current = current.$parent));
    }

    function decrementListenerCount(current, count, name) {
      do {
        current.$$listenerCount[name] -= count;

        if (current.$$listenerCount[name] === 0) {
          delete current.$$listenerCount[name];
        }
      } while ((current = current.$parent));
    }

    /**
     * function used as an initial value for watchers.
     * because it's unique we can easily tell it apart from other values
     */
    function initWatchVal() {}

    function flushApplyAsync() {
      while (applyAsyncQueue.length) {
        try {
          applyAsyncQueue.shift()();
        } catch (e) {
          $exceptionHandler(e);
        }
      }
      applyAsyncId = null;
    }

    function scheduleApplyAsync() {
      if (applyAsyncId === null) {
        applyAsyncId = $browser.defer(function() {
          $rootScope.$apply(flushApplyAsync);
        });
      }
    }
  }];
}

/**
 * @description
 * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
 */
function $$SanitizeUriProvider() {
  var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
    imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;

  /**
   * @description
   * Retrieves or overrides the default regular expression that is used for whitelisting of safe
   * urls during a[href] sanitization.
   *
   * The sanitization is a security measure aimed at prevent XSS attacks via html links.
   *
   * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
   * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
   * regular expression. If a match is found, the original url is written into the dom. Otherwise,
   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
   *
   * @param {RegExp=} regexp New regexp to whitelist urls with.
   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
   *    chaining otherwise.
   */
  this.aHrefSanitizationWhitelist = function(regexp) {
    if (isDefined(regexp)) {
      aHrefSanitizationWhitelist = regexp;
      return this;
    }
    return aHrefSanitizationWhitelist;
  };


  /**
   * @description
   * Retrieves or overrides the default regular expression that is used for whitelisting of safe
   * urls during img[src] sanitization.
   *
   * The sanitization is a security measure aimed at prevent XSS attacks via html links.
   *
   * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
   * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
   * regular expression. If a match is found, the original url is written into the dom. Otherwise,
   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
   *
   * @param {RegExp=} regexp New regexp to whitelist urls with.
   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
   *    chaining otherwise.
   */
  this.imgSrcSanitizationWhitelist = function(regexp) {
    if (isDefined(regexp)) {
      imgSrcSanitizationWhitelist = regexp;
      return this;
    }
    return imgSrcSanitizationWhitelist;
  };

  this.$get = function() {
    return function sanitizeUri(uri, isImage) {
      var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
      var normalizedVal;
      normalizedVal = urlResolve(uri).href;
      if (normalizedVal !== '' && !normalizedVal.match(regex)) {
        return 'unsafe:' + normalizedVal;
      }
      return uri;
    };
  };
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *     Any commits to this file should be reviewed with security in mind.  *
 *   Changes to this file can potentially create security vulnerabilities. *
 *          An approval from 2 Core members with history of modifying      *
 *                         this file is required.                          *
 *                                                                         *
 *  Does the change somehow allow for arbitrary javascript to be executed? *
 *    Or allows for someone to change the prototype of built-in objects?   *
 *     Or gives undesired access to variables likes document or window?    *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

var $sceMinErr = minErr('$sce');

var SCE_CONTEXTS = {
  HTML: 'html',
  CSS: 'css',
  URL: 'url',
  // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  // url.  (e.g. ng-include, script src, templateUrl)
  RESOURCE_URL: 'resourceUrl',
  JS: 'js'
};

// Helper functions follow.

function adjustMatcher(matcher) {
  if (matcher === 'self') {
    return matcher;
  } else if (isString(matcher)) {
    // Strings match exactly except for 2 wildcards - '*' and '**'.
    // '*' matches any character except those from the set ':/.?&'.
    // '**' matches any character (like .* in a RegExp).
    // More than 2 *'s raises an error as it's ill defined.
    if (matcher.indexOf('***') > -1) {
      throw $sceMinErr('iwcard',
          'Illegal sequence *** in string matcher.  String: {0}', matcher);
    }
    matcher = escapeForRegexp(matcher).
                  replace('\\*\\*', '.*').
                  replace('\\*', '[^:/.?&;]*');
    return new RegExp('^' + matcher + '$');
  } else if (isRegExp(matcher)) {
    // The only other type of matcher allowed is a Regexp.
    // Match entire URL / disallow partial matches.
    // Flags are reset (i.e. no global, ignoreCase or multiline)
    return new RegExp('^' + matcher.source + '$');
  } else {
    throw $sceMinErr('imatcher',
        'Matchers may only be "self", string patterns or RegExp objects');
  }
}


function adjustMatchers(matchers) {
  var adjustedMatchers = [];
  if (isDefined(matchers)) {
    forEach(matchers, function(matcher) {
      adjustedMatchers.push(adjustMatcher(matcher));
    });
  }
  return adjustedMatchers;
}


/**
 * @ngdoc service
 * @name $sceDelegate
 * @kind function
 *
 * @description
 *
 * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
 * Contextual Escaping (SCE)} services to AngularJS.
 *
 * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
 * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS.  This is
 * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
 * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
 * work because `$sce` delegates to `$sceDelegate` for these operations.
 *
 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
 *
 * The default instance of `$sceDelegate` should work out of the box with little pain.  While you
 * can override it completely to change the behavior of `$sce`, the common case would
 * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
 * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
 * templates.  Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
 * $sceDelegateProvider.resourceUrlWhitelist} and {@link
 * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
 */

/**
 * @ngdoc provider
 * @name $sceDelegateProvider
 * @description
 *
 * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
 * $sceDelegate} service.  This allows one to get/set the whitelists and blacklists used to ensure
 * that the URLs used for sourcing Angular templates are safe.  Refer {@link
 * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
 * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
 *
 * For the general details about this service in Angular, read the main page for {@link ng.$sce
 * Strict Contextual Escaping (SCE)}.
 *
 * **Example**:  Consider the following case. <a name="example"></a>
 *
 * - your app is hosted at url `http://myapp.example.com/`
 * - but some of your templates are hosted on other domains you control such as
 *   `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
 * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
 *
 * Here is what a secure configuration for this scenario might look like:
 *
 * ```
 *  angular.module('myApp', []).config(function($sceDelegateProvider) {
 *    $sceDelegateProvider.resourceUrlWhitelist([
 *      // Allow same origin resource loads.
 *      'self',
 *      // Allow loading from our assets domain.  Notice the difference between * and **.
 *      'http://srv*.assets.example.com/**'
 *    ]);
 *
 *    // The blacklist overrides the whitelist so the open redirect here is blocked.
 *    $sceDelegateProvider.resourceUrlBlacklist([
 *      'http://myapp.example.com/clickThru**'
 *    ]);
 *  });
 * ```
 */

function $SceDelegateProvider() {
  this.SCE_CONTEXTS = SCE_CONTEXTS;

  // Resource URLs can also be trusted by policy.
  var resourceUrlWhitelist = ['self'],
      resourceUrlBlacklist = [];

  /**
   * @ngdoc method
   * @name $sceDelegateProvider#resourceUrlWhitelist
   * @kind function
   *
   * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
   *     provided.  This must be an array or null.  A snapshot of this array is used so further
   *     changes to the array are ignored.
   *
   *     Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
   *     allowed in this array.
   *
   *     Note: **an empty whitelist array will block all URLs**!
   *
   * @return {Array} the currently set whitelist array.
   *
   * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
   * same origin resource requests.
   *
   * @description
   * Sets/Gets the whitelist of trusted resource URLs.
   */
  this.resourceUrlWhitelist = function(value) {
    if (arguments.length) {
      resourceUrlWhitelist = adjustMatchers(value);
    }
    return resourceUrlWhitelist;
  };

  /**
   * @ngdoc method
   * @name $sceDelegateProvider#resourceUrlBlacklist
   * @kind function
   *
   * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
   *     provided.  This must be an array or null.  A snapshot of this array is used so further
   *     changes to the array are ignored.
   *
   *     Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
   *     allowed in this array.
   *
   *     The typical usage for the blacklist is to **block
   *     [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
   *     these would otherwise be trusted but actually return content from the redirected domain.
   *
   *     Finally, **the blacklist overrides the whitelist** and has the final say.
   *
   * @return {Array} the currently set blacklist array.
   *
   * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
   * is no blacklist.)
   *
   * @description
   * Sets/Gets the blacklist of trusted resource URLs.
   */

  this.resourceUrlBlacklist = function(value) {
    if (arguments.length) {
      resourceUrlBlacklist = adjustMatchers(value);
    }
    return resourceUrlBlacklist;
  };

  this.$get = ['$injector', function($injector) {

    var htmlSanitizer = function htmlSanitizer(html) {
      throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
    };

    if ($injector.has('$sanitize')) {
      htmlSanitizer = $injector.get('$sanitize');
    }


    function matchUrl(matcher, parsedUrl) {
      if (matcher === 'self') {
        return urlIsSameOrigin(parsedUrl);
      } else {
        // definitely a regex.  See adjustMatchers()
        return !!matcher.exec(parsedUrl.href);
      }
    }

    function isResourceUrlAllowedByPolicy(url) {
      var parsedUrl = urlResolve(url.toString());
      var i, n, allowed = false;
      // Ensure that at least one item from the whitelist allows this url.
      for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
        if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
          allowed = true;
          break;
        }
      }
      if (allowed) {
        // Ensure that no item from the blacklist blocked this url.
        for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
          if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
            allowed = false;
            break;
          }
        }
      }
      return allowed;
    }

    function generateHolderType(Base) {
      var holderType = function TrustedValueHolderType(trustedValue) {
        this.$$unwrapTrustedValue = function() {
          return trustedValue;
        };
      };
      if (Base) {
        holderType.prototype = new Base();
      }
      holderType.prototype.valueOf = function sceValueOf() {
        return this.$$unwrapTrustedValue();
      };
      holderType.prototype.toString = function sceToString() {
        return this.$$unwrapTrustedValue().toString();
      };
      return holderType;
    }

    var trustedValueHolderBase = generateHolderType(),
        byType = {};

    byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
    byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
    byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
    byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
    byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);

    /**
     * @ngdoc method
     * @name $sceDelegate#trustAs
     *
     * @description
     * Returns an object that is trusted by angular for use in specified strict
     * contextual escaping contexts (such as ng-bind-html, ng-include, any src
     * attribute interpolation, any dom event binding attribute interpolation
     * such as for onclick,  etc.) that uses the provided value.
     * See {@link ng.$sce $sce} for enabling strict contextual escaping.
     *
     * @param {string} type The kind of context in which this value is safe for use.  e.g. url,
     *   resourceUrl, html, js and css.
     * @param {*} value The value that that should be considered trusted/safe.
     * @returns {*} A value that can be used to stand in for the provided `value` in places
     * where Angular expects a $sce.trustAs() return value.
     */
    function trustAs(type, trustedValue) {
      var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
      if (!Constructor) {
        throw $sceMinErr('icontext',
            'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
            type, trustedValue);
      }
      if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
        return trustedValue;
      }
      // All the current contexts in SCE_CONTEXTS happen to be strings.  In order to avoid trusting
      // mutable objects, we ensure here that the value passed in is actually a string.
      if (typeof trustedValue !== 'string') {
        throw $sceMinErr('itype',
            'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
            type);
      }
      return new Constructor(trustedValue);
    }

    /**
     * @ngdoc method
     * @name $sceDelegate#valueOf
     *
     * @description
     * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
     * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
     * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
     *
     * If the passed parameter is not a value that had been returned by {@link
     * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
     *
     * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
     *      call or anything else.
     * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
     *     `$sceDelegate.trustAs`} if `value` is the result of such a call.  Otherwise, returns
     *     `value` unchanged.
     */
    function valueOf(maybeTrusted) {
      if (maybeTrusted instanceof trustedValueHolderBase) {
        return maybeTrusted.$$unwrapTrustedValue();
      } else {
        return maybeTrusted;
      }
    }

    /**
     * @ngdoc method
     * @name $sceDelegate#getTrusted
     *
     * @description
     * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
     * returns the originally supplied value if the queried context type is a supertype of the
     * created type.  If this condition isn't satisfied, throws an exception.
     *
     * @param {string} type The kind of context in which this value is to be used.
     * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
     *     `$sceDelegate.trustAs`} call.
     * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
     *     `$sceDelegate.trustAs`} if valid in this context.  Otherwise, throws an exception.
     */
    function getTrusted(type, maybeTrusted) {
      if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
        return maybeTrusted;
      }
      var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
      if (constructor && maybeTrusted instanceof constructor) {
        return maybeTrusted.$$unwrapTrustedValue();
      }
      // If we get here, then we may only take one of two actions.
      // 1. sanitize the value for the requested type, or
      // 2. throw an exception.
      if (type === SCE_CONTEXTS.RESOURCE_URL) {
        if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
          return maybeTrusted;
        } else {
          throw $sceMinErr('insecurl',
              'Blocked loading resource from url not allowed by $sceDelegate policy.  URL: {0}',
              maybeTrusted.toString());
        }
      } else if (type === SCE_CONTEXTS.HTML) {
        return htmlSanitizer(maybeTrusted);
      }
      throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
    }

    return { trustAs: trustAs,
             getTrusted: getTrusted,
             valueOf: valueOf };
  }];
}


/**
 * @ngdoc provider
 * @name $sceProvider
 * @description
 *
 * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
 * -   enable/disable Strict Contextual Escaping (SCE) in a module
 * -   override the default implementation with a custom delegate
 *
 * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
 */

/* jshint maxlen: false*/

/**
 * @ngdoc service
 * @name $sce
 * @kind function
 *
 * @description
 *
 * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
 *
 * # Strict Contextual Escaping
 *
 * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
 * contexts to result in a value that is marked as safe to use for that context.  One example of
 * such a context is binding arbitrary html controlled by the user via `ng-bind-html`.  We refer
 * to these contexts as privileged or SCE contexts.
 *
 * As of version 1.2, Angular ships with SCE enabled by default.
 *
 * Note:  When enabled (the default), IE<11 in quirks mode is not supported.  In this mode, IE<11 allow
 * one to execute arbitrary javascript by the use of the expression() syntax.  Refer
 * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
 * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
 * to the top of your HTML document.
 *
 * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
 * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
 *
 * Here's an example of a binding in a privileged context:
 *
 * ```
 * <input ng-model="userHtml" aria-label="User input">
 * <div ng-bind-html="userHtml"></div>
 * ```
 *
 * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user.  With SCE
 * disabled, this application allows the user to render arbitrary HTML into the DIV.
 * In a more realistic example, one may be rendering user comments, blog articles, etc. via
 * bindings.  (HTML is just one example of a context where rendering user controlled input creates
 * security vulnerabilities.)
 *
 * For the case of HTML, you might use a library, either on the client side, or on the server side,
 * to sanitize unsafe HTML before binding to the value and rendering it in the document.
 *
 * How would you ensure that every place that used these types of bindings was bound to a value that
 * was sanitized by your library (or returned as safe for rendering by your server?)  How can you
 * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
 * properties/fields and forgot to update the binding to the sanitized value?
 *
 * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
 * determine that something explicitly says it's safe to use a value for binding in that
 * context.  You can then audit your code (a simple grep would do) to ensure that this is only done
 * for those values that you can easily tell are safe - because they were received from your server,
 * sanitized by your library, etc.  You can organize your codebase to help with this - perhaps
 * allowing only the files in a specific directory to do this.  Ensuring that the internal API
 * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
 *
 * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
 * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
 * obtain values that will be accepted by SCE / privileged contexts.
 *
 *
 * ## How does it work?
 *
 * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
 * $sce.getTrusted(context, value)} rather than to the value directly.  Directives use {@link
 * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
 * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
 *
 * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
 * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}.  Here's the actual code (slightly
 * simplified):
 *
 * ```
 * var ngBindHtmlDirective = ['$sce', function($sce) {
 *   return function(scope, element, attr) {
 *     scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
 *       element.html(value || '');
 *     });
 *   };
 * }];
 * ```
 *
 * ## Impact on loading templates
 *
 * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
 * `templateUrl`'s specified by {@link guide/directive directives}.
 *
 * By default, Angular only loads templates from the same domain and protocol as the application
 * document.  This is done by calling {@link ng.$sce#getTrustedResourceUrl
 * $sce.getTrustedResourceUrl} on the template URL.  To load templates from other domains and/or
 * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
 * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
 *
 * *Please note*:
 * The browser's
 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
 * policy apply in addition to this and may further restrict whether the template is successfully
 * loaded.  This means that without the right CORS policy, loading templates from a different domain
 * won't work on all browsers.  Also, loading templates from `file://` URL does not work on some
 * browsers.
 *
 * ## This feels like too much overhead
 *
 * It's important to remember that SCE only applies to interpolation expressions.
 *
 * If your expressions are constant literals, they're automatically trusted and you don't need to
 * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
 * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
 *
 * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
 * through {@link ng.$sce#getTrusted $sce.getTrusted}.  SCE doesn't play a role here.
 *
 * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
 * templates in `ng-include` from your application's domain without having to even know about SCE.
 * It blocks loading templates from other domains or loading templates over http from an https
 * served document.  You can change these by setting your own custom {@link
 * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
 * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
 *
 * This significantly reduces the overhead.  It is far easier to pay the small overhead and have an
 * application that's secure and can be audited to verify that with much more ease than bolting
 * security onto an application later.
 *
 * <a name="contexts"></a>
 * ## What trusted context types are supported?
 *
 * | Context             | Notes          |
 * |---------------------|----------------|
 * | `$sce.HTML`         | For HTML that's safe to source into the application.  The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
 * | `$sce.CSS`          | For CSS that's safe to source into the application.  Currently unused.  Feel free to use it in your own directives. |
 * | `$sce.URL`          | For URLs that are safe to follow as links.  Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
 * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application.  Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.)  <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
 * | `$sce.JS`           | For JavaScript that is safe to execute in your application's context.  Currently unused.  Feel free to use it in your own directives. |
 *
 * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
 *
 *  Each element in these arrays must be one of the following:
 *
 *  - **'self'**
 *    - The special **string**, `'self'`, can be used to match against all URLs of the **same
 *      domain** as the application document using the **same protocol**.
 *  - **String** (except the special value `'self'`)
 *    - The string is matched against the full *normalized / absolute URL* of the resource
 *      being tested (substring matches are not good enough.)
 *    - There are exactly **two wildcard sequences** - `*` and `**`.  All other characters
 *      match themselves.
 *    - `*`: matches zero or more occurrences of any character other than one of the following 6
 *      characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'.  It's a useful wildcard for use
 *      in a whitelist.
 *    - `**`: matches zero or more occurrences of *any* character.  As such, it's not
 *      not appropriate to use in for a scheme, domain, etc. as it would match too much.  (e.g.
 *      http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
 *      not have been the intention.)  Its usage at the very end of the path is ok.  (e.g.
 *      http://foo.example.com/templates/**).
 *  - **RegExp** (*see caveat below*)
 *    - *Caveat*:  While regular expressions are powerful and offer great flexibility,  their syntax
 *      (and all the inevitable escaping) makes them *harder to maintain*.  It's easy to
 *      accidentally introduce a bug when one updates a complex expression (imho, all regexes should
 *      have good test coverage.).  For instance, the use of `.` in the regex is correct only in a
 *      small number of cases.  A `.` character in the regex used when matching the scheme or a
 *      subdomain could be matched against a `:` or literal `.` that was likely not intended.   It
 *      is highly recommended to use the string patterns and only fall back to regular expressions
 *      if they as a last resort.
 *    - The regular expression must be an instance of RegExp (i.e. not a string.)  It is
 *      matched against the **entire** *normalized / absolute URL* of the resource being tested
 *      (even when the RegExp did not have the `^` and `$` codes.)  In addition, any flags
 *      present on the RegExp (such as multiline, global, ignoreCase) are ignored.
 *    - If you are generating your JavaScript from some other templating engine (not
 *      recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
 *      remember to escape your regular expression (and be aware that you might need more than
 *      one level of escaping depending on your templating engine and the way you interpolated
 *      the value.)  Do make use of your platform's escaping mechanism as it might be good
 *      enough before coding your own.  e.g. Ruby has
 *      [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
 *      and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
 *      Javascript lacks a similar built in function for escaping.  Take a look at Google
 *      Closure library's [goog.string.regExpEscape(s)](
 *      http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
 *
 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
 *
 * ## Show me an example using SCE.
 *
 * <example module="mySceApp" deps="angular-sanitize.js">
 * <file name="index.html">
 *   <div ng-controller="AppController as myCtrl">
 *     <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
 *     <b>User comments</b><br>
 *     By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
 *     $sanitize is available.  If $sanitize isn't available, this results in an error instead of an
 *     exploit.
 *     <div class="well">
 *       <div ng-repeat="userComment in myCtrl.userComments">
 *         <b>{{userComment.name}}</b>:
 *         <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
 *         <br>
 *       </div>
 *     </div>
 *   </div>
 * </file>
 *
 * <file name="script.js">
 *   angular.module('mySceApp', ['ngSanitize'])
 *     .controller('AppController', ['$http', '$templateCache', '$sce',
 *       function($http, $templateCache, $sce) {
 *         var self = this;
 *         $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
 *           self.userComments = userComments;
 *         });
 *         self.explicitlyTrustedHtml = $sce.trustAsHtml(
 *             '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
 *             'sanitization.&quot;">Hover over this text.</span>');
 *       }]);
 * </file>
 *
 * <file name="test_data.json">
 * [
 *   { "name": "Alice",
 *     "htmlComment":
 *         "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
 *   },
 *   { "name": "Bob",
 *     "htmlComment": "<i>Yes!</i>  Am I the only other one?"
 *   }
 * ]
 * </file>
 *
 * <file name="protractor.js" type="protractor">
 *   describe('SCE doc demo', function() {
 *     it('should sanitize untrusted values', function() {
 *       expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
 *           .toBe('<span>Is <i>anyone</i> reading this?</span>');
 *     });
 *
 *     it('should NOT sanitize explicitly trusted values', function() {
 *       expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
 *           '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
 *           'sanitization.&quot;">Hover over this text.</span>');
 *     });
 *   });
 * </file>
 * </example>
 *
 *
 *
 * ## Can I disable SCE completely?
 *
 * Yes, you can.  However, this is strongly discouraged.  SCE gives you a lot of security benefits
 * for little coding overhead.  It will be much harder to take an SCE disabled application and
 * either secure it on your own or enable SCE at a later stage.  It might make sense to disable SCE
 * for cases where you have a lot of existing code that was written before SCE was introduced and
 * you're migrating them a module at a time.
 *
 * That said, here's how you can completely disable SCE:
 *
 * ```
 * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
 *   // Completely disable SCE.  For demonstration purposes only!
 *   // Do not use in new projects.
 *   $sceProvider.enabled(false);
 * });
 * ```
 *
 */
/* jshint maxlen: 100 */

function $SceProvider() {
  var enabled = true;

  /**
   * @ngdoc method
   * @name $sceProvider#enabled
   * @kind function
   *
   * @param {boolean=} value If provided, then enables/disables SCE.
   * @return {boolean} true if SCE is enabled, false otherwise.
   *
   * @description
   * Enables/disables SCE and returns the current value.
   */
  this.enabled = function(value) {
    if (arguments.length) {
      enabled = !!value;
    }
    return enabled;
  };


  /* Design notes on the default implementation for SCE.
   *
   * The API contract for the SCE delegate
   * -------------------------------------
   * The SCE delegate object must provide the following 3 methods:
   *
   * - trustAs(contextEnum, value)
   *     This method is used to tell the SCE service that the provided value is OK to use in the
   *     contexts specified by contextEnum.  It must return an object that will be accepted by
   *     getTrusted() for a compatible contextEnum and return this value.
   *
   * - valueOf(value)
   *     For values that were not produced by trustAs(), return them as is.  For values that were
   *     produced by trustAs(), return the corresponding input value to trustAs.  Basically, if
   *     trustAs is wrapping the given values into some type, this operation unwraps it when given
   *     such a value.
   *
   * - getTrusted(contextEnum, value)
   *     This function should return the a value that is safe to use in the context specified by
   *     contextEnum or throw and exception otherwise.
   *
   * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
   * opaque or wrapped in some holder object.  That happens to be an implementation detail.  For
   * instance, an implementation could maintain a registry of all trusted objects by context.  In
   * such a case, trustAs() would return the same object that was passed in.  getTrusted() would
   * return the same object passed in if it was found in the registry under a compatible context or
   * throw an exception otherwise.  An implementation might only wrap values some of the time based
   * on some criteria.  getTrusted() might return a value and not throw an exception for special
   * constants or objects even if not wrapped.  All such implementations fulfill this contract.
   *
   *
   * A note on the inheritance model for SCE contexts
   * ------------------------------------------------
   * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types.  This
   * is purely an implementation details.
   *
   * The contract is simply this:
   *
   *     getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
   *     will also succeed.
   *
   * Inheritance happens to capture this in a natural way.  In some future, we
   * may not use inheritance anymore.  That is OK because no code outside of
   * sce.js and sceSpecs.js would need to be aware of this detail.
   */

  this.$get = ['$parse', '$sceDelegate', function(
                $parse,   $sceDelegate) {
    // Prereq: Ensure that we're not running in IE<11 quirks mode.  In that mode, IE < 11 allow
    // the "expression(javascript expression)" syntax which is insecure.
    if (enabled && msie < 8) {
      throw $sceMinErr('iequirks',
        'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
        'mode.  You can fix this by adding the text <!doctype html> to the top of your HTML ' +
        'document.  See http://docs.angularjs.org/api/ng.$sce for more information.');
    }

    var sce = shallowCopy(SCE_CONTEXTS);

    /**
     * @ngdoc method
     * @name $sce#isEnabled
     * @kind function
     *
     * @return {Boolean} true if SCE is enabled, false otherwise.  If you want to set the value, you
     * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
     *
     * @description
     * Returns a boolean indicating if SCE is enabled.
     */
    sce.isEnabled = function() {
      return enabled;
    };
    sce.trustAs = $sceDelegate.trustAs;
    sce.getTrusted = $sceDelegate.getTrusted;
    sce.valueOf = $sceDelegate.valueOf;

    if (!enabled) {
      sce.trustAs = sce.getTrusted = function(type, value) { return value; };
      sce.valueOf = identity;
    }

    /**
     * @ngdoc method
     * @name $sce#parseAs
     *
     * @description
     * Converts Angular {@link guide/expression expression} into a function.  This is like {@link
     * ng.$parse $parse} and is identical when the expression is a literal constant.  Otherwise, it
     * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
     * *result*)}
     *
     * @param {string} type The kind of SCE context in which this result will be used.
     * @param {string} expression String expression to compile.
     * @returns {function(context, locals)} a function which represents the compiled expression:
     *
     *    * `context` – `{object}` – an object against which any expressions embedded in the strings
     *      are evaluated against (typically a scope object).
     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
     *      `context`.
     */
    sce.parseAs = function sceParseAs(type, expr) {
      var parsed = $parse(expr);
      if (parsed.literal && parsed.constant) {
        return parsed;
      } else {
        return $parse(expr, function(value) {
          return sce.getTrusted(type, value);
        });
      }
    };

    /**
     * @ngdoc method
     * @name $sce#trustAs
     *
     * @description
     * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.  As such,
     * returns an object that is trusted by angular for use in specified strict contextual
     * escaping contexts (such as ng-bind-html, ng-include, any src attribute
     * interpolation, any dom event binding attribute interpolation such as for onclick,  etc.)
     * that uses the provided value.  See * {@link ng.$sce $sce} for enabling strict contextual
     * escaping.
     *
     * @param {string} type The kind of context in which this value is safe for use.  e.g. url,
     *   resourceUrl, html, js and css.
     * @param {*} value The value that that should be considered trusted/safe.
     * @returns {*} A value that can be used to stand in for the provided `value` in places
     * where Angular expects a $sce.trustAs() return value.
     */

    /**
     * @ngdoc method
     * @name $sce#trustAsHtml
     *
     * @description
     * Shorthand method.  `$sce.trustAsHtml(value)` →
     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
     *
     * @param {*} value The value to trustAs.
     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
     *     $sce.getTrustedHtml(value)} to obtain the original value.  (privileged directives
     *     only accept expressions that are either literal constants or are the
     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)
     */

    /**
     * @ngdoc method
     * @name $sce#trustAsUrl
     *
     * @description
     * Shorthand method.  `$sce.trustAsUrl(value)` →
     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
     *
     * @param {*} value The value to trustAs.
     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
     *     $sce.getTrustedUrl(value)} to obtain the original value.  (privileged directives
     *     only accept expressions that are either literal constants or are the
     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)
     */

    /**
     * @ngdoc method
     * @name $sce#trustAsResourceUrl
     *
     * @description
     * Shorthand method.  `$sce.trustAsResourceUrl(value)` →
     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
     *
     * @param {*} value The value to trustAs.
     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
     *     $sce.getTrustedResourceUrl(value)} to obtain the original value.  (privileged directives
     *     only accept expressions that are either literal constants or are the return
     *     value of {@link ng.$sce#trustAs $sce.trustAs}.)
     */

    /**
     * @ngdoc method
     * @name $sce#trustAsJs
     *
     * @description
     * Shorthand method.  `$sce.trustAsJs(value)` →
     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
     *
     * @param {*} value The value to trustAs.
     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
     *     $sce.getTrustedJs(value)} to obtain the original value.  (privileged directives
     *     only accept expressions that are either literal constants or are the
     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)
     */

    /**
     * @ngdoc method
     * @name $sce#getTrusted
     *
     * @description
     * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}.  As such,
     * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
     * originally supplied value if the queried context type is a supertype of the created type.
     * If this condition isn't satisfied, throws an exception.
     *
     * @param {string} type The kind of context in which this value is to be used.
     * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
     *                         call.
     * @returns {*} The value the was originally provided to
     *              {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
     *              Otherwise, throws an exception.
     */

    /**
     * @ngdoc method
     * @name $sce#getTrustedHtml
     *
     * @description
     * Shorthand method.  `$sce.getTrustedHtml(value)` →
     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
     *
     * @param {*} value The value to pass to `$sce.getTrusted`.
     * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
     */

    /**
     * @ngdoc method
     * @name $sce#getTrustedCss
     *
     * @description
     * Shorthand method.  `$sce.getTrustedCss(value)` →
     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
     *
     * @param {*} value The value to pass to `$sce.getTrusted`.
     * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
     */

    /**
     * @ngdoc method
     * @name $sce#getTrustedUrl
     *
     * @description
     * Shorthand method.  `$sce.getTrustedUrl(value)` →
     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
     *
     * @param {*} value The value to pass to `$sce.getTrusted`.
     * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
     */

    /**
     * @ngdoc method
     * @name $sce#getTrustedResourceUrl
     *
     * @description
     * Shorthand method.  `$sce.getTrustedResourceUrl(value)` →
     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
     *
     * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
     * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
     */

    /**
     * @ngdoc method
     * @name $sce#getTrustedJs
     *
     * @description
     * Shorthand method.  `$sce.getTrustedJs(value)` →
     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
     *
     * @param {*} value The value to pass to `$sce.getTrusted`.
     * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
     */

    /**
     * @ngdoc method
     * @name $sce#parseAsHtml
     *
     * @description
     * Shorthand method.  `$sce.parseAsHtml(expression string)` →
     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
     *
     * @param {string} expression String expression to compile.
     * @returns {function(context, locals)} a function which represents the compiled expression:
     *
     *    * `context` – `{object}` – an object against which any expressions embedded in the strings
     *      are evaluated against (typically a scope object).
     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
     *      `context`.
     */

    /**
     * @ngdoc method
     * @name $sce#parseAsCss
     *
     * @description
     * Shorthand method.  `$sce.parseAsCss(value)` →
     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
     *
     * @param {string} expression String expression to compile.
     * @returns {function(context, locals)} a function which represents the compiled expression:
     *
     *    * `context` – `{object}` – an object against which any expressions embedded in the strings
     *      are evaluated against (typically a scope object).
     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
     *      `context`.
     */

    /**
     * @ngdoc method
     * @name $sce#parseAsUrl
     *
     * @description
     * Shorthand method.  `$sce.parseAsUrl(value)` →
     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
     *
     * @param {string} expression String expression to compile.
     * @returns {function(context, locals)} a function which represents the compiled expression:
     *
     *    * `context` – `{object}` – an object against which any expressions embedded in the strings
     *      are evaluated against (typically a scope object).
     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
     *      `context`.
     */

    /**
     * @ngdoc method
     * @name $sce#parseAsResourceUrl
     *
     * @description
     * Shorthand method.  `$sce.parseAsResourceUrl(value)` →
     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
     *
     * @param {string} expression String expression to compile.
     * @returns {function(context, locals)} a function which represents the compiled expression:
     *
     *    * `context` – `{object}` – an object against which any expressions embedded in the strings
     *      are evaluated against (typically a scope object).
     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
     *      `context`.
     */

    /**
     * @ngdoc method
     * @name $sce#parseAsJs
     *
     * @description
     * Shorthand method.  `$sce.parseAsJs(value)` →
     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
     *
     * @param {string} expression String expression to compile.
     * @returns {function(context, locals)} a function which represents the compiled expression:
     *
     *    * `context` – `{object}` – an object against which any expressions embedded in the strings
     *      are evaluated against (typically a scope object).
     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
     *      `context`.
     */

    // Shorthand delegations.
    var parse = sce.parseAs,
        getTrusted = sce.getTrusted,
        trustAs = sce.trustAs;

    forEach(SCE_CONTEXTS, function(enumValue, name) {
      var lName = lowercase(name);
      sce[camelCase("parse_as_" + lName)] = function(expr) {
        return parse(enumValue, expr);
      };
      sce[camelCase("get_trusted_" + lName)] = function(value) {
        return getTrusted(enumValue, value);
      };
      sce[camelCase("trust_as_" + lName)] = function(value) {
        return trustAs(enumValue, value);
      };
    });

    return sce;
  }];
}

/**
 * !!! This is an undocumented "private" service !!!
 *
 * @name $sniffer
 * @requires $window
 * @requires $document
 *
 * @property {boolean} history Does the browser support html5 history api ?
 * @property {boolean} transitions Does the browser support CSS transition events ?
 * @property {boolean} animations Does the browser support CSS animation events ?
 *
 * @description
 * This is very simple implementation of testing browser's features.
 */
function $SnifferProvider() {
  this.$get = ['$window', '$document', function($window, $document) {
    var eventSupport = {},
        android =
          toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
        boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
        document = $document[0] || {},
        vendorPrefix,
        vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
        bodyStyle = document.body && document.body.style,
        transitions = false,
        animations = false,
        match;

    if (bodyStyle) {
      for (var prop in bodyStyle) {
        if (match = vendorRegex.exec(prop)) {
          vendorPrefix = match[0];
          vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
          break;
        }
      }

      if (!vendorPrefix) {
        vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
      }

      transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
      animations  = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));

      if (android && (!transitions ||  !animations)) {
        transitions = isString(bodyStyle.webkitTransition);
        animations = isString(bodyStyle.webkitAnimation);
      }
    }


    return {
      // Android has history.pushState, but it does not update location correctly
      // so let's not use the history API at all.
      // http://code.google.com/p/android/issues/detail?id=17471
      // https://github.com/angular/angular.js/issues/904

      // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
      // so let's not use the history API also
      // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
      // jshint -W018
      history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
      // jshint +W018
      hasEvent: function(event) {
        // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
        // it. In particular the event is not fired when backspace or delete key are pressed or
        // when cut operation is performed.
        // IE10+ implements 'input' event but it erroneously fires under various situations,
        // e.g. when placeholder changes, or a form is focused.
        if (event === 'input' && msie <= 11) return false;

        if (isUndefined(eventSupport[event])) {
          var divElm = document.createElement('div');
          eventSupport[event] = 'on' + event in divElm;
        }

        return eventSupport[event];
      },
      csp: csp(),
      vendorPrefix: vendorPrefix,
      transitions: transitions,
      animations: animations,
      android: android
    };
  }];
}

var $compileMinErr = minErr('$compile');

/**
 * @ngdoc service
 * @name $templateRequest
 *
 * @description
 * The `$templateRequest` service runs security checks then downloads the provided template using
 * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
 * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
 * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
 * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
 * when `tpl` is of type string and `$templateCache` has the matching entry.
 *
 * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
 * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
 *
 * @return {Promise} a promise for the HTTP response data of the given URL.
 *
 * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
 */
function $TemplateRequestProvider() {
  this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
    function handleRequestFn(tpl, ignoreRequestError) {
      handleRequestFn.totalPendingRequests++;

      // We consider the template cache holds only trusted templates, so
      // there's no need to go through whitelisting again for keys that already
      // are included in there. This also makes Angular accept any script
      // directive, no matter its name. However, we still need to unwrap trusted
      // types.
      if (!isString(tpl) || !$templateCache.get(tpl)) {
        tpl = $sce.getTrustedResourceUrl(tpl);
      }

      var transformResponse = $http.defaults && $http.defaults.transformResponse;

      if (isArray(transformResponse)) {
        transformResponse = transformResponse.filter(function(transformer) {
          return transformer !== defaultHttpResponseTransform;
        });
      } else if (transformResponse === defaultHttpResponseTransform) {
        transformResponse = null;
      }

      var httpOptions = {
        cache: $templateCache,
        transformResponse: transformResponse
      };

      return $http.get(tpl, httpOptions)
        ['finally'](function() {
          handleRequestFn.totalPendingRequests--;
        })
        .then(function(response) {
          $templateCache.put(tpl, response.data);
          return response.data;
        }, handleError);

      function handleError(resp) {
        if (!ignoreRequestError) {
          throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
            tpl, resp.status, resp.statusText);
        }
        return $q.reject(resp);
      }
    }

    handleRequestFn.totalPendingRequests = 0;

    return handleRequestFn;
  }];
}

function $$TestabilityProvider() {
  this.$get = ['$rootScope', '$browser', '$location',
       function($rootScope,   $browser,   $location) {

    /**
     * @name $testability
     *
     * @description
     * The private $$testability service provides a collection of methods for use when debugging
     * or by automated test and debugging tools.
     */
    var testability = {};

    /**
     * @name $$testability#findBindings
     *
     * @description
     * Returns an array of elements that are bound (via ng-bind or {{}})
     * to expressions matching the input.
     *
     * @param {Element} element The element root to search from.
     * @param {string} expression The binding expression to match.
     * @param {boolean} opt_exactMatch If true, only returns exact matches
     *     for the expression. Filters and whitespace are ignored.
     */
    testability.findBindings = function(element, expression, opt_exactMatch) {
      var bindings = element.getElementsByClassName('ng-binding');
      var matches = [];
      forEach(bindings, function(binding) {
        var dataBinding = angular.element(binding).data('$binding');
        if (dataBinding) {
          forEach(dataBinding, function(bindingName) {
            if (opt_exactMatch) {
              var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
              if (matcher.test(bindingName)) {
                matches.push(binding);
              }
            } else {
              if (bindingName.indexOf(expression) != -1) {
                matches.push(binding);
              }
            }
          });
        }
      });
      return matches;
    };

    /**
     * @name $$testability#findModels
     *
     * @description
     * Returns an array of elements that are two-way found via ng-model to
     * expressions matching the input.
     *
     * @param {Element} element The element root to search from.
     * @param {string} expression The model expression to match.
     * @param {boolean} opt_exactMatch If true, only returns exact matches
     *     for the expression.
     */
    testability.findModels = function(element, expression, opt_exactMatch) {
      var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
      for (var p = 0; p < prefixes.length; ++p) {
        var attributeEquals = opt_exactMatch ? '=' : '*=';
        var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
        var elements = element.querySelectorAll(selector);
        if (elements.length) {
          return elements;
        }
      }
    };

    /**
     * @name $$testability#getLocation
     *
     * @description
     * Shortcut for getting the location in a browser agnostic way. Returns
     *     the path, search, and hash. (e.g. /path?a=b#hash)
     */
    testability.getLocation = function() {
      return $location.url();
    };

    /**
     * @name $$testability#setLocation
     *
     * @description
     * Shortcut for navigating to a location without doing a full page reload.
     *
     * @param {string} url The location url (path, search and hash,
     *     e.g. /path?a=b#hash) to go to.
     */
    testability.setLocation = function(url) {
      if (url !== $location.url()) {
        $location.url(url);
        $rootScope.$digest();
      }
    };

    /**
     * @name $$testability#whenStable
     *
     * @description
     * Calls the callback when $timeout and $http requests are completed.
     *
     * @param {function} callback
     */
    testability.whenStable = function(callback) {
      $browser.notifyWhenNoOutstandingRequests(callback);
    };

    return testability;
  }];
}

function $TimeoutProvider() {
  this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
       function($rootScope,   $browser,   $q,   $$q,   $exceptionHandler) {

    var deferreds = {};


     /**
      * @ngdoc service
      * @name $timeout
      *
      * @description
      * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
      * block and delegates any exceptions to
      * {@link ng.$exceptionHandler $exceptionHandler} service.
      *
      * The return value of calling `$timeout` is a promise, which will be resolved when
      * the delay has passed and the timeout function, if provided, is executed.
      *
      * To cancel a timeout request, call `$timeout.cancel(promise)`.
      *
      * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
      * synchronously flush the queue of deferred functions.
      *
      * If you only want a promise that will be resolved after some specified delay
      * then you can call `$timeout` without the `fn` function.
      *
      * @param {function()=} fn A function, whose execution should be delayed.
      * @param {number=} [delay=0] Delay in milliseconds.
      * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
      *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
      * @param {...*=} Pass additional parameters to the executed function.
      * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
      *   promise will be resolved with is the return value of the `fn` function.
      *
      */
    function timeout(fn, delay, invokeApply) {
      if (!isFunction(fn)) {
        invokeApply = delay;
        delay = fn;
        fn = noop;
      }

      var args = sliceArgs(arguments, 3),
          skipApply = (isDefined(invokeApply) && !invokeApply),
          deferred = (skipApply ? $$q : $q).defer(),
          promise = deferred.promise,
          timeoutId;

      timeoutId = $browser.defer(function() {
        try {
          deferred.resolve(fn.apply(null, args));
        } catch (e) {
          deferred.reject(e);
          $exceptionHandler(e);
        }
        finally {
          delete deferreds[promise.$$timeoutId];
        }

        if (!skipApply) $rootScope.$apply();
      }, delay);

      promise.$$timeoutId = timeoutId;
      deferreds[timeoutId] = deferred;

      return promise;
    }


     /**
      * @ngdoc method
      * @name $timeout#cancel
      *
      * @description
      * Cancels a task associated with the `promise`. As a result of this, the promise will be
      * resolved with a rejection.
      *
      * @param {Promise=} promise Promise returned by the `$timeout` function.
      * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
      *   canceled.
      */
    timeout.cancel = function(promise) {
      if (promise && promise.$$timeoutId in deferreds) {
        deferreds[promise.$$timeoutId].reject('canceled');
        delete deferreds[promise.$$timeoutId];
        return $browser.defer.cancel(promise.$$timeoutId);
      }
      return false;
    };

    return timeout;
  }];
}

// NOTE:  The usage of window and document instead of $window and $document here is
// deliberate.  This service depends on the specific behavior of anchor nodes created by the
// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
// cause us to break tests.  In addition, when the browser resolves a URL for XHR, it
// doesn't know about mocked locations and resolves URLs to the real document - which is
// exactly the behavior needed here.  There is little value is mocking these out for this
// service.
var urlParsingNode = document.createElement("a");
var originUrl = urlResolve(window.location.href);


/**
 *
 * Implementation Notes for non-IE browsers
 * ----------------------------------------
 * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
 * results both in the normalizing and parsing of the URL.  Normalizing means that a relative
 * URL will be resolved into an absolute URL in the context of the application document.
 * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
 * properties are all populated to reflect the normalized URL.  This approach has wide
 * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc.  See
 * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
 *
 * Implementation Notes for IE
 * ---------------------------
 * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
 * browsers.  However, the parsed components will not be set if the URL assigned did not specify
 * them.  (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.)  We
 * work around that by performing the parsing in a 2nd step by taking a previously normalized
 * URL (e.g. by assigning to a.href) and assigning it a.href again.  This correctly populates the
 * properties such as protocol, hostname, port, etc.
 *
 * IE7 does not normalize the URL when assigned to an anchor node.  (Apparently, it does, if one
 * uses the inner HTML approach to assign the URL as part of an HTML snippet -
 * http://stackoverflow.com/a/472729)  However, setting img[src] does normalize the URL.
 * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
 * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
 * method and IE < 8 is unsupported.
 *
 * References:
 *   http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
 *   http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
 *   http://url.spec.whatwg.org/#urlutils
 *   https://github.com/angular/angular.js/pull/2902
 *   http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
 *
 * @kind function
 * @param {string} url The URL to be parsed.
 * @description Normalizes and parses a URL.
 * @returns {object} Returns the normalized URL as a dictionary.
 *
 *   | member name   | Description    |
 *   |---------------|----------------|
 *   | href          | A normalized version of the provided URL if it was not an absolute URL |
 *   | protocol      | The protocol including the trailing colon                              |
 *   | host          | The host and port (if the port is non-default) of the normalizedUrl    |
 *   | search        | The search params, minus the question mark                             |
 *   | hash          | The hash string, minus the hash symbol
 *   | hostname      | The hostname
 *   | port          | The port, without ":"
 *   | pathname      | The pathname, beginning with "/"
 *
 */
function urlResolve(url) {
  var href = url;

  if (msie) {
    // Normalize before parse.  Refer Implementation Notes on why this is
    // done in two steps on IE.
    urlParsingNode.setAttribute("href", href);
    href = urlParsingNode.href;
  }

  urlParsingNode.setAttribute('href', href);

  // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  return {
    href: urlParsingNode.href,
    protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
    host: urlParsingNode.host,
    search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
    hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
    hostname: urlParsingNode.hostname,
    port: urlParsingNode.port,
    pathname: (urlParsingNode.pathname.charAt(0) === '/')
      ? urlParsingNode.pathname
      : '/' + urlParsingNode.pathname
  };
}

/**
 * Parse a request URL and determine whether this is a same-origin request as the application document.
 *
 * @param {string|object} requestUrl The url of the request as a string that will be resolved
 * or a parsed URL object.
 * @returns {boolean} Whether the request is for the same origin as the application document.
 */
function urlIsSameOrigin(requestUrl) {
  var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  return (parsed.protocol === originUrl.protocol &&
          parsed.host === originUrl.host);
}

/**
 * @ngdoc service
 * @name $window
 *
 * @description
 * A reference to the browser's `window` object. While `window`
 * is globally available in JavaScript, it causes testability problems, because
 * it is a global variable. In angular we always refer to it through the
 * `$window` service, so it may be overridden, removed or mocked for testing.
 *
 * Expressions, like the one defined for the `ngClick` directive in the example
 * below, are evaluated with respect to the current scope.  Therefore, there is
 * no risk of inadvertently coding in a dependency on a global value in such an
 * expression.
 *
 * @example
   <example module="windowExample">
     <file name="index.html">
       <script>
         angular.module('windowExample', [])
           .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
             $scope.greeting = 'Hello, World!';
             $scope.doGreeting = function(greeting) {
               $window.alert(greeting);
             };
           }]);
       </script>
       <div ng-controller="ExampleController">
         <input type="text" ng-model="greeting" aria-label="greeting" />
         <button ng-click="doGreeting(greeting)">ALERT</button>
       </div>
     </file>
     <file name="protractor.js" type="protractor">
      it('should display the greeting in the input box', function() {
       element(by.model('greeting')).sendKeys('Hello, E2E Tests');
       // If we click the button it will block the test runner
       // element(':button').click();
      });
     </file>
   </example>
 */
function $WindowProvider() {
  this.$get = valueFn(window);
}

/**
 * @name $$cookieReader
 * @requires $document
 *
 * @description
 * This is a private service for reading cookies used by $http and ngCookies
 *
 * @return {Object} a key/value map of the current cookies
 */
function $$CookieReader($document) {
  var rawDocument = $document[0] || {};
  var lastCookies = {};
  var lastCookieString = '';

  function safeDecodeURIComponent(str) {
    try {
      return decodeURIComponent(str);
    } catch (e) {
      return str;
    }
  }

  return function() {
    var cookieArray, cookie, i, index, name;
    var currentCookieString = rawDocument.cookie || '';

    if (currentCookieString !== lastCookieString) {
      lastCookieString = currentCookieString;
      cookieArray = lastCookieString.split('; ');
      lastCookies = {};

      for (i = 0; i < cookieArray.length; i++) {
        cookie = cookieArray[i];
        index = cookie.indexOf('=');
        if (index > 0) { //ignore nameless cookies
          name = safeDecodeURIComponent(cookie.substring(0, index));
          // the first value that is seen for a cookie is the most
          // specific one.  values for the same cookie name that
          // follow are for less specific paths.
          if (lastCookies[name] === undefined) {
            lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
          }
        }
      }
    }
    return lastCookies;
  };
}

$$CookieReader.$inject = ['$document'];

function $$CookieReaderProvider() {
  this.$get = $$CookieReader;
}

/* global currencyFilter: true,
 dateFilter: true,
 filterFilter: true,
 jsonFilter: true,
 limitToFilter: true,
 lowercaseFilter: true,
 numberFilter: true,
 orderByFilter: true,
 uppercaseFilter: true,
 */

/**
 * @ngdoc provider
 * @name $filterProvider
 * @description
 *
 * Filters are just functions which transform input to an output. However filters need to be
 * Dependency Injected. To achieve this a filter definition consists of a factory function which is
 * annotated with dependencies and is responsible for creating a filter function.
 *
 * <div class="alert alert-warning">
 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
 * (`myapp_subsection_filterx`).
 * </div>
 *
 * ```js
 *   // Filter registration
 *   function MyModule($provide, $filterProvider) {
 *     // create a service to demonstrate injection (not always needed)
 *     $provide.value('greet', function(name){
 *       return 'Hello ' + name + '!';
 *     });
 *
 *     // register a filter factory which uses the
 *     // greet service to demonstrate DI.
 *     $filterProvider.register('greet', function(greet){
 *       // return the filter function which uses the greet service
 *       // to generate salutation
 *       return function(text) {
 *         // filters need to be forgiving so check input validity
 *         return text && greet(text) || text;
 *       };
 *     });
 *   }
 * ```
 *
 * The filter function is registered with the `$injector` under the filter name suffix with
 * `Filter`.
 *
 * ```js
 *   it('should be the same instance', inject(
 *     function($filterProvider) {
 *       $filterProvider.register('reverse', function(){
 *         return ...;
 *       });
 *     },
 *     function($filter, reverseFilter) {
 *       expect($filter('reverse')).toBe(reverseFilter);
 *     });
 * ```
 *
 *
 * For more information about how angular filters work, and how to create your own filters, see
 * {@link guide/filter Filters} in the Angular Developer Guide.
 */

/**
 * @ngdoc service
 * @name $filter
 * @kind function
 * @description
 * Filters are used for formatting data displayed to the user.
 *
 * The general syntax in templates is as follows:
 *
 *         {{ expression [| filter_name[:parameter_value] ... ] }}
 *
 * @param {String} name Name of the filter function to retrieve
 * @return {Function} the filter function
 * @example
   <example name="$filter" module="filterExample">
     <file name="index.html">
       <div ng-controller="MainCtrl">
        <h3>{{ originalText }}</h3>
        <h3>{{ filteredText }}</h3>
       </div>
     </file>

     <file name="script.js">
      angular.module('filterExample', [])
      .controller('MainCtrl', function($scope, $filter) {
        $scope.originalText = 'hello';
        $scope.filteredText = $filter('uppercase')($scope.originalText);
      });
     </file>
   </example>
  */
$FilterProvider.$inject = ['$provide'];
function $FilterProvider($provide) {
  var suffix = 'Filter';

  /**
   * @ngdoc method
   * @name $filterProvider#register
   * @param {string|Object} name Name of the filter function, or an object map of filters where
   *    the keys are the filter names and the values are the filter factories.
   *
   *    <div class="alert alert-warning">
   *    **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
   *    Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
   *    your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
   *    (`myapp_subsection_filterx`).
   *    </div>
   * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
   *    of the registered filter instances.
   */
  function register(name, factory) {
    if (isObject(name)) {
      var filters = {};
      forEach(name, function(filter, key) {
        filters[key] = register(key, filter);
      });
      return filters;
    } else {
      return $provide.factory(name + suffix, factory);
    }
  }
  this.register = register;

  this.$get = ['$injector', function($injector) {
    return function(name) {
      return $injector.get(name + suffix);
    };
  }];

  ////////////////////////////////////////

  /* global
    currencyFilter: false,
    dateFilter: false,
    filterFilter: false,
    jsonFilter: false,
    limitToFilter: false,
    lowercaseFilter: false,
    numberFilter: false,
    orderByFilter: false,
    uppercaseFilter: false,
  */

  register('currency', currencyFilter);
  register('date', dateFilter);
  register('filter', filterFilter);
  register('json', jsonFilter);
  register('limitTo', limitToFilter);
  register('lowercase', lowercaseFilter);
  register('number', numberFilter);
  register('orderBy', orderByFilter);
  register('uppercase', uppercaseFilter);
}

/**
 * @ngdoc filter
 * @name filter
 * @kind function
 *
 * @description
 * Selects a subset of items from `array` and returns it as a new array.
 *
 * @param {Array} array The source array.
 * @param {string|Object|function()} expression The predicate to be used for selecting items from
 *   `array`.
 *
 *   Can be one of:
 *
 *   - `string`: The string is used for matching against the contents of the `array`. All strings or
 *     objects with string properties in `array` that match this string will be returned. This also
 *     applies to nested object properties.
 *     The predicate can be negated by prefixing the string with `!`.
 *
 *   - `Object`: A pattern object can be used to filter specific properties on objects contained
 *     by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
 *     which have property `name` containing "M" and property `phone` containing "1". A special
 *     property name `$` can be used (as in `{$:"text"}`) to accept a match against any
 *     property of the object or its nested object properties. That's equivalent to the simple
 *     substring match with a `string` as described above. The predicate can be negated by prefixing
 *     the string with `!`.
 *     For example `{name: "!M"}` predicate will return an array of items which have property `name`
 *     not containing "M".
 *
 *     Note that a named property will match properties on the same level only, while the special
 *     `$` property will match properties on the same level or deeper. E.g. an array item like
 *     `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
 *     **will** be matched by `{$: 'John'}`.
 *
 *   - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
 *     The function is called for each element of the array, with the element, its index, and
 *     the entire array itself as arguments.
 *
 *     The final result is an array of those elements that the predicate returned true for.
 *
 * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
 *     determining if the expected value (from the filter expression) and actual value (from
 *     the object in the array) should be considered a match.
 *
 *   Can be one of:
 *
 *   - `function(actual, expected)`:
 *     The function will be given the object value and the predicate value to compare and
 *     should return true if both values should be considered equal.
 *
 *   - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
 *     This is essentially strict comparison of expected and actual.
 *
 *   - `false|undefined`: A short hand for a function which will look for a substring match in case
 *     insensitive way.
 *
 *     Primitive values are converted to strings. Objects are not compared against primitives,
 *     unless they have a custom `toString` method (e.g. `Date` objects).
 *
 * @example
   <example>
     <file name="index.html">
       <div ng-init="friends = [{name:'John', phone:'555-1276'},
                                {name:'Mary', phone:'800-BIG-MARY'},
                                {name:'Mike', phone:'555-4321'},
                                {name:'Adam', phone:'555-5678'},
                                {name:'Julie', phone:'555-8765'},
                                {name:'Juliette', phone:'555-5678'}]"></div>

       <label>Search: <input ng-model="searchText"></label>
       <table id="searchTextResults">
         <tr><th>Name</th><th>Phone</th></tr>
         <tr ng-repeat="friend in friends | filter:searchText">
           <td>{{friend.name}}</td>
           <td>{{friend.phone}}</td>
         </tr>
       </table>
       <hr>
       <label>Any: <input ng-model="search.$"></label> <br>
       <label>Name only <input ng-model="search.name"></label><br>
       <label>Phone only <input ng-model="search.phone"></label><br>
       <label>Equality <input type="checkbox" ng-model="strict"></label><br>
       <table id="searchObjResults">
         <tr><th>Name</th><th>Phone</th></tr>
         <tr ng-repeat="friendObj in friends | filter:search:strict">
           <td>{{friendObj.name}}</td>
           <td>{{friendObj.phone}}</td>
         </tr>
       </table>
     </file>
     <file name="protractor.js" type="protractor">
       var expectFriendNames = function(expectedNames, key) {
         element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
           arr.forEach(function(wd, i) {
             expect(wd.getText()).toMatch(expectedNames[i]);
           });
         });
       };

       it('should search across all fields when filtering with a string', function() {
         var searchText = element(by.model('searchText'));
         searchText.clear();
         searchText.sendKeys('m');
         expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');

         searchText.clear();
         searchText.sendKeys('76');
         expectFriendNames(['John', 'Julie'], 'friend');
       });

       it('should search in specific fields when filtering with a predicate object', function() {
         var searchAny = element(by.model('search.$'));
         searchAny.clear();
         searchAny.sendKeys('i');
         expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
       });
       it('should use a equal comparison when comparator is true', function() {
         var searchName = element(by.model('search.name'));
         var strict = element(by.model('strict'));
         searchName.clear();
         searchName.sendKeys('Julie');
         strict.click();
         expectFriendNames(['Julie'], 'friendObj');
       });
     </file>
   </example>
 */
function filterFilter() {
  return function(array, expression, comparator) {
    if (!isArrayLike(array)) {
      if (array == null) {
        return array;
      } else {
        throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
      }
    }

    var expressionType = getTypeForFilter(expression);
    var predicateFn;
    var matchAgainstAnyProp;

    switch (expressionType) {
      case 'function':
        predicateFn = expression;
        break;
      case 'boolean':
      case 'null':
      case 'number':
      case 'string':
        matchAgainstAnyProp = true;
        //jshint -W086
      case 'object':
        //jshint +W086
        predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
        break;
      default:
        return array;
    }

    return Array.prototype.filter.call(array, predicateFn);
  };
}

// Helper functions for `filterFilter`
function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  var predicateFn;

  if (comparator === true) {
    comparator = equals;
  } else if (!isFunction(comparator)) {
    comparator = function(actual, expected) {
      if (isUndefined(actual)) {
        // No substring matching against `undefined`
        return false;
      }
      if ((actual === null) || (expected === null)) {
        // No substring matching against `null`; only match against `null`
        return actual === expected;
      }
      if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
        // Should not compare primitives against objects, unless they have custom `toString` method
        return false;
      }

      actual = lowercase('' + actual);
      expected = lowercase('' + expected);
      return actual.indexOf(expected) !== -1;
    };
  }

  predicateFn = function(item) {
    if (shouldMatchPrimitives && !isObject(item)) {
      return deepCompare(item, expression.$, comparator, false);
    }
    return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  };

  return predicateFn;
}

function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  var actualType = getTypeForFilter(actual);
  var expectedType = getTypeForFilter(expected);

  if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
    return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  } else if (isArray(actual)) {
    // In case `actual` is an array, consider it a match
    // if ANY of it's items matches `expected`
    return actual.some(function(item) {
      return deepCompare(item, expected, comparator, matchAgainstAnyProp);
    });
  }

  switch (actualType) {
    case 'object':
      var key;
      if (matchAgainstAnyProp) {
        for (key in actual) {
          if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
            return true;
          }
        }
        return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
      } else if (expectedType === 'object') {
        for (key in expected) {
          var expectedVal = expected[key];
          if (isFunction(expectedVal) || isUndefined(expectedVal)) {
            continue;
          }

          var matchAnyProperty = key === '$';
          var actualVal = matchAnyProperty ? actual : actual[key];
          if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
            return false;
          }
        }
        return true;
      } else {
        return comparator(actual, expected);
      }
      break;
    case 'function':
      return false;
    default:
      return comparator(actual, expected);
  }
}

// Used for easily differentiating between `null` and actual `object`
function getTypeForFilter(val) {
  return (val === null) ? 'null' : typeof val;
}

/**
 * @ngdoc filter
 * @name currency
 * @kind function
 *
 * @description
 * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
 * symbol for current locale is used.
 *
 * @param {number} amount Input to filter.
 * @param {string=} symbol Currency symbol or identifier to be displayed.
 * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
 * @returns {string} Formatted number.
 *
 *
 * @example
   <example module="currencyExample">
     <file name="index.html">
       <script>
         angular.module('currencyExample', [])
           .controller('ExampleController', ['$scope', function($scope) {
             $scope.amount = 1234.56;
           }]);
       </script>
       <div ng-controller="ExampleController">
         <input type="number" ng-model="amount" aria-label="amount"> <br>
         default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
         custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
         no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
       </div>
     </file>
     <file name="protractor.js" type="protractor">
       it('should init with 1234.56', function() {
         expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
         expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
         expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
       });
       it('should update', function() {
         if (browser.params.browser == 'safari') {
           // Safari does not understand the minus key. See
           // https://github.com/angular/protractor/issues/481
           return;
         }
         element(by.model('amount')).clear();
         element(by.model('amount')).sendKeys('-1234');
         expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
         expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');
         expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');
       });
     </file>
   </example>
 */
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale) {
  var formats = $locale.NUMBER_FORMATS;
  return function(amount, currencySymbol, fractionSize) {
    if (isUndefined(currencySymbol)) {
      currencySymbol = formats.CURRENCY_SYM;
    }

    if (isUndefined(fractionSize)) {
      fractionSize = formats.PATTERNS[1].maxFrac;
    }

    // if null or undefined pass it through
    return (amount == null)
        ? amount
        : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
            replace(/\u00A4/g, currencySymbol);
  };
}

/**
 * @ngdoc filter
 * @name number
 * @kind function
 *
 * @description
 * Formats a number as text.
 *
 * If the input is null or undefined, it will just be returned.
 * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
 * If the input is not a number an empty string is returned.
 *
 *
 * @param {number|string} number Number to format.
 * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
 * If this is not provided then the fraction size is computed from the current locale's number
 * formatting pattern. In the case of the default locale, it will be 3.
 * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
 *
 * @example
   <example module="numberFilterExample">
     <file name="index.html">
       <script>
         angular.module('numberFilterExample', [])
           .controller('ExampleController', ['$scope', function($scope) {
             $scope.val = 1234.56789;
           }]);
       </script>
       <div ng-controller="ExampleController">
         <label>Enter number: <input ng-model='val'></label><br>
         Default formatting: <span id='number-default'>{{val | number}}</span><br>
         No fractions: <span>{{val | number:0}}</span><br>
         Negative number: <span>{{-val | number:4}}</span>
       </div>
     </file>
     <file name="protractor.js" type="protractor">
       it('should format numbers', function() {
         expect(element(by.id('number-default')).getText()).toBe('1,234.568');
         expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
         expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
       });

       it('should update', function() {
         element(by.model('val')).clear();
         element(by.model('val')).sendKeys('3374.333');
         expect(element(by.id('number-default')).getText()).toBe('3,374.333');
         expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
         expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
      });
     </file>
   </example>
 */


numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
  var formats = $locale.NUMBER_FORMATS;
  return function(number, fractionSize) {

    // if null or undefined pass it through
    return (number == null)
        ? number
        : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
                       fractionSize);
  };
}

var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  if (isObject(number)) return '';

  var isNegative = number < 0;
  number = Math.abs(number);

  var isInfinity = number === Infinity;
  if (!isInfinity && !isFinite(number)) return '';

  var numStr = number + '',
      formatedText = '',
      hasExponent = false,
      parts = [];

  if (isInfinity) formatedText = '\u221e';

  if (!isInfinity && numStr.indexOf('e') !== -1) {
    var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
    if (match && match[2] == '-' && match[3] > fractionSize + 1) {
      number = 0;
    } else {
      formatedText = numStr;
      hasExponent = true;
    }
  }

  if (!isInfinity && !hasExponent) {
    var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;

    // determine fractionSize if it is not specified
    if (isUndefined(fractionSize)) {
      fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
    }

    // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
    // inspired by:
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
    number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);

    var fraction = ('' + number).split(DECIMAL_SEP);
    var whole = fraction[0];
    fraction = fraction[1] || '';

    var i, pos = 0,
        lgroup = pattern.lgSize,
        group = pattern.gSize;

    if (whole.length >= (lgroup + group)) {
      pos = whole.length - lgroup;
      for (i = 0; i < pos; i++) {
        if ((pos - i) % group === 0 && i !== 0) {
          formatedText += groupSep;
        }
        formatedText += whole.charAt(i);
      }
    }

    for (i = pos; i < whole.length; i++) {
      if ((whole.length - i) % lgroup === 0 && i !== 0) {
        formatedText += groupSep;
      }
      formatedText += whole.charAt(i);
    }

    // format fraction part.
    while (fraction.length < fractionSize) {
      fraction += '0';
    }

    if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  } else {
    if (fractionSize > 0 && number < 1) {
      formatedText = number.toFixed(fractionSize);
      number = parseFloat(formatedText);
    }
  }

  if (number === 0) {
    isNegative = false;
  }

  parts.push(isNegative ? pattern.negPre : pattern.posPre,
             formatedText,
             isNegative ? pattern.negSuf : pattern.posSuf);
  return parts.join('');
}

function padNumber(num, digits, trim) {
  var neg = '';
  if (num < 0) {
    neg =  '-';
    num = -num;
  }
  num = '' + num;
  while (num.length < digits) num = '0' + num;
  if (trim) {
    num = num.substr(num.length - digits);
  }
  return neg + num;
}


function dateGetter(name, size, offset, trim) {
  offset = offset || 0;
  return function(date) {
    var value = date['get' + name]();
    if (offset > 0 || value > -offset) {
      value += offset;
    }
    if (value === 0 && offset == -12) value = 12;
    return padNumber(value, size, trim);
  };
}

function dateStrGetter(name, shortForm) {
  return function(date, formats) {
    var value = date['get' + name]();
    var get = uppercase(shortForm ? ('SHORT' + name) : name);

    return formats[get][value];
  };
}

function timeZoneGetter(date, formats, offset) {
  var zone = -1 * offset;
  var paddedZone = (zone >= 0) ? "+" : "";

  paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
                padNumber(Math.abs(zone % 60), 2);

  return paddedZone;
}

function getFirstThursdayOfYear(year) {
    // 0 = index of January
    var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
    // 4 = index of Thursday (+1 to account for 1st = 5)
    // 11 = index of *next* Thursday (+1 account for 1st = 12)
    return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
}

function getThursdayThisWeek(datetime) {
    return new Date(datetime.getFullYear(), datetime.getMonth(),
      // 4 = index of Thursday
      datetime.getDate() + (4 - datetime.getDay()));
}

function weekGetter(size) {
   return function(date) {
      var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
         thisThurs = getThursdayThisWeek(date);

      var diff = +thisThurs - +firstThurs,
         result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week

      return padNumber(result, size);
   };
}

function ampmGetter(date, formats) {
  return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}

function eraGetter(date, formats) {
  return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
}

function longEraGetter(date, formats) {
  return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
}

var DATE_FORMATS = {
  yyyy: dateGetter('FullYear', 4),
    yy: dateGetter('FullYear', 2, 0, true),
     y: dateGetter('FullYear', 1),
  MMMM: dateStrGetter('Month'),
   MMM: dateStrGetter('Month', true),
    MM: dateGetter('Month', 2, 1),
     M: dateGetter('Month', 1, 1),
    dd: dateGetter('Date', 2),
     d: dateGetter('Date', 1),
    HH: dateGetter('Hours', 2),
     H: dateGetter('Hours', 1),
    hh: dateGetter('Hours', 2, -12),
     h: dateGetter('Hours', 1, -12),
    mm: dateGetter('Minutes', 2),
     m: dateGetter('Minutes', 1),
    ss: dateGetter('Seconds', 2),
     s: dateGetter('Seconds', 1),
     // while ISO 8601 requires fractions to be prefixed with `.` or `,`
     // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
   sss: dateGetter('Milliseconds', 3),
  EEEE: dateStrGetter('Day'),
   EEE: dateStrGetter('Day', true),
     a: ampmGetter,
     Z: timeZoneGetter,
    ww: weekGetter(2),
     w: weekGetter(1),
     G: eraGetter,
     GG: eraGetter,
     GGG: eraGetter,
     GGGG: longEraGetter
};

var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
    NUMBER_STRING = /^\-?\d+$/;

/**
 * @ngdoc filter
 * @name date
 * @kind function
 *
 * @description
 *   Formats `date` to a string based on the requested `format`.
 *
 *   `format` string can be composed of the following elements:
 *
 *   * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
 *   * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
 *   * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
 *   * `'MMMM'`: Month in year (January-December)
 *   * `'MMM'`: Month in year (Jan-Dec)
 *   * `'MM'`: Month in year, padded (01-12)
 *   * `'M'`: Month in year (1-12)
 *   * `'dd'`: Day in month, padded (01-31)
 *   * `'d'`: Day in month (1-31)
 *   * `'EEEE'`: Day in Week,(Sunday-Saturday)
 *   * `'EEE'`: Day in Week, (Sun-Sat)
 *   * `'HH'`: Hour in day, padded (00-23)
 *   * `'H'`: Hour in day (0-23)
 *   * `'hh'`: Hour in AM/PM, padded (01-12)
 *   * `'h'`: Hour in AM/PM, (1-12)
 *   * `'mm'`: Minute in hour, padded (00-59)
 *   * `'m'`: Minute in hour (0-59)
 *   * `'ss'`: Second in minute, padded (00-59)
 *   * `'s'`: Second in minute (0-59)
 *   * `'sss'`: Millisecond in second, padded (000-999)
 *   * `'a'`: AM/PM marker
 *   * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
 *   * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
 *   * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
 *   * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
 *   * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
 *
 *   `format` string can also be one of the following predefined
 *   {@link guide/i18n localizable formats}:
 *
 *   * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
 *     (e.g. Sep 3, 2010 12:05:08 PM)
 *   * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US  locale (e.g. 9/3/10 12:05 PM)
 *   * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US  locale
 *     (e.g. Friday, September 3, 2010)
 *   * `'longDate'`: equivalent to `'MMMM d, y'` for en_US  locale (e.g. September 3, 2010)
 *   * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US  locale (e.g. Sep 3, 2010)
 *   * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
 *   * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
 *   * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
 *
 *   `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
 *   `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
 *   (e.g. `"h 'o''clock'"`).
 *
 * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
 *    number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
 *    shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
 *    specified in the string input, the time is considered to be in the local timezone.
 * @param {string=} format Formatting rules (see Description). If not specified,
 *    `mediumDate` is used.
 * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
 *    continental US time zone abbreviations, but for general use, use a time zone offset, for
 *    example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
 *    If not specified, the timezone of the browser will be used.
 * @returns {string} Formatted string or the input if input is not recognized as date/millis.
 *
 * @example
   <example>
     <file name="index.html">
       <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
           <span>{{1288323623006 | date:'medium'}}</span><br>
       <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
          <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
       <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
          <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
       <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
          <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
     </file>
     <file name="protractor.js" type="protractor">
       it('should format date', function() {
         expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
            toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
         expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
            toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
         expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
            toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
         expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
            toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
       });
     </file>
   </example>
 */
dateFilter.$inject = ['$locale'];
function dateFilter($locale) {


  var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
                     // 1        2       3         4          5          6          7          8  9     10      11
  function jsonStringToDate(string) {
    var match;
    if (match = string.match(R_ISO8601_STR)) {
      var date = new Date(0),
          tzHour = 0,
          tzMin  = 0,
          dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
          timeSetter = match[8] ? date.setUTCHours : date.setHours;

      if (match[9]) {
        tzHour = toInt(match[9] + match[10]);
        tzMin = toInt(match[9] + match[11]);
      }
      dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
      var h = toInt(match[4] || 0) - tzHour;
      var m = toInt(match[5] || 0) - tzMin;
      var s = toInt(match[6] || 0);
      var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
      timeSetter.call(date, h, m, s, ms);
      return date;
    }
    return string;
  }


  return function(date, format, timezone) {
    var text = '',
        parts = [],
        fn, match;

    format = format || 'mediumDate';
    format = $locale.DATETIME_FORMATS[format] || format;
    if (isString(date)) {
      date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
    }

    if (isNumber(date)) {
      date = new Date(date);
    }

    if (!isDate(date) || !isFinite(date.getTime())) {
      return date;
    }

    while (format) {
      match = DATE_FORMATS_SPLIT.exec(format);
      if (match) {
        parts = concat(parts, match, 1);
        format = parts.pop();
      } else {
        parts.push(format);
        format = null;
      }
    }

    var dateTimezoneOffset = date.getTimezoneOffset();
    if (timezone) {
      dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
      date = convertTimezoneToLocal(date, timezone, true);
    }
    forEach(parts, function(value) {
      fn = DATE_FORMATS[value];
      text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
                 : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
    });

    return text;
  };
}


/**
 * @ngdoc filter
 * @name json
 * @kind function
 *
 * @description
 *   Allows you to convert a JavaScript object into JSON string.
 *
 *   This filter is mostly useful for debugging. When using the double curly {{value}} notation
 *   the binding is automatically converted to JSON.
 *
 * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
 * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
 * @returns {string} JSON string.
 *
 *
 * @example
   <example>
     <file name="index.html">
       <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
       <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
     </file>
     <file name="protractor.js" type="protractor">
       it('should jsonify filtered objects', function() {
         expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n  "name": ?"value"\n}/);
         expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n    "name": ?"value"\n}/);
       });
     </file>
   </example>
 *
 */
function jsonFilter() {
  return function(object, spacing) {
    if (isUndefined(spacing)) {
        spacing = 2;
    }
    return toJson(object, spacing);
  };
}


/**
 * @ngdoc filter
 * @name lowercase
 * @kind function
 * @description
 * Converts string to lowercase.
 * @see angular.lowercase
 */
var lowercaseFilter = valueFn(lowercase);


/**
 * @ngdoc filter
 * @name uppercase
 * @kind function
 * @description
 * Converts string to uppercase.
 * @see angular.uppercase
 */
var uppercaseFilter = valueFn(uppercase);

/**
 * @ngdoc filter
 * @name limitTo
 * @kind function
 *
 * @description
 * Creates a new array or string containing only a specified number of elements. The elements
 * are taken from either the beginning or the end of the source array, string or number, as specified by
 * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
 * converted to a string.
 *
 * @param {Array|string|number} input Source array, string or number to be limited.
 * @param {string|number} limit The length of the returned array or string. If the `limit` number
 *     is positive, `limit` number of items from the beginning of the source array/string are copied.
 *     If the number is negative, `limit` number  of items from the end of the source array/string
 *     are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
 *     the input will be returned unchanged.
 * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
 *     indicates an offset from the end of `input`. Defaults to `0`.
 * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
 *     had less than `limit` elements.
 *
 * @example
   <example module="limitToExample">
     <file name="index.html">
       <script>
         angular.module('limitToExample', [])
           .controller('ExampleController', ['$scope', function($scope) {
             $scope.numbers = [1,2,3,4,5,6,7,8,9];
             $scope.letters = "abcdefghi";
             $scope.longNumber = 2345432342;
             $scope.numLimit = 3;
             $scope.letterLimit = 3;
             $scope.longNumberLimit = 3;
           }]);
       </script>
       <div ng-controller="ExampleController">
         <label>
            Limit {{numbers}} to:
            <input type="number" step="1" ng-model="numLimit">
         </label>
         <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
         <label>
            Limit {{letters}} to:
            <input type="number" step="1" ng-model="letterLimit">
         </label>
         <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
         <label>
            Limit {{longNumber}} to:
            <input type="number" step="1" ng-model="longNumberLimit">
         </label>
         <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
       </div>
     </file>
     <file name="protractor.js" type="protractor">
       var numLimitInput = element(by.model('numLimit'));
       var letterLimitInput = element(by.model('letterLimit'));
       var longNumberLimitInput = element(by.model('longNumberLimit'));
       var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
       var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
       var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));

       it('should limit the number array to first three items', function() {
         expect(numLimitInput.getAttribute('value')).toBe('3');
         expect(letterLimitInput.getAttribute('value')).toBe('3');
         expect(longNumberLimitInput.getAttribute('value')).toBe('3');
         expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
         expect(limitedLetters.getText()).toEqual('Output letters: abc');
         expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
       });

       // There is a bug in safari and protractor that doesn't like the minus key
       // it('should update the output when -3 is entered', function() {
       //   numLimitInput.clear();
       //   numLimitInput.sendKeys('-3');
       //   letterLimitInput.clear();
       //   letterLimitInput.sendKeys('-3');
       //   longNumberLimitInput.clear();
       //   longNumberLimitInput.sendKeys('-3');
       //   expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
       //   expect(limitedLetters.getText()).toEqual('Output letters: ghi');
       //   expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
       // });

       it('should not exceed the maximum size of input array', function() {
         numLimitInput.clear();
         numLimitInput.sendKeys('100');
         letterLimitInput.clear();
         letterLimitInput.sendKeys('100');
         longNumberLimitInput.clear();
         longNumberLimitInput.sendKeys('100');
         expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
         expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
         expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
       });
     </file>
   </example>
*/
function limitToFilter() {
  return function(input, limit, begin) {
    if (Math.abs(Number(limit)) === Infinity) {
      limit = Number(limit);
    } else {
      limit = toInt(limit);
    }
    if (isNaN(limit)) return input;

    if (isNumber(input)) input = input.toString();
    if (!isArray(input) && !isString(input)) return input;

    begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
    begin = (begin < 0 && begin >= -input.length) ? input.length + begin : begin;

    if (limit >= 0) {
      return input.slice(begin, begin + limit);
    } else {
      if (begin === 0) {
        return input.slice(limit, input.length);
      } else {
        return input.slice(Math.max(0, begin + limit), begin);
      }
    }
  };
}

/**
 * @ngdoc filter
 * @name orderBy
 * @kind function
 *
 * @description
 * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
 * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
 * as expected, make sure they are actually being saved as numbers and not strings.
 *
 * @param {Array} array The array to sort.
 * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
 *    used by the comparator to determine the order of elements.
 *
 *    Can be one of:
 *
 *    - `function`: Getter function. The result of this function will be sorted using the
 *      `<`, `===`, `>` operator.
 *    - `string`: An Angular expression. The result of this expression is used to compare elements
 *      (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
 *      3 first characters of a property called `name`). The result of a constant expression
 *      is interpreted as a property name to be used in comparisons (for example `"special name"`
 *      to sort object by the value of their `special name` property). An expression can be
 *      optionally prefixed with `+` or `-` to control ascending or descending sort order
 *      (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
 *      element itself is used to compare where sorting.
 *    - `Array`: An array of function or string predicates. The first predicate in the array
 *      is used for sorting, but when two items are equivalent, the next predicate is used.
 *
 *    If the predicate is missing or empty then it defaults to `'+'`.
 *
 * @param {boolean=} reverse Reverse the order of the array.
 * @returns {Array} Sorted copy of the source array.
 *
 *
 * @example
 * The example below demonstrates a simple ngRepeat, where the data is sorted
 * by age in descending order (predicate is set to `'-age'`).
 * `reverse` is not set, which means it defaults to `false`.
   <example module="orderByExample">
     <file name="index.html">
       <script>
         angular.module('orderByExample', [])
           .controller('ExampleController', ['$scope', function($scope) {
             $scope.friends =
                 [{name:'John', phone:'555-1212', age:10},
                  {name:'Mary', phone:'555-9876', age:19},
                  {name:'Mike', phone:'555-4321', age:21},
                  {name:'Adam', phone:'555-5678', age:35},
                  {name:'Julie', phone:'555-8765', age:29}];
           }]);
       </script>
       <div ng-controller="ExampleController">
         <table class="friend">
           <tr>
             <th>Name</th>
             <th>Phone Number</th>
             <th>Age</th>
           </tr>
           <tr ng-repeat="friend in friends | orderBy:'-age'">
             <td>{{friend.name}}</td>
             <td>{{friend.phone}}</td>
             <td>{{friend.age}}</td>
           </tr>
         </table>
       </div>
     </file>
   </example>
 *
 * The predicate and reverse parameters can be controlled dynamically through scope properties,
 * as shown in the next example.
 * @example
   <example module="orderByExample">
     <file name="index.html">
       <script>
         angular.module('orderByExample', [])
           .controller('ExampleController', ['$scope', function($scope) {
             $scope.friends =
                 [{name:'John', phone:'555-1212', age:10},
                  {name:'Mary', phone:'555-9876', age:19},
                  {name:'Mike', phone:'555-4321', age:21},
                  {name:'Adam', phone:'555-5678', age:35},
                  {name:'Julie', phone:'555-8765', age:29}];
             $scope.predicate = 'age';
             $scope.reverse = true;
             $scope.order = function(predicate) {
               $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
               $scope.predicate = predicate;
             };
           }]);
       </script>
       <style type="text/css">
         .sortorder:after {
           content: '\25b2';
         }
         .sortorder.reverse:after {
           content: '\25bc';
         }
       </style>
       <div ng-controller="ExampleController">
         <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
         <hr/>
         [ <a href="" ng-click="predicate=''">unsorted</a> ]
         <table class="friend">
           <tr>
             <th>
               <a href="" ng-click="order('name')">Name</a>
               <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
             </th>
             <th>
               <a href="" ng-click="order('phone')">Phone Number</a>
               <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
             </th>
             <th>
               <a href="" ng-click="order('age')">Age</a>
               <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
             </th>
           </tr>
           <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
             <td>{{friend.name}}</td>
             <td>{{friend.phone}}</td>
             <td>{{friend.age}}</td>
           </tr>
         </table>
       </div>
     </file>
   </example>
 *
 * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
 * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
 * desired parameters.
 *
 * Example:
 *
 * @example
  <example module="orderByExample">
    <file name="index.html">
      <div ng-controller="ExampleController">
        <table class="friend">
          <tr>
            <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
              (<a href="" ng-click="order('-name',false)">^</a>)</th>
            <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
            <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
          </tr>
          <tr ng-repeat="friend in friends">
            <td>{{friend.name}}</td>
            <td>{{friend.phone}}</td>
            <td>{{friend.age}}</td>
          </tr>
        </table>
      </div>
    </file>

    <file name="script.js">
      angular.module('orderByExample', [])
        .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
          var orderBy = $filter('orderBy');
          $scope.friends = [
            { name: 'John',    phone: '555-1212',    age: 10 },
            { name: 'Mary',    phone: '555-9876',    age: 19 },
            { name: 'Mike',    phone: '555-4321',    age: 21 },
            { name: 'Adam',    phone: '555-5678',    age: 35 },
            { name: 'Julie',   phone: '555-8765',    age: 29 }
          ];
          $scope.order = function(predicate, reverse) {
            $scope.friends = orderBy($scope.friends, predicate, reverse);
          };
          $scope.order('-age',false);
        }]);
    </file>
</example>
 */
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse) {
  return function(array, sortPredicate, reverseOrder) {

    if (!(isArrayLike(array))) return array;

    if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
    if (sortPredicate.length === 0) { sortPredicate = ['+']; }

    var predicates = processPredicates(sortPredicate, reverseOrder);

    // The next three lines are a version of a Swartzian Transform idiom from Perl
    // (sometimes called the Decorate-Sort-Undecorate idiom)
    // See https://en.wikipedia.org/wiki/Schwartzian_transform
    var compareValues = Array.prototype.map.call(array, getComparisonObject);
    compareValues.sort(doComparison);
    array = compareValues.map(function(item) { return item.value; });

    return array;

    function getComparisonObject(value, index) {
      return {
        value: value,
        predicateValues: predicates.map(function(predicate) {
          return getPredicateValue(predicate.get(value), index);
        })
      };
    }

    function doComparison(v1, v2) {
      var result = 0;
      for (var index=0, length = predicates.length; index < length; ++index) {
        result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
        if (result) break;
      }
      return result;
    }
  };

  function processPredicates(sortPredicate, reverseOrder) {
    reverseOrder = reverseOrder ? -1 : 1;
    return sortPredicate.map(function(predicate) {
      var descending = 1, get = identity;

      if (isFunction(predicate)) {
        get = predicate;
      } else if (isString(predicate)) {
        if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
          descending = predicate.charAt(0) == '-' ? -1 : 1;
          predicate = predicate.substring(1);
        }
        if (predicate !== '') {
          get = $parse(predicate);
          if (get.constant) {
            var key = get();
            get = function(value) { return value[key]; };
          }
        }
      }
      return { get: get, descending: descending * reverseOrder };
    });
  }

  function isPrimitive(value) {
    switch (typeof value) {
      case 'number': /* falls through */
      case 'boolean': /* falls through */
      case 'string':
        return true;
      default:
        return false;
    }
  }

  function objectValue(value, index) {
    // If `valueOf` is a valid function use that
    if (typeof value.valueOf === 'function') {
      value = value.valueOf();
      if (isPrimitive(value)) return value;
    }
    // If `toString` is a valid function and not the one from `Object.prototype` use that
    if (hasCustomToString(value)) {
      value = value.toString();
      if (isPrimitive(value)) return value;
    }
    // We have a basic object so we use the position of the object in the collection
    return index;
  }

  function getPredicateValue(value, index) {
    var type = typeof value;
    if (value === null) {
      type = 'string';
      value = 'null';
    } else if (type === 'string') {
      value = value.toLowerCase();
    } else if (type === 'object') {
      value = objectValue(value, index);
    }
    return { value: value, type: type };
  }

  function compare(v1, v2) {
    var result = 0;
    if (v1.type === v2.type) {
      if (v1.value !== v2.value) {
        result = v1.value < v2.value ? -1 : 1;
      }
    } else {
      result = v1.type < v2.type ? -1 : 1;
    }
    return result;
  }
}

function ngDirective(directive) {
  if (isFunction(directive)) {
    directive = {
      link: directive
    };
  }
  directive.restrict = directive.restrict || 'AC';
  return valueFn(directive);
}

/**
 * @ngdoc directive
 * @name a
 * @restrict E
 *
 * @description
 * Modifies the default behavior of the html A tag so that the default action is prevented when
 * the href attribute is empty.
 *
 * This change permits the easy creation of action links with the `ngClick` directive
 * without changing the location or causing page reloads, e.g.:
 * `<a href="" ng-click="list.addItem()">Add Item</a>`
 */
var htmlAnchorDirective = valueFn({
  restrict: 'E',
  compile: function(element, attr) {
    if (!attr.href && !attr.xlinkHref) {
      return function(scope, element) {
        // If the linked element is not an anchor tag anymore, do nothing
        if (element[0].nodeName.toLowerCase() !== 'a') return;

        // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
        var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
                   'xlink:href' : 'href';
        element.on('click', function(event) {
          // if we have no href url, then don't navigate anywhere.
          if (!element.attr(href)) {
            event.preventDefault();
          }
        });
      };
    }
  }
});

/**
 * @ngdoc directive
 * @name ngHref
 * @restrict A
 * @priority 99
 *
 * @description
 * Using Angular markup like `{{hash}}` in an href attribute will
 * make the link go to the wrong URL if the user clicks it before
 * Angular has a chance to replace the `{{hash}}` markup with its
 * value. Until Angular replaces the markup the link will be broken
 * and will most likely return a 404 error. The `ngHref` directive
 * solves this problem.
 *
 * The wrong way to write it:
 * ```html
 * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
 * ```
 *
 * The correct way to write it:
 * ```html
 * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
 * ```
 *
 * @element A
 * @param {template} ngHref any string which can contain `{{}}` markup.
 *
 * @example
 * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
 * in links and their different behaviors:
    <example>
      <file name="index.html">
        <input ng-model="value" /><br />
        <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
        <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
        <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
        <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
        <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
        <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
      </file>
      <file name="protractor.js" type="protractor">
        it('should execute ng-click but not reload when href without value', function() {
          element(by.id('link-1')).click();
          expect(element(by.model('value')).getAttribute('value')).toEqual('1');
          expect(element(by.id('link-1')).getAttribute('href')).toBe('');
        });

        it('should execute ng-click but not reload when href empty string', function() {
          element(by.id('link-2')).click();
          expect(element(by.model('value')).getAttribute('value')).toEqual('2');
          expect(element(by.id('link-2')).getAttribute('href')).toBe('');
        });

        it('should execute ng-click and change url when ng-href specified', function() {
          expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);

          element(by.id('link-3')).click();

          // At this point, we navigate away from an Angular page, so we need
          // to use browser.driver to get the base webdriver.

          browser.wait(function() {
            return browser.driver.getCurrentUrl().then(function(url) {
              return url.match(/\/123$/);
            });
          }, 5000, 'page should navigate to /123');
        });

        it('should execute ng-click but not reload when href empty string and name specified', function() {
          element(by.id('link-4')).click();
          expect(element(by.model('value')).getAttribute('value')).toEqual('4');
          expect(element(by.id('link-4')).getAttribute('href')).toBe('');
        });

        it('should execute ng-click but not reload when no href but name specified', function() {
          element(by.id('link-5')).click();
          expect(element(by.model('value')).getAttribute('value')).toEqual('5');
          expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
        });

        it('should only change url when only ng-href', function() {
          element(by.model('value')).clear();
          element(by.model('value')).sendKeys('6');
          expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);

          element(by.id('link-6')).click();

          // At this point, we navigate away from an Angular page, so we need
          // to use browser.driver to get the base webdriver.
          browser.wait(function() {
            return browser.driver.getCurrentUrl().then(function(url) {
              return url.match(/\/6$/);
            });
          }, 5000, 'page should navigate to /6');
        });
      </file>
    </example>
 */

/**
 * @ngdoc directive
 * @name ngSrc
 * @restrict A
 * @priority 99
 *
 * @description
 * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
 * work right: The browser will fetch from the URL with the literal
 * text `{{hash}}` until Angular replaces the expression inside
 * `{{hash}}`. The `ngSrc` directive solves this problem.
 *
 * The buggy way to write it:
 * ```html
 * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
 * ```
 *
 * The correct way to write it:
 * ```html
 * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
 * ```
 *
 * @element IMG
 * @param {template} ngSrc any string which can contain `{{}}` markup.
 */

/**
 * @ngdoc directive
 * @name ngSrcset
 * @restrict A
 * @priority 99
 *
 * @description
 * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
 * work right: The browser will fetch from the URL with the literal
 * text `{{hash}}` until Angular replaces the expression inside
 * `{{hash}}`. The `ngSrcset` directive solves this problem.
 *
 * The buggy way to write it:
 * ```html
 * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
 * ```
 *
 * The correct way to write it:
 * ```html
 * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
 * ```
 *
 * @element IMG
 * @param {template} ngSrcset any string which can contain `{{}}` markup.
 */

/**
 * @ngdoc directive
 * @name ngDisabled
 * @restrict A
 * @priority 100
 *
 * @description
 *
 * This directive sets the `disabled` attribute on the element if the
 * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
 *
 * A special directive is necessary because we cannot use interpolation inside the `disabled`
 * attribute.  The following example would make the button enabled on Chrome/Firefox
 * but not on older IEs:
 *
 * ```html
 * <!-- See below for an example of ng-disabled being used correctly -->
 * <div ng-init="isDisabled = false">
 *  <button disabled="{{isDisabled}}">Disabled</button>
 * </div>
 * ```
 *
 * This is because the HTML specification does not require browsers to preserve the values of
 * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
 * If we put an Angular interpolation expression into such an attribute then the
 * binding information would be lost when the browser removes the attribute.
 *
 * @example
    <example>
      <file name="index.html">
        <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
        <button ng-model="button" ng-disabled="checked">Button</button>
      </file>
      <file name="protractor.js" type="protractor">
        it('should toggle button', function() {
          expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
          element(by.model('checked')).click();
          expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
        });
      </file>
    </example>
 *
 * @element INPUT
 * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
 *     then the `disabled` attribute will be set on the element
 */


/**
 * @ngdoc directive
 * @name ngChecked
 * @restrict A
 * @priority 100
 *
 * @description
 * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
 *
 * Note that this directive should not be used together with {@link ngModel `ngModel`},
 * as this can lead to unexpected behavior.
 *
 * ### Why do we need `ngChecked`?
 *
 * The HTML specification does not require browsers to preserve the values of boolean attributes
 * such as checked. (Their presence means true and their absence means false.)
 * If we put an Angular interpolation expression into such an attribute then the
 * binding information would be lost when the browser removes the attribute.
 * The `ngChecked` directive solves this problem for the `checked` attribute.
 * This complementary directive is not removed by the browser and so provides
 * a permanent reliable place to store the binding information.
 * @example
    <example>
      <file name="index.html">
        <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
        <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
      </file>
      <file name="protractor.js" type="protractor">
        it('should check both checkBoxes', function() {
          expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
          element(by.model('master')).click();
          expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
        });
      </file>
    </example>
 *
 * @element INPUT
 * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
 *     then the `checked` attribute will be set on the element
 */


/**
 * @ngdoc directive
 * @name ngReadonly
 * @restrict A
 * @priority 100
 *
 * @description
 * The HTML specification does not require browsers to preserve the values of boolean attributes
 * such as readonly. (Their presence means true and their absence means false.)
 * If we put an Angular interpolation expression into such an attribute then the
 * binding information would be lost when the browser removes the attribute.
 * The `ngReadonly` directive solves this problem for the `readonly` attribute.
 * This complementary directive is not removed by the browser and so provides
 * a permanent reliable place to store the binding information.
 * @example
    <example>
      <file name="index.html">
        <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
        <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
      </file>
      <file name="protractor.js" type="protractor">
        it('should toggle readonly attr', function() {
          expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
          element(by.model('checked')).click();
          expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
        });
      </file>
    </example>
 *
 * @element INPUT
 * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
 *     then special attribute "readonly" will be set on the element
 */


/**
 * @ngdoc directive
 * @name ngSelected
 * @restrict A
 * @priority 100
 *
 * @description
 * The HTML specification does not require browsers to preserve the values of boolean attributes
 * such as selected. (Their presence means true and their absence means false.)
 * If we put an Angular interpolation expression into such an attribute then the
 * binding information would be lost when the browser removes the attribute.
 * The `ngSelected` directive solves this problem for the `selected` attribute.
 * This complementary directive is not removed by the browser and so provides
 * a permanent reliable place to store the binding information.
 *
 * @example
    <example>
      <file name="index.html">
        <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
        <select aria-label="ngSelected demo">
          <option>Hello!</option>
          <option id="greet" ng-selected="selected">Greetings!</option>
        </select>
      </file>
      <file name="protractor.js" type="protractor">
        it('should select Greetings!', function() {
          expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
          element(by.model('selected')).click();
          expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
        });
      </file>
    </example>
 *
 * @element OPTION
 * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
 *     then special attribute "selected" will be set on the element
 */

/**
 * @ngdoc directive
 * @name ngOpen
 * @restrict A
 * @priority 100
 *
 * @description
 * The HTML specification does not require browsers to preserve the values of boolean attributes
 * such as open. (Their presence means true and their absence means false.)
 * If we put an Angular interpolation expression into such an attribute then the
 * binding information would be lost when the browser removes the attribute.
 * The `ngOpen` directive solves this problem for the `open` attribute.
 * This complementary directive is not removed by the browser and so provides
 * a permanent reliable place to store the binding information.
 * @example
     <example>
       <file name="index.html">
         <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
         <details id="details" ng-open="open">
            <summary>Show/Hide me</summary>
         </details>
       </file>
       <file name="protractor.js" type="protractor">
         it('should toggle open', function() {
           expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
           element(by.model('open')).click();
           expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
         });
       </file>
     </example>
 *
 * @element DETAILS
 * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
 *     then special attribute "open" will be set on the element
 */

var ngAttributeAliasDirectives = {};

// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
  // binding to multiple is not supported
  if (propName == "multiple") return;

  function defaultLinkFn(scope, element, attr) {
    scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
      attr.$set(attrName, !!value);
    });
  }

  var normalized = directiveNormalize('ng-' + attrName);
  var linkFn = defaultLinkFn;

  if (propName === 'checked') {
    linkFn = function(scope, element, attr) {
      // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
      if (attr.ngModel !== attr[normalized]) {
        defaultLinkFn(scope, element, attr);
      }
    };
  }

  ngAttributeAliasDirectives[normalized] = function() {
    return {
      restrict: 'A',
      priority: 100,
      link: linkFn
    };
  };
});

// aliased input attrs are evaluated
forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  ngAttributeAliasDirectives[ngAttr] = function() {
    return {
      priority: 100,
      link: function(scope, element, attr) {
        //special case ngPattern when a literal regular expression value
        //is used as the expression (this way we don't have to watch anything).
        if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
          var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
          if (match) {
            attr.$set("ngPattern", new RegExp(match[1], match[2]));
            return;
          }
        }

        scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
          attr.$set(ngAttr, value);
        });
      }
    };
  };
});

// ng-src, ng-srcset, ng-href are interpolated
forEach(['src', 'srcset', 'href'], function(attrName) {
  var normalized = directiveNormalize('ng-' + attrName);
  ngAttributeAliasDirectives[normalized] = function() {
    return {
      priority: 99, // it needs to run after the attributes are interpolated
      link: function(scope, element, attr) {
        var propName = attrName,
            name = attrName;

        if (attrName === 'href' &&
            toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
          name = 'xlinkHref';
          attr.$attr[name] = 'xlink:href';
          propName = null;
        }

        attr.$observe(normalized, function(value) {
          if (!value) {
            if (attrName === 'href') {
              attr.$set(name, null);
            }
            return;
          }

          attr.$set(name, value);

          // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
          // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
          // to set the property as well to achieve the desired effect.
          // we use attr[attrName] value since $set can sanitize the url.
          if (msie && propName) element.prop(propName, attr[name]);
        });
      }
    };
  };
});

/* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
 */
var nullFormCtrl = {
  $addControl: noop,
  $$renameControl: nullFormRenameControl,
  $removeControl: noop,
  $setValidity: noop,
  $setDirty: noop,
  $setPristine: noop,
  $setSubmitted: noop
},
SUBMITTED_CLASS = 'ng-submitted';

function nullFormRenameControl(control, name) {
  control.$name = name;
}

/**
 * @ngdoc type
 * @name form.FormController
 *
 * @property {boolean} $pristine True if user has not interacted with the form yet.
 * @property {boolean} $dirty True if user has already interacted with the form.
 * @property {boolean} $valid True if all of the containing forms and controls are valid.
 * @property {boolean} $invalid True if at least one containing control or form is invalid.
 * @property {boolean} $submitted True if user has submitted the form even if its invalid.
 *
 * @property {Object} $error Is an object hash, containing references to controls or
 *  forms with failing validators, where:
 *
 *  - keys are validation tokens (error names),
 *  - values are arrays of controls or forms that have a failing validator for given error name.
 *
 *  Built-in validation tokens:
 *
 *  - `email`
 *  - `max`
 *  - `maxlength`
 *  - `min`
 *  - `minlength`
 *  - `number`
 *  - `pattern`
 *  - `required`
 *  - `url`
 *  - `date`
 *  - `datetimelocal`
 *  - `time`
 *  - `week`
 *  - `month`
 *
 * @description
 * `FormController` keeps track of all its controls and nested forms as well as the state of them,
 * such as being valid/invalid or dirty/pristine.
 *
 * Each {@link ng.directive:form form} directive creates an instance
 * of `FormController`.
 *
 */
//asks for $scope to fool the BC controller module
FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
function FormController(element, attrs, $scope, $animate, $interpolate) {
  var form = this,
      controls = [];

  var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;

  // init state
  form.$error = {};
  form.$$success = {};
  form.$pending = undefined;
  form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  form.$dirty = false;
  form.$pristine = true;
  form.$valid = true;
  form.$invalid = false;
  form.$submitted = false;

  parentForm.$addControl(form);

  /**
   * @ngdoc method
   * @name form.FormController#$rollbackViewValue
   *
   * @description
   * Rollback all form controls pending updates to the `$modelValue`.
   *
   * Updates may be pending by a debounced event or because the input is waiting for a some future
   * event defined in `ng-model-options`. This method is typically needed by the reset button of
   * a form that uses `ng-model-options` to pend updates.
   */
  form.$rollbackViewValue = function() {
    forEach(controls, function(control) {
      control.$rollbackViewValue();
    });
  };

  /**
   * @ngdoc method
   * @name form.FormController#$commitViewValue
   *
   * @description
   * Commit all form controls pending updates to the `$modelValue`.
   *
   * Updates may be pending by a debounced event or because the input is waiting for a some future
   * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
   * usually handles calling this in response to input events.
   */
  form.$commitViewValue = function() {
    forEach(controls, function(control) {
      control.$commitViewValue();
    });
  };

  /**
   * @ngdoc method
   * @name form.FormController#$addControl
   *
   * @description
   * Register a control with the form.
   *
   * Input elements using ngModelController do this automatically when they are linked.
   */
  form.$addControl = function(control) {
    // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
    // and not added to the scope.  Now we throw an error.
    assertNotHasOwnProperty(control.$name, 'input');
    controls.push(control);

    if (control.$name) {
      form[control.$name] = control;
    }
  };

  // Private API: rename a form control
  form.$$renameControl = function(control, newName) {
    var oldName = control.$name;

    if (form[oldName] === control) {
      delete form[oldName];
    }
    form[newName] = control;
    control.$name = newName;
  };

  /**
   * @ngdoc method
   * @name form.FormController#$removeControl
   *
   * @description
   * Deregister a control from the form.
   *
   * Input elements using ngModelController do this automatically when they are destroyed.
   */
  form.$removeControl = function(control) {
    if (control.$name && form[control.$name] === control) {
      delete form[control.$name];
    }
    forEach(form.$pending, function(value, name) {
      form.$setValidity(name, null, control);
    });
    forEach(form.$error, function(value, name) {
      form.$setValidity(name, null, control);
    });
    forEach(form.$$success, function(value, name) {
      form.$setValidity(name, null, control);
    });

    arrayRemove(controls, control);
  };


  /**
   * @ngdoc method
   * @name form.FormController#$setValidity
   *
   * @description
   * Sets the validity of a form control.
   *
   * This method will also propagate to parent forms.
   */
  addSetValidityMethod({
    ctrl: this,
    $element: element,
    set: function(object, property, controller) {
      var list = object[property];
      if (!list) {
        object[property] = [controller];
      } else {
        var index = list.indexOf(controller);
        if (index === -1) {
          list.push(controller);
        }
      }
    },
    unset: function(object, property, controller) {
      var list = object[property];
      if (!list) {
        return;
      }
      arrayRemove(list, controller);
      if (list.length === 0) {
        delete object[property];
      }
    },
    parentForm: parentForm,
    $animate: $animate
  });

  /**
   * @ngdoc method
   * @name form.FormController#$setDirty
   *
   * @description
   * Sets the form to a dirty state.
   *
   * This method can be called to add the 'ng-dirty' class and set the form to a dirty
   * state (ng-dirty class). This method will also propagate to parent forms.
   */
  form.$setDirty = function() {
    $animate.removeClass(element, PRISTINE_CLASS);
    $animate.addClass(element, DIRTY_CLASS);
    form.$dirty = true;
    form.$pristine = false;
    parentForm.$setDirty();
  };

  /**
   * @ngdoc method
   * @name form.FormController#$setPristine
   *
   * @description
   * Sets the form to its pristine state.
   *
   * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
   * state (ng-pristine class). This method will also propagate to all the controls contained
   * in this form.
   *
   * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
   * saving or resetting it.
   */
  form.$setPristine = function() {
    $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
    form.$dirty = false;
    form.$pristine = true;
    form.$submitted = false;
    forEach(controls, function(control) {
      control.$setPristine();
    });
  };

  /**
   * @ngdoc method
   * @name form.FormController#$setUntouched
   *
   * @description
   * Sets the form to its untouched state.
   *
   * This method can be called to remove the 'ng-touched' class and set the form controls to their
   * untouched state (ng-untouched class).
   *
   * Setting a form controls back to their untouched state is often useful when setting the form
   * back to its pristine state.
   */
  form.$setUntouched = function() {
    forEach(controls, function(control) {
      control.$setUntouched();
    });
  };

  /**
   * @ngdoc method
   * @name form.FormController#$setSubmitted
   *
   * @description
   * Sets the form to its submitted state.
   */
  form.$setSubmitted = function() {
    $animate.addClass(element, SUBMITTED_CLASS);
    form.$submitted = true;
    parentForm.$setSubmitted();
  };
}

/**
 * @ngdoc directive
 * @name ngForm
 * @restrict EAC
 *
 * @description
 * Nestable alias of {@link ng.directive:form `form`} directive. HTML
 * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
 * sub-group of controls needs to be determined.
 *
 * Note: the purpose of `ngForm` is to group controls,
 * but not to be a replacement for the `<form>` tag with all of its capabilities
 * (e.g. posting to the server, ...).
 *
 * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
 *                       related scope, under this name.
 *
 */

 /**
 * @ngdoc directive
 * @name form
 * @restrict E
 *
 * @description
 * Directive that instantiates
 * {@link form.FormController FormController}.
 *
 * If the `name` attribute is specified, the form controller is published onto the current scope under
 * this name.
 *
 * # Alias: {@link ng.directive:ngForm `ngForm`}
 *
 * In Angular, forms can be nested. This means that the outer form is valid when all of the child
 * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
 * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
 * `<form>` but can be nested.  This allows you to have nested forms, which is very useful when
 * using Angular validation directives in forms that are dynamically generated using the
 * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
 * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
 * `ngForm` directive and nest these in an outer `form` element.
 *
 *
 * # CSS classes
 *  - `ng-valid` is set if the form is valid.
 *  - `ng-invalid` is set if the form is invalid.
 *  - `ng-pristine` is set if the form is pristine.
 *  - `ng-dirty` is set if the form is dirty.
 *  - `ng-submitted` is set if the form was submitted.
 *
 * Keep in mind that ngAnimate can detect each of these classes when added and removed.
 *
 *
 * # Submitting a form and preventing the default action
 *
 * Since the role of forms in client-side Angular applications is different than in classical
 * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
 * page reload that sends the data to the server. Instead some javascript logic should be triggered
 * to handle the form submission in an application-specific way.
 *
 * For this reason, Angular prevents the default action (form submission to the server) unless the
 * `<form>` element has an `action` attribute specified.
 *
 * You can use one of the following two ways to specify what javascript method should be called when
 * a form is submitted:
 *
 * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
 * - {@link ng.directive:ngClick ngClick} directive on the first
  *  button or input field of type submit (input[type=submit])
 *
 * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
 * or {@link ng.directive:ngClick ngClick} directives.
 * This is because of the following form submission rules in the HTML specification:
 *
 * - If a form has only one input field then hitting enter in this field triggers form submit
 * (`ngSubmit`)
 * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
 * doesn't trigger submit
 * - if a form has one or more input fields and one or more buttons or input[type=submit] then
 * hitting enter in any of the input fields will trigger the click handler on the *first* button or
 * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
 *
 * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
 * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
 * to have access to the updated model.
 *
 * ## Animation Hooks
 *
 * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
 * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
 * other validations that are performed within the form. Animations in ngForm are similar to how
 * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
 * as JS animations.
 *
 * The following example shows a simple way to utilize CSS transitions to style a form element
 * that has been rendered as invalid after it has been validated:
 *
 * <pre>
 * //be sure to include ngAnimate as a module to hook into more
 * //advanced animations
 * .my-form {
 *   transition:0.5s linear all;
 *   background: white;
 * }
 * .my-form.ng-invalid {
 *   background: red;
 *   color:white;
 * }
 * </pre>
 *
 * @example
    <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
      <file name="index.html">
       <script>
         angular.module('formExample', [])
           .controller('FormController', ['$scope', function($scope) {
             $scope.userType = 'guest';
           }]);
       </script>
       <style>
        .my-form {
          -webkit-transition:all linear 0.5s;
          transition:all linear 0.5s;
          background: transparent;
        }
        .my-form.ng-invalid {
          background: red;
        }
       </style>
       <form name="myForm" ng-controller="FormController" class="my-form">
         userType: <input name="input" ng-model="userType" required>
         <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
         <code>userType = {{userType}}</code><br>
         <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
         <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
         <code>myForm.$valid = {{myForm.$valid}}</code><br>
         <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
        </form>
      </file>
      <file name="protractor.js" type="protractor">
        it('should initialize to model', function() {
          var userType = element(by.binding('userType'));
          var valid = element(by.binding('myForm.input.$valid'));

          expect(userType.getText()).toContain('guest');
          expect(valid.getText()).toContain('true');
        });

        it('should be invalid if empty', function() {
          var userType = element(by.binding('userType'));
          var valid = element(by.binding('myForm.input.$valid'));
          var userInput = element(by.model('userType'));

          userInput.clear();
          userInput.sendKeys('');

          expect(userType.getText()).toEqual('userType =');
          expect(valid.getText()).toContain('false');
        });
      </file>
    </example>
 *
 * @param {string=} name Name of the form. If specified, the form controller will be published into
 *                       related scope, under this name.
 */
var formDirectiveFactory = function(isNgForm) {
  return ['$timeout', function($timeout) {
    var formDirective = {
      name: 'form',
      restrict: isNgForm ? 'EAC' : 'E',
      controller: FormController,
      compile: function ngFormCompile(formElement, attr) {
        // Setup initial state of the control
        formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);

        var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);

        return {
          pre: function ngFormPreLink(scope, formElement, attr, controller) {
            // if `action` attr is not present on the form, prevent the default action (submission)
            if (!('action' in attr)) {
              // we can't use jq events because if a form is destroyed during submission the default
              // action is not prevented. see #1238
              //
              // IE 9 is not affected because it doesn't fire a submit event and try to do a full
              // page reload if the form was destroyed by submission of the form via a click handler
              // on a button in the form. Looks like an IE9 specific bug.
              var handleFormSubmission = function(event) {
                scope.$apply(function() {
                  controller.$commitViewValue();
                  controller.$setSubmitted();
                });

                event.preventDefault();
              };

              addEventListenerFn(formElement[0], 'submit', handleFormSubmission);

              // unregister the preventDefault listener so that we don't not leak memory but in a
              // way that will achieve the prevention of the default action.
              formElement.on('$destroy', function() {
                $timeout(function() {
                  removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
                }, 0, false);
              });
            }

            var parentFormCtrl = controller.$$parentForm;

            if (nameAttr) {
              setter(scope, controller.$name, controller, controller.$name);
              attr.$observe(nameAttr, function(newValue) {
                if (controller.$name === newValue) return;
                setter(scope, controller.$name, undefined, controller.$name);
                parentFormCtrl.$$renameControl(controller, newValue);
                setter(scope, controller.$name, controller, controller.$name);
              });
            }
            formElement.on('$destroy', function() {
              parentFormCtrl.$removeControl(controller);
              if (nameAttr) {
                setter(scope, attr[nameAttr], undefined, controller.$name);
              }
              extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
            });
          }
        };
      }
    };

    return formDirective;
  }];
};

var formDirective = formDirectiveFactory();
var ngFormDirective = formDirectiveFactory(true);

/* global VALID_CLASS: false,
  INVALID_CLASS: false,
  PRISTINE_CLASS: false,
  DIRTY_CLASS: false,
  UNTOUCHED_CLASS: false,
  TOUCHED_CLASS: false,
  $ngModelMinErr: false,
*/

// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;

var inputType = {

  /**
   * @ngdoc input
   * @name input[text]
   *
   * @description
   * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
   *
   *
   * @param {string} ngModel Assignable angular expression to data-bind to.
   * @param {string=} name Property name of the form under which the control is published.
   * @param {string=} required Adds `required` validation error key if the value is not entered.
   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
   *    `required` when you want to data-bind to the `required` attribute.
   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
   *    minlength.
   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
   *    any length.
   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
   *    that contains the regular expression body that will be converted to a regular expression
   *    as in the ngPattern directive.
   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
   *    a RegExp found by evaluating the Angular expression given in the attribute value.
   *    If the expression evaluates to a RegExp object, then this is used directly.
   *    If the expression evaluates to a string, then it will be converted to a RegExp
   *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
   *    `new RegExp('^abc$')`.<br />
   *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
   *    start at the index of the last search's match, thus not taking the whole input value into
   *    account.
   * @param {string=} ngChange Angular expression to be executed when input changes due to user
   *    interaction with the input element.
   * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
   *    This parameter is ignored for input[type=password] controls, which will never trim the
   *    input.
   *
   * @example
      <example name="text-input-directive" module="textInputExample">
        <file name="index.html">
         <script>
           angular.module('textInputExample', [])
             .controller('ExampleController', ['$scope', function($scope) {
               $scope.example = {
                 text: 'guest',
                 word: /^\s*\w*\s*$/
               };
             }]);
         </script>
         <form name="myForm" ng-controller="ExampleController">
           <label>Single word:
             <input type="text" name="input" ng-model="example.text"
                    ng-pattern="example.word" required ng-trim="false">
           </label>
           <div role="alert">
             <span class="error" ng-show="myForm.input.$error.required">
               Required!</span>
             <span class="error" ng-show="myForm.input.$error.pattern">
               Single word only!</span>
           </div>
           <tt>text = {{example.text}}</tt><br/>
           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
          </form>
        </file>
        <file name="protractor.js" type="protractor">
          var text = element(by.binding('example.text'));
          var valid = element(by.binding('myForm.input.$valid'));
          var input = element(by.model('example.text'));

          it('should initialize to model', function() {
            expect(text.getText()).toContain('guest');
            expect(valid.getText()).toContain('true');
          });

          it('should be invalid if empty', function() {
            input.clear();
            input.sendKeys('');

            expect(text.getText()).toEqual('text =');
            expect(valid.getText()).toContain('false');
          });

          it('should be invalid if multi word', function() {
            input.clear();
            input.sendKeys('hello world');

            expect(valid.getText()).toContain('false');
          });
        </file>
      </example>
   */
  'text': textInputType,

    /**
     * @ngdoc input
     * @name input[date]
     *
     * @description
     * Input with date validation and transformation. In browsers that do not yet support
     * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
     * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
     * modern browsers do not yet support this input type, it is important to provide cues to users on the
     * expected input format via a placeholder or label.
     *
     * The model must always be a Date object, otherwise Angular will throw an error.
     * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
     *
     * The timezone to be used to read/write the `Date` instance in the model can be defined using
     * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
     *
     * @param {string} ngModel Assignable angular expression to data-bind to.
     * @param {string=} name Property name of the form under which the control is published.
     * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
     * valid ISO date string (yyyy-MM-dd).
     * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
     * a valid ISO date string (yyyy-MM-dd).
     * @param {string=} required Sets `required` validation error key if the value is not entered.
     * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
     *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
     *    `required` when you want to data-bind to the `required` attribute.
     * @param {string=} ngChange Angular expression to be executed when input changes due to user
     *    interaction with the input element.
     *
     * @example
     <example name="date-input-directive" module="dateInputExample">
     <file name="index.html">
       <script>
          angular.module('dateInputExample', [])
            .controller('DateController', ['$scope', function($scope) {
              $scope.example = {
                value: new Date(2013, 9, 22)
              };
            }]);
       </script>
       <form name="myForm" ng-controller="DateController as dateCtrl">
          <label for="exampleInput">Pick a date in 2013:</label>
          <input type="date" id="exampleInput" name="input" ng-model="example.value"
              placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
          <div role="alert">
            <span class="error" ng-show="myForm.input.$error.required">
                Required!</span>
            <span class="error" ng-show="myForm.input.$error.date">
                Not a valid date!</span>
           </div>
           <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
       </form>
     </file>
     <file name="protractor.js" type="protractor">
        var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
        var valid = element(by.binding('myForm.input.$valid'));
        var input = element(by.model('example.value'));

        // currently protractor/webdriver does not support
        // sending keys to all known HTML5 input controls
        // for various browsers (see https://github.com/angular/protractor/issues/562).
        function setInput(val) {
          // set the value of the element and force validation.
          var scr = "var ipt = document.getElementById('exampleInput'); " +
          "ipt.value = '" + val + "';" +
          "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
          browser.executeScript(scr);
        }

        it('should initialize to model', function() {
          expect(value.getText()).toContain('2013-10-22');
          expect(valid.getText()).toContain('myForm.input.$valid = true');
        });

        it('should be invalid if empty', function() {
          setInput('');
          expect(value.getText()).toEqual('value =');
          expect(valid.getText()).toContain('myForm.input.$valid = false');
        });

        it('should be invalid if over max', function() {
          setInput('2015-01-01');
          expect(value.getText()).toContain('');
          expect(valid.getText()).toContain('myForm.input.$valid = false');
        });
     </file>
     </example>
     */
  'date': createDateInputType('date', DATE_REGEXP,
         createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
         'yyyy-MM-dd'),

   /**
    * @ngdoc input
    * @name input[datetime-local]
    *
    * @description
    * Input with datetime validation and transformation. In browsers that do not yet support
    * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
    * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
    *
    * The model must always be a Date object, otherwise Angular will throw an error.
    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
    *
    * The timezone to be used to read/write the `Date` instance in the model can be defined using
    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
    *
    * @param {string} ngModel Assignable angular expression to data-bind to.
    * @param {string=} name Property name of the form under which the control is published.
    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
    * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
    * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
    * @param {string=} required Sets `required` validation error key if the value is not entered.
    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
    *    `required` when you want to data-bind to the `required` attribute.
    * @param {string=} ngChange Angular expression to be executed when input changes due to user
    *    interaction with the input element.
    *
    * @example
    <example name="datetimelocal-input-directive" module="dateExample">
    <file name="index.html">
      <script>
        angular.module('dateExample', [])
          .controller('DateController', ['$scope', function($scope) {
            $scope.example = {
              value: new Date(2010, 11, 28, 14, 57)
            };
          }]);
      </script>
      <form name="myForm" ng-controller="DateController as dateCtrl">
        <label for="exampleInput">Pick a date between in 2013:</label>
        <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
            placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
        <div role="alert">
          <span class="error" ng-show="myForm.input.$error.required">
              Required!</span>
          <span class="error" ng-show="myForm.input.$error.datetimelocal">
              Not a valid date!</span>
        </div>
        <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
      </form>
    </file>
    <file name="protractor.js" type="protractor">
      var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
      var valid = element(by.binding('myForm.input.$valid'));
      var input = element(by.model('example.value'));

      // currently protractor/webdriver does not support
      // sending keys to all known HTML5 input controls
      // for various browsers (https://github.com/angular/protractor/issues/562).
      function setInput(val) {
        // set the value of the element and force validation.
        var scr = "var ipt = document.getElementById('exampleInput'); " +
        "ipt.value = '" + val + "';" +
        "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
        browser.executeScript(scr);
      }

      it('should initialize to model', function() {
        expect(value.getText()).toContain('2010-12-28T14:57:00');
        expect(valid.getText()).toContain('myForm.input.$valid = true');
      });

      it('should be invalid if empty', function() {
        setInput('');
        expect(value.getText()).toEqual('value =');
        expect(valid.getText()).toContain('myForm.input.$valid = false');
      });

      it('should be invalid if over max', function() {
        setInput('2015-01-01T23:59:00');
        expect(value.getText()).toContain('');
        expect(valid.getText()).toContain('myForm.input.$valid = false');
      });
    </file>
    </example>
    */
  'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
      createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
      'yyyy-MM-ddTHH:mm:ss.sss'),

  /**
   * @ngdoc input
   * @name input[time]
   *
   * @description
   * Input with time validation and transformation. In browsers that do not yet support
   * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
   * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
   * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
   *
   * The model must always be a Date object, otherwise Angular will throw an error.
   * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
   *
   * The timezone to be used to read/write the `Date` instance in the model can be defined using
   * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
   *
   * @param {string} ngModel Assignable angular expression to data-bind to.
   * @param {string=} name Property name of the form under which the control is published.
   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
   * valid ISO time format (HH:mm:ss).
   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
   * valid ISO time format (HH:mm:ss).
   * @param {string=} required Sets `required` validation error key if the value is not entered.
   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
   *    `required` when you want to data-bind to the `required` attribute.
   * @param {string=} ngChange Angular expression to be executed when input changes due to user
   *    interaction with the input element.
   *
   * @example
   <example name="time-input-directive" module="timeExample">
   <file name="index.html">
     <script>
      angular.module('timeExample', [])
        .controller('DateController', ['$scope', function($scope) {
          $scope.example = {
            value: new Date(1970, 0, 1, 14, 57, 0)
          };
        }]);
     </script>
     <form name="myForm" ng-controller="DateController as dateCtrl">
        <label for="exampleInput">Pick a between 8am and 5pm:</label>
        <input type="time" id="exampleInput" name="input" ng-model="example.value"
            placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
        <div role="alert">
          <span class="error" ng-show="myForm.input.$error.required">
              Required!</span>
          <span class="error" ng-show="myForm.input.$error.time">
              Not a valid date!</span>
        </div>
        <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
     </form>
   </file>
   <file name="protractor.js" type="protractor">
      var value = element(by.binding('example.value | date: "HH:mm:ss"'));
      var valid = element(by.binding('myForm.input.$valid'));
      var input = element(by.model('example.value'));

      // currently protractor/webdriver does not support
      // sending keys to all known HTML5 input controls
      // for various browsers (https://github.com/angular/protractor/issues/562).
      function setInput(val) {
        // set the value of the element and force validation.
        var scr = "var ipt = document.getElementById('exampleInput'); " +
        "ipt.value = '" + val + "';" +
        "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
        browser.executeScript(scr);
      }

      it('should initialize to model', function() {
        expect(value.getText()).toContain('14:57:00');
        expect(valid.getText()).toContain('myForm.input.$valid = true');
      });

      it('should be invalid if empty', function() {
        setInput('');
        expect(value.getText()).toEqual('value =');
        expect(valid.getText()).toContain('myForm.input.$valid = false');
      });

      it('should be invalid if over max', function() {
        setInput('23:59:00');
        expect(value.getText()).toContain('');
        expect(valid.getText()).toContain('myForm.input.$valid = false');
      });
   </file>
   </example>
   */
  'time': createDateInputType('time', TIME_REGEXP,
      createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
     'HH:mm:ss.sss'),

   /**
    * @ngdoc input
    * @name input[week]
    *
    * @description
    * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
    * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
    * week format (yyyy-W##), for example: `2013-W02`.
    *
    * The model must always be a Date object, otherwise Angular will throw an error.
    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
    *
    * The timezone to be used to read/write the `Date` instance in the model can be defined using
    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
    *
    * @param {string} ngModel Assignable angular expression to data-bind to.
    * @param {string=} name Property name of the form under which the control is published.
    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
    * valid ISO week format (yyyy-W##).
    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
    * a valid ISO week format (yyyy-W##).
    * @param {string=} required Sets `required` validation error key if the value is not entered.
    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
    *    `required` when you want to data-bind to the `required` attribute.
    * @param {string=} ngChange Angular expression to be executed when input changes due to user
    *    interaction with the input element.
    *
    * @example
    <example name="week-input-directive" module="weekExample">
    <file name="index.html">
      <script>
      angular.module('weekExample', [])
        .controller('DateController', ['$scope', function($scope) {
          $scope.example = {
            value: new Date(2013, 0, 3)
          };
        }]);
      </script>
      <form name="myForm" ng-controller="DateController as dateCtrl">
        <label>Pick a date between in 2013:
          <input id="exampleInput" type="week" name="input" ng-model="example.value"
                 placeholder="YYYY-W##" min="2012-W32"
                 max="2013-W52" required />
        </label>
        <div role="alert">
          <span class="error" ng-show="myForm.input.$error.required">
              Required!</span>
          <span class="error" ng-show="myForm.input.$error.week">
              Not a valid date!</span>
        </div>
        <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
      </form>
    </file>
    <file name="protractor.js" type="protractor">
      var value = element(by.binding('example.value | date: "yyyy-Www"'));
      var valid = element(by.binding('myForm.input.$valid'));
      var input = element(by.model('example.value'));

      // currently protractor/webdriver does not support
      // sending keys to all known HTML5 input controls
      // for various browsers (https://github.com/angular/protractor/issues/562).
      function setInput(val) {
        // set the value of the element and force validation.
        var scr = "var ipt = document.getElementById('exampleInput'); " +
        "ipt.value = '" + val + "';" +
        "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
        browser.executeScript(scr);
      }

      it('should initialize to model', function() {
        expect(value.getText()).toContain('2013-W01');
        expect(valid.getText()).toContain('myForm.input.$valid = true');
      });

      it('should be invalid if empty', function() {
        setInput('');
        expect(value.getText()).toEqual('value =');
        expect(valid.getText()).toContain('myForm.input.$valid = false');
      });

      it('should be invalid if over max', function() {
        setInput('2015-W01');
        expect(value.getText()).toContain('');
        expect(valid.getText()).toContain('myForm.input.$valid = false');
      });
    </file>
    </example>
    */
  'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),

  /**
   * @ngdoc input
   * @name input[month]
   *
   * @description
   * Input with month validation and transformation. In browsers that do not yet support
   * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
   * month format (yyyy-MM), for example: `2009-01`.
   *
   * The model must always be a Date object, otherwise Angular will throw an error.
   * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
   * If the model is not set to the first of the month, the next view to model update will set it
   * to the first of the month.
   *
   * The timezone to be used to read/write the `Date` instance in the model can be defined using
   * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
   *
   * @param {string} ngModel Assignable angular expression to data-bind to.
   * @param {string=} name Property name of the form under which the control is published.
   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
   * a valid ISO month format (yyyy-MM).
   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
   * be a valid ISO month format (yyyy-MM).
   * @param {string=} required Sets `required` validation error key if the value is not entered.
   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
   *    `required` when you want to data-bind to the `required` attribute.
   * @param {string=} ngChange Angular expression to be executed when input changes due to user
   *    interaction with the input element.
   *
   * @example
   <example name="month-input-directive" module="monthExample">
   <file name="index.html">
     <script>
      angular.module('monthExample', [])
        .controller('DateController', ['$scope', function($scope) {
          $scope.example = {
            value: new Date(2013, 9, 1)
          };
        }]);
     </script>
     <form name="myForm" ng-controller="DateController as dateCtrl">
       <label for="exampleInput">Pick a month in 2013:</label>
       <input id="exampleInput" type="month" name="input" ng-model="example.value"
          placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
       <div role="alert">
         <span class="error" ng-show="myForm.input.$error.required">
            Required!</span>
         <span class="error" ng-show="myForm.input.$error.month">
            Not a valid month!</span>
       </div>
       <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
       <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
       <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
       <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
       <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
     </form>
   </file>
   <file name="protractor.js" type="protractor">
      var value = element(by.binding('example.value | date: "yyyy-MM"'));
      var valid = element(by.binding('myForm.input.$valid'));
      var input = element(by.model('example.value'));

      // currently protractor/webdriver does not support
      // sending keys to all known HTML5 input controls
      // for various browsers (https://github.com/angular/protractor/issues/562).
      function setInput(val) {
        // set the value of the element and force validation.
        var scr = "var ipt = document.getElementById('exampleInput'); " +
        "ipt.value = '" + val + "';" +
        "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
        browser.executeScript(scr);
      }

      it('should initialize to model', function() {
        expect(value.getText()).toContain('2013-10');
        expect(valid.getText()).toContain('myForm.input.$valid = true');
      });

      it('should be invalid if empty', function() {
        setInput('');
        expect(value.getText()).toEqual('value =');
        expect(valid.getText()).toContain('myForm.input.$valid = false');
      });

      it('should be invalid if over max', function() {
        setInput('2015-01');
        expect(value.getText()).toContain('');
        expect(valid.getText()).toContain('myForm.input.$valid = false');
      });
   </file>
   </example>
   */
  'month': createDateInputType('month', MONTH_REGEXP,
     createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
     'yyyy-MM'),

  /**
   * @ngdoc input
   * @name input[number]
   *
   * @description
   * Text input with number validation and transformation. Sets the `number` validation
   * error if not a valid number.
   *
   * <div class="alert alert-warning">
   * The model must always be of type `number` otherwise Angular will throw an error.
   * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
   * error docs for more information and an example of how to convert your model if necessary.
   * </div>
   *
   * ## Issues with HTML5 constraint validation
   *
   * In browsers that follow the
   * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
   * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
   * If a non-number is entered in the input, the browser will report the value as an empty string,
   * which means the view / model values in `ngModel` and subsequently the scope value
   * will also be an empty string.
   *
   *
   * @param {string} ngModel Assignable angular expression to data-bind to.
   * @param {string=} name Property name of the form under which the control is published.
   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
   * @param {string=} required Sets `required` validation error key if the value is not entered.
   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
   *    `required` when you want to data-bind to the `required` attribute.
   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
   *    minlength.
   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
   *    any length.
   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
   *    that contains the regular expression body that will be converted to a regular expression
   *    as in the ngPattern directive.
   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
   *    a RegExp found by evaluating the Angular expression given in the attribute value.
   *    If the expression evaluates to a RegExp object, then this is used directly.
   *    If the expression evaluates to a string, then it will be converted to a RegExp
   *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
   *    `new RegExp('^abc$')`.<br />
   *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
   *    start at the index of the last search's match, thus not taking the whole input value into
   *    account.
   * @param {string=} ngChange Angular expression to be executed when input changes due to user
   *    interaction with the input element.
   *
   * @example
      <example name="number-input-directive" module="numberExample">
        <file name="index.html">
         <script>
           angular.module('numberExample', [])
             .controller('ExampleController', ['$scope', function($scope) {
               $scope.example = {
                 value: 12
               };
             }]);
         </script>
         <form name="myForm" ng-controller="ExampleController">
           <label>Number:
             <input type="number" name="input" ng-model="example.value"
                    min="0" max="99" required>
          </label>
           <div role="alert">
             <span class="error" ng-show="myForm.input.$error.required">
               Required!</span>
             <span class="error" ng-show="myForm.input.$error.number">
               Not valid number!</span>
           </div>
           <tt>value = {{example.value}}</tt><br/>
           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
          </form>
        </file>
        <file name="protractor.js" type="protractor">
          var value = element(by.binding('example.value'));
          var valid = element(by.binding('myForm.input.$valid'));
          var input = element(by.model('example.value'));

          it('should initialize to model', function() {
            expect(value.getText()).toContain('12');
            expect(valid.getText()).toContain('true');
          });

          it('should be invalid if empty', function() {
            input.clear();
            input.sendKeys('');
            expect(value.getText()).toEqual('value =');
            expect(valid.getText()).toContain('false');
          });

          it('should be invalid if over max', function() {
            input.clear();
            input.sendKeys('123');
            expect(value.getText()).toEqual('value =');
            expect(valid.getText()).toContain('false');
          });
        </file>
      </example>
   */
  'number': numberInputType,


  /**
   * @ngdoc input
   * @name input[url]
   *
   * @description
   * Text input with URL validation. Sets the `url` validation error key if the content is not a
   * valid URL.
   *
   * <div class="alert alert-warning">
   * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
   * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
   * the built-in validators (see the {@link guide/forms Forms guide})
   * </div>
   *
   * @param {string} ngModel Assignable angular expression to data-bind to.
   * @param {string=} name Property name of the form under which the control is published.
   * @param {string=} required Sets `required` validation error key if the value is not entered.
   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
   *    `required` when you want to data-bind to the `required` attribute.
   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
   *    minlength.
   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
   *    any length.
   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
   *    that contains the regular expression body that will be converted to a regular expression
   *    as in the ngPattern directive.
   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
   *    a RegExp found by evaluating the Angular expression given in the attribute value.
   *    If the expression evaluates to a RegExp object, then this is used directly.
   *    If the expression evaluates to a string, then it will be converted to a RegExp
   *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
   *    `new RegExp('^abc$')`.<br />
   *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
   *    start at the index of the last search's match, thus not taking the whole input value into
   *    account.
   * @param {string=} ngChange Angular expression to be executed when input changes due to user
   *    interaction with the input element.
   *
   * @example
      <example name="url-input-directive" module="urlExample">
        <file name="index.html">
         <script>
           angular.module('urlExample', [])
             .controller('ExampleController', ['$scope', function($scope) {
               $scope.url = {
                 text: 'http://google.com'
               };
             }]);
         </script>
         <form name="myForm" ng-controller="ExampleController">
           <label>URL:
             <input type="url" name="input" ng-model="url.text" required>
           <label>
           <div role="alert">
             <span class="error" ng-show="myForm.input.$error.required">
               Required!</span>
             <span class="error" ng-show="myForm.input.$error.url">
               Not valid url!</span>
           </div>
           <tt>text = {{url.text}}</tt><br/>
           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
           <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
          </form>
        </file>
        <file name="protractor.js" type="protractor">
          var text = element(by.binding('url.text'));
          var valid = element(by.binding('myForm.input.$valid'));
          var input = element(by.model('url.text'));

          it('should initialize to model', function() {
            expect(text.getText()).toContain('http://google.com');
            expect(valid.getText()).toContain('true');
          });

          it('should be invalid if empty', function() {
            input.clear();
            input.sendKeys('');

            expect(text.getText()).toEqual('text =');
            expect(valid.getText()).toContain('false');
          });

          it('should be invalid if not url', function() {
            input.clear();
            input.sendKeys('box');

            expect(valid.getText()).toContain('false');
          });
        </file>
      </example>
   */
  'url': urlInputType,


  /**
   * @ngdoc input
   * @name input[email]
   *
   * @description
   * Text input with email validation. Sets the `email` validation error key if not a valid email
   * address.
   *
   * <div class="alert alert-warning">
   * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
   * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
   * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
   * </div>
   *
   * @param {string} ngModel Assignable angular expression to data-bind to.
   * @param {string=} name Property name of the form under which the control is published.
   * @param {string=} required Sets `required` validation error key if the value is not entered.
   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
   *    `required` when you want to data-bind to the `required` attribute.
   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
   *    minlength.
   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
   *    any length.
   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
   *    that contains the regular expression body that will be converted to a regular expression
   *    as in the ngPattern directive.
   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
   *    a RegExp found by evaluating the Angular expression given in the attribute value.
   *    If the expression evaluates to a RegExp object, then this is used directly.
   *    If the expression evaluates to a string, then it will be converted to a RegExp
   *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
   *    `new RegExp('^abc$')`.<br />
   *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
   *    start at the index of the last search's match, thus not taking the whole input value into
   *    account.
   * @param {string=} ngChange Angular expression to be executed when input changes due to user
   *    interaction with the input element.
   *
   * @example
      <example name="email-input-directive" module="emailExample">
        <file name="index.html">
         <script>
           angular.module('emailExample', [])
             .controller('ExampleController', ['$scope', function($scope) {
               $scope.email = {
                 text: 'me@example.com'
               };
             }]);
         </script>
           <form name="myForm" ng-controller="ExampleController">
             <label>Email:
               <input type="email" name="input" ng-model="email.text" required>
             </label>
             <div role="alert">
               <span class="error" ng-show="myForm.input.$error.required">
                 Required!</span>
               <span class="error" ng-show="myForm.input.$error.email">
                 Not valid email!</span>
             </div>
             <tt>text = {{email.text}}</tt><br/>
             <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
             <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
             <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
             <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
             <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
           </form>
         </file>
        <file name="protractor.js" type="protractor">
          var text = element(by.binding('email.text'));
          var valid = element(by.binding('myForm.input.$valid'));
          var input = element(by.model('email.text'));

          it('should initialize to model', function() {
            expect(text.getText()).toContain('me@example.com');
            expect(valid.getText()).toContain('true');
          });

          it('should be invalid if empty', function() {
            input.clear();
            input.sendKeys('');
            expect(text.getText()).toEqual('text =');
            expect(valid.getText()).toContain('false');
          });

          it('should be invalid if not email', function() {
            input.clear();
            input.sendKeys('xxx');

            expect(valid.getText()).toContain('false');
          });
        </file>
      </example>
   */
  'email': emailInputType,


  /**
   * @ngdoc input
   * @name input[radio]
   *
   * @description
   * HTML radio button.
   *
   * @param {string} ngModel Assignable angular expression to data-bind to.
   * @param {string} value The value to which the `ngModel` expression should be set when selected.
   *    Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
   *    too. Use `ngValue` if you need complex models (`number`, `object`, ...).
   * @param {string=} name Property name of the form under which the control is published.
   * @param {string=} ngChange Angular expression to be executed when input changes due to user
   *    interaction with the input element.
   * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
   *    is selected. Should be used instead of the `value` attribute if you need
   *    a non-string `ngModel` (`boolean`, `array`, ...).
   *
   * @example
      <example name="radio-input-directive" module="radioExample">
        <file name="index.html">
         <script>
           angular.module('radioExample', [])
             .controller('ExampleController', ['$scope', function($scope) {
               $scope.color = {
                 name: 'blue'
               };
               $scope.specialValue = {
                 "id": "12345",
                 "value": "green"
               };
             }]);
         </script>
         <form name="myForm" ng-controller="ExampleController">
           <label>
             <input type="radio" ng-model="color.name" value="red">
             Red
           </label><br/>
           <label>
             <input type="radio" ng-model="color.name" ng-value="specialValue">
             Green
           </label><br/>
           <label>
             <input type="radio" ng-model="color.name" value="blue">
             Blue
           </label><br/>
           <tt>color = {{color.name | json}}</tt><br/>
          </form>
          Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
        </file>
        <file name="protractor.js" type="protractor">
          it('should change state', function() {
            var color = element(by.binding('color.name'));

            expect(color.getText()).toContain('blue');

            element.all(by.model('color.name')).get(0).click();

            expect(color.getText()).toContain('red');
          });
        </file>
      </example>
   */
  'radio': radioInputType,


  /**
   * @ngdoc input
   * @name input[checkbox]
   *
   * @description
   * HTML checkbox.
   *
   * @param {string} ngModel Assignable angular expression to data-bind to.
   * @param {string=} name Property name of the form under which the control is published.
   * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
   * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
   * @param {string=} ngChange Angular expression to be executed when input changes due to user
   *    interaction with the input element.
   *
   * @example
      <example name="checkbox-input-directive" module="checkboxExample">
        <file name="index.html">
         <script>
           angular.module('checkboxExample', [])
             .controller('ExampleController', ['$scope', function($scope) {
               $scope.checkboxModel = {
                value1 : true,
                value2 : 'YES'
              };
             }]);
         </script>
         <form name="myForm" ng-controller="ExampleController">
           <label>Value1:
             <input type="checkbox" ng-model="checkboxModel.value1">
           </label><br/>
           <label>Value2:
             <input type="checkbox" ng-model="checkboxModel.value2"
                    ng-true-value="'YES'" ng-false-value="'NO'">
            </label><br/>
           <tt>value1 = {{checkboxModel.value1}}</tt><br/>
           <tt>value2 = {{checkboxModel.value2}}</tt><br/>
          </form>
        </file>
        <file name="protractor.js" type="protractor">
          it('should change state', function() {
            var value1 = element(by.binding('checkboxModel.value1'));
            var value2 = element(by.binding('checkboxModel.value2'));

            expect(value1.getText()).toContain('true');
            expect(value2.getText()).toContain('YES');

            element(by.model('checkboxModel.value1')).click();
            element(by.model('checkboxModel.value2')).click();

            expect(value1.getText()).toContain('false');
            expect(value2.getText()).toContain('NO');
          });
        </file>
      </example>
   */
  'checkbox': checkboxInputType,

  'hidden': noop,
  'button': noop,
  'submit': noop,
  'reset': noop,
  'file': noop
};

function stringBasedInputType(ctrl) {
  ctrl.$formatters.push(function(value) {
    return ctrl.$isEmpty(value) ? value : value.toString();
  });
}

function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  stringBasedInputType(ctrl);
}

function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  var type = lowercase(element[0].type);

  // In composition mode, users are still inputing intermediate text buffer,
  // hold the listener until composition is done.
  // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  if (!$sniffer.android) {
    var composing = false;

    element.on('compositionstart', function(data) {
      composing = true;
    });

    element.on('compositionend', function() {
      composing = false;
      listener();
    });
  }

  var listener = function(ev) {
    if (timeout) {
      $browser.defer.cancel(timeout);
      timeout = null;
    }
    if (composing) return;
    var value = element.val(),
        event = ev && ev.type;

    // By default we will trim the value
    // If the attribute ng-trim exists we will avoid trimming
    // If input type is 'password', the value is never trimmed
    if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
      value = trim(value);
    }

    // If a control is suffering from bad input (due to native validators), browsers discard its
    // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
    // control's value is the same empty value twice in a row.
    if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
      ctrl.$setViewValue(value, event);
    }
  };

  // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  // input event on backspace, delete or cut
  if ($sniffer.hasEvent('input')) {
    element.on('input', listener);
  } else {
    var timeout;

    var deferListener = function(ev, input, origValue) {
      if (!timeout) {
        timeout = $browser.defer(function() {
          timeout = null;
          if (!input || input.value !== origValue) {
            listener(ev);
          }
        });
      }
    };

    element.on('keydown', function(event) {
      var key = event.keyCode;

      // ignore
      //    command            modifiers                   arrows
      if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;

      deferListener(event, this, this.value);
    });

    // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
    if ($sniffer.hasEvent('paste')) {
      element.on('paste cut', deferListener);
    }
  }

  // if user paste into input using mouse on older browser
  // or form autocomplete on newer browser, we need "change" event to catch it
  element.on('change', listener);

  ctrl.$render = function() {
    element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  };
}

function weekParser(isoWeek, existingDate) {
  if (isDate(isoWeek)) {
    return isoWeek;
  }

  if (isString(isoWeek)) {
    WEEK_REGEXP.lastIndex = 0;
    var parts = WEEK_REGEXP.exec(isoWeek);
    if (parts) {
      var year = +parts[1],
          week = +parts[2],
          hours = 0,
          minutes = 0,
          seconds = 0,
          milliseconds = 0,
          firstThurs = getFirstThursdayOfYear(year),
          addDays = (week - 1) * 7;

      if (existingDate) {
        hours = existingDate.getHours();
        minutes = existingDate.getMinutes();
        seconds = existingDate.getSeconds();
        milliseconds = existingDate.getMilliseconds();
      }

      return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
    }
  }

  return NaN;
}

function createDateParser(regexp, mapping) {
  return function(iso, date) {
    var parts, map;

    if (isDate(iso)) {
      return iso;
    }

    if (isString(iso)) {
      // When a date is JSON'ified to wraps itself inside of an extra
      // set of double quotes. This makes the date parsing code unable
      // to match the date string and parse it as a date.
      if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
        iso = iso.substring(1, iso.length - 1);
      }
      if (ISO_DATE_REGEXP.test(iso)) {
        return new Date(iso);
      }
      regexp.lastIndex = 0;
      parts = regexp.exec(iso);

      if (parts) {
        parts.shift();
        if (date) {
          map = {
            yyyy: date.getFullYear(),
            MM: date.getMonth() + 1,
            dd: date.getDate(),
            HH: date.getHours(),
            mm: date.getMinutes(),
            ss: date.getSeconds(),
            sss: date.getMilliseconds() / 1000
          };
        } else {
          map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
        }

        forEach(parts, function(part, index) {
          if (index < mapping.length) {
            map[mapping[index]] = +part;
          }
        });
        return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
      }
    }

    return NaN;
  };
}

function createDateInputType(type, regexp, parseDate, format) {
  return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
    badInputChecker(scope, element, attr, ctrl);
    baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
    var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
    var previousDate;

    ctrl.$$parserName = type;
    ctrl.$parsers.push(function(value) {
      if (ctrl.$isEmpty(value)) return null;
      if (regexp.test(value)) {
        // Note: We cannot read ctrl.$modelValue, as there might be a different
        // parser/formatter in the processing chain so that the model
        // contains some different data format!
        var parsedDate = parseDate(value, previousDate);
        if (timezone) {
          parsedDate = convertTimezoneToLocal(parsedDate, timezone);
        }
        return parsedDate;
      }
      return undefined;
    });

    ctrl.$formatters.push(function(value) {
      if (value && !isDate(value)) {
        throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
      }
      if (isValidDate(value)) {
        previousDate = value;
        if (previousDate && timezone) {
          previousDate = convertTimezoneToLocal(previousDate, timezone, true);
        }
        return $filter('date')(value, format, timezone);
      } else {
        previousDate = null;
        return '';
      }
    });

    if (isDefined(attr.min) || attr.ngMin) {
      var minVal;
      ctrl.$validators.min = function(value) {
        return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
      };
      attr.$observe('min', function(val) {
        minVal = parseObservedDateValue(val);
        ctrl.$validate();
      });
    }

    if (isDefined(attr.max) || attr.ngMax) {
      var maxVal;
      ctrl.$validators.max = function(value) {
        return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
      };
      attr.$observe('max', function(val) {
        maxVal = parseObservedDateValue(val);
        ctrl.$validate();
      });
    }

    function isValidDate(value) {
      // Invalid Date: getTime() returns NaN
      return value && !(value.getTime && value.getTime() !== value.getTime());
    }

    function parseObservedDateValue(val) {
      return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
    }
  };
}

function badInputChecker(scope, element, attr, ctrl) {
  var node = element[0];
  var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  if (nativeValidation) {
    ctrl.$parsers.push(function(value) {
      var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
      // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
      // - also sets validity.badInput (should only be validity.typeMismatch).
      // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
      // - can ignore this case as we can still read out the erroneous email...
      return validity.badInput && !validity.typeMismatch ? undefined : value;
    });
  }
}

function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  badInputChecker(scope, element, attr, ctrl);
  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);

  ctrl.$$parserName = 'number';
  ctrl.$parsers.push(function(value) {
    if (ctrl.$isEmpty(value))      return null;
    if (NUMBER_REGEXP.test(value)) return parseFloat(value);
    return undefined;
  });

  ctrl.$formatters.push(function(value) {
    if (!ctrl.$isEmpty(value)) {
      if (!isNumber(value)) {
        throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
      }
      value = value.toString();
    }
    return value;
  });

  if (isDefined(attr.min) || attr.ngMin) {
    var minVal;
    ctrl.$validators.min = function(value) {
      return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
    };

    attr.$observe('min', function(val) {
      if (isDefined(val) && !isNumber(val)) {
        val = parseFloat(val, 10);
      }
      minVal = isNumber(val) && !isNaN(val) ? val : undefined;
      // TODO(matsko): implement validateLater to reduce number of validations
      ctrl.$validate();
    });
  }

  if (isDefined(attr.max) || attr.ngMax) {
    var maxVal;
    ctrl.$validators.max = function(value) {
      return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
    };

    attr.$observe('max', function(val) {
      if (isDefined(val) && !isNumber(val)) {
        val = parseFloat(val, 10);
      }
      maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
      // TODO(matsko): implement validateLater to reduce number of validations
      ctrl.$validate();
    });
  }
}

function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  // Note: no badInputChecker here by purpose as `url` is only a validation
  // in browsers, i.e. we can always read out input.value even if it is not valid!
  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  stringBasedInputType(ctrl);

  ctrl.$$parserName = 'url';
  ctrl.$validators.url = function(modelValue, viewValue) {
    var value = modelValue || viewValue;
    return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  };
}

function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  // Note: no badInputChecker here by purpose as `url` is only a validation
  // in browsers, i.e. we can always read out input.value even if it is not valid!
  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  stringBasedInputType(ctrl);

  ctrl.$$parserName = 'email';
  ctrl.$validators.email = function(modelValue, viewValue) {
    var value = modelValue || viewValue;
    return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  };
}

function radioInputType(scope, element, attr, ctrl) {
  // make the name unique, if not defined
  if (isUndefined(attr.name)) {
    element.attr('name', nextUid());
  }

  var listener = function(ev) {
    if (element[0].checked) {
      ctrl.$setViewValue(attr.value, ev && ev.type);
    }
  };

  element.on('click', listener);

  ctrl.$render = function() {
    var value = attr.value;
    element[0].checked = (value == ctrl.$viewValue);
  };

  attr.$observe('value', ctrl.$render);
}

function parseConstantExpr($parse, context, name, expression, fallback) {
  var parseFn;
  if (isDefined(expression)) {
    parseFn = $parse(expression);
    if (!parseFn.constant) {
      throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
                                   '`{1}`.', name, expression);
    }
    return parseFn(context);
  }
  return fallback;
}

function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);

  var listener = function(ev) {
    ctrl.$setViewValue(element[0].checked, ev && ev.type);
  };

  element.on('click', listener);

  ctrl.$render = function() {
    element[0].checked = ctrl.$viewValue;
  };

  // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  // it to a boolean.
  ctrl.$isEmpty = function(value) {
    return value === false;
  };

  ctrl.$formatters.push(function(value) {
    return equals(value, trueValue);
  });

  ctrl.$parsers.push(function(value) {
    return value ? trueValue : falseValue;
  });
}


/**
 * @ngdoc directive
 * @name textarea
 * @restrict E
 *
 * @description
 * HTML textarea element control with angular data-binding. The data-binding and validation
 * properties of this element are exactly the same as those of the
 * {@link ng.directive:input input element}.
 *
 * @param {string} ngModel Assignable angular expression to data-bind to.
 * @param {string=} name Property name of the form under which the control is published.
 * @param {string=} required Sets `required` validation error key if the value is not entered.
 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
 *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
 *    `required` when you want to data-bind to the `required` attribute.
 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
 *    minlength.
 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
 *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
 *    length.
 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
 *    a RegExp found by evaluating the Angular expression given in the attribute value.
 *    If the expression evaluates to a RegExp object, then this is used directly.
 *    If the expression evaluates to a string, then it will be converted to a RegExp
 *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
 *    `new RegExp('^abc$')`.<br />
 *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
 *    start at the index of the last search's match, thus not taking the whole input value into
 *    account.
 * @param {string=} ngChange Angular expression to be executed when input changes due to user
 *    interaction with the input element.
 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
 */


/**
 * @ngdoc directive
 * @name input
 * @restrict E
 *
 * @description
 * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
 * input state control, and validation.
 * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
 *
 * <div class="alert alert-warning">
 * **Note:** Not every feature offered is available for all input types.
 * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
 * </div>
 *
 * @param {string} ngModel Assignable angular expression to data-bind to.
 * @param {string=} name Property name of the form under which the control is published.
 * @param {string=} required Sets `required` validation error key if the value is not entered.
 * @param {boolean=} ngRequired Sets `required` attribute if set to true
 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
 *    minlength.
 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
 *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
 *    length.
 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
 *    a RegExp found by evaluating the Angular expression given in the attribute value.
 *    If the expression evaluates to a RegExp object, then this is used directly.
 *    If the expression evaluates to a string, then it will be converted to a RegExp
 *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
 *    `new RegExp('^abc$')`.<br />
 *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
 *    start at the index of the last search's match, thus not taking the whole input value into
 *    account.
 * @param {string=} ngChange Angular expression to be executed when input changes due to user
 *    interaction with the input element.
 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
 *    This parameter is ignored for input[type=password] controls, which will never trim the
 *    input.
 *
 * @example
    <example name="input-directive" module="inputExample">
      <file name="index.html">
       <script>
          angular.module('inputExample', [])
            .controller('ExampleController', ['$scope', function($scope) {
              $scope.user = {name: 'guest', last: 'visitor'};
            }]);
       </script>
       <div ng-controller="ExampleController">
         <form name="myForm">
           <label>
              User name:
              <input type="text" name="userName" ng-model="user.name" required>
           </label>
           <div role="alert">
             <span class="error" ng-show="myForm.userName.$error.required">
              Required!</span>
           </div>
           <label>
              Last name:
              <input type="text" name="lastName" ng-model="user.last"
              ng-minlength="3" ng-maxlength="10">
           </label>
           <div role="alert">
             <span class="error" ng-show="myForm.lastName.$error.minlength">
               Too short!</span>
             <span class="error" ng-show="myForm.lastName.$error.maxlength">
               Too long!</span>
           </div>
         </form>
         <hr>
         <tt>user = {{user}}</tt><br/>
         <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
         <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
         <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
         <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
         <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
         <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
         <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
       </div>
      </file>
      <file name="protractor.js" type="protractor">
        var user = element(by.exactBinding('user'));
        var userNameValid = element(by.binding('myForm.userName.$valid'));
        var lastNameValid = element(by.binding('myForm.lastName.$valid'));
        var lastNameError = element(by.binding('myForm.lastName.$error'));
        var formValid = element(by.binding('myForm.$valid'));
        var userNameInput = element(by.model('user.name'));
        var userLastInput = element(by.model('user.last'));

        it('should initialize to model', function() {
          expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
          expect(userNameValid.getText()).toContain('true');
          expect(formValid.getText()).toContain('true');
        });

        it('should be invalid if empty when required', function() {
          userNameInput.clear();
          userNameInput.sendKeys('');

          expect(user.getText()).toContain('{"last":"visitor"}');
          expect(userNameValid.getText()).toContain('false');
          expect(formValid.getText()).toContain('false');
        });

        it('should be valid if empty when min length is set', function() {
          userLastInput.clear();
          userLastInput.sendKeys('');

          expect(user.getText()).toContain('{"name":"guest","last":""}');
          expect(lastNameValid.getText()).toContain('true');
          expect(formValid.getText()).toContain('true');
        });

        it('should be invalid if less than required min length', function() {
          userLastInput.clear();
          userLastInput.sendKeys('xx');

          expect(user.getText()).toContain('{"name":"guest"}');
          expect(lastNameValid.getText()).toContain('false');
          expect(lastNameError.getText()).toContain('minlength');
          expect(formValid.getText()).toContain('false');
        });

        it('should be invalid if longer than max length', function() {
          userLastInput.clear();
          userLastInput.sendKeys('some ridiculously long name');

          expect(user.getText()).toContain('{"name":"guest"}');
          expect(lastNameValid.getText()).toContain('false');
          expect(lastNameError.getText()).toContain('maxlength');
          expect(formValid.getText()).toContain('false');
        });
      </file>
    </example>
 */
var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
    function($browser, $sniffer, $filter, $parse) {
  return {
    restrict: 'E',
    require: ['?ngModel'],
    link: {
      pre: function(scope, element, attr, ctrls) {
        if (ctrls[0]) {
          (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
                                                              $browser, $filter, $parse);
        }
      }
    }
  };
}];



var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
/**
 * @ngdoc directive
 * @name ngValue
 *
 * @description
 * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
 * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
 * the bound value.
 *
 * `ngValue` is useful when dynamically generating lists of radio buttons using
 * {@link ngRepeat `ngRepeat`}, as shown below.
 *
 * Likewise, `ngValue` can be used to generate `<option>` elements for
 * the {@link select `select`} element. In that case however, only strings are supported
 * for the `value `attribute, so the resulting `ngModel` will always be a string.
 * Support for `select` models with non-string values is available via `ngOptions`.
 *
 * @element input
 * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
 *   of the `input` element
 *
 * @example
    <example name="ngValue-directive" module="valueExample">
      <file name="index.html">
       <script>
          angular.module('valueExample', [])
            .controller('ExampleController', ['$scope', function($scope) {
              $scope.names = ['pizza', 'unicorns', 'robots'];
              $scope.my = { favorite: 'unicorns' };
            }]);
       </script>
        <form ng-controller="ExampleController">
          <h2>Which is your favorite?</h2>
            <label ng-repeat="name in names" for="{{name}}">
              {{name}}
              <input type="radio"
                     ng-model="my.favorite"
                     ng-value="name"
                     id="{{name}}"
                     name="favorite">
            </label>
          <div>You chose {{my.favorite}}</div>
        </form>
      </file>
      <file name="protractor.js" type="protractor">
        var favorite = element(by.binding('my.favorite'));

        it('should initialize to model', function() {
          expect(favorite.getText()).toContain('unicorns');
        });
        it('should bind the values to the inputs', function() {
          element.all(by.model('my.favorite')).get(0).click();
          expect(favorite.getText()).toContain('pizza');
        });
      </file>
    </example>
 */
var ngValueDirective = function() {
  return {
    restrict: 'A',
    priority: 100,
    compile: function(tpl, tplAttr) {
      if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
        return function ngValueConstantLink(scope, elm, attr) {
          attr.$set('value', scope.$eval(attr.ngValue));
        };
      } else {
        return function ngValueLink(scope, elm, attr) {
          scope.$watch(attr.ngValue, function valueWatchAction(value) {
            attr.$set('value', value);
          });
        };
      }
    }
  };
};

/**
 * @ngdoc directive
 * @name ngBind
 * @restrict AC
 *
 * @description
 * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
 * with the value of a given expression, and to update the text content when the value of that
 * expression changes.
 *
 * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
 * `{{ expression }}` which is similar but less verbose.
 *
 * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
 * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
 * element attribute, it makes the bindings invisible to the user while the page is loading.
 *
 * An alternative solution to this problem would be using the
 * {@link ng.directive:ngCloak ngCloak} directive.
 *
 *
 * @element ANY
 * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
 *
 * @example
 * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
   <example module="bindExample">
     <file name="index.html">
       <script>
         angular.module('bindExample', [])
           .controller('ExampleController', ['$scope', function($scope) {
             $scope.name = 'Whirled';
           }]);
       </script>
       <div ng-controller="ExampleController">
         <label>Enter name: <input type="text" ng-model="name"></label><br>
         Hello <span ng-bind="name"></span>!
       </div>
     </file>
     <file name="protractor.js" type="protractor">
       it('should check ng-bind', function() {
         var nameInput = element(by.model('name'));

         expect(element(by.binding('name')).getText()).toBe('Whirled');
         nameInput.clear();
         nameInput.sendKeys('world');
         expect(element(by.binding('name')).getText()).toBe('world');
       });
     </file>
   </example>
 */
var ngBindDirective = ['$compile', function($compile) {
  return {
    restrict: 'AC',
    compile: function ngBindCompile(templateElement) {
      $compile.$$addBindingClass(templateElement);
      return function ngBindLink(scope, element, attr) {
        $compile.$$addBindingInfo(element, attr.ngBind);
        element = element[0];
        scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
          element.textContent = value === undefined ? '' : value;
        });
      };
    }
  };
}];


/**
 * @ngdoc directive
 * @name ngBindTemplate
 *
 * @description
 * The `ngBindTemplate` directive specifies that the element
 * text content should be replaced with the interpolation of the template
 * in the `ngBindTemplate` attribute.
 * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
 * expressions. This directive is needed since some HTML elements
 * (such as TITLE and OPTION) cannot contain SPAN elements.
 *
 * @element ANY
 * @param {string} ngBindTemplate template of form
 *   <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
 *
 * @example
 * Try it here: enter text in text box and watch the greeting change.
   <example module="bindExample">
     <file name="index.html">
       <script>
         angular.module('bindExample', [])
           .controller('ExampleController', ['$scope', function($scope) {
             $scope.salutation = 'Hello';
             $scope.name = 'World';
           }]);
       </script>
       <div ng-controller="ExampleController">
        <label>Salutation: <input type="text" ng-model="salutation"></label><br>
        <label>Name: <input type="text" ng-model="name"></label><br>
        <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
       </div>
     </file>
     <file name="protractor.js" type="protractor">
       it('should check ng-bind', function() {
         var salutationElem = element(by.binding('salutation'));
         var salutationInput = element(by.model('salutation'));
         var nameInput = element(by.model('name'));

         expect(salutationElem.getText()).toBe('Hello World!');

         salutationInput.clear();
         salutationInput.sendKeys('Greetings');
         nameInput.clear();
         nameInput.sendKeys('user');

         expect(salutationElem.getText()).toBe('Greetings user!');
       });
     </file>
   </example>
 */
var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  return {
    compile: function ngBindTemplateCompile(templateElement) {
      $compile.$$addBindingClass(templateElement);
      return function ngBindTemplateLink(scope, element, attr) {
        var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
        $compile.$$addBindingInfo(element, interpolateFn.expressions);
        element = element[0];
        attr.$observe('ngBindTemplate', function(value) {
          element.textContent = value === undefined ? '' : value;
        });
      };
    }
  };
}];


/**
 * @ngdoc directive
 * @name ngBindHtml
 *
 * @description
 * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
 * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
 * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
 * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
 * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
 *
 * You may also bypass sanitization for values you know are safe. To do so, bind to
 * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}.  See the example
 * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
 *
 * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
 * will have an exception (instead of an exploit.)
 *
 * @element ANY
 * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
 *
 * @example

   <example module="bindHtmlExample" deps="angular-sanitize.js">
     <file name="index.html">
       <div ng-controller="ExampleController">
        <p ng-bind-html="myHTML"></p>
       </div>
     </file>

     <file name="script.js">
       angular.module('bindHtmlExample', ['ngSanitize'])
         .controller('ExampleController', ['$scope', function($scope) {
           $scope.myHTML =
              'I am an <code>HTML</code>string with ' +
              '<a href="#">links!</a> and other <em>stuff</em>';
         }]);
     </file>

     <file name="protractor.js" type="protractor">
       it('should check ng-bind-html', function() {
         expect(element(by.binding('myHTML')).getText()).toBe(
             'I am an HTMLstring with links! and other stuff');
       });
     </file>
   </example>
 */
var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  return {
    restrict: 'A',
    compile: function ngBindHtmlCompile(tElement, tAttrs) {
      var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
      var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
        return (value || '').toString();
      });
      $compile.$$addBindingClass(tElement);

      return function ngBindHtmlLink(scope, element, attr) {
        $compile.$$addBindingInfo(element, attr.ngBindHtml);

        scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
          // we re-evaluate the expr because we want a TrustedValueHolderType
          // for $sce, not a string
          element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
        });
      };
    }
  };
}];

/**
 * @ngdoc directive
 * @name ngChange
 *
 * @description
 * Evaluate the given expression when the user changes the input.
 * The expression is evaluated immediately, unlike the JavaScript onchange event
 * which only triggers at the end of a change (usually, when the user leaves the
 * form element or presses the return key).
 *
 * The `ngChange` expression is only evaluated when a change in the input value causes
 * a new value to be committed to the model.
 *
 * It will not be evaluated:
 * * if the value returned from the `$parsers` transformation pipeline has not changed
 * * if the input has continued to be invalid since the model will stay `null`
 * * if the model is changed programmatically and not by a change to the input value
 *
 *
 * Note, this directive requires `ngModel` to be present.
 *
 * @element input
 * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
 * in input value.
 *
 * @example
 * <example name="ngChange-directive" module="changeExample">
 *   <file name="index.html">
 *     <script>
 *       angular.module('changeExample', [])
 *         .controller('ExampleController', ['$scope', function($scope) {
 *           $scope.counter = 0;
 *           $scope.change = function() {
 *             $scope.counter++;
 *           };
 *         }]);
 *     </script>
 *     <div ng-controller="ExampleController">
 *       <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
 *       <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
 *       <label for="ng-change-example2">Confirmed</label><br />
 *       <tt>debug = {{confirmed}}</tt><br/>
 *       <tt>counter = {{counter}}</tt><br/>
 *     </div>
 *   </file>
 *   <file name="protractor.js" type="protractor">
 *     var counter = element(by.binding('counter'));
 *     var debug = element(by.binding('confirmed'));
 *
 *     it('should evaluate the expression if changing from view', function() {
 *       expect(counter.getText()).toContain('0');
 *
 *       element(by.id('ng-change-example1')).click();
 *
 *       expect(counter.getText()).toContain('1');
 *       expect(debug.getText()).toContain('true');
 *     });
 *
 *     it('should not evaluate the expression if changing from model', function() {
 *       element(by.id('ng-change-example2')).click();

 *       expect(counter.getText()).toContain('0');
 *       expect(debug.getText()).toContain('true');
 *     });
 *   </file>
 * </example>
 */
var ngChangeDirective = valueFn({
  restrict: 'A',
  require: 'ngModel',
  link: function(scope, element, attr, ctrl) {
    ctrl.$viewChangeListeners.push(function() {
      scope.$eval(attr.ngChange);
    });
  }
});

function classDirective(name, selector) {
  name = 'ngClass' + name;
  return ['$animate', function($animate) {
    return {
      restrict: 'AC',
      link: function(scope, element, attr) {
        var oldVal;

        scope.$watch(attr[name], ngClassWatchAction, true);

        attr.$observe('class', function(value) {
          ngClassWatchAction(scope.$eval(attr[name]));
        });


        if (name !== 'ngClass') {
          scope.$watch('$index', function($index, old$index) {
            // jshint bitwise: false
            var mod = $index & 1;
            if (mod !== (old$index & 1)) {
              var classes = arrayClasses(scope.$eval(attr[name]));
              mod === selector ?
                addClasses(classes) :
                removeClasses(classes);
            }
          });
        }

        function addClasses(classes) {
          var newClasses = digestClassCounts(classes, 1);
          attr.$addClass(newClasses);
        }

        function removeClasses(classes) {
          var newClasses = digestClassCounts(classes, -1);
          attr.$removeClass(newClasses);
        }

        function digestClassCounts(classes, count) {
          // Use createMap() to prevent class assumptions involving property
          // names in Object.prototype
          var classCounts = element.data('$classCounts') || createMap();
          var classesToUpdate = [];
          forEach(classes, function(className) {
            if (count > 0 || classCounts[className]) {
              classCounts[className] = (classCounts[className] || 0) + count;
              if (classCounts[className] === +(count > 0)) {
                classesToUpdate.push(className);
              }
            }
          });
          element.data('$classCounts', classCounts);
          return classesToUpdate.join(' ');
        }

        function updateClasses(oldClasses, newClasses) {
          var toAdd = arrayDifference(newClasses, oldClasses);
          var toRemove = arrayDifference(oldClasses, newClasses);
          toAdd = digestClassCounts(toAdd, 1);
          toRemove = digestClassCounts(toRemove, -1);
          if (toAdd && toAdd.length) {
            $animate.addClass(element, toAdd);
          }
          if (toRemove && toRemove.length) {
            $animate.removeClass(element, toRemove);
          }
        }

        function ngClassWatchAction(newVal) {
          if (selector === true || scope.$index % 2 === selector) {
            var newClasses = arrayClasses(newVal || []);
            if (!oldVal) {
              addClasses(newClasses);
            } else if (!equals(newVal,oldVal)) {
              var oldClasses = arrayClasses(oldVal);
              updateClasses(oldClasses, newClasses);
            }
          }
          oldVal = shallowCopy(newVal);
        }
      }
    };

    function arrayDifference(tokens1, tokens2) {
      var values = [];

      outer:
      for (var i = 0; i < tokens1.length; i++) {
        var token = tokens1[i];
        for (var j = 0; j < tokens2.length; j++) {
          if (token == tokens2[j]) continue outer;
        }
        values.push(token);
      }
      return values;
    }

    function arrayClasses(classVal) {
      var classes = [];
      if (isArray(classVal)) {
        forEach(classVal, function(v) {
          classes = classes.concat(arrayClasses(v));
        });
        return classes;
      } else if (isString(classVal)) {
        return classVal.split(' ');
      } else if (isObject(classVal)) {
        forEach(classVal, function(v, k) {
          if (v) {
            classes = classes.concat(k.split(' '));
          }
        });
        return classes;
      }
      return classVal;
    }
  }];
}

/**
 * @ngdoc directive
 * @name ngClass
 * @restrict AC
 *
 * @description
 * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
 * an expression that represents all classes to be added.
 *
 * The directive operates in three different ways, depending on which of three types the expression
 * evaluates to:
 *
 * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
 * names.
 *
 * 2. If the expression evaluates to an object, then for each key-value pair of the
 * object with a truthy value the corresponding key is used as a class name.
 *
 * 3. If the expression evaluates to an array, each element of the array should either be a string as in
 * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
 * to give you more control over what CSS classes appear. See the code below for an example of this.
 *
 *
 * The directive won't add duplicate classes if a particular class was already set.
 *
 * When the expression changes, the previously added classes are removed and only then are the
 * new classes added.
 *
 * @animations
 * **add** - happens just before the class is applied to the elements
 *
 * **remove** - happens just before the class is removed from the element
 *
 * @element ANY
 * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
 *   of the evaluation can be a string representing space delimited class
 *   names, an array, or a map of class names to boolean values. In the case of a map, the
 *   names of the properties whose values are truthy will be added as css classes to the
 *   element.
 *
 * @example Example that demonstrates basic bindings via ngClass directive.
   <example>
     <file name="index.html">
       <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
       <label>
          <input type="checkbox" ng-model="deleted">
          deleted (apply "strike" class)
       </label><br>
       <label>
          <input type="checkbox" ng-model="important">
          important (apply "bold" class)
       </label><br>
       <label>
          <input type="checkbox" ng-model="error">
          error (apply "has-error" class)
       </label>
       <hr>
       <p ng-class="style">Using String Syntax</p>
       <input type="text" ng-model="style"
              placeholder="Type: bold strike red" aria-label="Type: bold strike red">
       <hr>
       <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
       <input ng-model="style1"
              placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
       <input ng-model="style2"
              placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
       <input ng-model="style3"
              placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
       <hr>
       <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
       <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
       <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
     </file>
     <file name="style.css">
       .strike {
           text-decoration: line-through;
       }
       .bold {
           font-weight: bold;
       }
       .red {
           color: red;
       }
       .has-error {
           color: red;
           background-color: yellow;
       }
       .orange {
           color: orange;
       }
     </file>
     <file name="protractor.js" type="protractor">
       var ps = element.all(by.css('p'));

       it('should let you toggle the class', function() {

         expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
         expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);

         element(by.model('important')).click();
         expect(ps.first().getAttribute('class')).toMatch(/bold/);

         element(by.model('error')).click();
         expect(ps.first().getAttribute('class')).toMatch(/has-error/);
       });

       it('should let you toggle string example', function() {
         expect(ps.get(1).getAttribute('class')).toBe('');
         element(by.model('style')).clear();
         element(by.model('style')).sendKeys('red');
         expect(ps.get(1).getAttribute('class')).toBe('red');
       });

       it('array example should have 3 classes', function() {
         expect(ps.get(2).getAttribute('class')).toBe('');
         element(by.model('style1')).sendKeys('bold');
         element(by.model('style2')).sendKeys('strike');
         element(by.model('style3')).sendKeys('red');
         expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
       });

       it('array with map example should have 2 classes', function() {
         expect(ps.last().getAttribute('class')).toBe('');
         element(by.model('style4')).sendKeys('bold');
         element(by.model('warning')).click();
         expect(ps.last().getAttribute('class')).toBe('bold orange');
       });
     </file>
   </example>

   ## Animations

   The example below demonstrates how to perform animations using ngClass.

   <example module="ngAnimate" deps="angular-animate.js" animations="true">
     <file name="index.html">
      <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
      <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
      <br>
      <span class="base-class" ng-class="myVar">Sample Text</span>
     </file>
     <file name="style.css">
       .base-class {
         -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
       }

       .base-class.my-class {
         color: red;
         font-size:3em;
       }
     </file>
     <file name="protractor.js" type="protractor">
       it('should check ng-class', function() {
         expect(element(by.css('.base-class')).getAttribute('class')).not.
           toMatch(/my-class/);

         element(by.id('setbtn')).click();

         expect(element(by.css('.base-class')).getAttribute('class')).
           toMatch(/my-class/);

         element(by.id('clearbtn')).click();

         expect(element(by.css('.base-class')).getAttribute('class')).not.
           toMatch(/my-class/);
       });
     </file>
   </example>


   ## ngClass and pre-existing CSS3 Transitions/Animations
   The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
   Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
   any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
   to view the step by step details of {@link $animate#addClass $animate.addClass} and
   {@link $animate#removeClass $animate.removeClass}.
 */
var ngClassDirective = classDirective('', true);

/**
 * @ngdoc directive
 * @name ngClassOdd
 * @restrict AC
 *
 * @description
 * The `ngClassOdd` and `ngClassEven` directives work exactly as
 * {@link ng.directive:ngClass ngClass}, except they work in
 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
 *
 * This directive can be applied only within the scope of an
 * {@link ng.directive:ngRepeat ngRepeat}.
 *
 * @element ANY
 * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
 *   of the evaluation can be a string representing space delimited class names or an array.
 *
 * @example
   <example>
     <file name="index.html">
        <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
          <li ng-repeat="name in names">
           <span ng-class-odd="'odd'" ng-class-even="'even'">
             {{name}}
           </span>
          </li>
        </ol>
     </file>
     <file name="style.css">
       .odd {
         color: red;
       }
       .even {
         color: blue;
       }
     </file>
     <file name="protractor.js" type="protractor">
       it('should check ng-class-odd and ng-class-even', function() {
         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
           toMatch(/odd/);
         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
           toMatch(/even/);
       });
     </file>
   </example>
 */
var ngClassOddDirective = classDirective('Odd', 0);

/**
 * @ngdoc directive
 * @name ngClassEven
 * @restrict AC
 *
 * @description
 * The `ngClassOdd` and `ngClassEven` directives work exactly as
 * {@link ng.directive:ngClass ngClass}, except they work in
 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
 *
 * This directive can be applied only within the scope of an
 * {@link ng.directive:ngRepeat ngRepeat}.
 *
 * @element ANY
 * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
 *   result of the evaluation can be a string representing space delimited class names or an array.
 *
 * @example
   <example>
     <file name="index.html">
        <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
          <li ng-repeat="name in names">
           <span ng-class-odd="'odd'" ng-class-even="'even'">
             {{name}} &nbsp; &nbsp; &nbsp;
           </span>
          </li>
        </ol>
     </file>
     <file name="style.css">
       .odd {
         color: red;
       }
       .even {
         color: blue;
       }
     </file>
     <file name="protractor.js" type="protractor">
       it('should check ng-class-odd and ng-class-even', function() {
         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
           toMatch(/odd/);
         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
           toMatch(/even/);
       });
     </file>
   </example>
 */
var ngClassEvenDirective = classDirective('Even', 1);

/**
 * @ngdoc directive
 * @name ngCloak
 * @restrict AC
 *
 * @description
 * The `ngCloak` directive is used to prevent the Angular html template from being briefly
 * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
 * directive to avoid the undesirable flicker effect caused by the html template display.
 *
 * The directive can be applied to the `<body>` element, but the preferred usage is to apply
 * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
 * of the browser view.
 *
 * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
 * `angular.min.js`.
 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
 *
 * ```css
 * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
 *   display: none !important;
 * }
 * ```
 *
 * When this css rule is loaded by the browser, all html elements (including their children) that
 * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
 * during the compilation of the template it deletes the `ngCloak` element attribute, making
 * the compiled element visible.
 *
 * For the best result, the `angular.js` script must be loaded in the head section of the html
 * document; alternatively, the css rule above must be included in the external stylesheet of the
 * application.
 *
 * @element ANY
 *
 * @example
   <example>
     <file name="index.html">
        <div id="template1" ng-cloak>{{ 'hello' }}</div>
        <div id="template2" class="ng-cloak">{{ 'world' }}</div>
     </file>
     <file name="protractor.js" type="protractor">
       it('should remove the template directive and css class', function() {
         expect($('#template1').getAttribute('ng-cloak')).
           toBeNull();
         expect($('#template2').getAttribute('ng-cloak')).
           toBeNull();
       });
     </file>
   </example>
 *
 */
var ngCloakDirective = ngDirective({
  compile: function(element, attr) {
    attr.$set('ngCloak', undefined);
    element.removeClass('ng-cloak');
  }
});

/**
 * @ngdoc directive
 * @name ngController
 *
 * @description
 * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
 * supports the principles behind the Model-View-Controller design pattern.
 *
 * MVC components in angular:
 *
 * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
 *   are accessed through bindings.
 * * View — The template (HTML with data bindings) that is rendered into the View.
 * * Controller — The `ngController` directive specifies a Controller class; the class contains business
 *   logic behind the application to decorate the scope with functions and values
 *
 * Note that you can also attach controllers to the DOM by declaring it in a route definition
 * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
 * again using `ng-controller` in the template itself.  This will cause the controller to be attached
 * and executed twice.
 *
 * @element ANY
 * @scope
 * @priority 500
 * @param {expression} ngController Name of a constructor function registered with the current
 * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
 * that on the current scope evaluates to a constructor function.
 *
 * The controller instance can be published into a scope property by specifying
 * `ng-controller="as propertyName"`.
 *
 * If the current `$controllerProvider` is configured to use globals (via
 * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
 * also be the name of a globally accessible constructor function (not recommended).
 *
 * @example
 * Here is a simple form for editing user contact information. Adding, removing, clearing, and
 * greeting are methods declared on the controller (see source tab). These methods can
 * easily be called from the angular markup. Any changes to the data are automatically reflected
 * in the View without the need for a manual update.
 *
 * Two different declaration styles are included below:
 *
 * * one binds methods and properties directly onto the controller using `this`:
 * `ng-controller="SettingsController1 as settings"`
 * * one injects `$scope` into the controller:
 * `ng-controller="SettingsController2"`
 *
 * The second option is more common in the Angular community, and is generally used in boilerplates
 * and in this guide. However, there are advantages to binding properties directly to the controller
 * and avoiding scope.
 *
 * * Using `controller as` makes it obvious which controller you are accessing in the template when
 * multiple controllers apply to an element.
 * * If you are writing your controllers as classes you have easier access to the properties and
 * methods, which will appear on the scope, from inside the controller code.
 * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
 * inheritance masking primitives.
 *
 * This example demonstrates the `controller as` syntax.
 *
 * <example name="ngControllerAs" module="controllerAsExample">
 *   <file name="index.html">
 *    <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
 *      <label>Name: <input type="text" ng-model="settings.name"/></label>
 *      <button ng-click="settings.greet()">greet</button><br/>
 *      Contact:
 *      <ul>
 *        <li ng-repeat="contact in settings.contacts">
 *          <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
 *             <option>phone</option>
 *             <option>email</option>
 *          </select>
 *          <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
 *          <button ng-click="settings.clearContact(contact)">clear</button>
 *          <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
 *        </li>
 *        <li><button ng-click="settings.addContact()">add</button></li>
 *     </ul>
 *    </div>
 *   </file>
 *   <file name="app.js">
 *    angular.module('controllerAsExample', [])
 *      .controller('SettingsController1', SettingsController1);
 *
 *    function SettingsController1() {
 *      this.name = "John Smith";
 *      this.contacts = [
 *        {type: 'phone', value: '408 555 1212'},
 *        {type: 'email', value: 'john.smith@example.org'} ];
 *    }
 *
 *    SettingsController1.prototype.greet = function() {
 *      alert(this.name);
 *    };
 *
 *    SettingsController1.prototype.addContact = function() {
 *      this.contacts.push({type: 'email', value: 'yourname@example.org'});
 *    };
 *
 *    SettingsController1.prototype.removeContact = function(contactToRemove) {
 *     var index = this.contacts.indexOf(contactToRemove);
 *      this.contacts.splice(index, 1);
 *    };
 *
 *    SettingsController1.prototype.clearContact = function(contact) {
 *      contact.type = 'phone';
 *      contact.value = '';
 *    };
 *   </file>
 *   <file name="protractor.js" type="protractor">
 *     it('should check controller as', function() {
 *       var container = element(by.id('ctrl-as-exmpl'));
 *         expect(container.element(by.model('settings.name'))
 *           .getAttribute('value')).toBe('John Smith');
 *
 *       var firstRepeat =
 *           container.element(by.repeater('contact in settings.contacts').row(0));
 *       var secondRepeat =
 *           container.element(by.repeater('contact in settings.contacts').row(1));
 *
 *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
 *           .toBe('408 555 1212');
 *
 *       expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
 *           .toBe('john.smith@example.org');
 *
 *       firstRepeat.element(by.buttonText('clear')).click();
 *
 *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
 *           .toBe('');
 *
 *       container.element(by.buttonText('add')).click();
 *
 *       expect(container.element(by.repeater('contact in settings.contacts').row(2))
 *           .element(by.model('contact.value'))
 *           .getAttribute('value'))
 *           .toBe('yourname@example.org');
 *     });
 *   </file>
 * </example>
 *
 * This example demonstrates the "attach to `$scope`" style of controller.
 *
 * <example name="ngController" module="controllerExample">
 *  <file name="index.html">
 *   <div id="ctrl-exmpl" ng-controller="SettingsController2">
 *     <label>Name: <input type="text" ng-model="name"/></label>
 *     <button ng-click="greet()">greet</button><br/>
 *     Contact:
 *     <ul>
 *       <li ng-repeat="contact in contacts">
 *         <select ng-model="contact.type" id="select_{{$index}}">
 *            <option>phone</option>
 *            <option>email</option>
 *         </select>
 *         <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
 *         <button ng-click="clearContact(contact)">clear</button>
 *         <button ng-click="removeContact(contact)">X</button>
 *       </li>
 *       <li>[ <button ng-click="addContact()">add</button> ]</li>
 *    </ul>
 *   </div>
 *  </file>
 *  <file name="app.js">
 *   angular.module('controllerExample', [])
 *     .controller('SettingsController2', ['$scope', SettingsController2]);
 *
 *   function SettingsController2($scope) {
 *     $scope.name = "John Smith";
 *     $scope.contacts = [
 *       {type:'phone', value:'408 555 1212'},
 *       {type:'email', value:'john.smith@example.org'} ];
 *
 *     $scope.greet = function() {
 *       alert($scope.name);
 *     };
 *
 *     $scope.addContact = function() {
 *       $scope.contacts.push({type:'email', value:'yourname@example.org'});
 *     };
 *
 *     $scope.removeContact = function(contactToRemove) {
 *       var index = $scope.contacts.indexOf(contactToRemove);
 *       $scope.contacts.splice(index, 1);
 *     };
 *
 *     $scope.clearContact = function(contact) {
 *       contact.type = 'phone';
 *       contact.value = '';
 *     };
 *   }
 *  </file>
 *  <file name="protractor.js" type="protractor">
 *    it('should check controller', function() {
 *      var container = element(by.id('ctrl-exmpl'));
 *
 *      expect(container.element(by.model('name'))
 *          .getAttribute('value')).toBe('John Smith');
 *
 *      var firstRepeat =
 *          container.element(by.repeater('contact in contacts').row(0));
 *      var secondRepeat =
 *          container.element(by.repeater('contact in contacts').row(1));
 *
 *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
 *          .toBe('408 555 1212');
 *      expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
 *          .toBe('john.smith@example.org');
 *
 *      firstRepeat.element(by.buttonText('clear')).click();
 *
 *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
 *          .toBe('');
 *
 *      container.element(by.buttonText('add')).click();
 *
 *      expect(container.element(by.repeater('contact in contacts').row(2))
 *          .element(by.model('contact.value'))
 *          .getAttribute('value'))
 *          .toBe('yourname@example.org');
 *    });
 *  </file>
 *</example>

 */
var ngControllerDirective = [function() {
  return {
    restrict: 'A',
    scope: true,
    controller: '@',
    priority: 500
  };
}];

/**
 * @ngdoc directive
 * @name ngCsp
 *
 * @element html
 * @description
 * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
 *
 * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
 *
 * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
 * For Angular to be CSP compatible there are only two things that we need to do differently:
 *
 * - don't use `Function` constructor to generate optimized value getters
 * - don't inject custom stylesheet into the document
 *
 * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
 * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
 * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
 * be raised.
 *
 * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
 * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
 * To make those directives work in CSP mode, include the `angular-csp.css` manually.
 *
 * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
 * autodetection however triggers a CSP error to be logged in the console:
 *
 * ```
 * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
 * script in the following Content Security Policy directive: "default-src 'self'". Note that
 * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
 * ```
 *
 * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
 * directive on the root element of the application or on the `angular.js` script tag, whichever
 * appears first in the html document.
 *
 * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
 *
 * @example
 * This example shows how to apply the `ngCsp` directive to the `html` tag.
   ```html
     <!doctype html>
     <html ng-app ng-csp>
     ...
     ...
     </html>
   ```
  * @example
      // Note: the suffix `.csp` in the example name triggers
      // csp mode in our http server!
      <example name="example.csp" module="cspExample" ng-csp="true">
        <file name="index.html">
          <div ng-controller="MainController as ctrl">
            <div>
              <button ng-click="ctrl.inc()" id="inc">Increment</button>
              <span id="counter">
                {{ctrl.counter}}
              </span>
            </div>

            <div>
              <button ng-click="ctrl.evil()" id="evil">Evil</button>
              <span id="evilError">
                {{ctrl.evilError}}
              </span>
            </div>
          </div>
        </file>
        <file name="script.js">
           angular.module('cspExample', [])
             .controller('MainController', function() {
                this.counter = 0;
                this.inc = function() {
                  this.counter++;
                };
                this.evil = function() {
                  // jshint evil:true
                  try {
                    eval('1+2');
                  } catch (e) {
                    this.evilError = e.message;
                  }
                };
              });
        </file>
        <file name="protractor.js" type="protractor">
          var util, webdriver;

          var incBtn = element(by.id('inc'));
          var counter = element(by.id('counter'));
          var evilBtn = element(by.id('evil'));
          var evilError = element(by.id('evilError'));

          function getAndClearSevereErrors() {
            return browser.manage().logs().get('browser').then(function(browserLog) {
              return browserLog.filter(function(logEntry) {
                return logEntry.level.value > webdriver.logging.Level.WARNING.value;
              });
            });
          }

          function clearErrors() {
            getAndClearSevereErrors();
          }

          function expectNoErrors() {
            getAndClearSevereErrors().then(function(filteredLog) {
              expect(filteredLog.length).toEqual(0);
              if (filteredLog.length) {
                console.log('browser console errors: ' + util.inspect(filteredLog));
              }
            });
          }

          function expectError(regex) {
            getAndClearSevereErrors().then(function(filteredLog) {
              var found = false;
              filteredLog.forEach(function(log) {
                if (log.message.match(regex)) {
                  found = true;
                }
              });
              if (!found) {
                throw new Error('expected an error that matches ' + regex);
              }
            });
          }

          beforeEach(function() {
            util = require('util');
            webdriver = require('protractor/node_modules/selenium-webdriver');
          });

          // For now, we only test on Chrome,
          // as Safari does not load the page with Protractor's injected scripts,
          // and Firefox webdriver always disables content security policy (#6358)
          if (browser.params.browser !== 'chrome') {
            return;
          }

          it('should not report errors when the page is loaded', function() {
            // clear errors so we are not dependent on previous tests
            clearErrors();
            // Need to reload the page as the page is already loaded when
            // we come here
            browser.driver.getCurrentUrl().then(function(url) {
              browser.get(url);
            });
            expectNoErrors();
          });

          it('should evaluate expressions', function() {
            expect(counter.getText()).toEqual('0');
            incBtn.click();
            expect(counter.getText()).toEqual('1');
            expectNoErrors();
          });

          it('should throw and report an error when using "eval"', function() {
            evilBtn.click();
            expect(evilError.getText()).toMatch(/Content Security Policy/);
            expectError(/Content Security Policy/);
          });
        </file>
      </example>
  */

// ngCsp is not implemented as a proper directive any more, because we need it be processed while we
// bootstrap the system (before $parse is instantiated), for this reason we just have
// the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc

/**
 * @ngdoc directive
 * @name ngClick
 *
 * @description
 * The ngClick directive allows you to specify custom behavior when
 * an element is clicked.
 *
 * @element ANY
 * @priority 0
 * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
 * click. ({@link guide/expression#-event- Event object is available as `$event`})
 *
 * @example
   <example>
     <file name="index.html">
      <button ng-click="count = count + 1" ng-init="count=0">
        Increment
      </button>
      <span>
        count: {{count}}
      </span>
     </file>
     <file name="protractor.js" type="protractor">
       it('should check ng-click', function() {
         expect(element(by.binding('count')).getText()).toMatch('0');
         element(by.css('button')).click();
         expect(element(by.binding('count')).getText()).toMatch('1');
       });
     </file>
   </example>
 */
/*
 * A collection of directives that allows creation of custom event handlers that are defined as
 * angular expressions and are compiled and executed within the current scope.
 */
var ngEventDirectives = {};

// For events that might fire synchronously during DOM manipulation
// we need to execute their event handlers asynchronously using $evalAsync,
// so that they are not executed in an inconsistent state.
var forceAsyncEvents = {
  'blur': true,
  'focus': true
};
forEach(
  'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  function(eventName) {
    var directiveName = directiveNormalize('ng-' + eventName);
    ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
      return {
        restrict: 'A',
        compile: function($element, attr) {
          // We expose the powerful $event object on the scope that provides access to the Window,
          // etc. that isn't protected by the fast paths in $parse.  We explicitly request better
          // checks at the cost of speed since event handler expressions are not executed as
          // frequently as regular change detection.
          var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
          return function ngEventHandler(scope, element) {
            element.on(eventName, function(event) {
              var callback = function() {
                fn(scope, {$event:event});
              };
              if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
                scope.$evalAsync(callback);
              } else {
                scope.$apply(callback);
              }
            });
          };
        }
      };
    }];
  }
);

/**
 * @ngdoc directive
 * @name ngDblclick
 *
 * @description
 * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
 *
 * @element ANY
 * @priority 0
 * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
 * a dblclick. (The Event object is available as `$event`)
 *
 * @example
   <example>
     <file name="index.html">
      <button ng-dblclick="count = count + 1" ng-init="count=0">
        Increment (on double click)
      </button>
      count: {{count}}
     </file>
   </example>
 */


/**
 * @ngdoc directive
 * @name ngMousedown
 *
 * @description
 * The ngMousedown directive allows you to specify custom behavior on mousedown event.
 *
 * @element ANY
 * @priority 0
 * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
 * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
 *
 * @example
   <example>
     <file name="index.html">
      <button ng-mousedown="count = count + 1" ng-init="count=0">
        Increment (on mouse down)
      </button>
      count: {{count}}
     </file>
   </example>
 */


/**
 * @ngdoc directive
 * @name ngMouseup
 *
 * @description
 * Specify custom behavior on mouseup event.
 *
 * @element ANY
 * @priority 0
 * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
 * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
 *
 * @example
   <example>
     <file name="index.html">
      <button ng-mouseup="count = count + 1" ng-init="count=0">
        Increment (on mouse up)
      </button>
      count: {{count}}
     </file>
   </example>
 */

/**
 * @ngdoc directive
 * @name ngMouseover
 *
 * @description
 * Specify custom behavior on mouseover event.
 *
 * @element ANY
 * @priority 0
 * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
 * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
 *
 * @example
   <example>
     <file name="index.html">
      <button ng-mouseover="count = count + 1" ng-init="count=0">
        Increment (when mouse is over)
      </button>
      count: {{count}}
     </file>
   </example>
 */


/**
 * @ngdoc directive
 * @name ngMouseenter
 *
 * @description
 * Specify custom behavior on mouseenter event.
 *
 * @element ANY
 * @priority 0
 * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
 * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
 *
 * @example
   <example>
     <file name="index.html">
      <button ng-mouseenter="count = count + 1" ng-init="count=0">
        Increment (when mouse enters)
      </button>
      count: {{count}}
     </file>
   </example>
 */


/**
 * @ngdoc directive
 * @name ngMouseleave
 *
 * @description
 * Specify custom behavior on mouseleave event.
 *
 * @element ANY
 * @priority 0
 * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
 * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
 *
 * @example
   <example>
     <file name="index.html">
      <button ng-mouseleave="count = count + 1" ng-init="count=0">
        Increment (when mouse leaves)
      </button>
      count: {{count}}
     </file>
   </example>
 */


/**
 * @ngdoc directive
 * @name ngMousemove
 *
 * @description
 * Specify custom behavior on mousemove event.
 *
 * @element ANY
 * @priority 0
 * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
 * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
 *
 * @example
   <example>
     <file name="index.html">
      <button ng-mousemove="count = count + 1" ng-init="count=0">
        Increment (when mouse moves)
      </button>
      count: {{count}}
     </file>
   </example>
 */


/**
 * @ngdoc directive
 * @name ngKeydown
 *
 * @description
 * Specify custom behavior on keydown event.
 *
 * @element ANY
 * @priority 0
 * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
 * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
 *
 * @example
   <example>
     <file name="index.html">
      <input ng-keydown="count = count + 1" ng-init="count=0">
      key down count: {{count}}
     </file>
   </example>
 */


/**
 * @ngdoc directive
 * @name ngKeyup
 *
 * @description
 * Specify custom behavior on keyup event.
 *
 * @element ANY
 * @priority 0
 * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
 * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
 *
 * @example
   <example>
     <file name="index.html">
       <p>Typing in the input box below updates the key count</p>
       <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}

       <p>Typing in the input box below updates the keycode</p>
       <input ng-keyup="event=$event">
       <p>event keyCode: {{ event.keyCode }}</p>
       <p>event altKey: {{ event.altKey }}</p>
     </file>
   </example>
 */


/**
 * @ngdoc directive
 * @name ngKeypress
 *
 * @description
 * Specify custom behavior on keypress event.
 *
 * @element ANY
 * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
 * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
 * and can be interrogated for keyCode, altKey, etc.)
 *
 * @example
   <example>
     <file name="index.html">
      <input ng-keypress="count = count + 1" ng-init="count=0">
      key press count: {{count}}
     </file>
   </example>
 */


/**
 * @ngdoc directive
 * @name ngSubmit
 *
 * @description
 * Enables binding angular expressions to onsubmit events.
 *
 * Additionally it prevents the default action (which for form means sending the request to the
 * server and reloading the current page), but only if the form does not contain `action`,
 * `data-action`, or `x-action` attributes.
 *
 * <div class="alert alert-warning">
 * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
 * `ngSubmit` handlers together. See the
 * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
 * for a detailed discussion of when `ngSubmit` may be triggered.
 * </div>
 *
 * @element form
 * @priority 0
 * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
 * ({@link guide/expression#-event- Event object is available as `$event`})
 *
 * @example
   <example module="submitExample">
     <file name="index.html">
      <script>
        angular.module('submitExample', [])
          .controller('ExampleController', ['$scope', function($scope) {
            $scope.list = [];
            $scope.text = 'hello';
            $scope.submit = function() {
              if ($scope.text) {
                $scope.list.push(this.text);
                $scope.text = '';
              }
            };
          }]);
      </script>
      <form ng-submit="submit()" ng-controller="ExampleController">
        Enter text and hit enter:
        <input type="text" ng-model="text" name="text" />
        <input type="submit" id="submit" value="Submit" />
        <pre>list={{list}}</pre>
      </form>
     </file>
     <file name="protractor.js" type="protractor">
       it('should check ng-submit', function() {
         expect(element(by.binding('list')).getText()).toBe('list=[]');
         element(by.css('#submit')).click();
         expect(element(by.binding('list')).getText()).toContain('hello');
         expect(element(by.model('text')).getAttribute('value')).toBe('');
       });
       it('should ignore empty strings', function() {
         expect(element(by.binding('list')).getText()).toBe('list=[]');
         element(by.css('#submit')).click();
         element(by.css('#submit')).click();
         expect(element(by.binding('list')).getText()).toContain('hello');
        });
     </file>
   </example>
 */

/**
 * @ngdoc directive
 * @name ngFocus
 *
 * @description
 * Specify custom behavior on focus event.
 *
 * Note: As the `focus` event is executed synchronously when calling `input.focus()`
 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
 * during an `$apply` to ensure a consistent state.
 *
 * @element window, input, select, textarea, a
 * @priority 0
 * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
 * focus. ({@link guide/expression#-event- Event object is available as `$event`})
 *
 * @example
 * See {@link ng.directive:ngClick ngClick}
 */

/**
 * @ngdoc directive
 * @name ngBlur
 *
 * @description
 * Specify custom behavior on blur event.
 *
 * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
 * an element has lost focus.
 *
 * Note: As the `blur` event is executed synchronously also during DOM manipulations
 * (e.g. removing a focussed input),
 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
 * during an `$apply` to ensure a consistent state.
 *
 * @element window, input, select, textarea, a
 * @priority 0
 * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
 * blur. ({@link guide/expression#-event- Event object is available as `$event`})
 *
 * @example
 * See {@link ng.directive:ngClick ngClick}
 */

/**
 * @ngdoc directive
 * @name ngCopy
 *
 * @description
 * Specify custom behavior on copy event.
 *
 * @element window, input, select, textarea, a
 * @priority 0
 * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
 * copy. ({@link guide/expression#-event- Event object is available as `$event`})
 *
 * @example
   <example>
     <file name="index.html">
      <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
      copied: {{copied}}
     </file>
   </example>
 */

/**
 * @ngdoc directive
 * @name ngCut
 *
 * @description
 * Specify custom behavior on cut event.
 *
 * @element window, input, select, textarea, a
 * @priority 0
 * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
 * cut. ({@link guide/expression#-event- Event object is available as `$event`})
 *
 * @example
   <example>
     <file name="index.html">
      <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
      cut: {{cut}}
     </file>
   </example>
 */

/**
 * @ngdoc directive
 * @name ngPaste
 *
 * @description
 * Specify custom behavior on paste event.
 *
 * @element window, input, select, textarea, a
 * @priority 0
 * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
 * paste. ({@link guide/expression#-event- Event object is available as `$event`})
 *
 * @example
   <example>
     <file name="index.html">
      <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
      pasted: {{paste}}
     </file>
   </example>
 */

/**
 * @ngdoc directive
 * @name ngIf
 * @restrict A
 * @multiElement
 *
 * @description
 * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
 * {expression}. If the expression assigned to `ngIf` evaluates to a false
 * value then the element is removed from the DOM, otherwise a clone of the
 * element is reinserted into the DOM.
 *
 * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
 * element in the DOM rather than changing its visibility via the `display` css property.  A common
 * case when this difference is significant is when using css selectors that rely on an element's
 * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
 *
 * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
 * is created when the element is restored.  The scope created within `ngIf` inherits from
 * its parent scope using
 * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
 * An important implication of this is if `ngModel` is used within `ngIf` to bind to
 * a javascript primitive defined in the parent scope. In this case any modifications made to the
 * variable within the child scope will override (hide) the value in the parent scope.
 *
 * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
 * is if an element's class attribute is directly modified after it's compiled, using something like
 * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
 * the added class will be lost because the original compiled state is used to regenerate the element.
 *
 * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
 * and `leave` effects.
 *
 * @animations
 * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
 * leave - happens just before the `ngIf` contents are removed from the DOM
 *
 * @element ANY
 * @scope
 * @priority 600
 * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
 *     the element is removed from the DOM tree. If it is truthy a copy of the compiled
 *     element is added to the DOM tree.
 *
 * @example
  <example module="ngAnimate" deps="angular-animate.js" animations="true">
    <file name="index.html">
      <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
      Show when checked:
      <span ng-if="checked" class="animate-if">
        This is removed when the checkbox is unchecked.
      </span>
    </file>
    <file name="animations.css">
      .animate-if {
        background:white;
        border:1px solid black;
        padding:10px;
      }

      .animate-if.ng-enter, .animate-if.ng-leave {
        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
      }

      .animate-if.ng-enter,
      .animate-if.ng-leave.ng-leave-active {
        opacity:0;
      }

      .animate-if.ng-leave,
      .animate-if.ng-enter.ng-enter-active {
        opacity:1;
      }
    </file>
  </example>
 */
var ngIfDirective = ['$animate', function($animate) {
  return {
    multiElement: true,
    transclude: 'element',
    priority: 600,
    terminal: true,
    restrict: 'A',
    $$tlb: true,
    link: function($scope, $element, $attr, ctrl, $transclude) {
        var block, childScope, previousElements;
        $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {

          if (value) {
            if (!childScope) {
              $transclude(function(clone, newScope) {
                childScope = newScope;
                clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
                // Note: We only need the first/last node of the cloned nodes.
                // However, we need to keep the reference to the jqlite wrapper as it might be changed later
                // by a directive with templateUrl when its template arrives.
                block = {
                  clone: clone
                };
                $animate.enter(clone, $element.parent(), $element);
              });
            }
          } else {
            if (previousElements) {
              previousElements.remove();
              previousElements = null;
            }
            if (childScope) {
              childScope.$destroy();
              childScope = null;
            }
            if (block) {
              previousElements = getBlockNodes(block.clone);
              $animate.leave(previousElements).then(function() {
                previousElements = null;
              });
              block = null;
            }
          }
        });
    }
  };
}];

/**
 * @ngdoc directive
 * @name ngInclude
 * @restrict ECA
 *
 * @description
 * Fetches, compiles and includes an external HTML fragment.
 *
 * By default, the template URL is restricted to the same domain and protocol as the
 * application document. This is done by calling {@link $sce#getTrustedResourceUrl
 * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
 * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
 * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
 * ng.$sce Strict Contextual Escaping}.
 *
 * In addition, the browser's
 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
 * policy may further restrict whether the template is successfully loaded.
 * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
 * access on some browsers.
 *
 * @animations
 * enter - animation is used to bring new content into the browser.
 * leave - animation is used to animate existing content away.
 *
 * The enter and leave animation occur concurrently.
 *
 * @scope
 * @priority 400
 *
 * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
 *                 make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
 * @param {string=} onload Expression to evaluate when a new partial is loaded.
 *
 * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
 *                  $anchorScroll} to scroll the viewport after the content is loaded.
 *
 *                  - If the attribute is not set, disable scrolling.
 *                  - If the attribute is set without value, enable scrolling.
 *                  - Otherwise enable scrolling only if the expression evaluates to truthy value.
 *
 * @example
  <example module="includeExample" deps="angular-animate.js" animations="true">
    <file name="index.html">
     <div ng-controller="ExampleController">
       <select ng-model="template" ng-options="t.name for t in templates">
        <option value="">(blank)</option>
       </select>
       url of the template: <code>{{template.url}}</code>
       <hr/>
       <div class="slide-animate-container">
         <div class="slide-animate" ng-include="template.url"></div>
       </div>
     </div>
    </file>
    <file name="script.js">
      angular.module('includeExample', ['ngAnimate'])
        .controller('ExampleController', ['$scope', function($scope) {
          $scope.templates =
            [ { name: 'template1.html', url: 'template1.html'},
              { name: 'template2.html', url: 'template2.html'} ];
          $scope.template = $scope.templates[0];
        }]);
     </file>
    <file name="template1.html">
      Content of template1.html
    </file>
    <file name="template2.html">
      Content of template2.html
    </file>
    <file name="animations.css">
      .slide-animate-container {
        position:relative;
        background:white;
        border:1px solid black;
        height:40px;
        overflow:hidden;
      }

      .slide-animate {
        padding:10px;
      }

      .slide-animate.ng-enter, .slide-animate.ng-leave {
        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;

        position:absolute;
        top:0;
        left:0;
        right:0;
        bottom:0;
        display:block;
        padding:10px;
      }

      .slide-animate.ng-enter {
        top:-50px;
      }
      .slide-animate.ng-enter.ng-enter-active {
        top:0;
      }

      .slide-animate.ng-leave {
        top:0;
      }
      .slide-animate.ng-leave.ng-leave-active {
        top:50px;
      }
    </file>
    <file name="protractor.js" type="protractor">
      var templateSelect = element(by.model('template'));
      var includeElem = element(by.css('[ng-include]'));

      it('should load template1.html', function() {
        expect(includeElem.getText()).toMatch(/Content of template1.html/);
      });

      it('should load template2.html', function() {
        if (browser.params.browser == 'firefox') {
          // Firefox can't handle using selects
          // See https://github.com/angular/protractor/issues/480
          return;
        }
        templateSelect.click();
        templateSelect.all(by.css('option')).get(2).click();
        expect(includeElem.getText()).toMatch(/Content of template2.html/);
      });

      it('should change to blank', function() {
        if (browser.params.browser == 'firefox') {
          // Firefox can't handle using selects
          return;
        }
        templateSelect.click();
        templateSelect.all(by.css('option')).get(0).click();
        expect(includeElem.isPresent()).toBe(false);
      });
    </file>
  </example>
 */


/**
 * @ngdoc event
 * @name ngInclude#$includeContentRequested
 * @eventType emit on the scope ngInclude was declared in
 * @description
 * Emitted every time the ngInclude content is requested.
 *
 * @param {Object} angularEvent Synthetic event object.
 * @param {String} src URL of content to load.
 */


/**
 * @ngdoc event
 * @name ngInclude#$includeContentLoaded
 * @eventType emit on the current ngInclude scope
 * @description
 * Emitted every time the ngInclude content is reloaded.
 *
 * @param {Object} angularEvent Synthetic event object.
 * @param {String} src URL of content to load.
 */


/**
 * @ngdoc event
 * @name ngInclude#$includeContentError
 * @eventType emit on the scope ngInclude was declared in
 * @description
 * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
 *
 * @param {Object} angularEvent Synthetic event object.
 * @param {String} src URL of content to load.
 */
var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
                  function($templateRequest,   $anchorScroll,   $animate) {
  return {
    restrict: 'ECA',
    priority: 400,
    terminal: true,
    transclude: 'element',
    controller: angular.noop,
    compile: function(element, attr) {
      var srcExp = attr.ngInclude || attr.src,
          onloadExp = attr.onload || '',
          autoScrollExp = attr.autoscroll;

      return function(scope, $element, $attr, ctrl, $transclude) {
        var changeCounter = 0,
            currentScope,
            previousElement,
            currentElement;

        var cleanupLastIncludeContent = function() {
          if (previousElement) {
            previousElement.remove();
            previousElement = null;
          }
          if (currentScope) {
            currentScope.$destroy();
            currentScope = null;
          }
          if (currentElement) {
            $animate.leave(currentElement).then(function() {
              previousElement = null;
            });
            previousElement = currentElement;
            currentElement = null;
          }
        };

        scope.$watch(srcExp, function ngIncludeWatchAction(src) {
          var afterAnimation = function() {
            if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
              $anchorScroll();
            }
          };
          var thisChangeId = ++changeCounter;

          if (src) {
            //set the 2nd param to true to ignore the template request error so that the inner
            //contents and scope can be cleaned up.
            $templateRequest(src, true).then(function(response) {
              if (thisChangeId !== changeCounter) return;
              var newScope = scope.$new();
              ctrl.template = response;

              // Note: This will also link all children of ng-include that were contained in the original
              // html. If that content contains controllers, ... they could pollute/change the scope.
              // However, using ng-include on an element with additional content does not make sense...
              // Note: We can't remove them in the cloneAttchFn of $transclude as that
              // function is called before linking the content, which would apply child
              // directives to non existing elements.
              var clone = $transclude(newScope, function(clone) {
                cleanupLastIncludeContent();
                $animate.enter(clone, null, $element).then(afterAnimation);
              });

              currentScope = newScope;
              currentElement = clone;

              currentScope.$emit('$includeContentLoaded', src);
              scope.$eval(onloadExp);
            }, function() {
              if (thisChangeId === changeCounter) {
                cleanupLastIncludeContent();
                scope.$emit('$includeContentError', src);
              }
            });
            scope.$emit('$includeContentRequested', src);
          } else {
            cleanupLastIncludeContent();
            ctrl.template = null;
          }
        });
      };
    }
  };
}];

// This directive is called during the $transclude call of the first `ngInclude` directive.
// It will replace and compile the content of the element with the loaded template.
// We need this directive so that the element content is already filled when
// the link function of another directive on the same element as ngInclude
// is called.
var ngIncludeFillContentDirective = ['$compile',
  function($compile) {
    return {
      restrict: 'ECA',
      priority: -400,
      require: 'ngInclude',
      link: function(scope, $element, $attr, ctrl) {
        if (/SVG/.test($element[0].toString())) {
          // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
          // support innerHTML, so detect this here and try to generate the contents
          // specially.
          $element.empty();
          $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
              function namespaceAdaptedClone(clone) {
            $element.append(clone);
          }, {futureParentElement: $element});
          return;
        }

        $element.html(ctrl.template);
        $compile($element.contents())(scope);
      }
    };
  }];

/**
 * @ngdoc directive
 * @name ngInit
 * @restrict AC
 *
 * @description
 * The `ngInit` directive allows you to evaluate an expression in the
 * current scope.
 *
 * <div class="alert alert-danger">
 * The only appropriate use of `ngInit` is for aliasing special properties of
 * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
 * should use {@link guide/controller controllers} rather than `ngInit`
 * to initialize values on a scope.
 * </div>
 * <div class="alert alert-warning">
 * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
 * sure you have parenthesis for correct precedence:
 * <pre class="prettyprint">
 * `<div ng-init="test1 = (data | orderBy:'name')"></div>`
 * </pre>
 * </div>
 *
 * @priority 450
 *
 * @element ANY
 * @param {expression} ngInit {@link guide/expression Expression} to eval.
 *
 * @example
   <example module="initExample">
     <file name="index.html">
   <script>
     angular.module('initExample', [])
       .controller('ExampleController', ['$scope', function($scope) {
         $scope.list = [['a', 'b'], ['c', 'd']];
       }]);
   </script>
   <div ng-controller="ExampleController">
     <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
       <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
          <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
       </div>
     </div>
   </div>
     </file>
     <file name="protractor.js" type="protractor">
       it('should alias index positions', function() {
         var elements = element.all(by.css('.example-init'));
         expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
         expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
         expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
         expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
       });
     </file>
   </example>
 */
var ngInitDirective = ngDirective({
  priority: 450,
  compile: function() {
    return {
      pre: function(scope, element, attrs) {
        scope.$eval(attrs.ngInit);
      }
    };
  }
});

/**
 * @ngdoc directive
 * @name ngList
 *
 * @description
 * Text input that converts between a delimited string and an array of strings. The default
 * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
 * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
 *
 * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
 * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
 *   list item is respected. This implies that the user of the directive is responsible for
 *   dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
 *   tab or newline character.
 * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
 *   when joining the list items back together) and whitespace around each list item is stripped
 *   before it is added to the model.
 *
 * ### Example with Validation
 *
 * <example name="ngList-directive" module="listExample">
 *   <file name="app.js">
 *      angular.module('listExample', [])
 *        .controller('ExampleController', ['$scope', function($scope) {
 *          $scope.names = ['morpheus', 'neo', 'trinity'];
 *        }]);
 *   </file>
 *   <file name="index.html">
 *    <form name="myForm" ng-controller="ExampleController">
 *      <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
 *      <span role="alert">
 *        <span class="error" ng-show="myForm.namesInput.$error.required">
 *        Required!</span>
 *      </span>
 *      <br>
 *      <tt>names = {{names}}</tt><br/>
 *      <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
 *      <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
 *      <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
 *      <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
 *     </form>
 *   </file>
 *   <file name="protractor.js" type="protractor">
 *     var listInput = element(by.model('names'));
 *     var names = element(by.exactBinding('names'));
 *     var valid = element(by.binding('myForm.namesInput.$valid'));
 *     var error = element(by.css('span.error'));
 *
 *     it('should initialize to model', function() {
 *       expect(names.getText()).toContain('["morpheus","neo","trinity"]');
 *       expect(valid.getText()).toContain('true');
 *       expect(error.getCssValue('display')).toBe('none');
 *     });
 *
 *     it('should be invalid if empty', function() {
 *       listInput.clear();
 *       listInput.sendKeys('');
 *
 *       expect(names.getText()).toContain('');
 *       expect(valid.getText()).toContain('false');
 *       expect(error.getCssValue('display')).not.toBe('none');
 *     });
 *   </file>
 * </example>
 *
 * ### Example - splitting on whitespace
 * <example name="ngList-directive-newlines">
 *   <file name="index.html">
 *    <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
 *    <pre>{{ list | json }}</pre>
 *   </file>
 *   <file name="protractor.js" type="protractor">
 *     it("should split the text by newlines", function() {
 *       var listInput = element(by.model('list'));
 *       var output = element(by.binding('list | json'));
 *       listInput.sendKeys('abc\ndef\nghi');
 *       expect(output.getText()).toContain('[\n  "abc",\n  "def",\n  "ghi"\n]');
 *     });
 *   </file>
 * </example>
 *
 * @element input
 * @param {string=} ngList optional delimiter that should be used to split the value.
 */
var ngListDirective = function() {
  return {
    restrict: 'A',
    priority: 100,
    require: 'ngModel',
    link: function(scope, element, attr, ctrl) {
      // We want to control whitespace trimming so we use this convoluted approach
      // to access the ngList attribute, which doesn't pre-trim the attribute
      var ngList = element.attr(attr.$attr.ngList) || ', ';
      var trimValues = attr.ngTrim !== 'false';
      var separator = trimValues ? trim(ngList) : ngList;

      var parse = function(viewValue) {
        // If the viewValue is invalid (say required but empty) it will be `undefined`
        if (isUndefined(viewValue)) return;

        var list = [];

        if (viewValue) {
          forEach(viewValue.split(separator), function(value) {
            if (value) list.push(trimValues ? trim(value) : value);
          });
        }

        return list;
      };

      ctrl.$parsers.push(parse);
      ctrl.$formatters.push(function(value) {
        if (isArray(value)) {
          return value.join(ngList);
        }

        return undefined;
      });

      // Override the standard $isEmpty because an empty array means the input is empty.
      ctrl.$isEmpty = function(value) {
        return !value || !value.length;
      };
    }
  };
};

/* global VALID_CLASS: true,
  INVALID_CLASS: true,
  PRISTINE_CLASS: true,
  DIRTY_CLASS: true,
  UNTOUCHED_CLASS: true,
  TOUCHED_CLASS: true,
*/

var VALID_CLASS = 'ng-valid',
    INVALID_CLASS = 'ng-invalid',
    PRISTINE_CLASS = 'ng-pristine',
    DIRTY_CLASS = 'ng-dirty',
    UNTOUCHED_CLASS = 'ng-untouched',
    TOUCHED_CLASS = 'ng-touched',
    PENDING_CLASS = 'ng-pending';


var $ngModelMinErr = new minErr('ngModel');

/**
 * @ngdoc type
 * @name ngModel.NgModelController
 *
 * @property {string} $viewValue Actual string value in the view.
 * @property {*} $modelValue The value in the model that the control is bound to.
 * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
       the control reads value from the DOM. The functions are called in array order, each passing
       its return value through to the next. The last return value is forwarded to the
       {@link ngModel.NgModelController#$validators `$validators`} collection.

Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
`$viewValue`}.

Returning `undefined` from a parser means a parse error occurred. In that case,
no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
is set to `true`. The parse error is stored in `ngModel.$error.parse`.

 *
 * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
       the model value changes. The functions are called in reverse array order, each passing the value through to the
       next. The last return value is used as the actual DOM value.
       Used to format / convert values for display in the control.
 * ```js
 * function formatter(value) {
 *   if (value) {
 *     return value.toUpperCase();
 *   }
 * }
 * ngModel.$formatters.push(formatter);
 * ```
 *
 * @property {Object.<string, function>} $validators A collection of validators that are applied
 *      whenever the model value changes. The key value within the object refers to the name of the
 *      validator while the function refers to the validation operation. The validation operation is
 *      provided with the model value as an argument and must return a true or false value depending
 *      on the response of that validation.
 *
 * ```js
 * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
 *   var value = modelValue || viewValue;
 *   return /[0-9]+/.test(value) &&
 *          /[a-z]+/.test(value) &&
 *          /[A-Z]+/.test(value) &&
 *          /\W+/.test(value);
 * };
 * ```
 *
 * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
 *      perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
 *      is expected to return a promise when it is run during the model validation process. Once the promise
 *      is delivered then the validation status will be set to true when fulfilled and false when rejected.
 *      When the asynchronous validators are triggered, each of the validators will run in parallel and the model
 *      value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
 *      is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
 *      will only run once all synchronous validators have passed.
 *
 * Please note that if $http is used then it is important that the server returns a success HTTP response code
 * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
 *
 * ```js
 * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
 *   var value = modelValue || viewValue;
 *
 *   // Lookup user by username
 *   return $http.get('/api/users/' + value).
 *      then(function resolved() {
 *        //username exists, this means validation fails
 *        return $q.reject('exists');
 *      }, function rejected() {
 *        //username does not exist, therefore this validation passes
 *        return true;
 *      });
 * };
 * ```
 *
 * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
 *     view value has changed. It is called with no arguments, and its return value is ignored.
 *     This can be used in place of additional $watches against the model value.
 *
 * @property {Object} $error An object hash with all failing validator ids as keys.
 * @property {Object} $pending An object hash with all pending validator ids as keys.
 *
 * @property {boolean} $untouched True if control has not lost focus yet.
 * @property {boolean} $touched True if control has lost focus.
 * @property {boolean} $pristine True if user has not interacted with the control yet.
 * @property {boolean} $dirty True if user has already interacted with the control.
 * @property {boolean} $valid True if there is no error.
 * @property {boolean} $invalid True if at least one error on the control.
 * @property {string} $name The name attribute of the control.
 *
 * @description
 *
 * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
 * The controller contains services for data-binding, validation, CSS updates, and value formatting
 * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
 * listening to DOM events.
 * Such DOM related logic should be provided by other directives which make use of
 * `NgModelController` for data-binding to control elements.
 * Angular provides this DOM logic for most {@link input `input`} elements.
 * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
 * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
 *
 * @example
 * ### Custom Control Example
 * This example shows how to use `NgModelController` with a custom control to achieve
 * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
 * collaborate together to achieve the desired result.
 *
 * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
 * contents be edited in place by the user.
 *
 * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
 * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
 * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
 * that content using the `$sce` service.
 *
 * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
    <file name="style.css">
      [contenteditable] {
        border: 1px solid black;
        background-color: white;
        min-height: 20px;
      }

      .ng-invalid {
        border: 1px solid red;
      }

    </file>
    <file name="script.js">
      angular.module('customControl', ['ngSanitize']).
        directive('contenteditable', ['$sce', function($sce) {
          return {
            restrict: 'A', // only activate on element attribute
            require: '?ngModel', // get a hold of NgModelController
            link: function(scope, element, attrs, ngModel) {
              if (!ngModel) return; // do nothing if no ng-model

              // Specify how UI should be updated
              ngModel.$render = function() {
                element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
              };

              // Listen for change events to enable binding
              element.on('blur keyup change', function() {
                scope.$evalAsync(read);
              });
              read(); // initialize

              // Write data to the model
              function read() {
                var html = element.html();
                // When we clear the content editable the browser leaves a <br> behind
                // If strip-br attribute is provided then we strip this out
                if ( attrs.stripBr && html == '<br>' ) {
                  html = '';
                }
                ngModel.$setViewValue(html);
              }
            }
          };
        }]);
    </file>
    <file name="index.html">
      <form name="myForm">
       <div contenteditable
            name="myWidget" ng-model="userContent"
            strip-br="true"
            required>Change me!</div>
        <span ng-show="myForm.myWidget.$error.required">Required!</span>
       <hr>
       <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
      </form>
    </file>
    <file name="protractor.js" type="protractor">
    it('should data-bind and become invalid', function() {
      if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
        // SafariDriver can't handle contenteditable
        // and Firefox driver can't clear contenteditables very well
        return;
      }
      var contentEditable = element(by.css('[contenteditable]'));
      var content = 'Change me!';

      expect(contentEditable.getText()).toEqual(content);

      contentEditable.clear();
      contentEditable.sendKeys(protractor.Key.BACK_SPACE);
      expect(contentEditable.getText()).toEqual('');
      expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
    });
    </file>
 * </example>
 *
 *
 */
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
    function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  this.$viewValue = Number.NaN;
  this.$modelValue = Number.NaN;
  this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  this.$validators = {};
  this.$asyncValidators = {};
  this.$parsers = [];
  this.$formatters = [];
  this.$viewChangeListeners = [];
  this.$untouched = true;
  this.$touched = false;
  this.$pristine = true;
  this.$dirty = false;
  this.$valid = true;
  this.$invalid = false;
  this.$error = {}; // keep invalid keys here
  this.$$success = {}; // keep valid keys here
  this.$pending = undefined; // keep pending keys here
  this.$name = $interpolate($attr.name || '', false)($scope);


  var parsedNgModel = $parse($attr.ngModel),
      parsedNgModelAssign = parsedNgModel.assign,
      ngModelGet = parsedNgModel,
      ngModelSet = parsedNgModelAssign,
      pendingDebounce = null,
      parserValid,
      ctrl = this;

  this.$$setOptions = function(options) {
    ctrl.$options = options;
    if (options && options.getterSetter) {
      var invokeModelGetter = $parse($attr.ngModel + '()'),
          invokeModelSetter = $parse($attr.ngModel + '($$$p)');

      ngModelGet = function($scope) {
        var modelValue = parsedNgModel($scope);
        if (isFunction(modelValue)) {
          modelValue = invokeModelGetter($scope);
        }
        return modelValue;
      };
      ngModelSet = function($scope, newValue) {
        if (isFunction(parsedNgModel($scope))) {
          invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
        } else {
          parsedNgModelAssign($scope, ctrl.$modelValue);
        }
      };
    } else if (!parsedNgModel.assign) {
      throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
          $attr.ngModel, startingTag($element));
    }
  };

  /**
   * @ngdoc method
   * @name ngModel.NgModelController#$render
   *
   * @description
   * Called when the view needs to be updated. It is expected that the user of the ng-model
   * directive will implement this method.
   *
   * The `$render()` method is invoked in the following situations:
   *
   * * `$rollbackViewValue()` is called.  If we are rolling back the view value to the last
   *   committed value then `$render()` is called to update the input control.
   * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
   *   the `$viewValue` are different from last time.
   *
   * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
   * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
   * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
   * invoked if you only change a property on the objects.
   */
  this.$render = noop;

  /**
   * @ngdoc method
   * @name ngModel.NgModelController#$isEmpty
   *
   * @description
   * This is called when we need to determine if the value of an input is empty.
   *
   * For instance, the required directive does this to work out if the input has data or not.
   *
   * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
   *
   * You can override this for input directives whose concept of being empty is different from the
   * default. The `checkboxInputType` directive does this because in its case a value of `false`
   * implies empty.
   *
   * @param {*} value The value of the input to check for emptiness.
   * @returns {boolean} True if `value` is "empty".
   */
  this.$isEmpty = function(value) {
    return isUndefined(value) || value === '' || value === null || value !== value;
  };

  var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
      currentValidationRunId = 0;

  /**
   * @ngdoc method
   * @name ngModel.NgModelController#$setValidity
   *
   * @description
   * Change the validity state, and notify the form.
   *
   * This method can be called within $parsers/$formatters or a custom validation implementation.
   * However, in most cases it should be sufficient to use the `ngModel.$validators` and
   * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
   *
   * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
   *        to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
   *        (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
   *        The `validationErrorKey` should be in camelCase and will get converted into dash-case
   *        for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
   *        class and can be bound to as  `{{someForm.someControl.$error.myError}}` .
   * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
   *                          or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
   *                          Skipped is used by Angular when validators do not run because of parse errors and
   *                          when `$asyncValidators` do not run because any of the `$validators` failed.
   */
  addSetValidityMethod({
    ctrl: this,
    $element: $element,
    set: function(object, property) {
      object[property] = true;
    },
    unset: function(object, property) {
      delete object[property];
    },
    parentForm: parentForm,
    $animate: $animate
  });

  /**
   * @ngdoc method
   * @name ngModel.NgModelController#$setPristine
   *
   * @description
   * Sets the control to its pristine state.
   *
   * This method can be called to remove the `ng-dirty` class and set the control to its pristine
   * state (`ng-pristine` class). A model is considered to be pristine when the control
   * has not been changed from when first compiled.
   */
  this.$setPristine = function() {
    ctrl.$dirty = false;
    ctrl.$pristine = true;
    $animate.removeClass($element, DIRTY_CLASS);
    $animate.addClass($element, PRISTINE_CLASS);
  };

  /**
   * @ngdoc method
   * @name ngModel.NgModelController#$setDirty
   *
   * @description
   * Sets the control to its dirty state.
   *
   * This method can be called to remove the `ng-pristine` class and set the control to its dirty
   * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
   * from when first compiled.
   */
  this.$setDirty = function() {
    ctrl.$dirty = true;
    ctrl.$pristine = false;
    $animate.removeClass($element, PRISTINE_CLASS);
    $animate.addClass($element, DIRTY_CLASS);
    parentForm.$setDirty();
  };

  /**
   * @ngdoc method
   * @name ngModel.NgModelController#$setUntouched
   *
   * @description
   * Sets the control to its untouched state.
   *
   * This method can be called to remove the `ng-touched` class and set the control to its
   * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
   * by default, however this function can be used to restore that state if the model has
   * already been touched by the user.
   */
  this.$setUntouched = function() {
    ctrl.$touched = false;
    ctrl.$untouched = true;
    $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  };

  /**
   * @ngdoc method
   * @name ngModel.NgModelController#$setTouched
   *
   * @description
   * Sets the control to its touched state.
   *
   * This method can be called to remove the `ng-untouched` class and set the control to its
   * touched state (`ng-touched` class). A model is considered to be touched when the user has
   * first focused the control element and then shifted focus away from the control (blur event).
   */
  this.$setTouched = function() {
    ctrl.$touched = true;
    ctrl.$untouched = false;
    $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  };

  /**
   * @ngdoc method
   * @name ngModel.NgModelController#$rollbackViewValue
   *
   * @description
   * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
   * which may be caused by a pending debounced event or because the input is waiting for a some
   * future event.
   *
   * If you have an input that uses `ng-model-options` to set up debounced events or events such
   * as blur you can have a situation where there is a period when the `$viewValue`
   * is out of synch with the ngModel's `$modelValue`.
   *
   * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
   * programmatically before these debounced/future events have resolved/occurred, because Angular's
   * dirty checking mechanism is not able to tell whether the model has actually changed or not.
   *
   * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
   * input which may have such events pending. This is important in order to make sure that the
   * input field will be updated with the new model value and any pending operations are cancelled.
   *
   * <example name="ng-model-cancel-update" module="cancel-update-example">
   *   <file name="app.js">
   *     angular.module('cancel-update-example', [])
   *
   *     .controller('CancelUpdateController', ['$scope', function($scope) {
   *       $scope.resetWithCancel = function(e) {
   *         if (e.keyCode == 27) {
   *           $scope.myForm.myInput1.$rollbackViewValue();
   *           $scope.myValue = '';
   *         }
   *       };
   *       $scope.resetWithoutCancel = function(e) {
   *         if (e.keyCode == 27) {
   *           $scope.myValue = '';
   *         }
   *       };
   *     }]);
   *   </file>
   *   <file name="index.html">
   *     <div ng-controller="CancelUpdateController">
   *       <p>Try typing something in each input.  See that the model only updates when you
   *          blur off the input.
   *        </p>
   *        <p>Now see what happens if you start typing then press the Escape key</p>
   *
   *       <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
   *         <p id="inputDescription1">With $rollbackViewValue()</p>
   *         <input name="myInput1" aria-describedby="inputDescription1" ng-model="myValue"
   *                ng-keydown="resetWithCancel($event)"><br/>
   *         myValue: "{{ myValue }}"
   *
   *         <p id="inputDescription2">Without $rollbackViewValue()</p>
   *         <input name="myInput2" aria-describedby="inputDescription2" ng-model="myValue"
   *                ng-keydown="resetWithoutCancel($event)"><br/>
   *         myValue: "{{ myValue }}"
   *       </form>
   *     </div>
   *   </file>
   * </example>
   */
  this.$rollbackViewValue = function() {
    $timeout.cancel(pendingDebounce);
    ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
    ctrl.$render();
  };

  /**
   * @ngdoc method
   * @name ngModel.NgModelController#$validate
   *
   * @description
   * Runs each of the registered validators (first synchronous validators and then
   * asynchronous validators).
   * If the validity changes to invalid, the model will be set to `undefined`,
   * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
   * If the validity changes to valid, it will set the model to the last available valid
   * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
   */
  this.$validate = function() {
    // ignore $validate before model is initialized
    if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
      return;
    }

    var viewValue = ctrl.$$lastCommittedViewValue;
    // Note: we use the $$rawModelValue as $modelValue might have been
    // set to undefined during a view -> model update that found validation
    // errors. We can't parse the view here, since that could change
    // the model although neither viewValue nor the model on the scope changed
    var modelValue = ctrl.$$rawModelValue;

    var prevValid = ctrl.$valid;
    var prevModelValue = ctrl.$modelValue;

    var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;

    ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
      // If there was no change in validity, don't update the model
      // This prevents changing an invalid modelValue to undefined
      if (!allowInvalid && prevValid !== allValid) {
        // Note: Don't check ctrl.$valid here, as we could have
        // external validators (e.g. calculated on the server),
        // that just call $setValidity and need the model value
        // to calculate their validity.
        ctrl.$modelValue = allValid ? modelValue : undefined;

        if (ctrl.$modelValue !== prevModelValue) {
          ctrl.$$writeModelToScope();
        }
      }
    });

  };

  this.$$runValidators = function(modelValue, viewValue, doneCallback) {
    currentValidationRunId++;
    var localValidationRunId = currentValidationRunId;

    // check parser error
    if (!processParseErrors()) {
      validationDone(false);
      return;
    }
    if (!processSyncValidators()) {
      validationDone(false);
      return;
    }
    processAsyncValidators();

    function processParseErrors() {
      var errorKey = ctrl.$$parserName || 'parse';
      if (parserValid === undefined) {
        setValidity(errorKey, null);
      } else {
        if (!parserValid) {
          forEach(ctrl.$validators, function(v, name) {
            setValidity(name, null);
          });
          forEach(ctrl.$asyncValidators, function(v, name) {
            setValidity(name, null);
          });
        }
        // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
        setValidity(errorKey, parserValid);
        return parserValid;
      }
      return true;
    }

    function processSyncValidators() {
      var syncValidatorsValid = true;
      forEach(ctrl.$validators, function(validator, name) {
        var result = validator(modelValue, viewValue);
        syncValidatorsValid = syncValidatorsValid && result;
        setValidity(name, result);
      });
      if (!syncValidatorsValid) {
        forEach(ctrl.$asyncValidators, function(v, name) {
          setValidity(name, null);
        });
        return false;
      }
      return true;
    }

    function processAsyncValidators() {
      var validatorPromises = [];
      var allValid = true;
      forEach(ctrl.$asyncValidators, function(validator, name) {
        var promise = validator(modelValue, viewValue);
        if (!isPromiseLike(promise)) {
          throw $ngModelMinErr("$asyncValidators",
            "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
        }
        setValidity(name, undefined);
        validatorPromises.push(promise.then(function() {
          setValidity(name, true);
        }, function(error) {
          allValid = false;
          setValidity(name, false);
        }));
      });
      if (!validatorPromises.length) {
        validationDone(true);
      } else {
        $q.all(validatorPromises).then(function() {
          validationDone(allValid);
        }, noop);
      }
    }

    function setValidity(name, isValid) {
      if (localValidationRunId === currentValidationRunId) {
        ctrl.$setValidity(name, isValid);
      }
    }

    function validationDone(allValid) {
      if (localValidationRunId === currentValidationRunId) {

        doneCallback(allValid);
      }
    }
  };

  /**
   * @ngdoc method
   * @name ngModel.NgModelController#$commitViewValue
   *
   * @description
   * Commit a pending update to the `$modelValue`.
   *
   * Updates may be pending by a debounced event or because the input is waiting for a some future
   * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
   * usually handles calling this in response to input events.
   */
  this.$commitViewValue = function() {
    var viewValue = ctrl.$viewValue;

    $timeout.cancel(pendingDebounce);

    // If the view value has not changed then we should just exit, except in the case where there is
    // a native validator on the element. In this case the validation state may have changed even though
    // the viewValue has stayed empty.
    if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
      return;
    }
    ctrl.$$lastCommittedViewValue = viewValue;

    // change to dirty
    if (ctrl.$pristine) {
      this.$setDirty();
    }
    this.$$parseAndValidate();
  };

  this.$$parseAndValidate = function() {
    var viewValue = ctrl.$$lastCommittedViewValue;
    var modelValue = viewValue;
    parserValid = isUndefined(modelValue) ? undefined : true;

    if (parserValid) {
      for (var i = 0; i < ctrl.$parsers.length; i++) {
        modelValue = ctrl.$parsers[i](modelValue);
        if (isUndefined(modelValue)) {
          parserValid = false;
          break;
        }
      }
    }
    if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
      // ctrl.$modelValue has not been touched yet...
      ctrl.$modelValue = ngModelGet($scope);
    }
    var prevModelValue = ctrl.$modelValue;
    var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
    ctrl.$$rawModelValue = modelValue;

    if (allowInvalid) {
      ctrl.$modelValue = modelValue;
      writeToModelIfNeeded();
    }

    // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
    // This can happen if e.g. $setViewValue is called from inside a parser
    ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
      if (!allowInvalid) {
        // Note: Don't check ctrl.$valid here, as we could have
        // external validators (e.g. calculated on the server),
        // that just call $setValidity and need the model value
        // to calculate their validity.
        ctrl.$modelValue = allValid ? modelValue : undefined;
        writeToModelIfNeeded();
      }
    });

    function writeToModelIfNeeded() {
      if (ctrl.$modelValue !== prevModelValue) {
        ctrl.$$writeModelToScope();
      }
    }
  };

  this.$$writeModelToScope = function() {
    ngModelSet($scope, ctrl.$modelValue);
    forEach(ctrl.$viewChangeListeners, function(listener) {
      try {
        listener();
      } catch (e) {
        $exceptionHandler(e);
      }
    });
  };

  /**
   * @ngdoc method
   * @name ngModel.NgModelController#$setViewValue
   *
   * @description
   * Update the view value.
   *
   * This method should be called when an input directive want to change the view value; typically,
   * this is done from within a DOM event handler.
   *
   * For example {@link ng.directive:input input} calls it when the value of the input changes and
   * {@link ng.directive:select select} calls it when an option is selected.
   *
   * If the new `value` is an object (rather than a string or a number), we should make a copy of the
   * object before passing it to `$setViewValue`.  This is because `ngModel` does not perform a deep
   * watch of objects, it only looks for a change of identity. If you only change the property of
   * the object then ngModel will not realise that the object has changed and will not invoke the
   * `$parsers` and `$validators` pipelines.
   *
   * For this reason, you should not change properties of the copy once it has been passed to
   * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
   *
   * When this method is called, the new `value` will be staged for committing through the `$parsers`
   * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
   * value sent directly for processing, finally to be applied to `$modelValue` and then the
   * **expression** specified in the `ng-model` attribute.
   *
   * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
   *
   * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
   * and the `default` trigger is not listed, all those actions will remain pending until one of the
   * `updateOn` events is triggered on the DOM element.
   * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
   * directive is used with a custom debounce for this particular event.
   *
   * Note that calling this function does not trigger a `$digest`.
   *
   * @param {string} value Value from the view.
   * @param {string} trigger Event that triggered the update.
   */
  this.$setViewValue = function(value, trigger) {
    ctrl.$viewValue = value;
    if (!ctrl.$options || ctrl.$options.updateOnDefault) {
      ctrl.$$debounceViewValueCommit(trigger);
    }
  };

  this.$$debounceViewValueCommit = function(trigger) {
    var debounceDelay = 0,
        options = ctrl.$options,
        debounce;

    if (options && isDefined(options.debounce)) {
      debounce = options.debounce;
      if (isNumber(debounce)) {
        debounceDelay = debounce;
      } else if (isNumber(debounce[trigger])) {
        debounceDelay = debounce[trigger];
      } else if (isNumber(debounce['default'])) {
        debounceDelay = debounce['default'];
      }
    }

    $timeout.cancel(pendingDebounce);
    if (debounceDelay) {
      pendingDebounce = $timeout(function() {
        ctrl.$commitViewValue();
      }, debounceDelay);
    } else if ($rootScope.$$phase) {
      ctrl.$commitViewValue();
    } else {
      $scope.$apply(function() {
        ctrl.$commitViewValue();
      });
    }
  };

  // model -> value
  // Note: we cannot use a normal scope.$watch as we want to detect the following:
  // 1. scope value is 'a'
  // 2. user enters 'b'
  // 3. ng-change kicks in and reverts scope value to 'a'
  //    -> scope value did not change since the last digest as
  //       ng-change executes in apply phase
  // 4. view should be changed back to 'a'
  $scope.$watch(function ngModelWatch() {
    var modelValue = ngModelGet($scope);

    // if scope model value and ngModel value are out of sync
    // TODO(perf): why not move this to the action fn?
    if (modelValue !== ctrl.$modelValue &&
       // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
       (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
    ) {
      ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
      parserValid = undefined;

      var formatters = ctrl.$formatters,
          idx = formatters.length;

      var viewValue = modelValue;
      while (idx--) {
        viewValue = formatters[idx](viewValue);
      }
      if (ctrl.$viewValue !== viewValue) {
        ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
        ctrl.$render();

        ctrl.$$runValidators(modelValue, viewValue, noop);
      }
    }

    return modelValue;
  });
}];


/**
 * @ngdoc directive
 * @name ngModel
 *
 * @element input
 * @priority 1
 *
 * @description
 * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
 * property on the scope using {@link ngModel.NgModelController NgModelController},
 * which is created and exposed by this directive.
 *
 * `ngModel` is responsible for:
 *
 * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
 *   require.
 * - Providing validation behavior (i.e. required, number, email, url).
 * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
 * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
 * - Registering the control with its parent {@link ng.directive:form form}.
 *
 * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
 * current scope. If the property doesn't already exist on this scope, it will be created
 * implicitly and added to the scope.
 *
 * For best practices on using `ngModel`, see:
 *
 *  - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
 *
 * For basic examples, how to use `ngModel`, see:
 *
 *  - {@link ng.directive:input input}
 *    - {@link input[text] text}
 *    - {@link input[checkbox] checkbox}
 *    - {@link input[radio] radio}
 *    - {@link input[number] number}
 *    - {@link input[email] email}
 *    - {@link input[url] url}
 *    - {@link input[date] date}
 *    - {@link input[datetime-local] datetime-local}
 *    - {@link input[time] time}
 *    - {@link input[month] month}
 *    - {@link input[week] week}
 *  - {@link ng.directive:select select}
 *  - {@link ng.directive:textarea textarea}
 *
 * # CSS classes
 * The following CSS classes are added and removed on the associated input/select/textarea element
 * depending on the validity of the model.
 *
 *  - `ng-valid`: the model is valid
 *  - `ng-invalid`: the model is invalid
 *  - `ng-valid-[key]`: for each valid key added by `$setValidity`
 *  - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
 *  - `ng-pristine`: the control hasn't been interacted with yet
 *  - `ng-dirty`: the control has been interacted with
 *  - `ng-touched`: the control has been blurred
 *  - `ng-untouched`: the control hasn't been blurred
 *  - `ng-pending`: any `$asyncValidators` are unfulfilled
 *
 * Keep in mind that ngAnimate can detect each of these classes when added and removed.
 *
 * ## Animation Hooks
 *
 * Animations within models are triggered when any of the associated CSS classes are added and removed
 * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
 * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
 * The animations that are triggered within ngModel are similar to how they work in ngClass and
 * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
 *
 * The following example shows a simple way to utilize CSS transitions to style an input element
 * that has been rendered as invalid after it has been validated:
 *
 * <pre>
 * //be sure to include ngAnimate as a module to hook into more
 * //advanced animations
 * .my-input {
 *   transition:0.5s linear all;
 *   background: white;
 * }
 * .my-input.ng-invalid {
 *   background: red;
 *   color:white;
 * }
 * </pre>
 *
 * @example
 * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
     <file name="index.html">
       <script>
        angular.module('inputExample', [])
          .controller('ExampleController', ['$scope', function($scope) {
            $scope.val = '1';
          }]);
       </script>
       <style>
         .my-input {
           -webkit-transition:all linear 0.5s;
           transition:all linear 0.5s;
           background: transparent;
         }
         .my-input.ng-invalid {
           color:white;
           background: red;
         }
       </style>
       <p id="inputDescription">
        Update input to see transitions when valid/invalid.
        Integer is a valid value.
       </p>
       <form name="testForm" ng-controller="ExampleController">
         <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
                aria-describedby="inputDescription" />
       </form>
     </file>
 * </example>
 *
 * ## Binding to a getter/setter
 *
 * Sometimes it's helpful to bind `ngModel` to a getter/setter function.  A getter/setter is a
 * function that returns a representation of the model when called with zero arguments, and sets
 * the internal state of a model when called with an argument. It's sometimes useful to use this
 * for models that have an internal representation that's different from what the model exposes
 * to the view.
 *
 * <div class="alert alert-success">
 * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
 * frequently than other parts of your code.
 * </div>
 *
 * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
 * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
 * a `<form>`, which will enable this behavior for all `<input>`s within it. See
 * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
 *
 * The following example shows how to use `ngModel` with a getter/setter:
 *
 * @example
 * <example name="ngModel-getter-setter" module="getterSetterExample">
     <file name="index.html">
       <div ng-controller="ExampleController">
         <form name="userForm">
           <label>Name:
             <input type="text" name="userName"
                    ng-model="user.name"
                    ng-model-options="{ getterSetter: true }" />
           </label>
         </form>
         <pre>user.name = <span ng-bind="user.name()"></span></pre>
       </div>
     </file>
     <file name="app.js">
       angular.module('getterSetterExample', [])
         .controller('ExampleController', ['$scope', function($scope) {
           var _name = 'Brian';
           $scope.user = {
             name: function(newName) {
              // Note that newName can be undefined for two reasons:
              // 1. Because it is called as a getter and thus called with no arguments
              // 2. Because the property should actually be set to undefined. This happens e.g. if the
              //    input is invalid
              return arguments.length ? (_name = newName) : _name;
             }
           };
         }]);
     </file>
 * </example>
 */
var ngModelDirective = ['$rootScope', function($rootScope) {
  return {
    restrict: 'A',
    require: ['ngModel', '^?form', '^?ngModelOptions'],
    controller: NgModelController,
    // Prelink needs to run before any input directive
    // so that we can set the NgModelOptions in NgModelController
    // before anyone else uses it.
    priority: 1,
    compile: function ngModelCompile(element) {
      // Setup initial state of the control
      element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);

      return {
        pre: function ngModelPreLink(scope, element, attr, ctrls) {
          var modelCtrl = ctrls[0],
              formCtrl = ctrls[1] || nullFormCtrl;

          modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);

          // notify others, especially parent forms
          formCtrl.$addControl(modelCtrl);

          attr.$observe('name', function(newValue) {
            if (modelCtrl.$name !== newValue) {
              formCtrl.$$renameControl(modelCtrl, newValue);
            }
          });

          scope.$on('$destroy', function() {
            formCtrl.$removeControl(modelCtrl);
          });
        },
        post: function ngModelPostLink(scope, element, attr, ctrls) {
          var modelCtrl = ctrls[0];
          if (modelCtrl.$options && modelCtrl.$options.updateOn) {
            element.on(modelCtrl.$options.updateOn, function(ev) {
              modelCtrl.$$debounceViewValueCommit(ev && ev.type);
            });
          }

          element.on('blur', function(ev) {
            if (modelCtrl.$touched) return;

            if ($rootScope.$$phase) {
              scope.$evalAsync(modelCtrl.$setTouched);
            } else {
              scope.$apply(modelCtrl.$setTouched);
            }
          });
        }
      };
    }
  };
}];

var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;

/**
 * @ngdoc directive
 * @name ngModelOptions
 *
 * @description
 * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
 * events that will trigger a model update and/or a debouncing delay so that the actual update only
 * takes place when a timer expires; this timer will be reset after another change takes place.
 *
 * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
 * be different from the value in the actual model. This means that if you update the model you
 * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
 * order to make sure it is synchronized with the model and that any debounced action is canceled.
 *
 * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
 * method is by making sure the input is placed inside a form that has a `name` attribute. This is
 * important because `form` controllers are published to the related scope under the name in their
 * `name` attribute.
 *
 * Any pending changes will take place immediately when an enclosing form is submitted via the
 * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
 * to have access to the updated model.
 *
 * `ngModelOptions` has an effect on the element it's declared on and its descendants.
 *
 * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
 *   - `updateOn`: string specifying which event should the input be bound to. You can set several
 *     events using an space delimited list. There is a special event called `default` that
 *     matches the default events belonging of the control.
 *   - `debounce`: integer value which contains the debounce model update value in milliseconds. A
 *     value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
 *     custom value for each event. For example:
 *     `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
 *   - `allowInvalid`: boolean value which indicates that the model can be set with values that did
 *     not validate correctly instead of the default behavior of setting the model to undefined.
 *   - `getterSetter`: boolean value which determines whether or not to treat functions bound to
       `ngModel` as getters/setters.
 *   - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
 *     `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
 *     continental US time zone abbreviations, but for general use, use a time zone offset, for
 *     example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
 *     If not specified, the timezone of the browser will be used.
 *
 * @example

  The following example shows how to override immediate updates. Changes on the inputs within the
  form will update the model only when the control loses focus (blur event). If `escape` key is
  pressed while the input field is focused, the value is reset to the value in the current model.

  <example name="ngModelOptions-directive-blur" module="optionsExample">
    <file name="index.html">
      <div ng-controller="ExampleController">
        <form name="userForm">
          <label>Name:
            <input type="text" name="userName"
                   ng-model="user.name"
                   ng-model-options="{ updateOn: 'blur' }"
                   ng-keyup="cancel($event)" />
          </label><br />
          <label>Other data:
            <input type="text" ng-model="user.data" />
          </label><br />
        </form>
        <pre>user.name = <span ng-bind="user.name"></span></pre>
      </div>
    </file>
    <file name="app.js">
      angular.module('optionsExample', [])
        .controller('ExampleController', ['$scope', function($scope) {
          $scope.user = { name: 'say', data: '' };

          $scope.cancel = function(e) {
            if (e.keyCode == 27) {
              $scope.userForm.userName.$rollbackViewValue();
            }
          };
        }]);
    </file>
    <file name="protractor.js" type="protractor">
      var model = element(by.binding('user.name'));
      var input = element(by.model('user.name'));
      var other = element(by.model('user.data'));

      it('should allow custom events', function() {
        input.sendKeys(' hello');
        input.click();
        expect(model.getText()).toEqual('say');
        other.click();
        expect(model.getText()).toEqual('say hello');
      });

      it('should $rollbackViewValue when model changes', function() {
        input.sendKeys(' hello');
        expect(input.getAttribute('value')).toEqual('say hello');
        input.sendKeys(protractor.Key.ESCAPE);
        expect(input.getAttribute('value')).toEqual('say');
        other.click();
        expect(model.getText()).toEqual('say');
      });
    </file>
  </example>

  This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.

  <example name="ngModelOptions-directive-debounce" module="optionsExample">
    <file name="index.html">
      <div ng-controller="ExampleController">
        <form name="userForm">
          <label>Name:
            <input type="text" name="userName"
                   ng-model="user.name"
                   ng-model-options="{ debounce: 1000 }" />
          </label>
          <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
          <br />
        </form>
        <pre>user.name = <span ng-bind="user.name"></span></pre>
      </div>
    </file>
    <file name="app.js">
      angular.module('optionsExample', [])
        .controller('ExampleController', ['$scope', function($scope) {
          $scope.user = { name: 'say' };
        }]);
    </file>
  </example>

  This one shows how to bind to getter/setters:

  <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
    <file name="index.html">
      <div ng-controller="ExampleController">
        <form name="userForm">
          <label>Name:
            <input type="text" name="userName"
                   ng-model="user.name"
                   ng-model-options="{ getterSetter: true }" />
          </label>
        </form>
        <pre>user.name = <span ng-bind="user.name()"></span></pre>
      </div>
    </file>
    <file name="app.js">
      angular.module('getterSetterExample', [])
        .controller('ExampleController', ['$scope', function($scope) {
          var _name = 'Brian';
          $scope.user = {
            name: function(newName) {
              // Note that newName can be undefined for two reasons:
              // 1. Because it is called as a getter and thus called with no arguments
              // 2. Because the property should actually be set to undefined. This happens e.g. if the
              //    input is invalid
              return arguments.length ? (_name = newName) : _name;
            }
          };
        }]);
    </file>
  </example>
 */
var ngModelOptionsDirective = function() {
  return {
    restrict: 'A',
    controller: ['$scope', '$attrs', function($scope, $attrs) {
      var that = this;
      this.$options = copy($scope.$eval($attrs.ngModelOptions));
      // Allow adding/overriding bound events
      if (this.$options.updateOn !== undefined) {
        this.$options.updateOnDefault = false;
        // extract "default" pseudo-event from list of events that can trigger a model update
        this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
          that.$options.updateOnDefault = true;
          return ' ';
        }));
      } else {
        this.$options.updateOnDefault = true;
      }
    }]
  };
};



// helper methods
function addSetValidityMethod(context) {
  var ctrl = context.ctrl,
      $element = context.$element,
      classCache = {},
      set = context.set,
      unset = context.unset,
      parentForm = context.parentForm,
      $animate = context.$animate;

  classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));

  ctrl.$setValidity = setValidity;

  function setValidity(validationErrorKey, state, controller) {
    if (state === undefined) {
      createAndSet('$pending', validationErrorKey, controller);
    } else {
      unsetAndCleanup('$pending', validationErrorKey, controller);
    }
    if (!isBoolean(state)) {
      unset(ctrl.$error, validationErrorKey, controller);
      unset(ctrl.$$success, validationErrorKey, controller);
    } else {
      if (state) {
        unset(ctrl.$error, validationErrorKey, controller);
        set(ctrl.$$success, validationErrorKey, controller);
      } else {
        set(ctrl.$error, validationErrorKey, controller);
        unset(ctrl.$$success, validationErrorKey, controller);
      }
    }
    if (ctrl.$pending) {
      cachedToggleClass(PENDING_CLASS, true);
      ctrl.$valid = ctrl.$invalid = undefined;
      toggleValidationCss('', null);
    } else {
      cachedToggleClass(PENDING_CLASS, false);
      ctrl.$valid = isObjectEmpty(ctrl.$error);
      ctrl.$invalid = !ctrl.$valid;
      toggleValidationCss('', ctrl.$valid);
    }

    // re-read the state as the set/unset methods could have
    // combined state in ctrl.$error[validationError] (used for forms),
    // where setting/unsetting only increments/decrements the value,
    // and does not replace it.
    var combinedState;
    if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
      combinedState = undefined;
    } else if (ctrl.$error[validationErrorKey]) {
      combinedState = false;
    } else if (ctrl.$$success[validationErrorKey]) {
      combinedState = true;
    } else {
      combinedState = null;
    }

    toggleValidationCss(validationErrorKey, combinedState);
    parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  }

  function createAndSet(name, value, controller) {
    if (!ctrl[name]) {
      ctrl[name] = {};
    }
    set(ctrl[name], value, controller);
  }

  function unsetAndCleanup(name, value, controller) {
    if (ctrl[name]) {
      unset(ctrl[name], value, controller);
    }
    if (isObjectEmpty(ctrl[name])) {
      ctrl[name] = undefined;
    }
  }

  function cachedToggleClass(className, switchValue) {
    if (switchValue && !classCache[className]) {
      $animate.addClass($element, className);
      classCache[className] = true;
    } else if (!switchValue && classCache[className]) {
      $animate.removeClass($element, className);
      classCache[className] = false;
    }
  }

  function toggleValidationCss(validationErrorKey, isValid) {
    validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';

    cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
    cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  }
}

function isObjectEmpty(obj) {
  if (obj) {
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        return false;
      }
    }
  }
  return true;
}

/**
 * @ngdoc directive
 * @name ngNonBindable
 * @restrict AC
 * @priority 1000
 *
 * @description
 * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
 * DOM element. This is useful if the element contains what appears to be Angular directives and
 * bindings but which should be ignored by Angular. This could be the case if you have a site that
 * displays snippets of code, for instance.
 *
 * @element ANY
 *
 * @example
 * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
 * but the one wrapped in `ngNonBindable` is left alone.
 *
 * @example
    <example>
      <file name="index.html">
        <div>Normal: {{1 + 2}}</div>
        <div ng-non-bindable>Ignored: {{1 + 2}}</div>
      </file>
      <file name="protractor.js" type="protractor">
       it('should check ng-non-bindable', function() {
         expect(element(by.binding('1 + 2')).getText()).toContain('3');
         expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
       });
      </file>
    </example>
 */
var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });

/* global jqLiteRemove */

var ngOptionsMinErr = minErr('ngOptions');

/**
 * @ngdoc directive
 * @name ngOptions
 * @restrict A
 *
 * @description
 *
 * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
 * elements for the `<select>` element using the array or object obtained by evaluating the
 * `ngOptions` comprehension expression.
 *
 * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
 * similar result. However, `ngOptions` provides some benefits such as reducing memory and
 * increasing speed by not creating a new scope for each repeated instance, as well as providing
 * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
 * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
 *  to a non-string value. This is because an option element can only be bound to string values at
 * present.
 *
 * When an item in the `<select>` menu is selected, the array element or object property
 * represented by the selected option will be bound to the model identified by the `ngModel`
 * directive.
 *
 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
 * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
 * option. See example below for demonstration.
 *
 * ## Complex Models (objects or collections)
 *
 * **Note:** By default, `ngModel` watches the model by reference, not value. This is important when
 * binding any input directive to a model that is an object or a collection.
 *
 * Since this is a common situation for `ngOptions` the directive additionally watches the model using
 * `$watchCollection` when the select has the `multiple` attribute or when there is a `track by` clause in
 * the options expression. This allows ngOptions to trigger a re-rendering of the options even if the actual
 * object/collection has not changed identity but only a property on the object or an item in the collection
 * changes.
 *
 * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
 * if the model is an array). This means that changing a property deeper inside the object/collection that the
 * first level will not trigger a re-rendering.
 *
 *
 * ## `select` **`as`**
 *
 * Using `select` **`as`** will bind the result of the `select` expression to the model, but
 * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
 * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
 * is used, the result of that expression will be set as the value of the `option` and `select` elements.
 *
 *
 * ### `select` **`as`** and **`track by`**
 *
 * <div class="alert alert-warning">
 * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
 * </div>
 *
 * Consider the following example:
 *
 * ```html
 * <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected">
 * ```
 *
 * ```js
 * $scope.values = [{
 *   id: 1,
 *   label: 'aLabel',
 *   subItem: { name: 'aSubItem' }
 * }, {
 *   id: 2,
 *   label: 'bLabel',
 *   subItem: { name: 'bSubItem' }
 * }];
 *
 * $scope.selected = { name: 'aSubItem' };
 * ```
 *
 * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
 * of the data source (to `item` in this example). To calculate whether an element is selected, we do the
 * following:
 *
 * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
 * 2. Apply **`track by`** to the already selected value in `ngModel`.
 *    In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
 *    value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
 *    a wrong object, the selected element can't be found, `<select>` is always reset to the "not
 *    selected" option.
 *
 *
 * @param {string} ngModel Assignable angular expression to data-bind to.
 * @param {string=} name Property name of the form under which the control is published.
 * @param {string=} required The control is considered valid only if value is entered.
 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
 *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
 *    `required` when you want to data-bind to the `required` attribute.
 * @param {comprehension_expression=} ngOptions in one of the following forms:
 *
 *   * for array data sources:
 *     * `label` **`for`** `value` **`in`** `array`
 *     * `select` **`as`** `label` **`for`** `value` **`in`** `array`
 *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
 *     * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
 *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
 *     * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
 *     * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
 *        (for including a filter with `track by`)
 *   * for object data sources:
 *     * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
 *     * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
 *     * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
 *     * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
 *     * `select` **`as`** `label` **`group by`** `group`
 *         **`for` `(`**`key`**`,`** `value`**`) in`** `object`
 *     * `select` **`as`** `label` **`disable when`** `disable`
 *         **`for` `(`**`key`**`,`** `value`**`) in`** `object`
 *
 * Where:
 *
 *   * `array` / `object`: an expression which evaluates to an array / object to iterate over.
 *   * `value`: local variable which will refer to each item in the `array` or each property value
 *      of `object` during iteration.
 *   * `key`: local variable which will refer to a property name in `object` during iteration.
 *   * `label`: The result of this expression will be the label for `<option>` element. The
 *     `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
 *   * `select`: The result of this expression will be bound to the model of the parent `<select>`
 *      element. If not specified, `select` expression will default to `value`.
 *   * `group`: The result of this expression will be used to group options using the `<optgroup>`
 *      DOM element.
 *   * `disable`: The result of this expression will be used to disable the rendered `<option>`
 *      element. Return `true` to disable.
 *   * `trackexpr`: Used when working with an array of objects. The result of this expression will be
 *      used to identify the objects in the array. The `trackexpr` will most likely refer to the
 *     `value` variable (e.g. `value.propertyName`). With this the selection is preserved
 *      even when the options are recreated (e.g. reloaded from the server).
 *
 * @example
    <example module="selectExample">
      <file name="index.html">
        <script>
        angular.module('selectExample', [])
          .controller('ExampleController', ['$scope', function($scope) {
            $scope.colors = [
              {name:'black', shade:'dark'},
              {name:'white', shade:'light', notAnOption: true},
              {name:'red', shade:'dark'},
              {name:'blue', shade:'dark', notAnOption: true},
              {name:'yellow', shade:'light', notAnOption: false}
            ];
            $scope.myColor = $scope.colors[2]; // red
          }]);
        </script>
        <div ng-controller="ExampleController">
          <ul>
            <li ng-repeat="color in colors">
              <label>Name: <input ng-model="color.name"></label>
              <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
              <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
            </li>
            <li>
              <button ng-click="colors.push({})">add</button>
            </li>
          </ul>
          <hr/>
          <label>Color (null not allowed):
            <select ng-model="myColor" ng-options="color.name for color in colors"></select>
          </label><br/>
          <label>Color (null allowed):
          <span  class="nullable">
            <select ng-model="myColor" ng-options="color.name for color in colors">
              <option value="">-- choose color --</option>
            </select>
          </span></label><br/>

          <label>Color grouped by shade:
            <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
            </select>
          </label><br/>

          <label>Color grouped by shade, with some disabled:
            <select ng-model="myColor"
                  ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
            </select>
          </label><br/>



          Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
          <br/>
          <hr/>
          Currently selected: {{ {selected_color:myColor} }}
          <div style="border:solid 1px black; height:20px"
               ng-style="{'background-color':myColor.name}">
          </div>
        </div>
      </file>
      <file name="protractor.js" type="protractor">
         it('should check ng-options', function() {
           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
           element.all(by.model('myColor')).first().click();
           element.all(by.css('select[ng-model="myColor"] option')).first().click();
           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
           element(by.css('.nullable select[ng-model="myColor"]')).click();
           element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
         });
      </file>
    </example>
 */

// jshint maxlen: false
//                     //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
                        // 1: value expression (valueFn)
                        // 2: label expression (displayFn)
                        // 3: group by expression (groupByFn)
                        // 4: disable when expression (disableWhenFn)
                        // 5: array item variable name
                        // 6: object item key variable name
                        // 7: object item value variable name
                        // 8: collection expression
                        // 9: track by expression
// jshint maxlen: 100


var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {

  function parseOptionsExpression(optionsExp, selectElement, scope) {

    var match = optionsExp.match(NG_OPTIONS_REGEXP);
    if (!(match)) {
      throw ngOptionsMinErr('iexp',
        "Expected expression in form of " +
        "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
        " but got '{0}'. Element: {1}",
        optionsExp, startingTag(selectElement));
    }

    // Extract the parts from the ngOptions expression

    // The variable name for the value of the item in the collection
    var valueName = match[5] || match[7];
    // The variable name for the key of the item in the collection
    var keyName = match[6];

    // An expression that generates the viewValue for an option if there is a label expression
    var selectAs = / as /.test(match[0]) && match[1];
    // An expression that is used to track the id of each object in the options collection
    var trackBy = match[9];
    // An expression that generates the viewValue for an option if there is no label expression
    var valueFn = $parse(match[2] ? match[1] : valueName);
    var selectAsFn = selectAs && $parse(selectAs);
    var viewValueFn = selectAsFn || valueFn;
    var trackByFn = trackBy && $parse(trackBy);

    // Get the value by which we are going to track the option
    // if we have a trackFn then use that (passing scope and locals)
    // otherwise just hash the given viewValue
    var getTrackByValueFn = trackBy ?
                              function(value, locals) { return trackByFn(scope, locals); } :
                              function getHashOfValue(value) { return hashKey(value); };
    var getTrackByValue = function(value, key) {
      return getTrackByValueFn(value, getLocals(value, key));
    };

    var displayFn = $parse(match[2] || match[1]);
    var groupByFn = $parse(match[3] || '');
    var disableWhenFn = $parse(match[4] || '');
    var valuesFn = $parse(match[8]);

    var locals = {};
    var getLocals = keyName ? function(value, key) {
      locals[keyName] = key;
      locals[valueName] = value;
      return locals;
    } : function(value) {
      locals[valueName] = value;
      return locals;
    };


    function Option(selectValue, viewValue, label, group, disabled) {
      this.selectValue = selectValue;
      this.viewValue = viewValue;
      this.label = label;
      this.group = group;
      this.disabled = disabled;
    }

    function getOptionValuesKeys(optionValues) {
      var optionValuesKeys;

      if (!keyName && isArrayLike(optionValues)) {
        optionValuesKeys = optionValues;
      } else {
        // if object, extract keys, in enumeration order, unsorted
        optionValuesKeys = [];
        for (var itemKey in optionValues) {
          if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
            optionValuesKeys.push(itemKey);
          }
        }
      }
      return optionValuesKeys;
    }

    return {
      trackBy: trackBy,
      getTrackByValue: getTrackByValue,
      getWatchables: $parse(valuesFn, function(optionValues) {
        // Create a collection of things that we would like to watch (watchedArray)
        // so that they can all be watched using a single $watchCollection
        // that only runs the handler once if anything changes
        var watchedArray = [];
        optionValues = optionValues || [];

        var optionValuesKeys = getOptionValuesKeys(optionValues);
        var optionValuesLength = optionValuesKeys.length;
        for (var index = 0; index < optionValuesLength; index++) {
          var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
          var value = optionValues[key];

          var locals = getLocals(optionValues[key], key);
          var selectValue = getTrackByValueFn(optionValues[key], locals);
          watchedArray.push(selectValue);

          // Only need to watch the displayFn if there is a specific label expression
          if (match[2] || match[1]) {
            var label = displayFn(scope, locals);
            watchedArray.push(label);
          }

          // Only need to watch the disableWhenFn if there is a specific disable expression
          if (match[4]) {
            var disableWhen = disableWhenFn(scope, locals);
            watchedArray.push(disableWhen);
          }
        }
        return watchedArray;
      }),

      getOptions: function() {

        var optionItems = [];
        var selectValueMap = {};

        // The option values were already computed in the `getWatchables` fn,
        // which must have been called to trigger `getOptions`
        var optionValues = valuesFn(scope) || [];
        var optionValuesKeys = getOptionValuesKeys(optionValues);
        var optionValuesLength = optionValuesKeys.length;

        for (var index = 0; index < optionValuesLength; index++) {
          var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
          var value = optionValues[key];
          var locals = getLocals(value, key);
          var viewValue = viewValueFn(scope, locals);
          var selectValue = getTrackByValueFn(viewValue, locals);
          var label = displayFn(scope, locals);
          var group = groupByFn(scope, locals);
          var disabled = disableWhenFn(scope, locals);
          var optionItem = new Option(selectValue, viewValue, label, group, disabled);

          optionItems.push(optionItem);
          selectValueMap[selectValue] = optionItem;
        }

        return {
          items: optionItems,
          selectValueMap: selectValueMap,
          getOptionFromViewValue: function(value) {
            return selectValueMap[getTrackByValue(value)];
          },
          getViewValueFromOption: function(option) {
            // If the viewValue could be an object that may be mutated by the application,
            // we need to make a copy and not return the reference to the value on the option.
            return trackBy ? angular.copy(option.viewValue) : option.viewValue;
          }
        };
      }
    };
  }


  // we can't just jqLite('<option>') since jqLite is not smart enough
  // to create it in <select> and IE barfs otherwise.
  var optionTemplate = document.createElement('option'),
      optGroupTemplate = document.createElement('optgroup');

  return {
    restrict: 'A',
    terminal: true,
    require: ['select', '?ngModel'],
    link: function(scope, selectElement, attr, ctrls) {

      // if ngModel is not defined, we don't need to do anything
      var ngModelCtrl = ctrls[1];
      if (!ngModelCtrl) return;

      var selectCtrl = ctrls[0];
      var multiple = attr.multiple;

      // The emptyOption allows the application developer to provide their own custom "empty"
      // option when the viewValue does not match any of the option values.
      var emptyOption;
      for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
        if (children[i].value === '') {
          emptyOption = children.eq(i);
          break;
        }
      }

      var providedEmptyOption = !!emptyOption;

      var unknownOption = jqLite(optionTemplate.cloneNode(false));
      unknownOption.val('?');

      var options;
      var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);


      var renderEmptyOption = function() {
        if (!providedEmptyOption) {
          selectElement.prepend(emptyOption);
        }
        selectElement.val('');
        emptyOption.prop('selected', true); // needed for IE
        emptyOption.attr('selected', true);
      };

      var removeEmptyOption = function() {
        if (!providedEmptyOption) {
          emptyOption.remove();
        }
      };


      var renderUnknownOption = function() {
        selectElement.prepend(unknownOption);
        selectElement.val('?');
        unknownOption.prop('selected', true); // needed for IE
        unknownOption.attr('selected', true);
      };

      var removeUnknownOption = function() {
        unknownOption.remove();
      };


      // Update the controller methods for multiple selectable options
      if (!multiple) {

        selectCtrl.writeValue = function writeNgOptionsValue(value) {
          var option = options.getOptionFromViewValue(value);

          if (option && !option.disabled) {
            if (selectElement[0].value !== option.selectValue) {
              removeUnknownOption();
              removeEmptyOption();

              selectElement[0].value = option.selectValue;
              option.element.selected = true;
              option.element.setAttribute('selected', 'selected');
            }
          } else {
            if (value === null || providedEmptyOption) {
              removeUnknownOption();
              renderEmptyOption();
            } else {
              removeEmptyOption();
              renderUnknownOption();
            }
          }
        };

        selectCtrl.readValue = function readNgOptionsValue() {

          var selectedOption = options.selectValueMap[selectElement.val()];

          if (selectedOption && !selectedOption.disabled) {
            removeEmptyOption();
            removeUnknownOption();
            return options.getViewValueFromOption(selectedOption);
          }
          return null;
        };

        // If we are using `track by` then we must watch the tracked value on the model
        // since ngModel only watches for object identity change
        if (ngOptions.trackBy) {
          scope.$watch(
            function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
            function() { ngModelCtrl.$render(); }
          );
        }

      } else {

        ngModelCtrl.$isEmpty = function(value) {
          return !value || value.length === 0;
        };


        selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
          options.items.forEach(function(option) {
            option.element.selected = false;
          });

          if (value) {
            value.forEach(function(item) {
              var option = options.getOptionFromViewValue(item);
              if (option && !option.disabled) option.element.selected = true;
            });
          }
        };


        selectCtrl.readValue = function readNgOptionsMultiple() {
          var selectedValues = selectElement.val() || [],
              selections = [];

          forEach(selectedValues, function(value) {
            var option = options.selectValueMap[value];
            if (!option.disabled) selections.push(options.getViewValueFromOption(option));
          });

          return selections;
        };

        // If we are using `track by` then we must watch these tracked values on the model
        // since ngModel only watches for object identity change
        if (ngOptions.trackBy) {

          scope.$watchCollection(function() {
            if (isArray(ngModelCtrl.$viewValue)) {
              return ngModelCtrl.$viewValue.map(function(value) {
                return ngOptions.getTrackByValue(value);
              });
            }
          }, function() {
            ngModelCtrl.$render();
          });

        }
      }


      if (providedEmptyOption) {

        // we need to remove it before calling selectElement.empty() because otherwise IE will
        // remove the label from the element. wtf?
        emptyOption.remove();

        // compile the element since there might be bindings in it
        $compile(emptyOption)(scope);

        // remove the class, which is added automatically because we recompile the element and it
        // becomes the compilation root
        emptyOption.removeClass('ng-scope');
      } else {
        emptyOption = jqLite(optionTemplate.cloneNode(false));
      }

      // We need to do this here to ensure that the options object is defined
      // when we first hit it in writeNgOptionsValue
      updateOptions();

      // We will re-render the option elements if the option values or labels change
      scope.$watchCollection(ngOptions.getWatchables, updateOptions);

      // ------------------------------------------------------------------ //


      function updateOptionElement(option, element) {
        option.element = element;
        element.disabled = option.disabled;
        if (option.value !== element.value) element.value = option.selectValue;
        if (option.label !== element.label) {
          element.label = option.label;
          element.textContent = option.label;
        }
      }

      function addOrReuseElement(parent, current, type, templateElement) {
        var element;
        // Check whether we can reuse the next element
        if (current && lowercase(current.nodeName) === type) {
          // The next element is the right type so reuse it
          element = current;
        } else {
          // The next element is not the right type so create a new one
          element = templateElement.cloneNode(false);
          if (!current) {
            // There are no more elements so just append it to the select
            parent.appendChild(element);
          } else {
            // The next element is not a group so insert the new one
            parent.insertBefore(element, current);
          }
        }
        return element;
      }


      function removeExcessElements(current) {
        var next;
        while (current) {
          next = current.nextSibling;
          jqLiteRemove(current);
          current = next;
        }
      }


      function skipEmptyAndUnknownOptions(current) {
        var emptyOption_ = emptyOption && emptyOption[0];
        var unknownOption_ = unknownOption && unknownOption[0];

        if (emptyOption_ || unknownOption_) {
          while (current &&
                (current === emptyOption_ ||
                current === unknownOption_)) {
            current = current.nextSibling;
          }
        }
        return current;
      }


      function updateOptions() {

        var previousValue = options && selectCtrl.readValue();

        options = ngOptions.getOptions();

        var groupMap = {};
        var currentElement = selectElement[0].firstChild;

        // Ensure that the empty option is always there if it was explicitly provided
        if (providedEmptyOption) {
          selectElement.prepend(emptyOption);
        }

        currentElement = skipEmptyAndUnknownOptions(currentElement);

        options.items.forEach(function updateOption(option) {
          var group;
          var groupElement;
          var optionElement;

          if (option.group) {

            // This option is to live in a group
            // See if we have already created this group
            group = groupMap[option.group];

            if (!group) {

              // We have not already created this group
              groupElement = addOrReuseElement(selectElement[0],
                                               currentElement,
                                               'optgroup',
                                               optGroupTemplate);
              // Move to the next element
              currentElement = groupElement.nextSibling;

              // Update the label on the group element
              groupElement.label = option.group;

              // Store it for use later
              group = groupMap[option.group] = {
                groupElement: groupElement,
                currentOptionElement: groupElement.firstChild
              };

            }

            // So now we have a group for this option we add the option to the group
            optionElement = addOrReuseElement(group.groupElement,
                                              group.currentOptionElement,
                                              'option',
                                              optionTemplate);
            updateOptionElement(option, optionElement);
            // Move to the next element
            group.currentOptionElement = optionElement.nextSibling;

          } else {

            // This option is not in a group
            optionElement = addOrReuseElement(selectElement[0],
                                              currentElement,
                                              'option',
                                              optionTemplate);
            updateOptionElement(option, optionElement);
            // Move to the next element
            currentElement = optionElement.nextSibling;
          }
        });


        // Now remove all excess options and group
        Object.keys(groupMap).forEach(function(key) {
          removeExcessElements(groupMap[key].currentOptionElement);
        });
        removeExcessElements(currentElement);

        ngModelCtrl.$render();

        // Check to see if the value has changed due to the update to the options
        if (!ngModelCtrl.$isEmpty(previousValue)) {
          var nextValue = selectCtrl.readValue();
          if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
            ngModelCtrl.$setViewValue(nextValue);
            ngModelCtrl.$render();
          }
        }

      }

    }
  };
}];

/**
 * @ngdoc directive
 * @name ngPluralize
 * @restrict EA
 *
 * @description
 * `ngPluralize` is a directive that displays messages according to en-US localization rules.
 * These rules are bundled with angular.js, but can be overridden
 * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
 * by specifying the mappings between
 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
 * and the strings to be displayed.
 *
 * # Plural categories and explicit number rules
 * There are two
 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
 * in Angular's default en-US locale: "one" and "other".
 *
 * While a plural category may match many numbers (for example, in en-US locale, "other" can match
 * any number that is not 1), an explicit number rule can only match one number. For example, the
 * explicit number rule for "3" matches the number 3. There are examples of plural categories
 * and explicit number rules throughout the rest of this documentation.
 *
 * # Configuring ngPluralize
 * You configure ngPluralize by providing 2 attributes: `count` and `when`.
 * You can also provide an optional attribute, `offset`.
 *
 * The value of the `count` attribute can be either a string or an {@link guide/expression
 * Angular expression}; these are evaluated on the current scope for its bound value.
 *
 * The `when` attribute specifies the mappings between plural categories and the actual
 * string to be displayed. The value of the attribute should be a JSON object.
 *
 * The following example shows how to configure ngPluralize:
 *
 * ```html
 * <ng-pluralize count="personCount"
                 when="{'0': 'Nobody is viewing.',
 *                      'one': '1 person is viewing.',
 *                      'other': '{} people are viewing.'}">
 * </ng-pluralize>
 *```
 *
 * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
 * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
 * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
 * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
 * show "a dozen people are viewing".
 *
 * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
 * into pluralized strings. In the previous example, Angular will replace `{}` with
 * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
 * for <span ng-non-bindable>{{numberExpression}}</span>.
 *
 * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
 * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
 *
 * # Configuring ngPluralize with offset
 * The `offset` attribute allows further customization of pluralized text, which can result in
 * a better user experience. For example, instead of the message "4 people are viewing this document",
 * you might display "John, Kate and 2 others are viewing this document".
 * The offset attribute allows you to offset a number by any desired value.
 * Let's take a look at an example:
 *
 * ```html
 * <ng-pluralize count="personCount" offset=2
 *               when="{'0': 'Nobody is viewing.',
 *                      '1': '{{person1}} is viewing.',
 *                      '2': '{{person1}} and {{person2}} are viewing.',
 *                      'one': '{{person1}}, {{person2}} and one other person are viewing.',
 *                      'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
 * </ng-pluralize>
 * ```
 *
 * Notice that we are still using two plural categories(one, other), but we added
 * three explicit number rules 0, 1 and 2.
 * When one person, perhaps John, views the document, "John is viewing" will be shown.
 * When three people view the document, no explicit number rule is found, so
 * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
 * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
 * is shown.
 *
 * Note that when you specify offsets, you must provide explicit number rules for
 * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
 * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
 * plural categories "one" and "other".
 *
 * @param {string|expression} count The variable to be bound to.
 * @param {string} when The mapping between plural category to its corresponding strings.
 * @param {number=} offset Offset to deduct from the total number.
 *
 * @example
    <example module="pluralizeExample">
      <file name="index.html">
        <script>
          angular.module('pluralizeExample', [])
            .controller('ExampleController', ['$scope', function($scope) {
              $scope.person1 = 'Igor';
              $scope.person2 = 'Misko';
              $scope.personCount = 1;
            }]);
        </script>
        <div ng-controller="ExampleController">
          <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
          <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
          <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>

          <!--- Example with simple pluralization rules for en locale --->
          Without Offset:
          <ng-pluralize count="personCount"
                        when="{'0': 'Nobody is viewing.',
                               'one': '1 person is viewing.',
                               'other': '{} people are viewing.'}">
          </ng-pluralize><br>

          <!--- Example with offset --->
          With Offset(2):
          <ng-pluralize count="personCount" offset=2
                        when="{'0': 'Nobody is viewing.',
                               '1': '{{person1}} is viewing.',
                               '2': '{{person1}} and {{person2}} are viewing.',
                               'one': '{{person1}}, {{person2}} and one other person are viewing.',
                               'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
          </ng-pluralize>
        </div>
      </file>
      <file name="protractor.js" type="protractor">
        it('should show correct pluralized string', function() {
          var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
          var withOffset = element.all(by.css('ng-pluralize')).get(1);
          var countInput = element(by.model('personCount'));

          expect(withoutOffset.getText()).toEqual('1 person is viewing.');
          expect(withOffset.getText()).toEqual('Igor is viewing.');

          countInput.clear();
          countInput.sendKeys('0');

          expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
          expect(withOffset.getText()).toEqual('Nobody is viewing.');

          countInput.clear();
          countInput.sendKeys('2');

          expect(withoutOffset.getText()).toEqual('2 people are viewing.');
          expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');

          countInput.clear();
          countInput.sendKeys('3');

          expect(withoutOffset.getText()).toEqual('3 people are viewing.');
          expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');

          countInput.clear();
          countInput.sendKeys('4');

          expect(withoutOffset.getText()).toEqual('4 people are viewing.');
          expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
        });
        it('should show data-bound names', function() {
          var withOffset = element.all(by.css('ng-pluralize')).get(1);
          var personCount = element(by.model('personCount'));
          var person1 = element(by.model('person1'));
          var person2 = element(by.model('person2'));
          personCount.clear();
          personCount.sendKeys('4');
          person1.clear();
          person1.sendKeys('Di');
          person2.clear();
          person2.sendKeys('Vojta');
          expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
        });
      </file>
    </example>
 */
var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  var BRACE = /{}/g,
      IS_WHEN = /^when(Minus)?(.+)$/;

  return {
    link: function(scope, element, attr) {
      var numberExp = attr.count,
          whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
          offset = attr.offset || 0,
          whens = scope.$eval(whenExp) || {},
          whensExpFns = {},
          startSymbol = $interpolate.startSymbol(),
          endSymbol = $interpolate.endSymbol(),
          braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
          watchRemover = angular.noop,
          lastCount;

      forEach(attr, function(expression, attributeName) {
        var tmpMatch = IS_WHEN.exec(attributeName);
        if (tmpMatch) {
          var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
          whens[whenKey] = element.attr(attr.$attr[attributeName]);
        }
      });
      forEach(whens, function(expression, key) {
        whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));

      });

      scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
        var count = parseFloat(newVal);
        var countIsNaN = isNaN(count);

        if (!countIsNaN && !(count in whens)) {
          // If an explicit number rule such as 1, 2, 3... is defined, just use it.
          // Otherwise, check it against pluralization rules in $locale service.
          count = $locale.pluralCat(count - offset);
        }

        // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
        // In JS `NaN !== NaN`, so we have to exlicitly check.
        if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
          watchRemover();
          var whenExpFn = whensExpFns[count];
          if (isUndefined(whenExpFn)) {
            if (newVal != null) {
              $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
            }
            watchRemover = noop;
            updateElementText();
          } else {
            watchRemover = scope.$watch(whenExpFn, updateElementText);
          }
          lastCount = count;
        }
      });

      function updateElementText(newText) {
        element.text(newText || '');
      }
    }
  };
}];

/**
 * @ngdoc directive
 * @name ngRepeat
 * @multiElement
 *
 * @description
 * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
 * instance gets its own scope, where the given loop variable is set to the current collection item,
 * and `$index` is set to the item index or key.
 *
 * Special properties are exposed on the local scope of each template instance, including:
 *
 * | Variable  | Type            | Details                                                                     |
 * |-----------|-----------------|-----------------------------------------------------------------------------|
 * | `$index`  | {@type number}  | iterator offset of the repeated element (0..length-1)                       |
 * | `$first`  | {@type boolean} | true if the repeated element is first in the iterator.                      |
 * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
 * | `$last`   | {@type boolean} | true if the repeated element is last in the iterator.                       |
 * | `$even`   | {@type boolean} | true if the iterator position `$index` is even (otherwise false).           |
 * | `$odd`    | {@type boolean} | true if the iterator position `$index` is odd (otherwise false).            |
 *
 * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
 * This may be useful when, for instance, nesting ngRepeats.
 *
 *
 * # Iterating over object properties
 *
 * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
 * syntax:
 *
 * ```js
 * <div ng-repeat="(key, value) in myObj"> ... </div>
 * ```
 *
 * You need to be aware that the JavaScript specification does not define the order of keys
 * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
 * used to sort the keys alphabetically.)
 *
 * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
 * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
 * keys in the order in which they were defined, although there are exceptions when keys are deleted
 * and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues
 *
 * If this is not desired, the recommended workaround is to convert your object into an array
 * that is sorted into the order that you prefer before providing it to `ngRepeat`.  You could
 * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
 * or implement a `$watch` on the object yourself.
 *
 *
 * # Tracking and Duplicates
 *
 * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:
 *
 * * When an item is added, a new instance of the template is added to the DOM.
 * * When an item is removed, its template instance is removed from the DOM.
 * * When items are reordered, their respective templates are reordered in the DOM.
 *
 * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when
 * there are duplicates, it is not possible to maintain a one-to-one mapping between collection
 * items and DOM elements.
 *
 * If you do need to repeat duplicate items, you can substitute the default tracking behavior
 * with your own using the `track by` expression.
 *
 * For example, you may track items by the index of each item in the collection, using the
 * special scope property `$index`:
 * ```html
 *    <div ng-repeat="n in [42, 42, 43, 43] track by $index">
 *      {{n}}
 *    </div>
 * ```
 *
 * You may use arbitrary expressions in `track by`, including references to custom functions
 * on the scope:
 * ```html
 *    <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
 *      {{n}}
 *    </div>
 * ```
 *
 * If you are working with objects that have an identifier property, you can track
 * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
 * will not have to rebuild the DOM elements for items it has already rendered, even if the
 * JavaScript objects in the collection have been substituted for new ones:
 * ```html
 *    <div ng-repeat="model in collection track by model.id">
 *      {{model.name}}
 *    </div>
 * ```
 *
 * When no `track by` expression is provided, it is equivalent to tracking by the built-in
 * `$id` function, which tracks items by their identity:
 * ```html
 *    <div ng-repeat="obj in collection track by $id(obj)">
 *      {{obj.prop}}
 *    </div>
 * ```
 *
 * <div class="alert alert-warning">
 * **Note:** `track by` must always be the last expression:
 * </div>
 * ```
 * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
 *     {{model.name}}
 * </div>
 * ```
 *
 * # Special repeat start and end points
 * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
 * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
 * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
 * up to and including the ending HTML tag where **ng-repeat-end** is placed.
 *
 * The example below makes use of this feature:
 * ```html
 *   <header ng-repeat-start="item in items">
 *     Header {{ item }}
 *   </header>
 *   <div class="body">
 *     Body {{ item }}
 *   </div>
 *   <footer ng-repeat-end>
 *     Footer {{ item }}
 *   </footer>
 * ```
 *
 * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
 * ```html
 *   <header>
 *     Header A
 *   </header>
 *   <div class="body">
 *     Body A
 *   </div>
 *   <footer>
 *     Footer A
 *   </footer>
 *   <header>
 *     Header B
 *   </header>
 *   <div class="body">
 *     Body B
 *   </div>
 *   <footer>
 *     Footer B
 *   </footer>
 * ```
 *
 * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
 * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
 *
 * @animations
 * **.enter** - when a new item is added to the list or when an item is revealed after a filter
 *
 * **.leave** - when an item is removed from the list or when an item is filtered out
 *
 * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
 *
 * @element ANY
 * @scope
 * @priority 1000
 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
 *   formats are currently supported:
 *
 *   * `variable in expression` – where variable is the user defined loop variable and `expression`
 *     is a scope expression giving the collection to enumerate.
 *
 *     For example: `album in artist.albums`.
 *
 *   * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
 *     and `expression` is the scope expression giving the collection to enumerate.
 *
 *     For example: `(name, age) in {'adam':10, 'amalie':12}`.
 *
 *   * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
 *     which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
 *     is specified, ng-repeat associates elements by identity. It is an error to have
 *     more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
 *     mapped to the same DOM element, which is not possible.)
 *
 *     Note that the tracking expression must come last, after any filters, and the alias expression.
 *
 *     For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
 *     will be associated by item identity in the array.
 *
 *     For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
 *     `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
 *     with the corresponding item in the array by identity. Moving the same object in array would move the DOM
 *     element in the same way in the DOM.
 *
 *     For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
 *     case the object identity does not matter. Two objects are considered equivalent as long as their `id`
 *     property is same.
 *
 *     For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
 *     to items in conjunction with a tracking expression.
 *
 *   * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
 *     intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
 *     when a filter is active on the repeater, but the filtered result set is empty.
 *
 *     For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
 *     the items have been processed through the filter.
 *
 *     Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end
 *     (and not as operator, inside an expression).
 *
 *     For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
 *
 * @example
 * This example initializes the scope to a list of names and
 * then uses `ngRepeat` to display every person:
  <example module="ngAnimate" deps="angular-animate.js" animations="true">
    <file name="index.html">
      <div ng-init="friends = [
        {name:'John', age:25, gender:'boy'},
        {name:'Jessie', age:30, gender:'girl'},
        {name:'Johanna', age:28, gender:'girl'},
        {name:'Joy', age:15, gender:'girl'},
        {name:'Mary', age:28, gender:'girl'},
        {name:'Peter', age:95, gender:'boy'},
        {name:'Sebastian', age:50, gender:'boy'},
        {name:'Erika', age:27, gender:'girl'},
        {name:'Patrick', age:40, gender:'boy'},
        {name:'Samantha', age:60, gender:'girl'}
      ]">
        I have {{friends.length}} friends. They are:
        <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
        <ul class="example-animate-container">
          <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
            [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
          </li>
          <li class="animate-repeat" ng-if="results.length == 0">
            <strong>No results found...</strong>
          </li>
        </ul>
      </div>
    </file>
    <file name="animations.css">
      .example-animate-container {
        background:white;
        border:1px solid black;
        list-style:none;
        margin:0;
        padding:0 10px;
      }

      .animate-repeat {
        line-height:40px;
        list-style:none;
        box-sizing:border-box;
      }

      .animate-repeat.ng-move,
      .animate-repeat.ng-enter,
      .animate-repeat.ng-leave {
        -webkit-transition:all linear 0.5s;
        transition:all linear 0.5s;
      }

      .animate-repeat.ng-leave.ng-leave-active,
      .animate-repeat.ng-move,
      .animate-repeat.ng-enter {
        opacity:0;
        max-height:0;
      }

      .animate-repeat.ng-leave,
      .animate-repeat.ng-move.ng-move-active,
      .animate-repeat.ng-enter.ng-enter-active {
        opacity:1;
        max-height:40px;
      }
    </file>
    <file name="protractor.js" type="protractor">
      var friends = element.all(by.repeater('friend in friends'));

      it('should render initial data set', function() {
        expect(friends.count()).toBe(10);
        expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
        expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
        expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
        expect(element(by.binding('friends.length')).getText())
            .toMatch("I have 10 friends. They are:");
      });

       it('should update repeater when filter predicate changes', function() {
         expect(friends.count()).toBe(10);

         element(by.model('q')).sendKeys('ma');

         expect(friends.count()).toBe(2);
         expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
         expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
       });
      </file>
    </example>
 */
var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  var NG_REMOVED = '$$NG_REMOVED';
  var ngRepeatMinErr = minErr('ngRepeat');

  var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
    // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
    scope[valueIdentifier] = value;
    if (keyIdentifier) scope[keyIdentifier] = key;
    scope.$index = index;
    scope.$first = (index === 0);
    scope.$last = (index === (arrayLength - 1));
    scope.$middle = !(scope.$first || scope.$last);
    // jshint bitwise: false
    scope.$odd = !(scope.$even = (index&1) === 0);
    // jshint bitwise: true
  };

  var getBlockStart = function(block) {
    return block.clone[0];
  };

  var getBlockEnd = function(block) {
    return block.clone[block.clone.length - 1];
  };


  return {
    restrict: 'A',
    multiElement: true,
    transclude: 'element',
    priority: 1000,
    terminal: true,
    $$tlb: true,
    compile: function ngRepeatCompile($element, $attr) {
      var expression = $attr.ngRepeat;
      var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');

      var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);

      if (!match) {
        throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
            expression);
      }

      var lhs = match[1];
      var rhs = match[2];
      var aliasAs = match[3];
      var trackByExp = match[4];

      match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);

      if (!match) {
        throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
            lhs);
      }
      var valueIdentifier = match[3] || match[1];
      var keyIdentifier = match[2];

      if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
          /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
        throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
          aliasAs);
      }

      var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
      var hashFnLocals = {$id: hashKey};

      if (trackByExp) {
        trackByExpGetter = $parse(trackByExp);
      } else {
        trackByIdArrayFn = function(key, value) {
          return hashKey(value);
        };
        trackByIdObjFn = function(key) {
          return key;
        };
      }

      return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {

        if (trackByExpGetter) {
          trackByIdExpFn = function(key, value, index) {
            // assign key, value, and $index to the locals so that they can be used in hash functions
            if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
            hashFnLocals[valueIdentifier] = value;
            hashFnLocals.$index = index;
            return trackByExpGetter($scope, hashFnLocals);
          };
        }

        // Store a list of elements from previous run. This is a hash where key is the item from the
        // iterator, and the value is objects with following properties.
        //   - scope: bound scope
        //   - element: previous element.
        //   - index: position
        //
        // We are using no-proto object so that we don't need to guard against inherited props via
        // hasOwnProperty.
        var lastBlockMap = createMap();

        //watch props
        $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
          var index, length,
              previousNode = $element[0],     // node that cloned nodes should be inserted after
                                              // initialized to the comment node anchor
              nextNode,
              // Same as lastBlockMap but it has the current state. It will become the
              // lastBlockMap on the next iteration.
              nextBlockMap = createMap(),
              collectionLength,
              key, value, // key/value of iteration
              trackById,
              trackByIdFn,
              collectionKeys,
              block,       // last object information {scope, element, id}
              nextBlockOrder,
              elementsToRemove;

          if (aliasAs) {
            $scope[aliasAs] = collection;
          }

          if (isArrayLike(collection)) {
            collectionKeys = collection;
            trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
          } else {
            trackByIdFn = trackByIdExpFn || trackByIdObjFn;
            // if object, extract keys, in enumeration order, unsorted
            collectionKeys = [];
            for (var itemKey in collection) {
              if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
                collectionKeys.push(itemKey);
              }
            }
          }

          collectionLength = collectionKeys.length;
          nextBlockOrder = new Array(collectionLength);

          // locate existing items
          for (index = 0; index < collectionLength; index++) {
            key = (collection === collectionKeys) ? index : collectionKeys[index];
            value = collection[key];
            trackById = trackByIdFn(key, value, index);
            if (lastBlockMap[trackById]) {
              // found previously seen block
              block = lastBlockMap[trackById];
              delete lastBlockMap[trackById];
              nextBlockMap[trackById] = block;
              nextBlockOrder[index] = block;
            } else if (nextBlockMap[trackById]) {
              // if collision detected. restore lastBlockMap and throw an error
              forEach(nextBlockOrder, function(block) {
                if (block && block.scope) lastBlockMap[block.id] = block;
              });
              throw ngRepeatMinErr('dupes',
                  "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
                  expression, trackById, value);
            } else {
              // new never before seen block
              nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
              nextBlockMap[trackById] = true;
            }
          }

          // remove leftover items
          for (var blockKey in lastBlockMap) {
            block = lastBlockMap[blockKey];
            elementsToRemove = getBlockNodes(block.clone);
            $animate.leave(elementsToRemove);
            if (elementsToRemove[0].parentNode) {
              // if the element was not removed yet because of pending animation, mark it as deleted
              // so that we can ignore it later
              for (index = 0, length = elementsToRemove.length; index < length; index++) {
                elementsToRemove[index][NG_REMOVED] = true;
              }
            }
            block.scope.$destroy();
          }

          // we are not using forEach for perf reasons (trying to avoid #call)
          for (index = 0; index < collectionLength; index++) {
            key = (collection === collectionKeys) ? index : collectionKeys[index];
            value = collection[key];
            block = nextBlockOrder[index];

            if (block.scope) {
              // if we have already seen this object, then we need to reuse the
              // associated scope/element

              nextNode = previousNode;

              // skip nodes that are already pending removal via leave animation
              do {
                nextNode = nextNode.nextSibling;
              } while (nextNode && nextNode[NG_REMOVED]);

              if (getBlockStart(block) != nextNode) {
                // existing item which got moved
                $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
              }
              previousNode = getBlockEnd(block);
              updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
            } else {
              // new item which we don't know about
              $transclude(function ngRepeatTransclude(clone, scope) {
                block.scope = scope;
                // http://jsperf.com/clone-vs-createcomment
                var endNode = ngRepeatEndComment.cloneNode(false);
                clone[clone.length++] = endNode;

                // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
                $animate.enter(clone, null, jqLite(previousNode));
                previousNode = endNode;
                // Note: We only need the first/last node of the cloned nodes.
                // However, we need to keep the reference to the jqlite wrapper as it might be changed later
                // by a directive with templateUrl when its template arrives.
                block.clone = clone;
                nextBlockMap[block.id] = block;
                updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
              });
            }
          }
          lastBlockMap = nextBlockMap;
        });
      };
    }
  };
}];

var NG_HIDE_CLASS = 'ng-hide';
var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
/**
 * @ngdoc directive
 * @name ngShow
 * @multiElement
 *
 * @description
 * The `ngShow` directive shows or hides the given HTML element based on the expression
 * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
 * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
 * in AngularJS and sets the display style to none (using an !important flag).
 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
 *
 * ```html
 * <!-- when $scope.myValue is truthy (element is visible) -->
 * <div ng-show="myValue"></div>
 *
 * <!-- when $scope.myValue is falsy (element is hidden) -->
 * <div ng-show="myValue" class="ng-hide"></div>
 * ```
 *
 * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
 * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
 * from the element causing the element not to appear hidden.
 *
 * ## Why is !important used?
 *
 * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
 * can be easily overridden by heavier selectors. For example, something as simple
 * as changing the display style on a HTML list item would make hidden elements appear visible.
 * This also becomes a bigger issue when dealing with CSS frameworks.
 *
 * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
 * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
 * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
 *
 * ### Overriding `.ng-hide`
 *
 * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
 * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
 * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
 * with extra animation classes that can be added.
 *
 * ```css
 * .ng-hide:not(.ng-hide-animate) {
 *   /&#42; this is just another form of hiding an element &#42;/
 *   display: block!important;
 *   position: absolute;
 *   top: -9999px;
 *   left: -9999px;
 * }
 * ```
 *
 * By default you don't need to override in CSS anything and the animations will work around the display style.
 *
 * ## A note about animations with `ngShow`
 *
 * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
 * is true and false. This system works like the animation system present with ngClass except that
 * you must also include the !important flag to override the display property
 * so that you can perform an animation when the element is hidden during the time of the animation.
 *
 * ```css
 * //
 * //a working example can be found at the bottom of this page
 * //
 * .my-element.ng-hide-add, .my-element.ng-hide-remove {
 *   /&#42; this is required as of 1.3x to properly
 *      apply all styling in a show/hide animation &#42;/
 *   transition: 0s linear all;
 * }
 *
 * .my-element.ng-hide-add-active,
 * .my-element.ng-hide-remove-active {
 *   /&#42; the transition is defined in the active class &#42;/
 *   transition: 1s linear all;
 * }
 *
 * .my-element.ng-hide-add { ... }
 * .my-element.ng-hide-add.ng-hide-add-active { ... }
 * .my-element.ng-hide-remove { ... }
 * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
 * ```
 *
 * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
 * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
 *
 * @animations
 * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
 * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
 *
 * @element ANY
 * @param {expression} ngShow If the {@link guide/expression expression} is truthy
 *     then the element is shown or hidden respectively.
 *
 * @example
  <example module="ngAnimate" deps="angular-animate.js" animations="true">
    <file name="index.html">
      Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
      <div>
        Show:
        <div class="check-element animate-show" ng-show="checked">
          <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
        </div>
      </div>
      <div>
        Hide:
        <div class="check-element animate-show" ng-hide="checked">
          <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
        </div>
      </div>
    </file>
    <file name="glyphicons.css">
      @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
    </file>
    <file name="animations.css">
      .animate-show {
        line-height: 20px;
        opacity: 1;
        padding: 10px;
        border: 1px solid black;
        background: white;
      }

      .animate-show.ng-hide-add.ng-hide-add-active,
      .animate-show.ng-hide-remove.ng-hide-remove-active {
        -webkit-transition: all linear 0.5s;
        transition: all linear 0.5s;
      }

      .animate-show.ng-hide {
        line-height: 0;
        opacity: 0;
        padding: 0 10px;
      }

      .check-element {
        padding: 10px;
        border: 1px solid black;
        background: white;
      }
    </file>
    <file name="protractor.js" type="protractor">
      var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
      var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));

      it('should check ng-show / ng-hide', function() {
        expect(thumbsUp.isDisplayed()).toBeFalsy();
        expect(thumbsDown.isDisplayed()).toBeTruthy();

        element(by.model('checked')).click();

        expect(thumbsUp.isDisplayed()).toBeTruthy();
        expect(thumbsDown.isDisplayed()).toBeFalsy();
      });
    </file>
  </example>
 */
var ngShowDirective = ['$animate', function($animate) {
  return {
    restrict: 'A',
    multiElement: true,
    link: function(scope, element, attr) {
      scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
        // we're adding a temporary, animation-specific class for ng-hide since this way
        // we can control when the element is actually displayed on screen without having
        // to have a global/greedy CSS selector that breaks when other animations are run.
        // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
        $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
          tempClasses: NG_HIDE_IN_PROGRESS_CLASS
        });
      });
    }
  };
}];


/**
 * @ngdoc directive
 * @name ngHide
 * @multiElement
 *
 * @description
 * The `ngHide` directive shows or hides the given HTML element based on the expression
 * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
 * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
 * in AngularJS and sets the display style to none (using an !important flag).
 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
 *
 * ```html
 * <!-- when $scope.myValue is truthy (element is hidden) -->
 * <div ng-hide="myValue" class="ng-hide"></div>
 *
 * <!-- when $scope.myValue is falsy (element is visible) -->
 * <div ng-hide="myValue"></div>
 * ```
 *
 * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
 * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
 * from the element causing the element not to appear hidden.
 *
 * ## Why is !important used?
 *
 * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
 * can be easily overridden by heavier selectors. For example, something as simple
 * as changing the display style on a HTML list item would make hidden elements appear visible.
 * This also becomes a bigger issue when dealing with CSS frameworks.
 *
 * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
 * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
 * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
 *
 * ### Overriding `.ng-hide`
 *
 * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
 * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
 * class in CSS:
 *
 * ```css
 * .ng-hide {
 *   /&#42; this is just another form of hiding an element &#42;/
 *   display: block!important;
 *   position: absolute;
 *   top: -9999px;
 *   left: -9999px;
 * }
 * ```
 *
 * By default you don't need to override in CSS anything and the animations will work around the display style.
 *
 * ## A note about animations with `ngHide`
 *
 * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
 * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
 * CSS class is added and removed for you instead of your own CSS class.
 *
 * ```css
 * //
 * //a working example can be found at the bottom of this page
 * //
 * .my-element.ng-hide-add, .my-element.ng-hide-remove {
 *   transition: 0.5s linear all;
 * }
 *
 * .my-element.ng-hide-add { ... }
 * .my-element.ng-hide-add.ng-hide-add-active { ... }
 * .my-element.ng-hide-remove { ... }
 * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
 * ```
 *
 * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
 * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
 *
 * @animations
 * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
 * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
 *
 * @element ANY
 * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
 *     the element is shown or hidden respectively.
 *
 * @example
  <example module="ngAnimate" deps="angular-animate.js" animations="true">
    <file name="index.html">
      Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
      <div>
        Show:
        <div class="check-element animate-hide" ng-show="checked">
          <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
        </div>
      </div>
      <div>
        Hide:
        <div class="check-element animate-hide" ng-hide="checked">
          <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
        </div>
      </div>
    </file>
    <file name="glyphicons.css">
      @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
    </file>
    <file name="animations.css">
      .animate-hide {
        -webkit-transition: all linear 0.5s;
        transition: all linear 0.5s;
        line-height: 20px;
        opacity: 1;
        padding: 10px;
        border: 1px solid black;
        background: white;
      }

      .animate-hide.ng-hide {
        line-height: 0;
        opacity: 0;
        padding: 0 10px;
      }

      .check-element {
        padding: 10px;
        border: 1px solid black;
        background: white;
      }
    </file>
    <file name="protractor.js" type="protractor">
      var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
      var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));

      it('should check ng-show / ng-hide', function() {
        expect(thumbsUp.isDisplayed()).toBeFalsy();
        expect(thumbsDown.isDisplayed()).toBeTruthy();

        element(by.model('checked')).click();

        expect(thumbsUp.isDisplayed()).toBeTruthy();
        expect(thumbsDown.isDisplayed()).toBeFalsy();
      });
    </file>
  </example>
 */
var ngHideDirective = ['$animate', function($animate) {
  return {
    restrict: 'A',
    multiElement: true,
    link: function(scope, element, attr) {
      scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
        // The comment inside of the ngShowDirective explains why we add and
        // remove a temporary class for the show/hide animation
        $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
          tempClasses: NG_HIDE_IN_PROGRESS_CLASS
        });
      });
    }
  };
}];

/**
 * @ngdoc directive
 * @name ngStyle
 * @restrict AC
 *
 * @description
 * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
 *
 * @element ANY
 * @param {expression} ngStyle
 *
 * {@link guide/expression Expression} which evals to an
 * object whose keys are CSS style names and values are corresponding values for those CSS
 * keys.
 *
 * Since some CSS style names are not valid keys for an object, they must be quoted.
 * See the 'background-color' style in the example below.
 *
 * @example
   <example>
     <file name="index.html">
        <input type="button" value="set color" ng-click="myStyle={color:'red'}">
        <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
        <input type="button" value="clear" ng-click="myStyle={}">
        <br/>
        <span ng-style="myStyle">Sample Text</span>
        <pre>myStyle={{myStyle}}</pre>
     </file>
     <file name="style.css">
       span {
         color: black;
       }
     </file>
     <file name="protractor.js" type="protractor">
       var colorSpan = element(by.css('span'));

       it('should check ng-style', function() {
         expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
         element(by.css('input[value=\'set color\']')).click();
         expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
         element(by.css('input[value=clear]')).click();
         expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
       });
     </file>
   </example>
 */
var ngStyleDirective = ngDirective(function(scope, element, attr) {
  scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
    if (oldStyles && (newStyles !== oldStyles)) {
      forEach(oldStyles, function(val, style) { element.css(style, '');});
    }
    if (newStyles) element.css(newStyles);
  }, true);
});

/**
 * @ngdoc directive
 * @name ngSwitch
 * @restrict EA
 *
 * @description
 * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
 * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
 * as specified in the template.
 *
 * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
 * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
 * matches the value obtained from the evaluated expression. In other words, you define a container element
 * (where you place the directive), place an expression on the **`on="..."` attribute**
 * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
 * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
 * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
 * attribute is displayed.
 *
 * <div class="alert alert-info">
 * Be aware that the attribute values to match against cannot be expressions. They are interpreted
 * as literal string values to match against.
 * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
 * value of the expression `$scope.someVal`.
 * </div>

 * @animations
 * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
 * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
 *
 * @usage
 *
 * ```
 * <ANY ng-switch="expression">
 *   <ANY ng-switch-when="matchValue1">...</ANY>
 *   <ANY ng-switch-when="matchValue2">...</ANY>
 *   <ANY ng-switch-default>...</ANY>
 * </ANY>
 * ```
 *
 *
 * @scope
 * @priority 1200
 * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
 * On child elements add:
 *
 * * `ngSwitchWhen`: the case statement to match against. If match then this
 *   case will be displayed. If the same match appears multiple times, all the
 *   elements will be displayed.
 * * `ngSwitchDefault`: the default case when no other case match. If there
 *   are multiple default cases, all of them will be displayed when no other
 *   case match.
 *
 *
 * @example
  <example module="switchExample" deps="angular-animate.js" animations="true">
    <file name="index.html">
      <div ng-controller="ExampleController">
        <select ng-model="selection" ng-options="item for item in items">
        </select>
        <code>selection={{selection}}</code>
        <hr/>
        <div class="animate-switch-container"
          ng-switch on="selection">
            <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
            <div class="animate-switch" ng-switch-when="home">Home Span</div>
            <div class="animate-switch" ng-switch-default>default</div>
        </div>
      </div>
    </file>
    <file name="script.js">
      angular.module('switchExample', ['ngAnimate'])
        .controller('ExampleController', ['$scope', function($scope) {
          $scope.items = ['settings', 'home', 'other'];
          $scope.selection = $scope.items[0];
        }]);
    </file>
    <file name="animations.css">
      .animate-switch-container {
        position:relative;
        background:white;
        border:1px solid black;
        height:40px;
        overflow:hidden;
      }

      .animate-switch {
        padding:10px;
      }

      .animate-switch.ng-animate {
        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;

        position:absolute;
        top:0;
        left:0;
        right:0;
        bottom:0;
      }

      .animate-switch.ng-leave.ng-leave-active,
      .animate-switch.ng-enter {
        top:-50px;
      }
      .animate-switch.ng-leave,
      .animate-switch.ng-enter.ng-enter-active {
        top:0;
      }
    </file>
    <file name="protractor.js" type="protractor">
      var switchElem = element(by.css('[ng-switch]'));
      var select = element(by.model('selection'));

      it('should start in settings', function() {
        expect(switchElem.getText()).toMatch(/Settings Div/);
      });
      it('should change to home', function() {
        select.all(by.css('option')).get(1).click();
        expect(switchElem.getText()).toMatch(/Home Span/);
      });
      it('should select default', function() {
        select.all(by.css('option')).get(2).click();
        expect(switchElem.getText()).toMatch(/default/);
      });
    </file>
  </example>
 */
var ngSwitchDirective = ['$animate', function($animate) {
  return {
    require: 'ngSwitch',

    // asks for $scope to fool the BC controller module
    controller: ['$scope', function ngSwitchController() {
     this.cases = {};
    }],
    link: function(scope, element, attr, ngSwitchController) {
      var watchExpr = attr.ngSwitch || attr.on,
          selectedTranscludes = [],
          selectedElements = [],
          previousLeaveAnimations = [],
          selectedScopes = [];

      var spliceFactory = function(array, index) {
          return function() { array.splice(index, 1); };
      };

      scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
        var i, ii;
        for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
          $animate.cancel(previousLeaveAnimations[i]);
        }
        previousLeaveAnimations.length = 0;

        for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
          var selected = getBlockNodes(selectedElements[i].clone);
          selectedScopes[i].$destroy();
          var promise = previousLeaveAnimations[i] = $animate.leave(selected);
          promise.then(spliceFactory(previousLeaveAnimations, i));
        }

        selectedElements.length = 0;
        selectedScopes.length = 0;

        if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
          forEach(selectedTranscludes, function(selectedTransclude) {
            selectedTransclude.transclude(function(caseElement, selectedScope) {
              selectedScopes.push(selectedScope);
              var anchor = selectedTransclude.element;
              caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
              var block = { clone: caseElement };

              selectedElements.push(block);
              $animate.enter(caseElement, anchor.parent(), anchor);
            });
          });
        }
      });
    }
  };
}];

var ngSwitchWhenDirective = ngDirective({
  transclude: 'element',
  priority: 1200,
  require: '^ngSwitch',
  multiElement: true,
  link: function(scope, element, attrs, ctrl, $transclude) {
    ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
    ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  }
});

var ngSwitchDefaultDirective = ngDirective({
  transclude: 'element',
  priority: 1200,
  require: '^ngSwitch',
  multiElement: true,
  link: function(scope, element, attr, ctrl, $transclude) {
    ctrl.cases['?'] = (ctrl.cases['?'] || []);
    ctrl.cases['?'].push({ transclude: $transclude, element: element });
   }
});

/**
 * @ngdoc directive
 * @name ngTransclude
 * @restrict EAC
 *
 * @description
 * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
 *
 * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
 *
 * @element ANY
 *
 * @example
   <example module="transcludeExample">
     <file name="index.html">
       <script>
         angular.module('transcludeExample', [])
          .directive('pane', function(){
             return {
               restrict: 'E',
               transclude: true,
               scope: { title:'@' },
               template: '<div style="border: 1px solid black;">' +
                           '<div style="background-color: gray">{{title}}</div>' +
                           '<ng-transclude></ng-transclude>' +
                         '</div>'
             };
         })
         .controller('ExampleController', ['$scope', function($scope) {
           $scope.title = 'Lorem Ipsum';
           $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
         }]);
       </script>
       <div ng-controller="ExampleController">
         <input ng-model="title" aria-label="title"> <br/>
         <textarea ng-model="text" aria-label="text"></textarea> <br/>
         <pane title="{{title}}">{{text}}</pane>
       </div>
     </file>
     <file name="protractor.js" type="protractor">
        it('should have transcluded', function() {
          var titleElement = element(by.model('title'));
          titleElement.clear();
          titleElement.sendKeys('TITLE');
          var textElement = element(by.model('text'));
          textElement.clear();
          textElement.sendKeys('TEXT');
          expect(element(by.binding('title')).getText()).toEqual('TITLE');
          expect(element(by.binding('text')).getText()).toEqual('TEXT');
        });
     </file>
   </example>
 *
 */
var ngTranscludeDirective = ngDirective({
  restrict: 'EAC',
  link: function($scope, $element, $attrs, controller, $transclude) {
    if (!$transclude) {
      throw minErr('ngTransclude')('orphan',
       'Illegal use of ngTransclude directive in the template! ' +
       'No parent directive that requires a transclusion found. ' +
       'Element: {0}',
       startingTag($element));
    }

    $transclude(function(clone) {
      $element.empty();
      $element.append(clone);
    });
  }
});

/**
 * @ngdoc directive
 * @name script
 * @restrict E
 *
 * @description
 * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
 * template can be used by {@link ng.directive:ngInclude `ngInclude`},
 * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
 * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
 * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
 *
 * @param {string} type Must be set to `'text/ng-template'`.
 * @param {string} id Cache name of the template.
 *
 * @example
  <example>
    <file name="index.html">
      <script type="text/ng-template" id="/tpl.html">
        Content of the template.
      </script>

      <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
      <div id="tpl-content" ng-include src="currentTpl"></div>
    </file>
    <file name="protractor.js" type="protractor">
      it('should load template defined inside script tag', function() {
        element(by.css('#tpl-link')).click();
        expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
      });
    </file>
  </example>
 */
var scriptDirective = ['$templateCache', function($templateCache) {
  return {
    restrict: 'E',
    terminal: true,
    compile: function(element, attr) {
      if (attr.type == 'text/ng-template') {
        var templateUrl = attr.id,
            text = element[0].text;

        $templateCache.put(templateUrl, text);
      }
    }
  };
}];

var noopNgModelController = { $setViewValue: noop, $render: noop };

/**
 * @ngdoc type
 * @name  select.SelectController
 * @description
 * The controller for the `<select>` directive. This provides support for reading
 * and writing the selected value(s) of the control and also coordinates dynamically
 * added `<option>` elements, perhaps by an `ngRepeat` directive.
 */
var SelectController =
        ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {

  var self = this,
      optionsMap = new HashMap();

  // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  self.ngModelCtrl = noopNgModelController;

  // The "unknown" option is one that is prepended to the list if the viewValue
  // does not match any of the options. When it is rendered the value of the unknown
  // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  //
  // We can't just jqLite('<option>') since jqLite is not smart enough
  // to create it in <select> and IE barfs otherwise.
  self.unknownOption = jqLite(document.createElement('option'));
  self.renderUnknownOption = function(val) {
    var unknownVal = '? ' + hashKey(val) + ' ?';
    self.unknownOption.val(unknownVal);
    $element.prepend(self.unknownOption);
    $element.val(unknownVal);
  };

  $scope.$on('$destroy', function() {
    // disable unknown option so that we don't do work when the whole select is being destroyed
    self.renderUnknownOption = noop;
  });

  self.removeUnknownOption = function() {
    if (self.unknownOption.parent()) self.unknownOption.remove();
  };


  // Read the value of the select control, the implementation of this changes depending
  // upon whether the select can have multiple values and whether ngOptions is at work.
  self.readValue = function readSingleValue() {
    self.removeUnknownOption();
    return $element.val();
  };


  // Write the value to the select control, the implementation of this changes depending
  // upon whether the select can have multiple values and whether ngOptions is at work.
  self.writeValue = function writeSingleValue(value) {
    if (self.hasOption(value)) {
      self.removeUnknownOption();
      $element.val(value);
      if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
    } else {
      if (value == null && self.emptyOption) {
        self.removeUnknownOption();
        $element.val('');
      } else {
        self.renderUnknownOption(value);
      }
    }
  };


  // Tell the select control that an option, with the given value, has been added
  self.addOption = function(value, element) {
    assertNotHasOwnProperty(value, '"option value"');
    if (value === '') {
      self.emptyOption = element;
    }
    var count = optionsMap.get(value) || 0;
    optionsMap.put(value, count + 1);
  };

  // Tell the select control that an option, with the given value, has been removed
  self.removeOption = function(value) {
    var count = optionsMap.get(value);
    if (count) {
      if (count === 1) {
        optionsMap.remove(value);
        if (value === '') {
          self.emptyOption = undefined;
        }
      } else {
        optionsMap.put(value, count - 1);
      }
    }
  };

  // Check whether the select control has an option matching the given value
  self.hasOption = function(value) {
    return !!optionsMap.get(value);
  };
}];

/**
 * @ngdoc directive
 * @name select
 * @restrict E
 *
 * @description
 * HTML `SELECT` element with angular data-binding.
 *
 * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
 * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits such as reducing
 * memory and increasing speed by not creating a new scope for each repeated instance, as well as providing
 * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
 * comprehension expression.
 *
 * When an item in the `<select>` menu is selected, the array element or object property
 * represented by the selected option will be bound to the model identified by the `ngModel`
 * directive.
 *
 * If the viewValue contains a value that doesn't match any of the options then the control
 * will automatically add an "unknown" option, which it then removes when this is resolved.
 *
 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
 * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
 * option. See example below for demonstration.
 *
 * <div class="alert alert-info">
 * The value of a `select` directive used without `ngOptions` is always a string.
 * When the model needs to be bound to a non-string value, you must either explictly convert it
 * using a directive (see example below) or use `ngOptions` to specify the set of options.
 * This is because an option element can only be bound to string values at present.
 * </div>
 *
 * ### Example (binding `select` to a non-string value)
 *
 * <example name="select-with-non-string-options" module="nonStringSelect">
 *   <file name="index.html">
 *     <select ng-model="model.id" convert-to-number>
 *       <option value="0">Zero</option>
 *       <option value="1">One</option>
 *       <option value="2">Two</option>
 *     </select>
 *     {{ model }}
 *   </file>
 *   <file name="app.js">
 *     angular.module('nonStringSelect', [])
 *       .run(function($rootScope) {
 *         $rootScope.model = { id: 2 };
 *       })
 *       .directive('convertToNumber', function() {
 *         return {
 *           require: 'ngModel',
 *           link: function(scope, element, attrs, ngModel) {
 *             ngModel.$parsers.push(function(val) {
 *               return parseInt(val, 10);
 *             });
 *             ngModel.$formatters.push(function(val) {
 *               return '' + val;
 *             });
 *           }
 *         };
 *       });
 *   </file>
 *   <file name="protractor.js" type="protractor">
 *     it('should initialize to model', function() {
 *       var select = element(by.css('select'));
 *       expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
 *     });
 *   </file>
 * </example>
 *
 */
var selectDirective = function() {

  return {
    restrict: 'E',
    require: ['select', '?ngModel'],
    controller: SelectController,
    link: function(scope, element, attr, ctrls) {

      // if ngModel is not defined, we don't need to do anything
      var ngModelCtrl = ctrls[1];
      if (!ngModelCtrl) return;

      var selectCtrl = ctrls[0];

      selectCtrl.ngModelCtrl = ngModelCtrl;

      // We delegate rendering to the `writeValue` method, which can be changed
      // if the select can have multiple selected values or if the options are being
      // generated by `ngOptions`
      ngModelCtrl.$render = function() {
        selectCtrl.writeValue(ngModelCtrl.$viewValue);
      };

      // When the selected item(s) changes we delegate getting the value of the select control
      // to the `readValue` method, which can be changed if the select can have multiple
      // selected values or if the options are being generated by `ngOptions`
      element.on('change', function() {
        scope.$apply(function() {
          ngModelCtrl.$setViewValue(selectCtrl.readValue());
        });
      });

      // If the select allows multiple values then we need to modify how we read and write
      // values from and to the control; also what it means for the value to be empty and
      // we have to add an extra watch since ngModel doesn't work well with arrays - it
      // doesn't trigger rendering if only an item in the array changes.
      if (attr.multiple) {

        // Read value now needs to check each option to see if it is selected
        selectCtrl.readValue = function readMultipleValue() {
          var array = [];
          forEach(element.find('option'), function(option) {
            if (option.selected) {
              array.push(option.value);
            }
          });
          return array;
        };

        // Write value now needs to set the selected property of each matching option
        selectCtrl.writeValue = function writeMultipleValue(value) {
          var items = new HashMap(value);
          forEach(element.find('option'), function(option) {
            option.selected = isDefined(items.get(option.value));
          });
        };

        // we have to do it on each watch since ngModel watches reference, but
        // we need to work of an array, so we need to see if anything was inserted/removed
        var lastView, lastViewRef = NaN;
        scope.$watch(function selectMultipleWatch() {
          if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
            lastView = shallowCopy(ngModelCtrl.$viewValue);
            ngModelCtrl.$render();
          }
          lastViewRef = ngModelCtrl.$viewValue;
        });

        // If we are a multiple select then value is now a collection
        // so the meaning of $isEmpty changes
        ngModelCtrl.$isEmpty = function(value) {
          return !value || value.length === 0;
        };

      }
    }
  };
};


// The option directive is purely designed to communicate the existence (or lack of)
// of dynamically created (and destroyed) option elements to their containing select
// directive via its controller.
var optionDirective = ['$interpolate', function($interpolate) {

  function chromeHack(optionElement) {
    // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
    // Adding an <option selected="selected"> element to a <select required="required"> should
    // automatically select the new element
    if (optionElement[0].hasAttribute('selected')) {
      optionElement[0].selected = true;
    }
  }

  return {
    restrict: 'E',
    priority: 100,
    compile: function(element, attr) {

      // If the value attribute is not defined then we fall back to the
      // text content of the option element, which may be interpolated
      if (isUndefined(attr.value)) {
        var interpolateFn = $interpolate(element.text(), true);
        if (!interpolateFn) {
          attr.$set('value', element.text());
        }
      }

      return function(scope, element, attr) {

        // This is an optimization over using ^^ since we don't want to have to search
        // all the way to the root of the DOM for every single option element
        var selectCtrlName = '$selectController',
            parent = element.parent(),
            selectCtrl = parent.data(selectCtrlName) ||
              parent.parent().data(selectCtrlName); // in case we are in optgroup

        // Only update trigger option updates if this is an option within a `select`
        // that also has `ngModel` attached
        if (selectCtrl && selectCtrl.ngModelCtrl) {

          if (interpolateFn) {
            scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
              attr.$set('value', newVal);
              if (oldVal !== newVal) {
                selectCtrl.removeOption(oldVal);
              }
              selectCtrl.addOption(newVal, element);
              selectCtrl.ngModelCtrl.$render();
              chromeHack(element);
            });
          } else {
            selectCtrl.addOption(attr.value, element);
            selectCtrl.ngModelCtrl.$render();
            chromeHack(element);
          }

          element.on('$destroy', function() {
            selectCtrl.removeOption(attr.value);
            selectCtrl.ngModelCtrl.$render();
          });
        }
      };
    }
  };
}];

var styleDirective = valueFn({
  restrict: 'E',
  terminal: false
});

var requiredDirective = function() {
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function(scope, elm, attr, ctrl) {
      if (!ctrl) return;
      attr.required = true; // force truthy in case we are on non input element

      ctrl.$validators.required = function(modelValue, viewValue) {
        return !attr.required || !ctrl.$isEmpty(viewValue);
      };

      attr.$observe('required', function() {
        ctrl.$validate();
      });
    }
  };
};


var patternDirective = function() {
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function(scope, elm, attr, ctrl) {
      if (!ctrl) return;

      var regexp, patternExp = attr.ngPattern || attr.pattern;
      attr.$observe('pattern', function(regex) {
        if (isString(regex) && regex.length > 0) {
          regex = new RegExp('^' + regex + '$');
        }

        if (regex && !regex.test) {
          throw minErr('ngPattern')('noregexp',
            'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
            regex, startingTag(elm));
        }

        regexp = regex || undefined;
        ctrl.$validate();
      });

      ctrl.$validators.pattern = function(value) {
        return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
      };
    }
  };
};


var maxlengthDirective = function() {
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function(scope, elm, attr, ctrl) {
      if (!ctrl) return;

      var maxlength = -1;
      attr.$observe('maxlength', function(value) {
        var intVal = toInt(value);
        maxlength = isNaN(intVal) ? -1 : intVal;
        ctrl.$validate();
      });
      ctrl.$validators.maxlength = function(modelValue, viewValue) {
        return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
      };
    }
  };
};

var minlengthDirective = function() {
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function(scope, elm, attr, ctrl) {
      if (!ctrl) return;

      var minlength = 0;
      attr.$observe('minlength', function(value) {
        minlength = toInt(value) || 0;
        ctrl.$validate();
      });
      ctrl.$validators.minlength = function(modelValue, viewValue) {
        return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
      };
    }
  };
};

  if (window.angular.bootstrap) {
    //AngularJS is already loaded, so we can return here...
    console.log('WARNING: Tried to load angular more than once.');
    return;
  }

  //try to bind to jquery now so that one can write jqLite(document).ready()
  //but we will rebind on bootstrap again.
  bindJQuery();

  publishExternalAPI(angular);

  jqLite(document).ready(function() {
    angularInit(document, bootstrap);
  });

})(window, document);

!window.angular.$$csp() && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');// Generated by CoffeeScript 1.6.2
(function() {
  var $, Analyze, Blender, Calculate, Caman, CamanParser, Canvas, Convert, Event, Fiber, Filter, IO, Image, Layer, Log, Module, Pixel, Plugin, Renderer, Root, Store, Util, fs, moduleKeywords, slice, vignetteFilters,
    __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
    __slice = [].slice,
    __hasProp = {}.hasOwnProperty,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  moduleKeywords = ['extended', 'included'];

  Module = (function() {
    function Module() {}

    Module["extends"] = function(obj) {
      var key, value, _ref;

      for (key in obj) {
        value = obj[key];
        if (__indexOf.call(moduleKeywords, key) < 0) {
          this[key] = value;
        }
      }
      if ((_ref = obj.extended) != null) {
        _ref.apply(this);
      }
      return this;
    };

    Module.includes = function(obj) {
      var key, value, _ref;

      for (key in obj) {
        value = obj[key];
        if (__indexOf.call(moduleKeywords, key) < 0) {
          this.prototype[key] = value;
        }
      }
      if ((_ref = obj.included) != null) {
        _ref.apply(this);
      }
      return this;
    };

    Module.delegate = function() {
      var args, source, target, _i, _len, _results;

      args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
      target = args.pop();
      _results = [];
      for (_i = 0, _len = args.length; _i < _len; _i++) {
        source = args[_i];
        _results.push(this.prototype[source] = target.prototype[source]);
      }
      return _results;
    };

    Module.aliasFunction = function(to, from) {
      var _this = this;

      return this.prototype[to] = function() {
        var args;

        args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
        return _this.prototype[from].apply(_this, args);
      };
    };

    Module.aliasProperty = function(to, from) {
      return Object.defineProperty(this.prototype, to, {
        get: function() {
          return this[from];
        },
        set: function(val) {
          return this[from] = val;
        }
      });
    };

    Module.included = function(func) {
      return func.call(this, this.prototype);
    };

    return Module;

  })();

  slice = Array.prototype.slice;

  $ = function(sel, root) {
    if (root == null) {
      root = document;
    }
    if (typeof sel === "object" || (typeof exports !== "undefined" && exports !== null)) {
      return sel;
    }
    return root.querySelector(sel);
  };

  Util = (function() {
    function Util() {}

    Util.uniqid = (function() {
      var id;

      id = 0;
      return {
        get: function() {
          return id++;
        }
      };
    })();

    Util.extend = function() {
      var copy, dest, obj, prop, src, _i, _len;

      obj = arguments[0], src = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      dest = obj;
      for (_i = 0, _len = src.length; _i < _len; _i++) {
        copy = src[_i];
        for (prop in copy) {
          if (!__hasProp.call(copy, prop)) continue;
          dest[prop] = copy[prop];
        }
      }
      return dest;
    };

    Util.clampRGB = function(val) {
      if (val < 0) {
        return 0;
      }
      if (val > 255) {
        return 255;
      }
      return val;
    };

    Util.copyAttributes = function(from, to, opts) {
      var attr, _i, _len, _ref, _ref1, _results;

      if (opts == null) {
        opts = {};
      }
      _ref = from.attributes;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        attr = _ref[_i];
        if ((opts.except != null) && (_ref1 = attr.nodeName, __indexOf.call(opts.except, _ref1) >= 0)) {
          continue;
        }
        _results.push(to.setAttribute(attr.nodeName, attr.nodeValue));
      }
      return _results;
    };

    Util.dataArray = function(length) {
      if (length == null) {
        length = 0;
      }
      if (Caman.NodeJS || (window.Uint8Array != null)) {
        return new Uint8Array(length);
      }
      return new Array(length);
    };

    return Util;

  })();

  if (typeof exports !== "undefined" && exports !== null) {
    Root = exports;
    Canvas = require('canvas');
    Image = Canvas.Image;
    Fiber = require('fibers');
    fs = require('fs');
  } else {
    Root = window;
  }

  Caman = (function(_super) {
    __extends(Caman, _super);

    Caman.version = {
      release: "4.1.2",
      date: "7/27/2013"
    };

    Caman.DEBUG = false;

    Caman.allowRevert = true;

    Caman.crossOrigin = "anonymous";

    Caman.remoteProxy = "";

    Caman.proxyParam = "camanProxyUrl";

    Caman.NodeJS = typeof exports !== "undefined" && exports !== null;

    Caman.autoload = !Caman.NodeJS;

    Caman.toString = function() {
      return "Version " + Caman.version.release + ", Released " + Caman.version.date;
    };

    Caman.getAttrId = function(canvas) {
      if (Caman.NodeJS) {
        return true;
      }
      if (typeof canvas === "string") {
        canvas = $(canvas);
      }
      if (!((canvas != null) && (canvas.getAttribute != null))) {
        return null;
      }
      return canvas.getAttribute('data-caman-id');
    };

    function Caman() {
      this.nodeFileReady = __bind(this.nodeFileReady, this);
      var args, callback, id,
        _this = this;

      if (arguments.length === 0) {
        throw "Invalid arguments";
      }
      if (this instanceof Caman) {
        this.finishInit = this.finishInit.bind(this);
        this.imageLoaded = this.imageLoaded.bind(this);
        args = arguments[0];
        if (!Caman.NodeJS) {
          id = parseInt(Caman.getAttrId(args[0]), 10);
          callback = typeof args[1] === "function" ? args[1] : typeof args[2] === "function" ? args[2] : function() {};
          if (!isNaN(id) && Store.has(id)) {
            return Store.execute(id, callback);
          }
        }
        this.id = Util.uniqid.get();
        this.initializedPixelData = this.originalPixelData = null;
        this.cropCoordinates = {
          x: 0,
          y: 0
        };
        this.cropped = false;
        this.resized = false;
        this.pixelStack = [];
        this.layerStack = [];
        this.canvasQueue = [];
        this.currentLayer = null;
        this.scaled = false;
        this.analyze = new Analyze(this);
        this.renderer = new Renderer(this);
        this.domIsLoaded(function() {
          _this.parseArguments(args);
          return _this.setup();
        });
        return this;
      } else {
        return new Caman(arguments);
      }
    }

    Caman.prototype.domIsLoaded = function(cb) {
      var listener,
        _this = this;

      if (Caman.NodeJS) {
        return setTimeout(function() {
          return cb.call(_this);
        }, 0);
      } else {
        if (document.readyState === "complete") {
          Log.debug("DOM initialized");
          return setTimeout(function() {
            return cb.call(_this);
          }, 0);
        } else {
          listener = function() {
            if (document.readyState === "complete") {
              Log.debug("DOM initialized");
              return cb.call(_this);
            }
          };
          return document.addEventListener("readystatechange", listener, false);
        }
      }
    };

    Caman.prototype.parseArguments = function(args) {
      var key, val, _ref, _results;

      if (args.length === 0) {
        throw "Invalid arguments given";
      }
      this.initObj = null;
      this.initType = null;
      this.imageUrl = null;
      this.callback = function() {};
      this.setInitObject(args[0]);
      if (args.length === 1) {
        return;
      }
      switch (typeof args[1]) {
        case "string":
          this.imageUrl = args[1];
          break;
        case "function":
          this.callback = args[1];
      }
      if (args.length === 2) {
        return;
      }
      this.callback = args[2];
      if (args.length === 4) {
        _ref = args[4];
        _results = [];
        for (key in _ref) {
          if (!__hasProp.call(_ref, key)) continue;
          val = _ref[key];
          _results.push(this.options[key] = val);
        }
        return _results;
      }
    };

    Caman.prototype.setInitObject = function(obj) {
      if (Caman.NodeJS) {
        this.initObj = obj;
        this.initType = 'node';
        return;
      }
      if (typeof obj === "object") {
        this.initObj = obj;
      } else {
        this.initObj = $(obj);
      }
      if (this.initObj == null) {
        throw "Could not find image or canvas for initialization.";
      }
      return this.initType = this.initObj.nodeName.toLowerCase();
    };

    Caman.prototype.setup = function() {
      switch (this.initType) {
        case "node":
          return this.initNode();
        case "img":
          return this.initImage();
        case "canvas":
          return this.initCanvas();
      }
    };

    Caman.prototype.initNode = function() {
      Log.debug("Initializing for NodeJS");
      if (typeof this.initObj === "string") {
        return fs.readFile(this.initObj, this.nodeFileReady);
      } else {
        return this.nodeFileReady(null, this.initObj);
      }
    };

    Caman.prototype.nodeFileReady = function(err, data) {
      if (err) {
        throw err;
      }
      this.image = new Image();
      this.image.src = data;
      Log.debug("Image loaded. Width = " + (this.imageWidth()) + ", Height = " + (this.imageHeight()));
      this.canvas = new Canvas(this.imageWidth(), this.imageHeight());
      return this.finishInit();
    };

    Caman.prototype.initImage = function() {
      this.image = this.initObj;
      this.canvas = document.createElement('canvas');
      this.context = this.canvas.getContext('2d');
      Util.copyAttributes(this.image, this.canvas, {
        except: ['src']
      });
      this.image.parentNode.replaceChild(this.canvas, this.image);
      this.imageAdjustments();
      return this.waitForImageLoaded();
    };

    Caman.prototype.initCanvas = function() {
      this.canvas = this.initObj;
      this.context = this.canvas.getContext('2d');
      if (this.imageUrl != null) {
        this.image = document.createElement('img');
        this.image.src = this.imageUrl;
        this.imageAdjustments();
        return this.waitForImageLoaded();
      } else {
        return this.finishInit();
      }
    };

    Caman.prototype.imageAdjustments = function() {
      if (this.needsHiDPISwap()) {
        Log.debug(this.image.src, "->", this.hiDPIReplacement());
        this.swapped = true;
        this.image.src = this.hiDPIReplacement();
      }
      if (IO.isRemote(this.image)) {
        this.image.src = IO.proxyUrl(this.image.src);
        return Log.debug("Remote image detected, using URL = " + this.image.src);
      }
    };

    Caman.prototype.waitForImageLoaded = function() {
      if (this.isImageLoaded()) {
        return this.imageLoaded();
      } else {
        return this.image.onload = this.imageLoaded;
      }
    };

    Caman.prototype.isImageLoaded = function() {
      if (!this.image.complete) {
        return false;
      }
      if ((this.image.naturalWidth != null) && this.image.naturalWidth === 0) {
        return false;
      }
      return true;
    };

    Caman.prototype.imageWidth = function() {
      return this.image.width || this.image.naturalWidth;
    };

    Caman.prototype.imageHeight = function() {
      return this.image.height || this.image.naturalHeight;
    };

    Caman.prototype.imageLoaded = function() {
      Log.debug("Image loaded. Width = " + (this.imageWidth()) + ", Height = " + (this.imageHeight()));
      if (this.swapped) {
        this.canvas.width = this.imageWidth() / this.hiDPIRatio();
        this.canvas.height = this.imageHeight() / this.hiDPIRatio();
      } else {
        this.canvas.width = this.imageWidth();
        this.canvas.height = this.imageHeight();
      }
      return this.finishInit();
    };

    Caman.prototype.finishInit = function() {
      var i, pixel, _i, _len, _ref;

      if (this.context == null) {
        this.context = this.canvas.getContext('2d');
      }
      this.originalWidth = this.preScaledWidth = this.width = this.canvas.width;
      this.originalHeight = this.preScaledHeight = this.height = this.canvas.height;
      this.hiDPIAdjustments();
      if (!this.hasId()) {
        this.assignId();
      }
      if (this.image != null) {
        this.context.drawImage(this.image, 0, 0, this.imageWidth(), this.imageHeight(), 0, 0, this.preScaledWidth, this.preScaledHeight);
      }
      this.imageData = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
      this.pixelData = this.imageData.data;
      if (Caman.allowRevert) {
        this.initializedPixelData = Util.dataArray(this.pixelData.length);
        this.originalPixelData = Util.dataArray(this.pixelData.length);
        _ref = this.pixelData;
        for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
          pixel = _ref[i];
          this.initializedPixelData[i] = pixel;
          this.originalPixelData[i] = pixel;
        }
      }
      this.dimensions = {
        width: this.canvas.width,
        height: this.canvas.height
      };
      if (!Caman.NodeJS) {
        Store.put(this.id, this);
      }
      this.callback.call(this, this);
      return this.callback = function() {};
    };

    Caman.prototype.reloadCanvasData = function() {
      this.imageData = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
      return this.pixelData = this.imageData.data;
    };

    Caman.prototype.resetOriginalPixelData = function() {
      var i, pixel, _i, _len, _ref, _results;

      if (!Caman.allowRevert) {
        throw "Revert disabled";
      }
      this.originalPixelData = Util.dataArray(this.pixelData.length);
      _ref = this.pixelData;
      _results = [];
      for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
        pixel = _ref[i];
        _results.push(this.originalPixelData[i] = pixel);
      }
      return _results;
    };

    Caman.prototype.hasId = function() {
      return Caman.getAttrId(this.canvas) != null;
    };

    Caman.prototype.assignId = function() {
      if (Caman.NodeJS || this.canvas.getAttribute('data-caman-id')) {
        return;
      }
      return this.canvas.setAttribute('data-caman-id', this.id);
    };

    Caman.prototype.hiDPIDisabled = function() {
      return this.canvas.getAttribute('data-caman-hidpi-disabled') !== null;
    };

    Caman.prototype.hiDPIAdjustments = function() {
      var ratio;

      if (Caman.NodeJS || !this.needsHiDPISwap()) {
        return;
      }
      ratio = this.hiDPIRatio();
      if (ratio !== 1) {
        Log.debug("HiDPI ratio = " + ratio);
        this.scaled = true;
        this.preScaledWidth = this.canvas.width;
        this.preScaledHeight = this.canvas.height;
        this.canvas.width = this.preScaledWidth * ratio;
        this.canvas.height = this.preScaledHeight * ratio;
        this.canvas.style.width = "" + this.preScaledWidth + "px";
        this.canvas.style.height = "" + this.preScaledHeight + "px";
        this.context.scale(ratio, ratio);
        this.width = this.originalWidth = this.canvas.width;
        return this.height = this.originalHeight = this.canvas.height;
      }
    };

    Caman.prototype.hiDPIRatio = function() {
      var backingStoreRatio, devicePixelRatio;

      devicePixelRatio = window.devicePixelRatio || 1;
      backingStoreRatio = this.context.webkitBackingStorePixelRatio || this.context.mozBackingStorePixelRatio || this.context.msBackingStorePixelRatio || this.context.oBackingStorePixelRatio || this.context.backingStorePixelRatio || 1;
      return devicePixelRatio / backingStoreRatio;
    };

    Caman.prototype.hiDPICapable = function() {
      return (window.devicePixelRatio != null) && window.devicePixelRatio !== 1;
    };

    Caman.prototype.needsHiDPISwap = function() {
      if (this.hiDPIDisabled() || !this.hiDPICapable()) {
        return false;
      }
      return this.hiDPIReplacement() !== null;
    };

    Caman.prototype.hiDPIReplacement = function() {
      if (this.image == null) {
        return null;
      }
      return this.image.getAttribute('data-caman-hidpi');
    };

    Caman.prototype.replaceCanvas = function(newCanvas) {
      var oldCanvas;

      oldCanvas = this.canvas;
      this.canvas = newCanvas;
      this.context = this.canvas.getContext('2d');
      if (!Caman.NodeJS) {
        oldCanvas.parentNode.replaceChild(this.canvas, oldCanvas);
      }
      this.width = this.canvas.width;
      this.height = this.canvas.height;
      this.reloadCanvasData();
      return this.dimensions = {
        width: this.canvas.width,
        height: this.canvas.height
      };
    };

    Caman.prototype.render = function(callback) {
      var _this = this;

      if (callback == null) {
        callback = function() {};
      }
      Event.trigger(this, "renderStart");
      return this.renderer.execute(function() {
        _this.context.putImageData(_this.imageData, 0, 0);
        return callback.call(_this);
      });
    };

    Caman.prototype.revert = function(updateContext) {
      var i, pixel, _i, _len, _ref;

      if (updateContext == null) {
        updateContext = true;
      }
      if (!Caman.allowRevert) {
        throw "Revert disabled";
      }
      _ref = this.originalVisiblePixels();
      for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
        pixel = _ref[i];
        this.pixelData[i] = pixel;
      }
      if (updateContext) {
        return this.context.putImageData(this.imageData, 0, 0);
      }
    };

    Caman.prototype.reset = function() {
      var canvas, ctx, i, imageData, pixel, pixelData, _i, _len, _ref;

      canvas = document.createElement('canvas');
      Util.copyAttributes(this.canvas, canvas);
      canvas.width = this.originalWidth;
      canvas.height = this.originalHeight;
      ctx = canvas.getContext('2d');
      imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      pixelData = imageData.data;
      _ref = this.initializedPixelData;
      for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
        pixel = _ref[i];
        pixelData[i] = pixel;
      }
      ctx.putImageData(imageData, 0, 0);
      this.cropCoordinates = {
        x: 0,
        y: 0
      };
      this.resized = false;
      return this.replaceCanvas(canvas);
    };

    Caman.prototype.originalVisiblePixels = function() {
      var canvas, coord, ctx, endX, endY, i, imageData, pixel, pixelData, pixels, scaledCanvas, startX, startY, width, _i, _j, _len, _ref, _ref1, _ref2, _ref3;

      if (!Caman.allowRevert) {
        throw "Revert disabled";
      }
      pixels = [];
      startX = this.cropCoordinates.x;
      endX = startX + this.width;
      startY = this.cropCoordinates.y;
      endY = startY + this.height;
      if (this.resized) {
        canvas = document.createElement('canvas');
        canvas.width = this.originalWidth;
        canvas.height = this.originalHeight;
        ctx = canvas.getContext('2d');
        imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        pixelData = imageData.data;
        _ref = this.originalPixelData;
        for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
          pixel = _ref[i];
          pixelData[i] = pixel;
        }
        ctx.putImageData(imageData, 0, 0);
        scaledCanvas = document.createElement('canvas');
        scaledCanvas.width = this.width;
        scaledCanvas.height = this.height;
        ctx = scaledCanvas.getContext('2d');
        ctx.drawImage(canvas, 0, 0, this.originalWidth, this.originalHeight, 0, 0, this.width, this.height);
        pixelData = ctx.getImageData(0, 0, this.width, this.height).data;
        width = this.width;
      } else {
        pixelData = this.originalPixelData;
        width = this.originalWidth;
      }
      for (i = _j = 0, _ref1 = pixelData.length; _j < _ref1; i = _j += 4) {
        coord = Pixel.locationToCoordinates(i, width);
        if (((startX <= (_ref2 = coord.x) && _ref2 < endX)) && ((startY <= (_ref3 = coord.y) && _ref3 < endY))) {
          pixels.push(pixelData[i], pixelData[i + 1], pixelData[i + 2], pixelData[i + 3]);
        }
      }
      return pixels;
    };

    Caman.prototype.process = function(name, processFn) {
      this.renderer.add({
        type: Filter.Type.Single,
        name: name,
        processFn: processFn
      });
      return this;
    };

    Caman.prototype.processKernel = function(name, adjust, divisor, bias) {
      var i, _i, _ref;

      if (divisor == null) {
        divisor = null;
      }
      if (bias == null) {
        bias = 0;
      }
      if (divisor == null) {
        divisor = 0;
        for (i = _i = 0, _ref = adjust.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
          divisor += adjust[i];
        }
      }
      this.renderer.add({
        type: Filter.Type.Kernel,
        name: name,
        adjust: adjust,
        divisor: divisor,
        bias: bias
      });
      return this;
    };

    Caman.prototype.processPlugin = function(plugin, args) {
      this.renderer.add({
        type: Filter.Type.Plugin,
        plugin: plugin,
        args: args
      });
      return this;
    };

    Caman.prototype.newLayer = function(callback) {
      var layer;

      layer = new Layer(this);
      this.canvasQueue.push(layer);
      this.renderer.add({
        type: Filter.Type.LayerDequeue
      });
      callback.call(layer);
      this.renderer.add({
        type: Filter.Type.LayerFinished
      });
      return this;
    };

    Caman.prototype.executeLayer = function(layer) {
      return this.pushContext(layer);
    };

    Caman.prototype.pushContext = function(layer) {
      this.layerStack.push(this.currentLayer);
      this.pixelStack.push(this.pixelData);
      this.currentLayer = layer;
      return this.pixelData = layer.pixelData;
    };

    Caman.prototype.popContext = function() {
      this.pixelData = this.pixelStack.pop();
      return this.currentLayer = this.layerStack.pop();
    };

    Caman.prototype.applyCurrentLayer = function() {
      return this.currentLayer.applyToParent();
    };

    return Caman;

  })(Module);

  Root.Caman = Caman;

  Caman.Analyze = (function() {
    function Analyze(c) {
      this.c = c;
    }

    Analyze.prototype.calculateLevels = function() {
      var i, levels, numPixels, _i, _j, _k, _ref;

      levels = {
        r: {},
        g: {},
        b: {}
      };
      for (i = _i = 0; _i <= 255; i = ++_i) {
        levels.r[i] = 0;
        levels.g[i] = 0;
        levels.b[i] = 0;
      }
      for (i = _j = 0, _ref = this.c.pixelData.length; _j < _ref; i = _j += 4) {
        levels.r[this.c.pixelData[i]]++;
        levels.g[this.c.pixelData[i + 1]]++;
        levels.b[this.c.pixelData[i + 2]]++;
      }
      numPixels = this.c.pixelData.length / 4;
      for (i = _k = 0; _k <= 255; i = ++_k) {
        levels.r[i] /= numPixels;
        levels.g[i] /= numPixels;
        levels.b[i] /= numPixels;
      }
      return levels;
    };

    return Analyze;

  })();

  Analyze = Caman.Analyze;

  Caman.DOMUpdated = function() {
    var img, imgs, parser, _i, _len, _results;

    imgs = document.querySelectorAll("img[data-caman]");
    if (!(imgs.length > 0)) {
      return;
    }
    _results = [];
    for (_i = 0, _len = imgs.length; _i < _len; _i++) {
      img = imgs[_i];
      _results.push(parser = new CamanParser(img, function() {
        this.parse();
        return this.execute();
      }));
    }
    return _results;
  };

  if (Caman.autoload) {
    (function() {
      if (document.readyState === "complete") {
        return Caman.DOMUpdated();
      } else {
        return document.addEventListener("DOMContentLoaded", Caman.DOMUpdated, false);
      }
    })();
  }

  CamanParser = (function() {
    var INST_REGEX;

    INST_REGEX = "(\\w+)\\((.*?)\\)";

    function CamanParser(ele, ready) {
      this.dataStr = ele.getAttribute('data-caman');
      this.caman = Caman(ele, ready.bind(this));
    }

    CamanParser.prototype.parse = function() {
      var args, e, filter, func, inst, instFunc, m, r, unparsedInstructions, _i, _len, _ref, _results;

      this.ele = this.caman.canvas;
      r = new RegExp(INST_REGEX, 'g');
      unparsedInstructions = this.dataStr.match(r);
      if (!(unparsedInstructions.length > 0)) {
        return;
      }
      r = new RegExp(INST_REGEX);
      _results = [];
      for (_i = 0, _len = unparsedInstructions.length; _i < _len; _i++) {
        inst = unparsedInstructions[_i];
        _ref = inst.match(r), m = _ref[0], filter = _ref[1], args = _ref[2];
        instFunc = new Function("return function() {        this." + filter + "(" + args + ");      };");
        try {
          func = instFunc();
          _results.push(func.call(this.caman));
        } catch (_error) {
          e = _error;
          _results.push(Log.debug(e));
        }
      }
      return _results;
    };

    CamanParser.prototype.execute = function() {
      var ele;

      ele = this.ele;
      return this.caman.render(function() {
        return ele.parentNode.replaceChild(this.toImage(), ele);
      });
    };

    return CamanParser;

  })();

  Caman.Blender = (function() {
    function Blender() {}

    Blender.blenders = {};

    Blender.register = function(name, func) {
      return this.blenders[name] = func;
    };

    Blender.execute = function(name, rgbaLayer, rgbaParent) {
      return this.blenders[name](rgbaLayer, rgbaParent);
    };

    return Blender;

  })();

  Blender = Caman.Blender;

  Caman.Calculate = (function() {
    function Calculate() {}

    Calculate.distance = function(x1, y1, x2, y2) {
      return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
    };

    Calculate.randomRange = function(min, max, getFloat) {
      var rand;

      if (getFloat == null) {
        getFloat = false;
      }
      rand = min + (Math.random() * (max - min));
      if (getFloat) {
        return rand.toFixed(getFloat);
      } else {
        return Math.round(rand);
      }
    };

    Calculate.luminance = function(rgba) {
      return (0.299 * rgba.r) + (0.587 * rgba.g) + (0.114 * rgba.b);
    };

    Calculate.bezier = function(start, ctrl1, ctrl2, end, lowBound, highBound) {
      var Ax, Ay, Bx, By, Cx, Cy, bezier, curveX, curveY, i, j, leftCoord, rightCoord, t, x0, x1, x2, x3, y0, y1, y2, y3, _i, _j, _k, _ref, _ref1;

      x0 = start[0];
      y0 = start[1];
      x1 = ctrl1[0];
      y1 = ctrl1[1];
      x2 = ctrl2[0];
      y2 = ctrl2[1];
      x3 = end[0];
      y3 = end[1];
      bezier = {};
      Cx = parseInt(3 * (x1 - x0), 10);
      Bx = 3 * (x2 - x1) - Cx;
      Ax = x3 - x0 - Cx - Bx;
      Cy = 3 * (y1 - y0);
      By = 3 * (y2 - y1) - Cy;
      Ay = y3 - y0 - Cy - By;
      for (i = _i = 0; _i < 1000; i = ++_i) {
        t = i / 1000;
        curveX = Math.round((Ax * Math.pow(t, 3)) + (Bx * Math.pow(t, 2)) + (Cx * t) + x0);
        curveY = Math.round((Ay * Math.pow(t, 3)) + (By * Math.pow(t, 2)) + (Cy * t) + y0);
        if (lowBound && curveY < lowBound) {
          curveY = lowBound;
        } else if (highBound && curveY > highBound) {
          curveY = highBound;
        }
        bezier[curveX] = curveY;
      }
      if (bezier.length < end[0] + 1) {
        for (i = _j = 0, _ref = end[0]; 0 <= _ref ? _j <= _ref : _j >= _ref; i = 0 <= _ref ? ++_j : --_j) {
          if (bezier[i] == null) {
            leftCoord = [i - 1, bezier[i - 1]];
            for (j = _k = i, _ref1 = end[0]; i <= _ref1 ? _k <= _ref1 : _k >= _ref1; j = i <= _ref1 ? ++_k : --_k) {
              if (bezier[j] != null) {
                rightCoord = [j, bezier[j]];
                break;
              }
            }
            bezier[i] = leftCoord[1] + ((rightCoord[1] - leftCoord[1]) / (rightCoord[0] - leftCoord[0])) * (i - leftCoord[0]);
          }
        }
      }
      if (bezier[end[0]] == null) {
        bezier[end[0]] = bezier[end[0] - 1];
      }
      return bezier;
    };

    return Calculate;

  })();

  Calculate = Caman.Calculate;

  Caman.Convert = (function() {
    function Convert() {}

    Convert.hexToRGB = function(hex) {
      var b, g, r;

      if (hex.charAt(0) === "#") {
        hex = hex.substr(1);
      }
      r = parseInt(hex.substr(0, 2), 16);
      g = parseInt(hex.substr(2, 2), 16);
      b = parseInt(hex.substr(4, 2), 16);
      return {
        r: r,
        g: g,
        b: b
      };
    };

    Convert.rgbToHSL = function(r, g, b) {
      var d, h, l, max, min, s;

      if (typeof r === "object") {
        g = r.g;
        b = r.b;
        r = r.r;
      }
      r /= 255;
      g /= 255;
      b /= 255;
      max = Math.max(r, g, b);
      min = Math.min(r, g, b);
      l = (max + min) / 2;
      if (max === min) {
        h = s = 0;
      } else {
        d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        h = (function() {
          switch (max) {
            case r:
              return (g - b) / d + (g < b ? 6 : 0);
            case g:
              return (b - r) / d + 2;
            case b:
              return (r - g) / d + 4;
          }
        })();
        h /= 6;
      }
      return {
        h: h,
        s: s,
        l: l
      };
    };

    Convert.hslToRGB = function(h, s, l) {
      var b, g, p, q, r;

      if (typeof h === "object") {
        s = h.s;
        l = h.l;
        h = h.h;
      }
      if (s === 0) {
        r = g = b = l;
      } else {
        q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        p = 2 * l - q;
        r = this.hueToRGB(p, q, h + 1 / 3);
        g = this.hueToRGB(p, q, h);
        b = this.hueToRGB(p, q, h - 1 / 3);
      }
      return {
        r: r * 255,
        g: g * 255,
        b: b * 255
      };
    };

    Convert.hueToRGB = function(p, q, t) {
      if (t < 0) {
        t += 1;
      }
      if (t > 1) {
        t -= 1;
      }
      if (t < 1 / 6) {
        return p + (q - p) * 6 * t;
      }
      if (t < 1 / 2) {
        return q;
      }
      if (t < 2 / 3) {
        return p + (q - p) * (2 / 3 - t) * 6;
      }
      return p;
    };

    Convert.rgbToHSV = function(r, g, b) {
      var d, h, max, min, s, v;

      r /= 255;
      g /= 255;
      b /= 255;
      max = Math.max(r, g, b);
      min = Math.min(r, g, b);
      v = max;
      d = max - min;
      s = max === 0 ? 0 : d / max;
      if (max === min) {
        h = 0;
      } else {
        h = (function() {
          switch (max) {
            case r:
              return (g - b) / d + (g < b ? 6 : 0);
            case g:
              return (b - r) / d + 2;
            case b:
              return (r - g) / d + 4;
          }
        })();
        h /= 6;
      }
      return {
        h: h,
        s: s,
        v: v
      };
    };

    Convert.hsvToRGB = function(h, s, v) {
      var b, f, g, i, p, q, r, t;

      i = Math.floor(h * 6);
      f = h * 6 - i;
      p = v * (1 - s);
      q = v * (1 - f * s);
      t = v * (1 - (1 - f) * s);
      switch (i % 6) {
        case 0:
          r = v;
          g = t;
          b = p;
          break;
        case 1:
          r = q;
          g = v;
          b = p;
          break;
        case 2:
          r = p;
          g = v;
          b = t;
          break;
        case 3:
          r = p;
          g = q;
          b = v;
          break;
        case 4:
          r = t;
          g = p;
          b = v;
          break;
        case 5:
          r = v;
          g = p;
          b = q;
      }
      return {
        r: Math.floor(r * 255),
        g: Math.floor(g * 255),
        b: Math.floor(b * 255)
      };
    };

    Convert.rgbToXYZ = function(r, g, b) {
      var x, y, z;

      r /= 255;
      g /= 255;
      b /= 255;
      if (r > 0.04045) {
        r = Math.pow((r + 0.055) / 1.055, 2.4);
      } else {
        r /= 12.92;
      }
      if (g > 0.04045) {
        g = Math.pow((g + 0.055) / 1.055, 2.4);
      } else {
        g /= 12.92;
      }
      if (b > 0.04045) {
        b = Math.pow((b + 0.055) / 1.055, 2.4);
      } else {
        b /= 12.92;
      }
      x = r * 0.4124 + g * 0.3576 + b * 0.1805;
      y = r * 0.2126 + g * 0.7152 + b * 0.0722;
      z = r * 0.0193 + g * 0.1192 + b * 0.9505;
      return {
        x: x * 100,
        y: y * 100,
        z: z * 100
      };
    };

    Convert.xyzToRGB = function(x, y, z) {
      var b, g, r;

      x /= 100;
      y /= 100;
      z /= 100;
      r = (3.2406 * x) + (-1.5372 * y) + (-0.4986 * z);
      g = (-0.9689 * x) + (1.8758 * y) + (0.0415 * z);
      b = (0.0557 * x) + (-0.2040 * y) + (1.0570 * z);
      if (r > 0.0031308) {
        r = (1.055 * Math.pow(r, 0.4166666667)) - 0.055;
      } else {
        r *= 12.92;
      }
      if (g > 0.0031308) {
        g = (1.055 * Math.pow(g, 0.4166666667)) - 0.055;
      } else {
        g *= 12.92;
      }
      if (b > 0.0031308) {
        b = (1.055 * Math.pow(b, 0.4166666667)) - 0.055;
      } else {
        b *= 12.92;
      }
      return {
        r: r * 255,
        g: g * 255,
        b: b * 255
      };
    };

    Convert.xyzToLab = function(x, y, z) {
      var a, b, l, whiteX, whiteY, whiteZ;

      if (typeof x === "object") {
        y = x.y;
        z = x.z;
        x = x.x;
      }
      whiteX = 95.047;
      whiteY = 100.0;
      whiteZ = 108.883;
      x /= whiteX;
      y /= whiteY;
      z /= whiteZ;
      if (x > 0.008856451679) {
        x = Math.pow(x, 0.3333333333);
      } else {
        x = (7.787037037 * x) + 0.1379310345;
      }
      if (y > 0.008856451679) {
        y = Math.pow(y, 0.3333333333);
      } else {
        y = (7.787037037 * y) + 0.1379310345;
      }
      if (z > 0.008856451679) {
        z = Math.pow(z, 0.3333333333);
      } else {
        z = (7.787037037 * z) + 0.1379310345;
      }
      l = 116 * y - 16;
      a = 500 * (x - y);
      b = 200 * (y - z);
      return {
        l: l,
        a: a,
        b: b
      };
    };

    Convert.labToXYZ = function(l, a, b) {
      var x, y, z;

      if (typeof l === "object") {
        a = l.a;
        b = l.b;
        l = l.l;
      }
      y = (l + 16) / 116;
      x = y + (a / 500);
      z = y - (b / 200);
      if (x > 0.2068965517) {
        x = x * x * x;
      } else {
        x = 0.1284185493 * (x - 0.1379310345);
      }
      if (y > 0.2068965517) {
        y = y * y * y;
      } else {
        y = 0.1284185493 * (y - 0.1379310345);
      }
      if (z > 0.2068965517) {
        z = z * z * z;
      } else {
        z = 0.1284185493 * (z - 0.1379310345);
      }
      return {
        x: x * 95.047,
        y: y * 100.0,
        z: z * 108.883
      };
    };

    Convert.rgbToLab = function(r, g, b) {
      var xyz;

      if (typeof r === "object") {
        g = r.g;
        b = r.b;
        r = r.r;
      }
      xyz = this.rgbToXYZ(r, g, b);
      return this.xyzToLab(xyz);
    };

    Convert.labToRGB = function(l, a, b) {};

    return Convert;

  })();

  Convert = Caman.Convert;

  Caman.Event = (function() {
    function Event() {}

    Event.events = {};

    Event.types = ["processStart", "processComplete", "renderStart", "renderFinished", "blockStarted", "blockFinished"];

    Event.trigger = function(target, type, data) {
      var event, _i, _len, _ref, _results;

      if (data == null) {
        data = null;
      }
      if (this.events[type] && this.events[type].length) {
        _ref = this.events[type];
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          event = _ref[_i];
          if (event.target === null || target.id === event.target.id) {
            _results.push(event.fn.call(target, data));
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      }
    };

    Event.listen = function(target, type, fn) {
      var _fn, _type;

      if (typeof target === "string") {
        _type = target;
        _fn = type;
        target = null;
        type = _type;
        fn = _fn;
      }
      if (__indexOf.call(this.types, type) < 0) {
        return false;
      }
      if (!this.events[type]) {
        this.events[type] = [];
      }
      this.events[type].push({
        target: target,
        fn: fn
      });
      return true;
    };

    return Event;

  })();

  Event = Caman.Event;

  Caman.Filter = (function() {
    function Filter() {}

    Filter.Type = {
      Single: 1,
      Kernel: 2,
      LayerDequeue: 3,
      LayerFinished: 4,
      LoadOverlay: 5,
      Plugin: 6
    };

    Filter.register = function(name, filterFunc) {
      return Caman.prototype[name] = filterFunc;
    };

    return Filter;

  })();

  Filter = Caman.Filter;

  Caman.IO = (function() {
    function IO() {}

    IO.domainRegex = /(?:(?:http|https):\/\/)((?:\w+)\.(?:(?:\w|\.)+))/;

    IO.isRemote = function(img) {
      if (img == null) {
        return false;
      }
      if (this.corsEnabled(img)) {
        return false;
      }
      return this.isURLRemote(img.src);
    };

    IO.corsEnabled = function(img) {
      var _ref;

      return (img.crossOrigin != null) && ((_ref = img.crossOrigin.toLowerCase()) === 'anonymous' || _ref === 'use-credentials');
    };

    IO.isURLRemote = function(url) {
      var matches;

      matches = url.match(this.domainRegex);
      if (matches) {
        return matches[1] !== document.domain;
      } else {
        return false;
      }
    };

    IO.remoteCheck = function(src) {
      if (this.isURLRemote(src)) {
        if (!Caman.remoteProxy.length) {
          Log.info("Attempting to load a remote image without a configured proxy. URL: " + src);
        } else {
          if (Caman.isURLRemote(Caman.remoteProxy)) {
            Log.info("Cannot use a remote proxy for loading images.");
            return;
          }
          return this.proxyUrl(src);
        }
      }
    };

    IO.proxyUrl = function(src) {
      return "" + Caman.remoteProxy + "?" + Caman.proxyParam + "=" + (encodeURIComponent(src));
    };

    IO.useProxy = function(lang) {
      var langToExt;

      langToExt = {
        ruby: 'rb',
        python: 'py',
        perl: 'pl',
        javascript: 'js'
      };
      lang = lang.toLowerCase();
      if (langToExt[lang] != null) {
        lang = langToExt[lang];
      }
      return "proxies/caman_proxy." + lang;
    };

    return IO;

  })();

  Caman.prototype.save = function() {
    if (typeof exports !== "undefined" && exports !== null) {
      return this.nodeSave.apply(this, arguments);
    } else {
      return this.browserSave.apply(this, arguments);
    }
  };

  Caman.prototype.browserSave = function(type) {
    var image;

    if (type == null) {
      type = "png";
    }
    type = type.toLowerCase();
    image = this.toBase64(type).replace("image/" + type, "image/octet-stream");
    return document.location.href = image;
  };

  Caman.prototype.nodeSave = function(file, overwrite) {
    var e, stats;

    if (overwrite == null) {
      overwrite = true;
    }
    try {
      stats = fs.statSync(file);
      if (stats.isFile() && !overwrite) {
        return false;
      }
    } catch (_error) {
      e = _error;
      Log.debug("Creating output file " + file);
    }
    return fs.writeFile(file, this.canvas.toBuffer(), function() {
      return Log.debug("Finished writing to " + file);
    });
  };

  Caman.prototype.toImage = function(type) {
    var img;

    img = document.createElement('img');
    img.src = this.toBase64(type);
    img.width = this.dimensions.width;
    img.height = this.dimensions.height;
    if (window.devicePixelRatio) {
      img.width /= window.devicePixelRatio;
      img.height /= window.devicePixelRatio;
    }
    return img;
  };

  Caman.prototype.toBase64 = function(type) {
    if (type == null) {
      type = "png";
    }
    type = type.toLowerCase();
    return this.canvas.toDataURL("image/" + type);
  };

  IO = Caman.IO;

  Caman.Layer = (function() {
    function Layer(c) {
      this.c = c;
      this.filter = this.c;
      this.options = {
        blendingMode: 'normal',
        opacity: 1.0
      };
      this.layerID = Util.uniqid.get();
      this.canvas = typeof exports !== "undefined" && exports !== null ? new Canvas() : document.createElement('canvas');
      this.canvas.width = this.c.dimensions.width;
      this.canvas.height = this.c.dimensions.height;
      this.context = this.canvas.getContext('2d');
      this.context.createImageData(this.canvas.width, this.canvas.height);
      this.imageData = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
      this.pixelData = this.imageData.data;
    }

    Layer.prototype.newLayer = function(cb) {
      return this.c.newLayer.call(this.c, cb);
    };

    Layer.prototype.setBlendingMode = function(mode) {
      this.options.blendingMode = mode;
      return this;
    };

    Layer.prototype.opacity = function(opacity) {
      this.options.opacity = opacity / 100;
      return this;
    };

    Layer.prototype.copyParent = function() {
      var i, parentData, _i, _ref;

      parentData = this.c.pixelData;
      for (i = _i = 0, _ref = this.c.pixelData.length; _i < _ref; i = _i += 4) {
        this.pixelData[i] = parentData[i];
        this.pixelData[i + 1] = parentData[i + 1];
        this.pixelData[i + 2] = parentData[i + 2];
        this.pixelData[i + 3] = parentData[i + 3];
      }
      return this;
    };

    Layer.prototype.fillColor = function() {
      return this.c.fillColor.apply(this.c, arguments);
    };

    Layer.prototype.overlayImage = function(image) {
      if (typeof image === "object") {
        image = image.src;
      } else if (typeof image === "string" && image[0] === "#") {
        image = $(image).src;
      }
      if (!image) {
        return this;
      }
      this.c.renderer.renderQueue.push({
        type: Filter.Type.LoadOverlay,
        src: image,
        layer: this
      });
      return this;
    };

    Layer.prototype.applyToParent = function() {
      var i, layerData, parentData, result, rgbaLayer, rgbaParent, _i, _ref, _results;

      parentData = this.c.pixelStack[this.c.pixelStack.length - 1];
      layerData = this.c.pixelData;
      _results = [];
      for (i = _i = 0, _ref = layerData.length; _i < _ref; i = _i += 4) {
        rgbaParent = {
          r: parentData[i],
          g: parentData[i + 1],
          b: parentData[i + 2],
          a: parentData[i + 3]
        };
        rgbaLayer = {
          r: layerData[i],
          g: layerData[i + 1],
          b: layerData[i + 2],
          a: layerData[i + 3]
        };
        result = Blender.execute(this.options.blendingMode, rgbaLayer, rgbaParent);
        result.r = Util.clampRGB(result.r);
        result.g = Util.clampRGB(result.g);
        result.b = Util.clampRGB(result.b);
        if (result.a == null) {
          result.a = rgbaLayer.a;
        }
        parentData[i] = rgbaParent.r - ((rgbaParent.r - result.r) * (this.options.opacity * (result.a / 255)));
        parentData[i + 1] = rgbaParent.g - ((rgbaParent.g - result.g) * (this.options.opacity * (result.a / 255)));
        _results.push(parentData[i + 2] = rgbaParent.b - ((rgbaParent.b - result.b) * (this.options.opacity * (result.a / 255))));
      }
      return _results;
    };

    return Layer;

  })();

  Layer = Caman.Layer;

  Caman.Logger = (function() {
    function Logger() {
      var name, _i, _len, _ref;

      _ref = ['log', 'info', 'warn', 'error'];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        name = _ref[_i];
        this[name] = (function(name) {
          return function() {
            var args, e;

            args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
            if (!Caman.DEBUG) {
              return;
            }
            try {
              return console[name].apply(console, args);
            } catch (_error) {
              e = _error;
              return console[name](args);
            }
          };
        })(name);
      }
      this.debug = this.log;
    }

    return Logger;

  })();

  Log = new Caman.Logger();

  Caman.Pixel = (function() {
    Pixel.coordinatesToLocation = function(x, y, width) {
      return (y * width + x) * 4;
    };

    Pixel.locationToCoordinates = function(loc, width) {
      var x, y;

      y = Math.floor(loc / (width * 4));
      x = (loc % (width * 4)) / 4;
      return {
        x: x,
        y: y
      };
    };

    function Pixel(r, g, b, a, c) {
      this.r = r != null ? r : 0;
      this.g = g != null ? g : 0;
      this.b = b != null ? b : 0;
      this.a = a != null ? a : 255;
      this.c = c != null ? c : null;
      this.loc = 0;
    }

    Pixel.prototype.setContext = function(c) {
      return this.c = c;
    };

    Pixel.prototype.locationXY = function() {
      var x, y;

      if (this.c == null) {
        throw "Requires a CamanJS context";
      }
      y = this.c.dimensions.height - Math.floor(this.loc / (this.c.dimensions.width * 4));
      x = (this.loc % (this.c.dimensions.width * 4)) / 4;
      return {
        x: x,
        y: y
      };
    };

    Pixel.prototype.pixelAtLocation = function(loc) {
      if (this.c == null) {
        throw "Requires a CamanJS context";
      }
      return new Pixel(this.c.pixelData[loc], this.c.pixelData[loc + 1], this.c.pixelData[loc + 2], this.c.pixelData[loc + 3], this.c);
    };

    Pixel.prototype.getPixelRelative = function(horiz, vert) {
      var newLoc;

      if (this.c == null) {
        throw "Requires a CamanJS context";
      }
      newLoc = this.loc + (this.c.dimensions.width * 4 * (vert * -1)) + (4 * horiz);
      if (newLoc > this.c.pixelData.length || newLoc < 0) {
        return new Pixel(0, 0, 0, 255, this.c);
      }
      return this.pixelAtLocation(newLoc);
    };

    Pixel.prototype.putPixelRelative = function(horiz, vert, rgba) {
      var nowLoc;

      if (this.c == null) {
        throw "Requires a CamanJS context";
      }
      nowLoc = this.loc + (this.c.dimensions.width * 4 * (vert * -1)) + (4 * horiz);
      if (newLoc > this.c.pixelData.length || newLoc < 0) {
        return;
      }
      this.c.pixelData[newLoc] = rgba.r;
      this.c.pixelData[newLoc + 1] = rgba.g;
      this.c.pixelData[newLoc + 2] = rgba.b;
      this.c.pixelData[newLoc + 3] = rgba.a;
      return true;
    };

    Pixel.prototype.getPixel = function(x, y) {
      var loc;

      if (this.c == null) {
        throw "Requires a CamanJS context";
      }
      loc = this.coordinatesToLocation(x, y, this.width);
      return this.pixelAtLocation(loc);
    };

    Pixel.prototype.putPixel = function(x, y, rgba) {
      var loc;

      if (this.c == null) {
        throw "Requires a CamanJS context";
      }
      loc = this.coordinatesToLocation(x, y, this.width);
      this.c.pixelData[loc] = rgba.r;
      this.c.pixelData[loc + 1] = rgba.g;
      this.c.pixelData[loc + 2] = rgba.b;
      return this.c.pixelData[loc + 3] = rgba.a;
    };

    Pixel.prototype.toString = function() {
      return this.toKey();
    };

    Pixel.prototype.toHex = function(includeAlpha) {
      var hex;

      if (includeAlpha == null) {
        includeAlpha = false;
      }
      hex = '#' + this.r.toString(16) + this.g.toString(16) + this.b.toString(16);
      if (includeAlpha) {
        return hex + this.a.toString(16);
      } else {
        return hex;
      }
    };

    return Pixel;

  })();

  Pixel = Caman.Pixel;

  Caman.Plugin = (function() {
    function Plugin() {}

    Plugin.plugins = {};

    Plugin.register = function(name, plugin) {
      return this.plugins[name] = plugin;
    };

    Plugin.execute = function(context, name, args) {
      return this.plugins[name].apply(context, args);
    };

    return Plugin;

  })();

  Plugin = Caman.Plugin;

  Caman.Renderer = (function() {
    Renderer.Blocks = Caman.NodeJS ? require('os').cpus().length : 4;

    function Renderer(c) {
      this.c = c;
      this.processNext = __bind(this.processNext, this);
      this.renderQueue = [];
      this.modPixelData = null;
    }

    Renderer.prototype.add = function(job) {
      if (job == null) {
        return;
      }
      return this.renderQueue.push(job);
    };

    Renderer.prototype.processNext = function() {
      var layer;

      if (this.renderQueue.length === 0) {
        Event.trigger(this, "renderFinished");
        if (this.finishedFn != null) {
          this.finishedFn.call(this.c);
        }
        return this;
      }
      this.currentJob = this.renderQueue.shift();
      switch (this.currentJob.type) {
        case Filter.Type.LayerDequeue:
          layer = this.c.canvasQueue.shift();
          this.c.executeLayer(layer);
          return this.processNext();
        case Filter.Type.LayerFinished:
          this.c.applyCurrentLayer();
          this.c.popContext();
          return this.processNext();
        case Filter.Type.LoadOverlay:
          return this.loadOverlay(this.currentJob.layer, this.currentJob.src);
        case Filter.Type.Plugin:
          return this.executePlugin();
        default:
          return this.executeFilter();
      }
    };

    Renderer.prototype.execute = function(callback) {
      this.finishedFn = callback;
      this.modPixelData = Util.dataArray(this.c.pixelData.length);
      return this.processNext();
    };

    Renderer.prototype.eachBlock = function(fn) {
      var blockN, blockPixelLength, bnum, end, f, i, lastBlockN, n, start, _i, _ref, _results,
        _this = this;

      this.blocksDone = 0;
      n = this.c.pixelData.length;
      blockPixelLength = Math.floor((n / 4) / Renderer.Blocks);
      blockN = blockPixelLength * 4;
      lastBlockN = blockN + ((n / 4) % Renderer.Blocks) * 4;
      _results = [];
      for (i = _i = 0, _ref = Renderer.Blocks; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
        start = i * blockN;
        end = start + (i === Renderer.Blocks - 1 ? lastBlockN : blockN);
        if (Caman.NodeJS) {
          f = Fiber(function() {
            return fn.call(_this, i, start, end);
          });
          bnum = f.run();
          _results.push(this.blockFinished(bnum));
        } else {
          _results.push(setTimeout((function(i, start, end) {
            return function() {
              return fn.call(_this, i, start, end);
            };
          })(i, start, end), 0));
        }
      }
      return _results;
    };

    Renderer.prototype.executeFilter = function() {
      Event.trigger(this.c, "processStart", this.currentJob);
      if (this.currentJob.type === Filter.Type.Single) {
        return this.eachBlock(this.renderBlock);
      } else {
        return this.eachBlock(this.renderKernel);
      }
    };

    Renderer.prototype.executePlugin = function() {
      Log.debug("Executing plugin " + this.currentJob.plugin);
      Plugin.execute(this.c, this.currentJob.plugin, this.currentJob.args);
      Log.debug("Plugin " + this.currentJob.plugin + " finished!");
      return this.processNext();
    };

    Renderer.prototype.renderBlock = function(bnum, start, end) {
      var i, pixel, _i;

      Log.debug("Block #" + bnum + " - Filter: " + this.currentJob.name + ", Start: " + start + ", End: " + end);
      Event.trigger(this.c, "blockStarted", {
        blockNum: bnum,
        totalBlocks: Renderer.Blocks,
        startPixel: start,
        endPixel: end
      });
      pixel = new Pixel();
      pixel.setContext(this.c);
      for (i = _i = start; _i < end; i = _i += 4) {
        pixel.loc = i;
        pixel.r = this.c.pixelData[i];
        pixel.g = this.c.pixelData[i + 1];
        pixel.b = this.c.pixelData[i + 2];
        pixel.a = this.c.pixelData[i + 3];
        this.currentJob.processFn(pixel);
        this.c.pixelData[i] = Util.clampRGB(pixel.r);
        this.c.pixelData[i + 1] = Util.clampRGB(pixel.g);
        this.c.pixelData[i + 2] = Util.clampRGB(pixel.b);
        this.c.pixelData[i + 3] = Util.clampRGB(pixel.a);
      }
      if (Caman.NodeJS) {
        return Fiber["yield"](bnum);
      } else {
        return this.blockFinished(bnum);
      }
    };

    Renderer.prototype.renderKernel = function(bnum, start, end) {
      var adjust, adjustSize, bias, builder, builderIndex, divisor, i, j, k, kernel, n, name, p, pixel, res, _i, _j, _k;

      name = this.currentJob.name;
      bias = this.currentJob.bias;
      divisor = this.currentJob.divisor;
      n = this.c.pixelData.length;
      adjust = this.currentJob.adjust;
      adjustSize = Math.sqrt(adjust.length);
      kernel = [];
      Log.debug("Rendering kernel - Filter: " + this.currentJob.name);
      start = Math.max(start, this.c.dimensions.width * 4 * ((adjustSize - 1) / 2));
      end = Math.min(end, n - (this.c.dimensions.width * 4 * ((adjustSize - 1) / 2)));
      builder = (adjustSize - 1) / 2;
      pixel = new Pixel();
      pixel.setContext(this.c);
      for (i = _i = start; _i < end; i = _i += 4) {
        pixel.loc = i;
        builderIndex = 0;
        for (j = _j = -builder; -builder <= builder ? _j <= builder : _j >= builder; j = -builder <= builder ? ++_j : --_j) {
          for (k = _k = builder; builder <= -builder ? _k <= -builder : _k >= -builder; k = builder <= -builder ? ++_k : --_k) {
            p = pixel.getPixelRelative(j, k);
            kernel[builderIndex * 3] = p.r;
            kernel[builderIndex * 3 + 1] = p.g;
            kernel[builderIndex * 3 + 2] = p.b;
            builderIndex++;
          }
        }
        res = this.processKernel(adjust, kernel, divisor, bias);
        this.modPixelData[i] = Util.clampRGB(res.r);
        this.modPixelData[i + 1] = Util.clampRGB(res.g);
        this.modPixelData[i + 2] = Util.clampRGB(res.b);
        this.modPixelData[i + 3] = this.c.pixelData[i + 3];
      }
      if (Caman.NodeJS) {
        return Fiber["yield"](bnum);
      } else {
        return this.blockFinished(bnum);
      }
    };

    Renderer.prototype.blockFinished = function(bnum) {
      var i, _i, _ref;

      if (bnum >= 0) {
        Log.debug("Block #" + bnum + " finished! Filter: " + this.currentJob.name);
      }
      this.blocksDone++;
      Event.trigger(this.c, "blockFinished", {
        blockNum: bnum,
        blocksFinished: this.blocksDone,
        totalBlocks: Renderer.Blocks
      });
      if (this.blocksDone === Renderer.Blocks) {
        if (this.currentJob.type === Filter.Type.Kernel) {
          for (i = _i = 0, _ref = this.c.pixelData.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
            this.c.pixelData[i] = this.modPixelData[i];
          }
        }
        if (bnum >= 0) {
          Log.debug("Filter " + this.currentJob.name + " finished!");
        }
        Event.trigger(this.c, "processComplete", this.currentJob);
        return this.processNext();
      }
    };

    Renderer.prototype.processKernel = function(adjust, kernel, divisor, bias) {
      var i, val, _i, _ref;

      val = {
        r: 0,
        g: 0,
        b: 0
      };
      for (i = _i = 0, _ref = adjust.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
        val.r += adjust[i] * kernel[i * 3];
        val.g += adjust[i] * kernel[i * 3 + 1];
        val.b += adjust[i] * kernel[i * 3 + 2];
      }
      val.r = (val.r / divisor) + bias;
      val.g = (val.g / divisor) + bias;
      val.b = (val.b / divisor) + bias;
      return val;
    };

    Renderer.prototype.loadOverlay = function(layer, src) {
      var img, proxyUrl,
        _this = this;

      img = document.createElement('img');
      img.onload = function() {
        layer.context.drawImage(img, 0, 0, _this.c.dimensions.width, _this.c.dimensions.height);
        layer.imageData = layer.context.getImageData(0, 0, _this.c.dimensions.width, _this.c.dimensions.height);
        layer.pixelData = layer.imageData.data;
        _this.c.pixelData = layer.pixelData;
        return _this.processNext();
      };
      proxyUrl = IO.remoteCheck(src);
      return img.src = proxyUrl != null ? proxyUrl : src;
    };

    return Renderer;

  })();

  Renderer = Caman.Renderer;

  Caman.Store = (function() {
    function Store() {}

    Store.items = {};

    Store.has = function(search) {
      return this.items[search] != null;
    };

    Store.get = function(search) {
      return this.items[search];
    };

    Store.put = function(name, obj) {
      return this.items[name] = obj;
    };

    Store.execute = function(search, callback) {
      var _this = this;

      setTimeout(function() {
        return callback.call(_this.get(search), _this.get(search));
      }, 0);
      return this.get(search);
    };

    Store.flush = function(name) {
      if (name == null) {
        name = false;
      }
      if (name) {
        return delete this.items[name];
      } else {
        return this.items = {};
      }
    };

    return Store;

  })();

  Store = Caman.Store;

  Blender.register("normal", function(rgbaLayer, rgbaParent) {
    return {
      r: rgbaLayer.r,
      g: rgbaLayer.g,
      b: rgbaLayer.b
    };
  });

  Blender.register("multiply", function(rgbaLayer, rgbaParent) {
    return {
      r: (rgbaLayer.r * rgbaParent.r) / 255,
      g: (rgbaLayer.g * rgbaParent.g) / 255,
      b: (rgbaLayer.b * rgbaParent.b) / 255
    };
  });

  Blender.register("screen", function(rgbaLayer, rgbaParent) {
    return {
      r: 255 - (((255 - rgbaLayer.r) * (255 - rgbaParent.r)) / 255),
      g: 255 - (((255 - rgbaLayer.g) * (255 - rgbaParent.g)) / 255),
      b: 255 - (((255 - rgbaLayer.b) * (255 - rgbaParent.b)) / 255)
    };
  });

  Blender.register("overlay", function(rgbaLayer, rgbaParent) {
    var result;

    result = {};
    result.r = rgbaParent.r > 128 ? 255 - 2 * (255 - rgbaLayer.r) * (255 - rgbaParent.r) / 255 : (rgbaParent.r * rgbaLayer.r * 2) / 255;
    result.g = rgbaParent.g > 128 ? 255 - 2 * (255 - rgbaLayer.g) * (255 - rgbaParent.g) / 255 : (rgbaParent.g * rgbaLayer.g * 2) / 255;
    result.b = rgbaParent.b > 128 ? 255 - 2 * (255 - rgbaLayer.b) * (255 - rgbaParent.b) / 255 : (rgbaParent.b * rgbaLayer.b * 2) / 255;
    return result;
  });

  Blender.register("difference", function(rgbaLayer, rgbaParent) {
    return {
      r: rgbaLayer.r - rgbaParent.r,
      g: rgbaLayer.g - rgbaParent.g,
      b: rgbaLayer.b - rgbaParent.b
    };
  });

  Blender.register("addition", function(rgbaLayer, rgbaParent) {
    return {
      r: rgbaParent.r + rgbaLayer.r,
      g: rgbaParent.g + rgbaLayer.g,
      b: rgbaParent.b + rgbaLayer.b
    };
  });

  Blender.register("exclusion", function(rgbaLayer, rgbaParent) {
    return {
      r: 128 - 2 * (rgbaParent.r - 128) * (rgbaLayer.r - 128) / 255,
      g: 128 - 2 * (rgbaParent.g - 128) * (rgbaLayer.g - 128) / 255,
      b: 128 - 2 * (rgbaParent.b - 128) * (rgbaLayer.b - 128) / 255
    };
  });

  Blender.register("softLight", function(rgbaLayer, rgbaParent) {
    var result;

    result = {};
    result.r = rgbaParent.r > 128 ? 255 - ((255 - rgbaParent.r) * (255 - (rgbaLayer.r - 128))) / 255 : (rgbaParent.r * (rgbaLayer.r + 128)) / 255;
    result.g = rgbaParent.g > 128 ? 255 - ((255 - rgbaParent.g) * (255 - (rgbaLayer.g - 128))) / 255 : (rgbaParent.g * (rgbaLayer.g + 128)) / 255;
    result.b = rgbaParent.b > 128 ? 255 - ((255 - rgbaParent.b) * (255 - (rgbaLayer.b - 128))) / 255 : (rgbaParent.b * (rgbaLayer.b + 128)) / 255;
    return result;
  });

  Blender.register("lighten", function(rgbaLayer, rgbaParent) {
    return {
      r: rgbaParent.r > rgbaLayer.r ? rgbaParent.r : rgbaLayer.r,
      g: rgbaParent.g > rgbaLayer.g ? rgbaParent.g : rgbaLayer.g,
      b: rgbaParent.b > rgbaLayer.b ? rgbaParent.b : rgbaLayer.b
    };
  });

  Blender.register("darken", function(rgbaLayer, rgbaParent) {
    return {
      r: rgbaParent.r > rgbaLayer.r ? rgbaLayer.r : rgbaParent.r,
      g: rgbaParent.g > rgbaLayer.g ? rgbaLayer.g : rgbaParent.g,
      b: rgbaParent.b > rgbaLayer.b ? rgbaLayer.b : rgbaParent.b
    };
  });

  Filter.register("fillColor", function() {
    var color;

    if (arguments.length === 1) {
      color = Convert.hexToRGB(arguments[0]);
    } else {
      color = {
        r: arguments[0],
        g: arguments[1],
        b: arguments[2]
      };
    }
    return this.process("fillColor", function(rgba) {
      rgba.r = color.r;
      rgba.g = color.g;
      rgba.b = color.b;
      rgba.a = 255;
      return rgba;
    });
  });

  Filter.register("brightness", function(adjust) {
    adjust = Math.floor(255 * (adjust / 100));
    return this.process("brightness", function(rgba) {
      rgba.r += adjust;
      rgba.g += adjust;
      rgba.b += adjust;
      return rgba;
    });
  });

  Filter.register("saturation", function(adjust) {
    adjust *= -0.01;
    return this.process("saturation", function(rgba) {
      var max;

      max = Math.max(rgba.r, rgba.g, rgba.b);
      if (rgba.r !== max) {
        rgba.r += (max - rgba.r) * adjust;
      }
      if (rgba.g !== max) {
        rgba.g += (max - rgba.g) * adjust;
      }
      if (rgba.b !== max) {
        rgba.b += (max - rgba.b) * adjust;
      }
      return rgba;
    });
  });

  Filter.register("vibrance", function(adjust) {
    adjust *= -1;
    return this.process("vibrance", function(rgba) {
      var amt, avg, max;

      max = Math.max(rgba.r, rgba.g, rgba.b);
      avg = (rgba.r + rgba.g + rgba.b) / 3;
      amt = ((Math.abs(max - avg) * 2 / 255) * adjust) / 100;
      if (rgba.r !== max) {
        rgba.r += (max - rgba.r) * amt;
      }
      if (rgba.g !== max) {
        rgba.g += (max - rgba.g) * amt;
      }
      if (rgba.b !== max) {
        rgba.b += (max - rgba.b) * amt;
      }
      return rgba;
    });
  });

  Filter.register("greyscale", function(adjust) {
    return this.process("greyscale", function(rgba) {
      var avg;

      avg = Calculate.luminance(rgba);
      rgba.r = avg;
      rgba.g = avg;
      rgba.b = avg;
      return rgba;
    });
  });

  Filter.register("contrast", function(adjust) {
    adjust = Math.pow((adjust + 100) / 100, 2);
    return this.process("contrast", function(rgba) {
      rgba.r /= 255;
      rgba.r -= 0.5;
      rgba.r *= adjust;
      rgba.r += 0.5;
      rgba.r *= 255;
      rgba.g /= 255;
      rgba.g -= 0.5;
      rgba.g *= adjust;
      rgba.g += 0.5;
      rgba.g *= 255;
      rgba.b /= 255;
      rgba.b -= 0.5;
      rgba.b *= adjust;
      rgba.b += 0.5;
      rgba.b *= 255;
      return rgba;
    });
  });

  Filter.register("hue", function(adjust) {
    return this.process("hue", function(rgba) {
      var b, g, h, hsv, r, _ref;

      hsv = Convert.rgbToHSV(rgba.r, rgba.g, rgba.b);
      h = hsv.h * 100;
      h += Math.abs(adjust);
      h = h % 100;
      h /= 100;
      hsv.h = h;
      _ref = Convert.hsvToRGB(hsv.h, hsv.s, hsv.v), r = _ref.r, g = _ref.g, b = _ref.b;
      rgba.r = r;
      rgba.g = g;
      rgba.b = b;
      return rgba;
    });
  });

  Filter.register("colorize", function() {
    var level, rgb;

    if (arguments.length === 2) {
      rgb = Convert.hexToRGB(arguments[0]);
      level = arguments[1];
    } else if (arguments.length === 4) {
      rgb = {
        r: arguments[0],
        g: arguments[1],
        b: arguments[2]
      };
      level = arguments[3];
    }
    return this.process("colorize", function(rgba) {
      rgba.r -= (rgba.r - rgb.r) * (level / 100);
      rgba.g -= (rgba.g - rgb.g) * (level / 100);
      rgba.b -= (rgba.b - rgb.b) * (level / 100);
      return rgba;
    });
  });

  Filter.register("invert", function() {
    return this.process("invert", function(rgba) {
      rgba.r = 255 - rgba.r;
      rgba.g = 255 - rgba.g;
      rgba.b = 255 - rgba.b;
      return rgba;
    });
  });

  Filter.register("sepia", function(adjust) {
    if (adjust == null) {
      adjust = 100;
    }
    adjust /= 100;
    return this.process("sepia", function(rgba) {
      rgba.r = Math.min(255, (rgba.r * (1 - (0.607 * adjust))) + (rgba.g * (0.769 * adjust)) + (rgba.b * (0.189 * adjust)));
      rgba.g = Math.min(255, (rgba.r * (0.349 * adjust)) + (rgba.g * (1 - (0.314 * adjust))) + (rgba.b * (0.168 * adjust)));
      rgba.b = Math.min(255, (rgba.r * (0.272 * adjust)) + (rgba.g * (0.534 * adjust)) + (rgba.b * (1 - (0.869 * adjust))));
      return rgba;
    });
  });

  Filter.register("gamma", function(adjust) {
    return this.process("gamma", function(rgba) {
      rgba.r = Math.pow(rgba.r / 255, adjust) * 255;
      rgba.g = Math.pow(rgba.g / 255, adjust) * 255;
      rgba.b = Math.pow(rgba.b / 255, adjust) * 255;
      return rgba;
    });
  });

  Filter.register("noise", function(adjust) {
    adjust = Math.abs(adjust) * 2.55;
    return this.process("noise", function(rgba) {
      var rand;

      rand = Calculate.randomRange(adjust * -1, adjust);
      rgba.r += rand;
      rgba.g += rand;
      rgba.b += rand;
      return rgba;
    });
  });

  Filter.register("clip", function(adjust) {
    adjust = Math.abs(adjust) * 2.55;
    return this.process("clip", function(rgba) {
      if (rgba.r > 255 - adjust) {
        rgba.r = 255;
      } else if (rgba.r < adjust) {
        rgba.r = 0;
      }
      if (rgba.g > 255 - adjust) {
        rgba.g = 255;
      } else if (rgba.g < adjust) {
        rgba.g = 0;
      }
      if (rgba.b > 255 - adjust) {
        rgba.b = 255;
      } else if (rgba.b < adjust) {
        rgba.b = 0;
      }
      return rgba;
    });
  });

  Filter.register("channels", function(options) {
    var chan, value;

    if (typeof options !== "object") {
      return this;
    }
    for (chan in options) {
      if (!__hasProp.call(options, chan)) continue;
      value = options[chan];
      if (value === 0) {
        delete options[chan];
        continue;
      }
      options[chan] /= 100;
    }
    if (options.length === 0) {
      return this;
    }
    return this.process("channels", function(rgba) {
      if (options.red != null) {
        if (options.red > 0) {
          rgba.r += (255 - rgba.r) * options.red;
        } else {
          rgba.r -= rgba.r * Math.abs(options.red);
        }
      }
      if (options.green != null) {
        if (options.green > 0) {
          rgba.g += (255 - rgba.g) * options.green;
        } else {
          rgba.g -= rgba.g * Math.abs(options.green);
        }
      }
      if (options.blue != null) {
        if (options.blue > 0) {
          rgba.b += (255 - rgba.b) * options.blue;
        } else {
          rgba.b -= rgba.b * Math.abs(options.blue);
        }
      }
      return rgba;
    });
  });

  Filter.register("curves", function() {
    var bezier, chans, cps, ctrl1, ctrl2, end, i, start, _i, _j, _ref, _ref1;

    chans = arguments[0], cps = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
    if (typeof chans === "string") {
      chans = chans.split("");
    }
    if (chans[0] === "v") {
      chans = ['r', 'g', 'b'];
    }
    if (cps.length < 3 || cps.length > 4) {
      throw "Invalid number of arguments to curves filter";
    }
    start = cps[0];
    ctrl1 = cps[1];
    ctrl2 = cps.length === 4 ? cps[2] : cps[1];
    end = cps[cps.length - 1];
    bezier = Calculate.bezier(start, ctrl1, ctrl2, end, 0, 255);
    if (start[0] > 0) {
      for (i = _i = 0, _ref = start[0]; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
        bezier[i] = start[1];
      }
    }
    if (end[0] < 255) {
      for (i = _j = _ref1 = end[0]; _ref1 <= 255 ? _j <= 255 : _j >= 255; i = _ref1 <= 255 ? ++_j : --_j) {
        bezier[i] = end[1];
      }
    }
    return this.process("curves", function(rgba) {
      var _k, _ref2;

      for (i = _k = 0, _ref2 = chans.length; 0 <= _ref2 ? _k < _ref2 : _k > _ref2; i = 0 <= _ref2 ? ++_k : --_k) {
        rgba[chans[i]] = bezier[rgba[chans[i]]];
      }
      return rgba;
    });
  });

  Filter.register("exposure", function(adjust) {
    var ctrl1, ctrl2, p;

    p = Math.abs(adjust) / 100;
    ctrl1 = [0, 255 * p];
    ctrl2 = [255 - (255 * p), 255];
    if (adjust < 0) {
      ctrl1 = ctrl1.reverse();
      ctrl2 = ctrl2.reverse();
    }
    return this.curves('rgb', [0, 0], ctrl1, ctrl2, [255, 255]);
  });

  Caman.Plugin.register("crop", function(width, height, x, y) {
    var canvas, ctx;

    if (x == null) {
      x = 0;
    }
    if (y == null) {
      y = 0;
    }
    if (typeof exports !== "undefined" && exports !== null) {
      canvas = new Canvas(width, height);
    } else {
      canvas = document.createElement('canvas');
      Util.copyAttributes(this.canvas, canvas);
      canvas.width = width;
      canvas.height = height;
    }
    ctx = canvas.getContext('2d');
    ctx.drawImage(this.canvas, x, y, width, height, 0, 0, width, height);
    this.cropCoordinates = {
      x: x,
      y: y
    };
    this.cropped = true;
    return this.replaceCanvas(canvas);
  });

  Caman.Plugin.register("resize", function(newDims) {
    var canvas, ctx;

    if (newDims == null) {
      newDims = null;
    }
    if (newDims === null || ((newDims.width == null) && (newDims.height == null))) {
      Log.error("Invalid or missing dimensions given for resize");
      return;
    }
    if (newDims.width == null) {
      newDims.width = this.canvas.width * newDims.height / this.canvas.height;
    } else if (newDims.height == null) {
      newDims.height = this.canvas.height * newDims.width / this.canvas.width;
    }
    if (typeof exports !== "undefined" && exports !== null) {
      canvas = new Canvas(newDims.width, newDims.height);
    } else {
      canvas = document.createElement('canvas');
      Util.copyAttributes(this.canvas, canvas);
      canvas.width = newDims.width;
      canvas.height = newDims.height;
    }
    ctx = canvas.getContext('2d');
    ctx.drawImage(this.canvas, 0, 0, this.canvas.width, this.canvas.height, 0, 0, newDims.width, newDims.height);
    this.resized = true;
    return this.replaceCanvas(canvas);
  });

  Caman.Filter.register("crop", function() {
    return this.processPlugin("crop", Array.prototype.slice.call(arguments, 0));
  });

  Caman.Filter.register("resize", function() {
    return this.processPlugin("resize", Array.prototype.slice.call(arguments, 0));
  });

  Caman.Filter.register("boxBlur", function() {
    return this.processKernel("Box Blur", [1, 1, 1, 1, 1, 1, 1, 1, 1]);
  });

  Caman.Filter.register("heavyRadialBlur", function() {
    return this.processKernel("Heavy Radial Blur", [0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0]);
  });

  Caman.Filter.register("gaussianBlur", function() {
    return this.processKernel("Gaussian Blur", [1, 4, 6, 4, 1, 4, 16, 24, 16, 4, 6, 24, 36, 24, 6, 4, 16, 24, 16, 4, 1, 4, 6, 4, 1]);
  });

  Caman.Filter.register("motionBlur", function(degrees) {
    var kernel;

    if (degrees === 0 || degrees === 180) {
      kernel = [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0];
    } else if ((degrees > 0 && degrees < 90) || (degrees > 180 && degrees < 270)) {
      kernel = [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0];
    } else if (degrees === 90 || degrees === 270) {
      kernel = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    } else {
      kernel = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1];
    }
    return this.processKernel("Motion Blur", kernel);
  });

  Caman.Filter.register("sharpen", function(amt) {
    if (amt == null) {
      amt = 100;
    }
    amt /= 100;
    return this.processKernel("Sharpen", [0, -amt, 0, -amt, 4 * amt + 1, -amt, 0, -amt, 0]);
  });

  vignetteFilters = {
    brightness: function(rgba, amt, opts) {
      rgba.r = rgba.r - (rgba.r * amt * opts.strength);
      rgba.g = rgba.g - (rgba.g * amt * opts.strength);
      rgba.b = rgba.b - (rgba.b * amt * opts.strength);
      return rgba;
    },
    gamma: function(rgba, amt, opts) {
      rgba.r = Math.pow(rgba.r / 255, Math.max(10 * amt * opts.strength, 1)) * 255;
      rgba.g = Math.pow(rgba.g / 255, Math.max(10 * amt * opts.strength, 1)) * 255;
      rgba.b = Math.pow(rgba.b / 255, Math.max(10 * amt * opts.strength, 1)) * 255;
      return rgba;
    },
    colorize: function(rgba, amt, opts) {
      rgba.r -= (rgba.r - opts.color.r) * amt;
      rgba.g -= (rgba.g - opts.color.g) * amt;
      rgba.b -= (rgba.b - opts.color.b) * amt;
      return rgba;
    }
  };

  Filter.register("vignette", function(size, strength) {
    var bezier, center, end, start;

    if (strength == null) {
      strength = 60;
    }
    if (typeof size === "string" && size.substr(-1) === "%") {
      if (this.dimensions.height > this.dimensions.width) {
        size = this.dimensions.width * (parseInt(size.substr(0, size.length - 1), 10) / 100);
      } else {
        size = this.dimensions.height * (parseInt(size.substr(0, size.length - 1), 10) / 100);
      }
    }
    strength /= 100;
    center = [this.dimensions.width / 2, this.dimensions.height / 2];
    start = Math.sqrt(Math.pow(center[0], 2) + Math.pow(center[1], 2));
    end = start - size;
    bezier = Calculate.bezier([0, 1], [30, 30], [70, 60], [100, 80]);
    return this.process("vignette", function(rgba) {
      var dist, div, loc;

      loc = rgba.locationXY();
      dist = Calculate.distance(loc.x, loc.y, center[0], center[1]);
      if (dist > end) {
        div = Math.max(1, (bezier[Math.round(((dist - end) / size) * 100)] / 10) * strength);
        rgba.r = Math.pow(rgba.r / 255, div) * 255;
        rgba.g = Math.pow(rgba.g / 255, div) * 255;
        rgba.b = Math.pow(rgba.b / 255, div) * 255;
      }
      return rgba;
    });
  });

  Filter.register("rectangularVignette", function(opts) {
    var defaults, dim, percent, size, _i, _len, _ref;

    defaults = {
      strength: 50,
      cornerRadius: 0,
      method: 'brightness',
      color: {
        r: 0,
        g: 0,
        b: 0
      }
    };
    opts = Util.extend(defaults, opts);
    if (!opts.size) {
      return this;
    } else if (typeof opts.size === "string") {
      percent = parseInt(opts.size, 10) / 100;
      opts.size = {
        width: this.dimensions.width * percent,
        height: this.dimensions.height * percent
      };
    } else if (typeof opts.size === "object") {
      _ref = ["width", "height"];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        dim = _ref[_i];
        if (typeof opts.size[dim] === "string") {
          opts.size[dim] = this.dimensions[dim] * (parseInt(opts.size[dim], 10) / 100);
        }
      }
    } else if (opts.size === "number") {
      size = opts.size;
      opts.size = {
        width: size,
        height: size
      };
    }
    if (typeof opts.cornerRadius === "string") {
      opts.cornerRadius = (opts.size.width / 2) * (parseInt(opts.cornerRadius, 10) / 100);
    }
    opts.strength /= 100;
    opts.size.width = Math.floor(opts.size.width);
    opts.size.height = Math.floor(opts.size.height);
    opts.image = {
      width: this.dimensions.width,
      height: this.dimensions.height
    };
    if (opts.method === "colorize" && typeof opts.color === "string") {
      opts.color = Convert.hexToRGB(opts.color);
    }
    opts.coords = {
      left: (this.dimensions.width - opts.size.width) / 2,
      right: this.dimensions.width - opts.coords.left,
      bottom: (this.dimensions.height - opts.size.height) / 2,
      top: this.dimensions.height - opts.coords.bottom
    };
    opts.corners = [
      {
        x: opts.coords.left + opts.cornerRadius,
        y: opts.coords.top - opts.cornerRadius
      }, {
        x: opts.coords.right - opts.cornerRadius,
        y: opts.coords.top - opts.cornerRadius
      }, {
        x: opts.coords.right - opts.cornerRadius,
        y: opts.coords.bottom + opts.cornerRadius
      }, {
        x: opts.coords.left + opts.cornerRadius,
        y: opts.coords.bottom + opts.cornerRadius
      }
    ];
    opts.maxDist = Calculate.distance(0, 0, opts.corners[3].x, opts.corners[3].y) - opts.cornerRadius;
    return this.process("rectangularVignette", function(rgba) {
      var amt, loc, radialDist;

      loc = rgba.locationXY();
      if ((loc.x > opts.corners[0].x && loc.x < opts.corners[1].x) && (loc.y > opts.coords.bottom && loc.y < opts.coords.top)) {
        return rgba;
      }
      if ((loc.x > opts.coords.left && loc.x < opts.coords.right) && (loc.y > opts.corners[3].y && loc.y < opts.corners[2].y)) {
        return rgba;
      }
      if (loc.x > opts.corners[0].x && loc.x < opts.corners[1].x && loc.y > opts.coords.top) {
        amt = (loc.y - opts.coords.top) / opts.maxDist;
      } else if (loc.y > opts.corners[2].y && loc.y < opts.corners[1].y && loc.x > opts.coords.right) {
        amt = (loc.x - opts.coords.right) / opts.maxDist;
      } else if (loc.x > opts.corners[0].x && loc.x < opts.corners[1].x && loc.y < opts.coords.bottom) {
        amt = (opts.coords.bottom - loc.y) / opts.maxDist;
      } else if (loc.y > opts.corners[2].y && loc.y < opts.corners[1].y && loc.x < opts.coords.left) {
        amt = (opts.coords.left - loc.x) / opts.maxDist;
      } else if (loc.x <= opts.corners[0].x && loc.y >= opts.corners[0].y) {
        radialDist = Caman.distance(loc.x, loc.y, opts.corners[0].x, opts.corners[0].y);
        amt = (radialDist - opts.cornerRadius) / opts.maxDist;
      } else if (loc.x >= opts.corners[1].x && loc.y >= opts.corners[1].y) {
        radialDist = Caman.distance(loc.x, loc.y, opts.corners[1].x, opts.corners[1].y);
        amt = (radialDist - opts.cornerRadius) / opts.maxDist;
      } else if (loc.x >= opts.corners[2].x && loc.y <= opts.corners[2].y) {
        radialDist = Caman.distance(loc.x, loc.y, opts.corners[2].x, opts.corners[2].y);
        amt = (radialDist - opts.cornerRadius) / opts.maxDist;
      } else if (loc.x <= opts.corners[3].x && loc.y <= opts.corners[3].y) {
        radialDist = Caman.distance(loc.x, loc.y, opts.corners[3].x, opts.corners[3].y);
        amt = (radialDist - opts.cornerRadius) / opts.maxDist;
      }
      if (amt < 0) {
        return rgba;
      }
      return vignetteFilters[opts.method](rgba, amt, opts);
    });
  });

  /*
  CompoundBlur - Blurring with varying radii for Canvas
  
  Version:   0.1
  Author:  Mario Klingemann
  Contact:   mario@quasimondo.com
  Website:  http://www.quasimondo.com/StackBlurForCanvas
  Twitter:  @quasimondo
  Modified By: Ryan LeFevre (@meltingice)
  
  In case you find this class useful - especially in commercial projects -
  I am not totally unhappy for a small donation to my PayPal account
  mario@quasimondo.de
  
  Copyright (c) 2011 Mario Klingemann
  
  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:
  
  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
  */


  (function() {
    var BlurStack, getLinearGradientMap, getRadialGradientMap, mul_table, shg_table;

    mul_table = [512, 512, 456, 512, 328, 456, 335, 512, 405, 328, 271, 456, 388, 335, 292, 512, 454, 405, 364, 328, 298, 271, 496, 456, 420, 388, 360, 335, 312, 292, 273, 512, 482, 454, 428, 405, 383, 364, 345, 328, 312, 298, 284, 271, 259, 496, 475, 456, 437, 420, 404, 388, 374, 360, 347, 335, 323, 312, 302, 292, 282, 273, 265, 512, 497, 482, 468, 454, 441, 428, 417, 405, 394, 383, 373, 364, 354, 345, 337, 328, 320, 312, 305, 298, 291, 284, 278, 271, 265, 259, 507, 496, 485, 475, 465, 456, 446, 437, 428, 420, 412, 404, 396, 388, 381, 374, 367, 360, 354, 347, 341, 335, 329, 323, 318, 312, 307, 302, 297, 292, 287, 282, 278, 273, 269, 265, 261, 512, 505, 497, 489, 482, 475, 468, 461, 454, 447, 441, 435, 428, 422, 417, 411, 405, 399, 394, 389, 383, 378, 373, 368, 364, 359, 354, 350, 345, 341, 337, 332, 328, 324, 320, 316, 312, 309, 305, 301, 298, 294, 291, 287, 284, 281, 278, 274, 271, 268, 265, 262, 259, 257, 507, 501, 496, 491, 485, 480, 475, 470, 465, 460, 456, 451, 446, 442, 437, 433, 428, 424, 420, 416, 412, 408, 404, 400, 396, 392, 388, 385, 381, 377, 374, 370, 367, 363, 360, 357, 354, 350, 347, 344, 341, 338, 335, 332, 329, 326, 323, 320, 318, 315, 312, 310, 307, 304, 302, 299, 297, 294, 292, 289, 287, 285, 282, 280, 278, 275, 273, 271, 269, 267, 265, 263, 261, 259];
    shg_table = [9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24];
    getLinearGradientMap = function(width, height, centerX, centerY, angle, length, mirrored) {
      var cnv, context, gradient, x1, x2, y1, y2;

      cnv = typeof exports !== "undefined" && exports !== null ? new Canvas() : document.createElement('canvas');
      cnv.width = width;
      cnv.height = height;
      x1 = centerX + Math.cos(angle) * length * 0.5;
      y1 = centerY + Math.sin(angle) * length * 0.5;
      x2 = centerX - Math.cos(angle) * length * 0.5;
      y2 = centerY - Math.sin(angle) * length * 0.5;
      context = cnv.getContext("2d");
      gradient = context.createLinearGradient(x1, y1, x2, y2);
      if (!mirrored) {
        gradient.addColorStop(0, "white");
        gradient.addColorStop(1, "black");
      } else {
        gradient.addColorStop(0, "white");
        gradient.addColorStop(0.5, "black");
        gradient.addColorStop(1, "white");
      }
      context.fillStyle = gradient;
      context.fillRect(0, 0, width, height);
      return context.getImageData(0, 0, width, height);
    };
    getRadialGradientMap = function(width, height, centerX, centerY, radius1, radius2) {
      var cnv, context, gradient;

      cnv = typeof exports !== "undefined" && exports !== null ? new Canvas() : document.createElement('canvas');
      cnv.width = width;
      cnv.height = height;
      context = cnv.getContext("2d");
      gradient = context.createRadialGradient(centerX, centerY, radius1, centerX, centerY, radius2);
      gradient.addColorStop(1, "white");
      gradient.addColorStop(0, "black");
      context.fillStyle = gradient;
      context.fillRect(0, 0, width, height);
      return context.getImageData(0, 0, width, height);
    };
    BlurStack = function() {
      this.r = 0;
      this.g = 0;
      this.b = 0;
      this.a = 0;
      return this.next = null;
    };
    Caman.Plugin.register("compoundBlur", function(radiusData, radius, increaseFactor, blurLevels) {
      var b_in_sum, b_out_sum, b_sum, blend, currentIndex, div, g_in_sum, g_out_sum, g_sum, height, heightMinus1, i, iblend, idx, imagePixels, index, iradius, lookupValue, mul_sum, p, pb, pg, pixels, pr, r_in_sum, r_out_sum, r_sum, radiusPixels, radiusPlus1, rbs, shg_sum, stack, stackEnd, stackIn, stackOut, stackStart, steps, sumFactor, w4, wh, wh4, width, widthMinus1, x, y, yi, yp, yw, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;

      width = this.dimensions.width;
      height = this.dimensions.height;
      imagePixels = this.pixelData;
      radiusPixels = radiusData.data;
      wh = width * height;
      wh4 = wh << 2;
      pixels = [];
      for (i = _i = 0; 0 <= wh4 ? _i < wh4 : _i > wh4; i = 0 <= wh4 ? ++_i : --_i) {
        pixels[i] = imagePixels[i];
      }
      currentIndex = 0;
      steps = blurLevels;
      blurLevels -= 1;
      while (steps-- >= 0) {
        iradius = (radius + 0.5) | 0;
        if (iradius === 0) {
          continue;
        }
        if (iradius > 256) {
          iradius = 256;
        }
        div = iradius + iradius + 1;
        w4 = width << 2;
        widthMinus1 = width - 1;
        heightMinus1 = height - 1;
        radiusPlus1 = iradius + 1;
        sumFactor = radiusPlus1 * (radiusPlus1 + 1) / 2;
        stackStart = new BlurStack();
        stackEnd = void 0;
        stack = stackStart;
        for (i = _j = 1; 1 <= div ? _j < div : _j > div; i = 1 <= div ? ++_j : --_j) {
          stack = stack.next = new BlurStack();
          if (i === radiusPlus1) {
            stackEnd = stack;
          }
        }
        stack.next = stackStart;
        stackIn = null;
        stackOut = null;
        yw = yi = 0;
        mul_sum = mul_table[iradius];
        shg_sum = shg_table[iradius];
        for (y = _k = 0; 0 <= height ? _k < height : _k > height; y = 0 <= height ? ++_k : --_k) {
          r_in_sum = g_in_sum = b_in_sum = r_sum = g_sum = b_sum = 0;
          r_out_sum = radiusPlus1 * (pr = pixels[yi]);
          g_out_sum = radiusPlus1 * (pg = pixels[yi + 1]);
          b_out_sum = radiusPlus1 * (pb = pixels[yi + 2]);
          r_sum += sumFactor * pr;
          g_sum += sumFactor * pg;
          b_sum += sumFactor * pb;
          stack = stackStart;
          for (i = _l = 0; 0 <= radiusPlus1 ? _l < radiusPlus1 : _l > radiusPlus1; i = 0 <= radiusPlus1 ? ++_l : --_l) {
            stack.r = pr;
            stack.g = pg;
            stack.b = pb;
            stack = stack.next;
          }
          for (i = _m = 1; 1 <= radiusPlus1 ? _m < radiusPlus1 : _m > radiusPlus1; i = 1 <= radiusPlus1 ? ++_m : --_m) {
            p = yi + ((widthMinus1 < i ? widthMinus1 : i) << 2);
            r_sum += (stack.r = (pr = pixels[p])) * (rbs = radiusPlus1 - i);
            g_sum += (stack.g = (pg = pixels[p + 1])) * rbs;
            b_sum += (stack.b = (pb = pixels[p + 2])) * rbs;
            r_in_sum += pr;
            g_in_sum += pg;
            b_in_sum += pb;
            stack = stack.next;
          }
          stackIn = stackStart;
          stackOut = stackEnd;
          for (x = _n = 0; 0 <= width ? _n < width : _n > width; x = 0 <= width ? ++_n : --_n) {
            pixels[yi] = (r_sum * mul_sum) >> shg_sum;
            pixels[yi + 1] = (g_sum * mul_sum) >> shg_sum;
            pixels[yi + 2] = (b_sum * mul_sum) >> shg_sum;
            r_sum -= r_out_sum;
            g_sum -= g_out_sum;
            b_sum -= b_out_sum;
            r_out_sum -= stackIn.r;
            g_out_sum -= stackIn.g;
            b_out_sum -= stackIn.b;
            p = (yw + ((p = x + radiusPlus1) < widthMinus1 ? p : widthMinus1)) << 2;
            r_in_sum += (stackIn.r = pixels[p]);
            g_in_sum += (stackIn.g = pixels[p + 1]);
            b_in_sum += (stackIn.b = pixels[p + 2]);
            r_sum += r_in_sum;
            g_sum += g_in_sum;
            b_sum += b_in_sum;
            stackIn = stackIn.next;
            r_out_sum += (pr = stackOut.r);
            g_out_sum += (pg = stackOut.g);
            b_out_sum += (pb = stackOut.b);
            r_in_sum -= pr;
            g_in_sum -= pg;
            b_in_sum -= pb;
            stackOut = stackOut.next;
            yi += 4;
          }
          yw += width;
        }
        for (x = _o = 0; 0 <= width ? _o < width : _o > width; x = 0 <= width ? ++_o : --_o) {
          g_in_sum = b_in_sum = r_in_sum = g_sum = b_sum = r_sum = 0;
          yi = x << 2;
          r_out_sum = radiusPlus1 * (pr = pixels[yi]);
          g_out_sum = radiusPlus1 * (pg = pixels[yi + 1]);
          b_out_sum = radiusPlus1 * (pb = pixels[yi + 2]);
          r_sum += sumFactor * pr;
          g_sum += sumFactor * pg;
          b_sum += sumFactor * pb;
          stack = stackStart;
          for (i = _p = 0; 0 <= radiusPlus1 ? _p < radiusPlus1 : _p > radiusPlus1; i = 0 <= radiusPlus1 ? ++_p : --_p) {
            stack.r = pr;
            stack.g = pg;
            stack.b = pb;
            stack = stack.next;
          }
          yp = width;
          for (i = _q = 1; 1 <= radiusPlus1 ? _q < radiusPlus1 : _q > radiusPlus1; i = 1 <= radiusPlus1 ? ++_q : --_q) {
            yi = (yp + x) << 2;
            r_sum += (stack.r = (pr = pixels[yi])) * (rbs = radiusPlus1 - i);
            g_sum += (stack.g = (pg = pixels[yi + 1])) * rbs;
            b_sum += (stack.b = (pb = pixels[yi + 2])) * rbs;
            r_in_sum += pr;
            g_in_sum += pg;
            b_in_sum += pb;
            stack = stack.next;
            if (i < heightMinus1) {
              yp += width;
            }
          }
          yi = x;
          stackIn = stackStart;
          stackOut = stackEnd;
          for (y = _r = 0; 0 <= height ? _r < height : _r > height; y = 0 <= height ? ++_r : --_r) {
            p = yi << 2;
            pixels[p] = (r_sum * mul_sum) >> shg_sum;
            pixels[p + 1] = (g_sum * mul_sum) >> shg_sum;
            pixels[p + 2] = (b_sum * mul_sum) >> shg_sum;
            r_sum -= r_out_sum;
            g_sum -= g_out_sum;
            b_sum -= b_out_sum;
            r_out_sum -= stackIn.r;
            g_out_sum -= stackIn.g;
            b_out_sum -= stackIn.b;
            p = (x + (((p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1) * width)) << 2;
            r_sum += (r_in_sum += (stackIn.r = pixels[p]));
            g_sum += (g_in_sum += (stackIn.g = pixels[p + 1]));
            b_sum += (b_in_sum += (stackIn.b = pixels[p + 2]));
            stackIn = stackIn.next;
            r_out_sum += (pr = stackOut.r);
            g_out_sum += (pg = stackOut.g);
            b_out_sum += (pb = stackOut.b);
            r_in_sum -= pr;
            g_in_sum -= pg;
            b_in_sum -= pb;
            stackOut = stackOut.next;
            yi += width;
          }
        }
        radius *= increaseFactor;
        i = wh;
        while (--i > -1) {
          idx = i << 2;
          lookupValue = (radiusPixels[idx + 2] & 0xff) / 255.0 * blurLevels;
          index = lookupValue | 0;
          if (index === currentIndex) {
            blend = 256.0 * (lookupValue - (lookupValue | 0));
            iblend = 256 - blend;
            imagePixels[idx] = (imagePixels[idx] * iblend + pixels[idx] * blend) >> 8;
            imagePixels[idx + 1] = (imagePixels[idx + 1] * iblend + pixels[idx + 1] * blend) >> 8;
            imagePixels[idx + 2] = (imagePixels[idx + 2] * iblend + pixels[idx + 2] * blend) >> 8;
          } else if (index === currentIndex + 1) {
            imagePixels[idx] = pixels[idx];
            imagePixels[idx + 1] = pixels[idx + 1];
            imagePixels[idx + 2] = pixels[idx + 2];
          }
        }
        currentIndex++;
      }
      return this;
    });
    Caman.Filter.register("tiltShift", function(opts) {
      var defaults, gradient;

      defaults = {
        center: {
          x: this.dimensions.width / 2,
          y: this.dimensions.height / 2
        },
        angle: 45,
        focusWidth: 200,
        startRadius: 3,
        radiusFactor: 1.5,
        steps: 3
      };
      opts = Util.extend(defaults, opts);
      opts.angle *= Math.PI / 180;
      gradient = getLinearGradientMap(this.dimensions.width, this.dimensions.height, opts.center.x, opts.center.y, opts.angle, opts.focusWidth, true);
      return this.processPlugin("compoundBlur", [gradient, opts.startRadius, opts.radiusFactor, opts.steps]);
    });
    return Caman.Filter.register("radialBlur", function(opts) {
      var defaults, gradient, radius1, radius2;

      defaults = {
        size: 50,
        center: {
          x: this.dimensions.width / 2,
          y: this.dimensions.height / 2
        },
        startRadius: 3,
        radiusFactor: 1.5,
        steps: 3,
        radius: null
      };
      opts = Util.extend(defaults, opts);
      if (!opts.radius) {
        opts.radius = this.dimensions.width < this.dimensions.height ? this.dimensions.height : this.dimensions.width;
      }
      radius1 = (opts.radius / 2) - opts.size;
      radius2 = opts.radius / 2;
      gradient = getRadialGradientMap(this.dimensions.width, this.dimensions.height, opts.center.x, opts.center.y, radius1, radius2);
      return this.processPlugin("compoundBlur", [gradient, opts.startRadius, opts.radiusFactor, opts.steps]);
    });
  })();

  Caman.Filter.register("edgeEnhance", function() {
    return this.processKernel("Edge Enhance", [0, 0, 0, -1, 1, 0, 0, 0, 0]);
  });

  Caman.Filter.register("edgeDetect", function() {
    return this.processKernel("Edge Detect", [-1, -1, -1, -1, 8, -1, -1, -1, -1]);
  });

  Caman.Filter.register("emboss", function() {
    return this.processKernel("Emboss", [-2, -1, 0, -1, 1, 1, 0, 1, 2]);
  });

  Caman.Filter.register("posterize", function(adjust) {
    var numOfAreas, numOfValues;

    numOfAreas = 256 / adjust;
    numOfValues = 255 / (adjust - 1);
    return this.process("posterize", function(rgba) {
      rgba.r = Math.floor(Math.floor(rgba.r / numOfAreas) * numOfValues);
      rgba.g = Math.floor(Math.floor(rgba.g / numOfAreas) * numOfValues);
      rgba.b = Math.floor(Math.floor(rgba.b / numOfAreas) * numOfValues);
      return rgba;
    });
  });

  Caman.Filter.register("vintage", function(vignette) {
    if (vignette == null) {
      vignette = true;
    }
    this.greyscale();
    this.contrast(5);
    this.noise(3);
    this.sepia(100);
    this.channels({
      red: 8,
      blue: 2,
      green: 4
    });
    this.gamma(0.87);
    if (vignette) {
      return this.vignette("40%", 30);
    }
  });

  Caman.Filter.register("lomo", function(vignette) {
    if (vignette == null) {
      vignette = true;
    }
    this.brightness(15);
    this.exposure(15);
    this.curves('rgb', [0, 0], [200, 0], [155, 255], [255, 255]);
    this.saturation(-20);
    this.gamma(1.8);
    if (vignette) {
      this.vignette("50%", 60);
    }
    return this.brightness(5);
  });

  Caman.Filter.register("clarity", function(grey) {
    if (grey == null) {
      grey = false;
    }
    this.vibrance(20);
    this.curves('rgb', [5, 0], [130, 150], [190, 220], [250, 255]);
    this.sharpen(15);
    this.vignette("45%", 20);
    if (grey) {
      this.greyscale();
      this.contrast(4);
    }
    return this;
  });

  Caman.Filter.register("sinCity", function() {
    this.contrast(100);
    this.brightness(15);
    this.exposure(10);
    this.posterize(80);
    this.clip(30);
    return this.greyscale();
  });

  Caman.Filter.register("sunrise", function() {
    this.exposure(3.5);
    this.saturation(-5);
    this.vibrance(50);
    this.sepia(60);
    this.colorize("#e87b22", 10);
    this.channels({
      red: 8,
      blue: 8
    });
    this.contrast(5);
    this.gamma(1.2);
    return this.vignette("55%", 25);
  });

  Caman.Filter.register("crossProcess", function() {
    this.exposure(5);
    this.colorize("#e87b22", 4);
    this.sepia(20);
    this.channels({
      blue: 8,
      red: 3
    });
    this.curves('b', [0, 0], [100, 150], [180, 180], [255, 255]);
    this.contrast(15);
    this.vibrance(75);
    return this.gamma(1.6);
  });

  Caman.Filter.register("orangePeel", function() {
    this.curves('rgb', [0, 0], [100, 50], [140, 200], [255, 255]);
    this.vibrance(-30);
    this.saturation(-30);
    this.colorize('#ff9000', 30);
    this.contrast(-5);
    return this.gamma(1.4);
  });

  Caman.Filter.register("love", function() {
    this.brightness(5);
    this.exposure(8);
    this.contrast(4);
    this.colorize('#c42007', 30);
    this.vibrance(50);
    return this.gamma(1.3);
  });

  Caman.Filter.register("grungy", function() {
    this.gamma(1.5);
    this.clip(25);
    this.saturation(-60);
    this.contrast(5);
    this.noise(5);
    return this.vignette("50%", 30);
  });

  Caman.Filter.register("jarques", function() {
    this.saturation(-35);
    this.curves('b', [20, 0], [90, 120], [186, 144], [255, 230]);
    this.curves('r', [0, 0], [144, 90], [138, 120], [255, 255]);
    this.curves('g', [10, 0], [115, 105], [148, 100], [255, 248]);
    this.curves('rgb', [0, 0], [120, 100], [128, 140], [255, 255]);
    return this.sharpen(20);
  });

  Caman.Filter.register("pinhole", function() {
    this.greyscale();
    this.sepia(10);
    this.exposure(10);
    this.contrast(15);
    return this.vignette("60%", 35);
  });

  Caman.Filter.register("oldBoot", function() {
    this.saturation(-20);
    this.vibrance(-50);
    this.gamma(1.1);
    this.sepia(30);
    this.channels({
      red: -10,
      blue: 5
    });
    this.curves('rgb', [0, 0], [80, 50], [128, 230], [255, 255]);
    return this.vignette("60%", 30);
  });

  Caman.Filter.register("glowingSun", function(vignette) {
    if (vignette == null) {
      vignette = true;
    }
    this.brightness(10);
    this.newLayer(function() {
      this.setBlendingMode("multiply");
      this.opacity(80);
      this.copyParent();
      this.filter.gamma(0.8);
      this.filter.contrast(50);
      return this.filter.exposure(10);
    });
    this.newLayer(function() {
      this.setBlendingMode("softLight");
      this.opacity(80);
      return this.fillColor("#f49600");
    });
    this.exposure(20);
    this.gamma(0.8);
    if (vignette) {
      return this.vignette("45%", 20);
    }
  });

  Caman.Filter.register("hazyDays", function() {
    this.gamma(1.2);
    this.newLayer(function() {
      this.setBlendingMode("overlay");
      this.opacity(60);
      this.copyParent();
      this.filter.channels({
        red: 5
      });
      return this.filter.stackBlur(15);
    });
    this.newLayer(function() {
      this.setBlendingMode("addition");
      this.opacity(40);
      return this.fillColor("#6899ba");
    });
    this.newLayer(function() {
      this.setBlendingMode("multiply");
      this.opacity(35);
      this.copyParent();
      this.filter.brightness(40);
      this.filter.vibrance(40);
      this.filter.exposure(30);
      this.filter.contrast(15);
      this.filter.curves('r', [0, 40], [128, 128], [128, 128], [255, 215]);
      this.filter.curves('g', [0, 40], [128, 128], [128, 128], [255, 215]);
      this.filter.curves('b', [0, 40], [128, 128], [128, 128], [255, 215]);
      return this.filter.stackBlur(5);
    });
    this.curves('r', [20, 0], [128, 158], [128, 128], [235, 255]);
    this.curves('g', [20, 0], [128, 128], [128, 128], [235, 255]);
    this.curves('b', [20, 0], [128, 108], [128, 128], [235, 255]);
    return this.vignette("45%", 20);
  });

  Caman.Filter.register("herMajesty", function() {
    this.brightness(40);
    this.colorize("#ea1c5d", 10);
    this.curves('b', [0, 10], [128, 180], [190, 190], [255, 255]);
    this.newLayer(function() {
      this.setBlendingMode('overlay');
      this.opacity(50);
      this.copyParent();
      this.filter.gamma(0.7);
      return this.newLayer(function() {
        this.setBlendingMode('normal');
        this.opacity(60);
        return this.fillColor('#ea1c5d');
      });
    });
    this.newLayer(function() {
      this.setBlendingMode('multiply');
      this.opacity(60);
      this.copyParent();
      this.filter.saturation(50);
      this.filter.hue(90);
      return this.filter.contrast(10);
    });
    this.gamma(1.4);
    this.vibrance(-30);
    this.newLayer(function() {
      this.opacity(10);
      return this.fillColor('#e5f0ff');
    });
    return this;
  });

  Caman.Filter.register("nostalgia", function() {
    this.saturation(20);
    this.gamma(1.4);
    this.greyscale();
    this.contrast(5);
    this.sepia(100);
    this.channels({
      red: 8,
      blue: 2,
      green: 4
    });
    this.gamma(0.8);
    this.contrast(5);
    this.exposure(10);
    this.newLayer(function() {
      this.setBlendingMode('overlay');
      this.copyParent();
      this.opacity(55);
      return this.filter.stackBlur(10);
    });
    return this.vignette("50%", 30);
  });

  Caman.Filter.register("hemingway", function() {
    this.greyscale();
    this.contrast(10);
    this.gamma(0.9);
    this.newLayer(function() {
      this.setBlendingMode("multiply");
      this.opacity(40);
      this.copyParent();
      this.filter.exposure(15);
      this.filter.contrast(15);
      return this.filter.channels({
        green: 10,
        red: 5
      });
    });
    this.sepia(30);
    this.curves('rgb', [0, 10], [120, 90], [180, 200], [235, 255]);
    this.channels({
      red: 5,
      green: -2
    });
    return this.exposure(15);
  });

  Caman.Filter.register("concentrate", function() {
    this.sharpen(40);
    this.saturation(-50);
    this.channels({
      red: 3
    });
    this.newLayer(function() {
      this.setBlendingMode("multiply");
      this.opacity(80);
      this.copyParent();
      this.filter.sharpen(5);
      this.filter.contrast(50);
      this.filter.exposure(10);
      return this.filter.channels({
        blue: 5
      });
    });
    return this.brightness(10);
  });

  Caman.Plugin.register("rotate", function(degrees) {
    var angle, canvas, ctx, height, to_radians, width, x, y;

    angle = degrees % 360;
    if (angle === 0) {
      return this.dimensions = {
        width: this.canvas.width,
        height: this.canvas.height
      };
    }
    to_radians = Math.PI / 180;
    if (typeof exports !== "undefined" && exports !== null) {
      canvas = new Canvas();
    } else {
      canvas = document.createElement('canvas');
      Util.copyAttributes(this.canvas, canvas);
    }
    if (angle === 90 || angle === -270 || angle === 270 || angle === -90) {
      width = this.canvas.height;
      height = this.canvas.width;
      x = width / 2;
      y = height / 2;
    } else if (angle === 180) {
      width = this.canvas.width;
      height = this.canvas.height;
      x = width / 2;
      y = height / 2;
    } else {
      width = Math.sqrt(Math.pow(this.originalWidth, 2) + Math.pow(this.originalHeight, 2));
      height = width;
      x = this.canvas.height / 2;
      y = this.canvas.width / 2;
    }
    canvas.width = width;
    canvas.height = height;
    ctx = canvas.getContext('2d');
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(angle * to_radians);
    ctx.drawImage(this.canvas, -this.canvas.width / 2, -this.canvas.height / 2, this.canvas.width, this.canvas.height);
    ctx.restore();
    return this.replaceCanvas(canvas);
  });

  Caman.Filter.register("rotate", function() {
    return this.processPlugin("rotate", Array.prototype.slice.call(arguments, 0));
  });

  /*
  StackBlur - a fast almost Gaussian Blur For Canvas v0.31 modified for CamanJS
  
  Version:   0.31
  Author:    Mario Klingemann
  Contact:   mario@quasimondo.com
  Website:  http://www.quasimondo.com/StackBlurForCanvas
  Twitter:  @quasimondo
  Modified By: Ryan LeFevre (@meltingice)
  
  In case you find this class useful - especially in commercial projects -
  I am not totally unhappy for a small donation to my PayPal account
  mario@quasimondo.de
  
  Or support me on flattr: 
  https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript
  
  Copyright (c) 2010 Mario Klingemann
  
  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:
  
  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
  */


  (function() {
    var BlurStack, mul_table, shg_table;

    mul_table = [512, 512, 456, 512, 328, 456, 335, 512, 405, 328, 271, 456, 388, 335, 292, 512, 454, 405, 364, 328, 298, 271, 496, 456, 420, 388, 360, 335, 312, 292, 273, 512, 482, 454, 428, 405, 383, 364, 345, 328, 312, 298, 284, 271, 259, 496, 475, 456, 437, 420, 404, 388, 374, 360, 347, 335, 323, 312, 302, 292, 282, 273, 265, 512, 497, 482, 468, 454, 441, 428, 417, 405, 394, 383, 373, 364, 354, 345, 337, 328, 320, 312, 305, 298, 291, 284, 278, 271, 265, 259, 507, 496, 485, 475, 465, 456, 446, 437, 428, 420, 412, 404, 396, 388, 381, 374, 367, 360, 354, 347, 341, 335, 329, 323, 318, 312, 307, 302, 297, 292, 287, 282, 278, 273, 269, 265, 261, 512, 505, 497, 489, 482, 475, 468, 461, 454, 447, 441, 435, 428, 422, 417, 411, 405, 399, 394, 389, 383, 378, 373, 368, 364, 359, 354, 350, 345, 341, 337, 332, 328, 324, 320, 316, 312, 309, 305, 301, 298, 294, 291, 287, 284, 281, 278, 274, 271, 268, 265, 262, 259, 257, 507, 501, 496, 491, 485, 480, 475, 470, 465, 460, 456, 451, 446, 442, 437, 433, 428, 424, 420, 416, 412, 408, 404, 400, 396, 392, 388, 385, 381, 377, 374, 370, 367, 363, 360, 357, 354, 350, 347, 344, 341, 338, 335, 332, 329, 326, 323, 320, 318, 315, 312, 310, 307, 304, 302, 299, 297, 294, 292, 289, 287, 285, 282, 280, 278, 275, 273, 271, 269, 267, 265, 263, 261, 259];
    shg_table = [9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24];
    BlurStack = function() {
      this.r = 0;
      this.g = 0;
      this.b = 0;
      this.a = 0;
      return this.next = null;
    };
    Caman.Plugin.register("stackBlur", function(radius) {
      var b_in_sum, b_out_sum, b_sum, div, g_in_sum, g_out_sum, g_sum, height, heightMinus1, i, mul_sum, p, pb, pg, pixels, pr, r_in_sum, r_out_sum, r_sum, radiusPlus1, rbs, shg_sum, stack, stackEnd, stackIn, stackOut, stackStart, sumFactor, w4, width, widthMinus1, x, y, yi, yp, yw, _i, _j, _k, _l, _m, _n, _o, _p, _q;

      if (isNaN(radius) || radius < 1) {
        return;
      }
      radius |= 0;
      pixels = this.pixelData;
      width = this.dimensions.width;
      height = this.dimensions.height;
      div = radius + radius + 1;
      w4 = width << 2;
      widthMinus1 = width - 1;
      heightMinus1 = height - 1;
      radiusPlus1 = radius + 1;
      sumFactor = radiusPlus1 * (radiusPlus1 + 1) / 2;
      stackStart = new BlurStack();
      stack = stackStart;
      for (i = _i = 1; 1 <= div ? _i < div : _i > div; i = 1 <= div ? ++_i : --_i) {
        stack = stack.next = new BlurStack();
        if (i === radiusPlus1) {
          stackEnd = stack;
        }
      }
      stack.next = stackStart;
      stackIn = null;
      stackOut = null;
      yw = yi = 0;
      mul_sum = mul_table[radius];
      shg_sum = shg_table[radius];
      for (y = _j = 0; 0 <= height ? _j < height : _j > height; y = 0 <= height ? ++_j : --_j) {
        r_in_sum = g_in_sum = b_in_sum = r_sum = g_sum = b_sum = 0;
        r_out_sum = radiusPlus1 * (pr = pixels[yi]);
        g_out_sum = radiusPlus1 * (pg = pixels[yi + 1]);
        b_out_sum = radiusPlus1 * (pb = pixels[yi + 2]);
        r_sum += sumFactor * pr;
        g_sum += sumFactor * pg;
        b_sum += sumFactor * pb;
        stack = stackStart;
        for (i = _k = 0; 0 <= radiusPlus1 ? _k < radiusPlus1 : _k > radiusPlus1; i = 0 <= radiusPlus1 ? ++_k : --_k) {
          stack.r = pr;
          stack.g = pg;
          stack.b = pb;
          stack = stack.next;
        }
        for (i = _l = 1; 1 <= radiusPlus1 ? _l < radiusPlus1 : _l > radiusPlus1; i = 1 <= radiusPlus1 ? ++_l : --_l) {
          p = yi + ((widthMinus1 < i ? widthMinus1 : i) << 2);
          r_sum += (stack.r = (pr = pixels[p])) * (rbs = radiusPlus1 - i);
          g_sum += (stack.g = (pg = pixels[p + 1])) * rbs;
          b_sum += (stack.b = (pb = pixels[p + 2])) * rbs;
          r_in_sum += pr;
          g_in_sum += pg;
          b_in_sum += pb;
          stack = stack.next;
        }
        stackIn = stackStart;
        stackOut = stackEnd;
        for (x = _m = 0; 0 <= width ? _m < width : _m > width; x = 0 <= width ? ++_m : --_m) {
          pixels[yi] = (r_sum * mul_sum) >> shg_sum;
          pixels[yi + 1] = (g_sum * mul_sum) >> shg_sum;
          pixels[yi + 2] = (b_sum * mul_sum) >> shg_sum;
          r_sum -= r_out_sum;
          g_sum -= g_out_sum;
          b_sum -= b_out_sum;
          r_out_sum -= stackIn.r;
          g_out_sum -= stackIn.g;
          b_out_sum -= stackIn.b;
          p = (yw + ((p = x + radius + 1) < widthMinus1 ? p : widthMinus1)) << 2;
          r_in_sum += (stackIn.r = pixels[p]);
          g_in_sum += (stackIn.g = pixels[p + 1]);
          b_in_sum += (stackIn.b = pixels[p + 2]);
          r_sum += r_in_sum;
          g_sum += g_in_sum;
          b_sum += b_in_sum;
          stackIn = stackIn.next;
          r_out_sum += (pr = stackOut.r);
          g_out_sum += (pg = stackOut.g);
          b_out_sum += (pb = stackOut.b);
          r_in_sum -= pr;
          g_in_sum -= pg;
          b_in_sum -= pb;
          stackOut = stackOut.next;
          yi += 4;
        }
        yw += width;
      }
      for (x = _n = 0; 0 <= width ? _n < width : _n > width; x = 0 <= width ? ++_n : --_n) {
        g_in_sum = b_in_sum = r_in_sum = g_sum = b_sum = r_sum = 0;
        yi = x << 2;
        r_out_sum = radiusPlus1 * (pr = pixels[yi]);
        g_out_sum = radiusPlus1 * (pg = pixels[yi + 1]);
        b_out_sum = radiusPlus1 * (pb = pixels[yi + 2]);
        r_sum += sumFactor * pr;
        g_sum += sumFactor * pg;
        b_sum += sumFactor * pb;
        stack = stackStart;
        for (i = _o = 0; 0 <= radiusPlus1 ? _o < radiusPlus1 : _o > radiusPlus1; i = 0 <= radiusPlus1 ? ++_o : --_o) {
          stack.r = pr;
          stack.g = pg;
          stack.b = pb;
          stack = stack.next;
        }
        yp = width;
        for (i = _p = 1; 1 <= radius ? _p <= radius : _p >= radius; i = 1 <= radius ? ++_p : --_p) {
          yi = (yp + x) << 2;
          r_sum += (stack.r = (pr = pixels[yi])) * (rbs = radiusPlus1 - i);
          g_sum += (stack.g = (pg = pixels[yi + 1])) * rbs;
          b_sum += (stack.b = (pb = pixels[yi + 2])) * rbs;
          r_in_sum += pr;
          g_in_sum += pg;
          b_in_sum += pb;
          stack = stack.next;
          if (i < heightMinus1) {
            yp += width;
          }
        }
        yi = x;
        stackIn = stackStart;
        stackOut = stackEnd;
        for (y = _q = 0; 0 <= height ? _q < height : _q > height; y = 0 <= height ? ++_q : --_q) {
          p = yi << 2;
          pixels[p] = (r_sum * mul_sum) >> shg_sum;
          pixels[p + 1] = (g_sum * mul_sum) >> shg_sum;
          pixels[p + 2] = (b_sum * mul_sum) >> shg_sum;
          r_sum -= r_out_sum;
          g_sum -= g_out_sum;
          b_sum -= b_out_sum;
          r_out_sum -= stackIn.r;
          g_out_sum -= stackIn.g;
          b_out_sum -= stackIn.b;
          p = (x + (((p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1) * width)) << 2;
          r_sum += (r_in_sum += (stackIn.r = pixels[p]));
          g_sum += (g_in_sum += (stackIn.g = pixels[p + 1]));
          b_sum += (b_in_sum += (stackIn.b = pixels[p + 2]));
          stackIn = stackIn.next;
          r_out_sum += (pr = stackOut.r);
          g_out_sum += (pg = stackOut.g);
          b_out_sum += (pb = stackOut.b);
          r_in_sum -= pr;
          g_in_sum -= pg;
          b_in_sum -= pb;
          stackOut = stackOut.next;
          yi += width;
        }
      }
      return this;
    });
    return Caman.Filter.register("stackBlur", function(radius) {
      return this.processPlugin("stackBlur", [radius]);
    });
  })();

  Caman.Filter.register("threshold", function(adjust) {
    return this.process("threshold", function(rgba) {
      var luminance;

      luminance = (0.2126 * rgba.r) + (0.7152 * rgba.g) + (0.0722 * rgba.b);
      if (luminance < adjust) {
        rgba.r = 0;
        rgba.g = 0;
        rgba.b = 0;
      } else {
        rgba.r = 255;
        rgba.g = 255;
        rgba.b = 255;
      }
      return rgba;
    });
  });

}).call(this);
//Created by TechSlides at http://techslides.com
//Instagram filter from: http://matthewruddy.github.io/jQuery-filter.me/js/production/jquery.filterme.js

//CamanJS Plugin
Caman.Plugin.register("rgba", function(rgba) {

  var imageData = this.imageData,
    data = imageData.data,
    length = data.length;

  // Apply the color R, G, B values to each individual pixel
  for ( i = 0; i < length; i += 4 ) {
    data[ i ] = rgba.r[ data[ i ] ];
    data[ i+1 ] = rgba.g[ data[ i+1 ] ];
    data[ i+2 ] = rgba.b[ data[ i+2 ] ];
  }

  // Apply the overall RGB contrast changes to each pixel
  for ( i = 0; i < length; i += 4 ) {
    data[ i ] = rgba.a[ data[ i ] ];
    data[ i+1 ] = rgba.a[ data[ i+1 ] ];
    data[ i+2 ] = rgba.a[ data[ i+2 ] ];
  }

  // Restore modified image data
  imageData.data = data;

  //apply the shit!
  this.context.putImageData(imageData,0,0);

  // Tell CamanJS to replace the current canvas with our new cropped one.
  //this.replaceCanvas(this.canvas);
  return this;
});


//1977 Filter
Caman.Filter.register("1977", function() {

  var rgba = {'a':[0,1,3,4,6,7,9,10,12,13,14,16,17,19,20,22,23,25,26,28,29,31,32,34,35,37,38,39,41,42,44,45,46,48,49,50,52,53,54,55,57,58,59,60,61,62,64,65,66,67,68,69,70,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,125,126,127,128,129,130,131,132,133,134,135,136,137,137,138,139,140,141,142,143,144,145,146,146,147,148,149,150,151,152,153,153,154,155,156,157,158,159,160,160,161,162,163,164,165,166,166,167,168,169,170,171,172,172,173,174,175,176,177,178,178,179,180,181,182,183,183,184,185,186,187,188,188,189,190,191,192,193,193,194,195,196,197,198,199,199,200,201,202,203,204,204,205,206,207,208,209,209,210,211,212,213,214,215,215,216,217,218,219,220,221,221,222,223,224,225,226,227,227,228,229,230,231,232,233,233,234,235,236,237,238,239,240,241,241,242,243,244,245,246,247,248,249,250,250,251,252,253,254,255,255], 'r':[58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,58,59,60,60,61,62,62,63,63,64,64,65,66,66,67,67,68,69,69,70,70,71,72,72,73,74,74,75,76,77,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,95,96,97,98,99,100,102,103,104,105,106,108,109,110,111,112,113,114,116,117,118,119,120,121,122,123,125,126,127,128,129,130,131,133,134,135,136,137,138,140,141,142,143,144,146,147,148,149,151,152,153,154,156,157,158,160,161,162,164,165,166,168,169,170,172,173,175,176,177,179,180,182,183,185,186,188,189,191,192,193,194,196,197,198,199,200,201,202,203,204,204,205,206,206,207,208,208,209,209,210,210,211,211,212,212,212,213,213,213,213,213,214,214,214,214,214,214,214,214,214,214,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,215,214,214,214,214,214,214,214,214,214,214,213,213,213,213,213,213,213,212,212,212,212,212], 'g':[40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,41,41,42,42,42,42,43,43,43,43,44,44,44,44,45,45,45,45,46,46,46,47,47,48,48,48,49,49,50,50,51,52,52,53,54,54,55,56,57,58,59,60,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,153,154,155,156,157,158,160,161,162,163,164,166,167,168,169,171,172,173,174,175,176,178,179,180,181,182,183,185,186,187,188,189,190,191,192,193,195,196,197,198,199,200,201,202,203,205,206,207,208,209,210,211,212,214,215,216,217,218,220,221,222,223,225,226,227,228,230,231,232,233,235,236,237,239,240,241,242,244,245,246,247,249,250,251,252,254,255,255], 'b':[45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,46,46,47,47,47,48,48,48,48,49,49,49,50,50,50,51,51,51,52,52,53,53,54,54,55,56,56,57,58,59,60,61,62,62,63,64,65,66,68,69,70,71,72,73,74,75,76,77,79,80,81,82,83,84,85,86,87,89,90,91,92,93,94,96,97,98,99,100,102,103,104,105,107,108,109,110,112,113,114,115,117,118,119,120,122,123,124,126,127,128,130,131,133,134,135,137,138,140,141,143,144,145,147,148,149,151,152,153,155,156,157,159,160,161,162,164,165,166,167,168,170,171,172,173,174,175,176,177,178,179,180,181,182,184,185,186,187,188,188,189,190,191,192,193,193,194,195,195,196,196,196,197,197,197,197,198,198,198,198,198,198,198,198,198,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,199,198,198,198,198,198,198,197,197,197,197,197,197,197,197,197,197,197,197,197,197,198,198,198,198,198,198,198]};

  //pass rgba object to our special rgba plugin
  this.processPlugin("rgba", [rgba]);
});


//Brannan
Caman.Filter.register("brannan", function() {
  var rgba = {'a':[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,255], 'r':[50,50,50,50,50,50,50,50,50,50,50,50,50,51,51,51,51,51,52,53,54,55,56,57,59,60,62,63,64,66,67,68,69,70,71,71,72,73,73,74,75,75,76,76,77,77,78,78,79,79,80,80,81,81,82,83,83,84,85,86,87,88,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,111,112,113,114,115,116,118,119,120,121,122,124,125,126,128,129,130,132,133,134,136,137,139,140,141,143,144,146,147,149,150,152,153,154,156,157,159,160,162,163,164,166,167,169,170,171,173,174,175,177,178,179,181,182,183,185,186,187,189,190,192,193,195,196,198,199,201,203,204,206,207,209,210,212,213,215,216,217,219,220,221,223,224,225,226,227,228,229,230,231,232,233,234,235,236,236,237,238,239,239,240,241,241,242,243,243,244,244,245,246,246,247,247,248,248,249,249,249,250,250,251,251,251,252,252,252,253,253,253,254,254,254,254,254,254,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,254,254,254,254,254], 'g':[0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,3,4,4,5,6,7,8,10,11,12,13,14,16,17,18,19,20,21,23,24,25,26,27,28,29,30,32,33,34,35,36,38,39,40,41,43,44,45,47,48,50,51,53,54,56,57,59,61,62,64,66,68,70,72,74,76,78,80,82,84,87,89,91,93,95,97,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,161,163,165,167,168,170,172,173,175,176,178,179,181,182,183,184,186,187,188,189,190,191,192,193,193,194,195,196,196,197,198,198,199,200,200,201,202,202,203,203,204,204,205,205,206,207,207,208,208,209,210,210,211,212,212,213,214,214,215,216,217,217,218,219,219,220,221,221,222,222,223,224,224,225,225,226,226,227,228,228,229,229,229,230,230,231,231,232,232,233,233,233,234,234,234,235,235,236,236,236,237,237,237,238,238,239,239,239,240,240,240,241,241,241,242,242,242,243,243,243,244,244,244,245,245,245,246,246,247,247,247,248,248,249,249,250,250,251,251,252,252,252], 'b':[48,48,48,48,48,48,48,48,49,49,49,49,49,49,49,50,50,50,51,51,51,52,52,53,53,54,54,54,55,55,56,56,57,57,58,58,59,60,60,61,61,62,62,63,64,64,65,66,66,67,68,68,69,70,71,71,72,73,74,75,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,92,93,94,95,96,98,99,100,101,102,103,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,132,133,134,135,136,137,138,139,140,141,141,142,143,144,145,146,146,147,148,148,149,150,151,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,168,169,170,171,172,173,174,175,176,177,178,178,179,180,181,181,182,183,183,184,184,185,185,185,186,186,187,187,187,188,188,188,189,189,190,190,191,191,192,193,193,194,195,195,196,197,198,199,200,200,201,202,203,204,205,206,206,207,208,209,210,211,211,212,213,214,214,215,216,216,217,218,218,219,219,220,220,221,222,222,222,223,223,224,224,224,225,225,225,225,225,225,225,225,225,225,225,225,225,225,225,225,225]};
  this.processPlugin("rgba", [rgba]);
});


//Gotham
Caman.Filter.register("gotham", function() {
  var rgba = {'a':[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,255], 'r':[50,50,50,50,50,50,50,50,50,50,50,50,50,51,51,51,51,51,52,53,54,55,56,57,59,60,62,63,64,66,67,68,69,70,71,71,72,73,73,74,75,75,76,76,77,77,78,78,79,79,80,80,81,81,82,83,83,84,85,86,87,88,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,111,112,113,114,115,116,118,119,120,121,122,124,125,126,128,129,130,132,133,134,136,137,139,140,141,143,144,146,147,149,150,152,153,154,156,157,159,160,162,163,164,166,167,169,170,171,173,174,175,177,178,179,181,182,183,185,186,187,189,190,192,193,195,196,198,199,201,203,204,206,207,209,210,212,213,215,216,217,219,220,221,223,224,225,226,227,228,229,230,231,232,233,234,235,236,236,237,238,239,239,240,241,241,242,243,243,244,244,245,246,246,247,247,248,248,249,249,249,250,250,251,251,251,252,252,252,253,253,253,254,254,254,254,254,254,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,254,254,254,254,254], 'g':[0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,3,4,4,5,6,7,8,10,11,12,13,14,16,17,18,19,20,21,23,24,25,26,27,28,29,30,32,33,34,35,36,38,39,40,41,43,44,45,47,48,50,51,53,54,56,57,59,61,62,64,66,68,70,72,74,76,78,80,82,84,87,89,91,93,95,97,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,161,163,165,167,168,170,172,173,175,176,178,179,181,182,183,184,186,187,188,189,190,191,192,193,193,194,195,196,196,197,198,198,199,200,200,201,202,202,203,203,204,204,205,205,206,207,207,208,208,209,210,210,211,212,212,213,214,214,215,216,217,217,218,219,219,220,221,221,222,222,223,224,224,225,225,226,226,227,228,228,229,229,229,230,230,231,231,232,232,233,233,233,234,234,234,235,235,236,236,236,237,237,237,238,238,239,239,239,240,240,240,241,241,241,242,242,242,243,243,243,244,244,244,245,245,245,246,246,247,247,247,248,248,249,249,250,250,251,251,252,252,252], 'b':[48,48,48,48,48,48,48,48,49,49,49,49,49,49,49,50,50,50,51,51,51,52,52,53,53,54,54,54,55,55,56,56,57,57,58,58,59,60,60,61,61,62,62,63,64,64,65,66,66,67,68,68,69,70,71,71,72,73,74,75,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,92,93,94,95,96,98,99,100,101,102,103,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,132,133,134,135,136,137,138,139,140,141,141,142,143,144,145,146,146,147,148,148,149,150,151,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,168,169,170,171,172,173,174,175,176,177,178,178,179,180,181,181,182,183,183,184,184,185,185,185,186,186,187,187,187,188,188,188,189,189,190,190,191,191,192,193,193,194,195,195,196,197,198,199,200,200,201,202,203,204,205,206,206,207,208,209,210,211,211,212,213,214,214,215,216,216,217,218,218,219,219,220,220,221,222,222,222,223,223,224,224,224,225,225,225,225,225,225,225,225,225,225,225,225,225,225,225,225,225]};
  this.greyscale();
  this.processPlugin("rgba", [rgba]);
});


//Hefe
Caman.Filter.register("hefe", function() {
  var rgba = {'a':[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,255], 'r':[32,32,32,32,32,32,32,32,32,32,32,32,32,33,33,33,33,33,34,35,36,38,39,41,43,45,48,50,52,54,56,58,60,62,64,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,96,98,100,102,104,106,108,110,112,114,116,117,119,121,123,125,126,128,130,132,133,135,137,139,140,142,144,146,147,149,151,152,154,155,157,158,160,161,163,164,166,167,168,170,171,172,173,175,176,177,178,179,180,181,182,184,185,186,187,188,189,190,190,191,192,193,194,195,196,197,197,198,199,200,201,201,202,203,204,204,205,205,206,206,207,207,208,208,209,209,210,210,211,211,212,212,213,213,214,214,215,215,216,216,217,217,218,218,219,219,220,220,221,221,221,222,222,223,223,224,224,225,225,225,226,226,227,227,228,228,228,229,229,230,230,231,231,231,232,232,233,233,233,234,234,235,235,235,236,236,236,237,237,238,238,238,239,239,239,240,240,240,241,241,242,242,242,243,243,243,244,244,245,245,245,246,246,247,248,248,249,249,250,250,251,251,252,252,252,252,252,252,252,252,252,252,252,252,252,252,252,252,252,252,252,252], 'g':[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,19,20,21,23,24,25,27,28,30,31,33,34,36,37,39,40,42,44,45,47,49,50,52,54,56,57,59,61,63,65,67,69,71,73,75,78,80,82,85,87,89,92,94,97,99,102,104,106,109,111,114,116,118,121,123,125,127,129,131,133,135,137,139,141,143,145,146,148,150,152,154,156,157,159,161,163,164,166,168,169,171,173,174,176,178,179,181,182,184,185,187,188,190,191,192,194,195,196,197,198,199,200,201,202,203,204,205,205,206,207,207,208,209,209,210,210,211,211,211,212,212,213,213,213,214,214,215,215,216,216,216,217,217,218,218,219,219,220,220,220,221,221,222,222,222,223,223,224,224,225,225,225,226,226,227,227,228,228,228,229,229,230,230,231,231,232,232,232,233,233,234,234,235,235,236,236,237,237,238,238,239,239,239,240,240,241,241,242,242,243,244,244,245,246,246,247,248,249,249,250,250,251,251,252,252,252,252,252,252,252,252,252,252,252,252,252,252,252,252,252,252,252], 'b':[2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5,6,6,6,6,6,7,7,7,8,8,9,9,9,10,10,11,12,12,13,13,14,15,15,16,17,17,18,19,19,20,21,22,23,24,24,25,26,27,28,29,30,32,33,34,35,36,38,39,40,42,43,45,47,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,87,89,91,93,95,96,98,100,101,103,105,107,108,110,112,113,115,117,118,120,122,123,125,127,128,130,131,133,135,136,138,140,141,143,145,146,148,149,151,153,154,156,158,159,161,163,164,166,167,169,170,171,173,174,175,177,178,179,180,182,183,184,185,186,187,189,190,191,192,193,194,195,195,196,197,198,198,199,200,200,201,201,202,202,203,203,204,204,204,205,205,205,206,206,206,207,207,207,207,208,208,209,209,209,210,210,211,211,211,212,212,213,213,214,214,214,215,215,216,216,216,217,217,218,218,218,219,219,220,220,220,221,221,222,222,222,223,223,224,224,225,225,226,226,227,227,227,228,228,228,228,228,228,228,228,228,228,228,228,228,228,228,228,228,228,228,228]};
  this.processPlugin("rgba", [rgba]);
});


//Lord Kelvin
Caman.Filter.register("lordkelvin", function() {
  var rgba = {'a':[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,255], 'r':[43,44,46,47,49,50,52,53,55,56,58,59,61,62,64,65,67,69,70,72,73,75,77,78,80,81,83,85,86,88,90,91,93,95,96,98,100,102,103,105,107,109,111,112,114,116,118,120,121,123,125,127,129,130,132,134,136,137,139,141,142,144,146,147,149,151,152,154,155,157,158,160,162,163,165,166,168,169,171,172,174,175,176,178,179,180,182,183,184,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,201,202,203,204,204,205,206,207,207,208,209,210,210,211,212,212,213,214,214,215,216,217,217,218,219,219,220,221,222,222,223,224,224,225,225,226,227,227,228,228,229,229,229,230,230,231,231,232,232,232,233,233,233,234,234,235,235,235,236,236,236,237,237,237,238,238,239,239,239,240,240,240,241,241,241,242,242,242,243,243,243,243,244,244,244,245,245,245,245,245,246,246,246,246,246,247,247,247,247,247,248,248,248,248,248,248,249,249,249,249,249,249,249,250,250,250,250,250,250,250,250,251,251,251,251,251,251,251,251,251,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253,253,253,254,254,254,254,254], 'g':[36,36,36,36,36,36,36,36,36,36,36,36,36,37,37,37,37,37,37,38,38,38,39,39,40,40,41,41,42,43,43,44,45,46,47,47,48,49,50,51,52,53,54,55,56,57,59,60,61,62,63,64,65,67,68,69,70,71,72,73,75,76,77,78,79,80,81,82,83,84,86,87,88,89,90,91,92,93,95,96,97,98,99,100,101,102,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,155,156,157,158,158,159,160,160,161,161,162,163,163,164,164,165,165,166,166,167,167,168,168,168,169,169,170,171,171,172,172,173,173,174,174,175,175,176,177,177,178,178,179,179,180,180,181,181,182,182,182,183,183,184,184,184,185,185,185,186,186,186,186,187,187,187,187,188,188,188,188,188,189,189,189,189,189,190,190,190,190,190,190,190,191,191,191,191,191,191,191,191,192,192,192,192,192,192,192,192,193,193,193,193,193,193,193,193,194,194,194,194,194,194,194,195,195,195,195], 'b':[69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,70,70,70,70,70,70,70,70,70,70,71,71,71,72,72,73,73,73,74,74,75,75,76,76,77,78,78,79,79,80,80,81,81,82,82,82,83,83,84,84,84,85,85,86,86,86,87,87,87,88,88,88,89,89,90,90,90,91,91,91,92,92,93,93,93,94,94,95,95,96,96,96,97,97,98,99,99,100,100,101,101,102,102,102,103,103,103,104,104,104,105,105,105,106,106,106,106,107,107,107,107,108,108,108,108,109,109,109,110,110,110,111,111,111,111,112,112,112,113,113,113,114,114,114,115,115,115,115,116,116,116,116,117,117,117,117,117,118,118,118,118,118,118,119,119,119,119,119,119,119,120,120,120,120,120,120,120,120,120,121,121,121,121,121,121,121,121,121,121,121,122,122,122,122,122,122,122,122,122,122,122,122,123,123,123,123,123,123,123,123,123,123,123,124,124,124,124,124,124]};
  this.processPlugin("rgba", [rgba]);
});


//Nashville
Caman.Filter.register("nashville", function() {
  var rgba = {'a':[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,255], 'r':[56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,57,57,58,58,59,59,60,61,62,63,64,65,66,67,68,69,71,72,73,75,76,78,79,81,82,84,85,87,88,90,91,93,95,96,98,100,102,104,106,108,110,113,115,117,120,122,124,127,129,131,133,136,138,140,142,144,146,148,150,152,154,155,157,159,160,162,164,165,167,168,170,171,173,174,175,177,178,179,181,182,183,185,186,187,189,190,191,192,194,195,196,197,198,200,201,202,203,204,205,206,208,209,209,210,211,212,213,214,215,216,217,217,218,219,220,220,221,222,223,223,224,225,226,226,227,228,228,229,230,230,231,231,232,233,233,234,234,235,235,236,237,237,238,238,239,239,240,240,240,241,241,242,242,243,243,243,244,244,245,245,245,246,246,246,247,247,247,248,248,248,248,249,249,249,249,250,250,250,250,251,251,251,251,251,252,252,252,252,252,253,253,253,253,253,254,254,254,254,254,254,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255], 'g':[38,39,39,40,41,41,42,42,43,44,44,45,46,46,47,48,49,50,51,52,53,55,56,57,59,60,61,63,64,65,67,68,69,71,72,73,74,76,77,78,80,81,82,84,85,86,87,89,90,91,93,94,95,97,98,99,101,102,103,104,106,107,108,110,111,112,114,115,116,118,119,121,122,123,125,126,128,129,130,132,133,134,136,137,138,140,141,142,143,145,146,147,148,149,150,151,152,153,154,155,156,157,158,158,159,160,161,162,163,163,164,165,166,166,167,168,169,169,170,171,172,172,173,174,175,176,176,177,178,179,180,181,181,182,183,184,185,186,187,187,188,189,189,190,191,191,192,193,193,194,194,195,195,196,197,197,198,198,199,199,200,200,201,201,202,202,202,203,203,204,204,205,205,205,206,206,207,207,207,208,208,208,209,209,209,210,210,210,211,211,211,212,212,212,213,213,213,213,214,214,214,214,215,215,215,215,216,216,216,216,216,217,217,217,217,217,218,218,218,218,218,218,219,219,219,219,219,220,220,220,220,220,220,220,221,221,221,221,221,221,221,221,221,221,221,221,221,221,221,221,221,221,221,221,221,221,221], 'b':[97,98,98,99,99,100,100,101,101,102,102,103,104,104,105,105,106,107,107,108,109,110,110,111,112,113,114,114,115,116,116,117,118,118,119,119,120,120,121,121,122,122,123,123,124,124,124,125,125,126,126,127,127,127,128,128,129,129,129,130,130,131,131,132,132,132,133,133,134,134,135,135,136,136,136,137,137,138,138,139,139,139,140,140,141,141,142,142,142,143,143,144,144,144,145,145,146,146,147,147,147,148,148,149,149,150,150,151,151,151,152,152,153,153,154,154,154,155,155,155,156,156,156,157,157,157,158,158,158,158,158,158,159,159,159,159,159,159,159,159,159,159,159,160,160,160,160,160,161,161,161,162,162,162,162,163,163,163,163,164,164,164,164,165,165,165,165,165,165,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,167,167,167,167,167,167,167,167,167,168,168,168,168,168,168,169,169,169,169,169,170,170,170,170,171,171,171,171,171,172,172,172,172,172,173,173,173,173,173,173,173,174,174,174,174,174,174,174,174,175,175,175,175,175,175,175,175,175,175,175,176,176,176,176,176,176,176,176,176,176]};
  this.processPlugin("rgba", [rgba]);
});


//X-PRO II
Caman.Filter.register("xpro", function() {
  var rgba = {'a':[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,255], 'r':[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,3,3,4,4,5,5,5,6,7,7,8,8,9,9,10,11,11,12,13,14,14,15,16,17,17,18,19,20,21,22,23,24,25,26,27,28,29,31,32,33,34,35,37,38,39,41,42,43,45,46,48,49,51,52,54,55,57,58,60,62,63,65,67,68,70,72,74,76,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,141,143,145,147,149,151,153,155,157,159,161,163,165,167,169,171,172,174,176,178,180,182,184,186,188,189,191,193,194,196,198,199,201,202,204,205,207,208,209,211,212,214,215,216,217,219,220,221,222,223,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,239,240,241,242,243,243,244,245,246,246,247,248,248,249,249,250,250,251,251,252,252,252,253,253,253,253,253,253,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,255,255,255,255,255,255,255,255], 'g':[0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,4,4,4,5,5,5,6,6,7,7,8,8,9,10,10,11,12,12,13,14,14,15,16,17,18,18,19,20,21,22,23,24,25,26,27,28,29,30,31,33,34,35,36,37,39,40,41,43,44,45,47,48,50,51,53,54,56,57,59,61,62,64,66,67,69,71,73,75,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,161,163,165,167,169,171,173,175,176,178,180,182,183,185,187,189,190,192,193,195,197,198,200,201,203,204,206,207,209,210,211,213,214,216,217,218,219,221,222,223,224,226,227,228,229,230,231,232,233,234,235,236,237,237,238,239,240,240,241,242,243,243,244,244,245,246,246,247,247,248,248,249,249,250,250,250,251,251,252,252,252,253,253,253,253,253,253,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,255,255,255,255,255,255,255,255,255,255], 'b':[24,25,26,27,28,28,29,30,31,32,33,34,35,35,36,37,38,39,40,41,41,42,43,44,45,45,46,47,48,49,49,50,51,52,53,53,54,55,56,56,57,58,59,59,60,61,62,62,63,64,64,65,66,67,67,68,69,70,70,71,72,73,73,74,75,76,77,77,78,79,80,81,81,82,83,84,85,86,86,87,88,89,90,91,91,92,93,94,95,96,96,97,98,99,100,101,101,102,103,104,105,106,107,107,108,109,110,111,112,113,114,114,115,116,117,118,119,119,120,121,122,123,124,124,125,126,127,127,128,129,129,130,130,131,131,132,132,133,134,134,135,136,137,138,138,139,140,141,142,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,162,163,164,165,165,166,167,168,168,169,170,171,171,172,173,173,174,175,176,176,177,178,178,179,180,181,182,182,183,184,185,185,186,187,188,189,189,190,191,192,193,193,194,195,196,197,197,198,199,200,200,201,202,203,204,204,205,206,206,207,208,208,209,210,210,211,212,212,213,214,215,215,216,217,218,218,219,220,221,221,222,223,224,225,226,226,227,228,229]};
  this.processPlugin("rgba", [rgba]);
});
/**
 * @license AngularJS v1.4.3
 * (c) 2010-2015 Google, Inc. http://angularjs.org
 * License: MIT
 */
(function(window, angular, undefined) {'use strict';

var $resourceMinErr = angular.$$minErr('$resource');

// Helper functions and regex to lookup a dotted path on an object
// stopping at undefined/null.  The path must be composed of ASCII
// identifiers (just like $parse)
var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;

function isValidDottedPath(path) {
  return (path != null && path !== '' && path !== 'hasOwnProperty' &&
      MEMBER_NAME_REGEX.test('.' + path));
}

function lookupDottedPath(obj, path) {
  if (!isValidDottedPath(path)) {
    throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path);
  }
  var keys = path.split('.');
  for (var i = 0, ii = keys.length; i < ii && obj !== undefined; i++) {
    var key = keys[i];
    obj = (obj !== null) ? obj[key] : undefined;
  }
  return obj;
}

/**
 * Create a shallow copy of an object and clear other fields from the destination
 */
function shallowClearAndCopy(src, dst) {
  dst = dst || {};

  angular.forEach(dst, function(value, key) {
    delete dst[key];
  });

  for (var key in src) {
    if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
      dst[key] = src[key];
    }
  }

  return dst;
}

/**
 * @ngdoc module
 * @name ngResource
 * @description
 *
 * # ngResource
 *
 * The `ngResource` module provides interaction support with RESTful services
 * via the $resource service.
 *
 *
 * <div doc-module-components="ngResource"></div>
 *
 * See {@link ngResource.$resource `$resource`} for usage.
 */

/**
 * @ngdoc service
 * @name $resource
 * @requires $http
 *
 * @description
 * A factory which creates a resource object that lets you interact with
 * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
 *
 * The returned resource object has action methods which provide high-level behaviors without
 * the need to interact with the low level {@link ng.$http $http} service.
 *
 * Requires the {@link ngResource `ngResource`} module to be installed.
 *
 * By default, trailing slashes will be stripped from the calculated URLs,
 * which can pose problems with server backends that do not expect that
 * behavior.  This can be disabled by configuring the `$resourceProvider` like
 * this:
 *
 * ```js
     app.config(['$resourceProvider', function($resourceProvider) {
       // Don't strip trailing slashes from calculated URLs
       $resourceProvider.defaults.stripTrailingSlashes = false;
     }]);
 * ```
 *
 * @param {string} url A parameterized URL template with parameters prefixed by `:` as in
 *   `/user/:username`. If you are using a URL with a port number (e.g.
 *   `http://example.com:8080/api`), it will be respected.
 *
 *   If you are using a url with a suffix, just add the suffix, like this:
 *   `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')`
 *   or even `$resource('http://example.com/resource/:resource_id.:format')`
 *   If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be
 *   collapsed down to a single `.`.  If you need this sequence to appear and not collapse then you
 *   can escape it with `/\.`.
 *
 * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
 *   `actions` methods. If any of the parameter value is a function, it will be executed every time
 *   when a param value needs to be obtained for a request (unless the param was overridden).
 *
 *   Each key value in the parameter object is first bound to url template if present and then any
 *   excess keys are appended to the url search query after the `?`.
 *
 *   Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
 *   URL `/path/greet?salutation=Hello`.
 *
 *   If the parameter value is prefixed with `@` then the value for that parameter will be extracted
 *   from the corresponding property on the `data` object (provided when calling an action method).  For
 *   example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of `someParam`
 *   will be `data.someProp`.
 *
 * @param {Object.<Object>=} actions Hash with declaration of custom actions that should extend
 *   the default set of resource actions. The declaration should be created in the format of {@link
 *   ng.$http#usage $http.config}:
 *
 *       {action1: {method:?, params:?, isArray:?, headers:?, ...},
 *        action2: {method:?, params:?, isArray:?, headers:?, ...},
 *        ...}
 *
 *   Where:
 *
 *   - **`action`** – {string} – The name of action. This name becomes the name of the method on
 *     your resource object.
 *   - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`,
 *     `DELETE`, `JSONP`, etc).
 *   - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of
 *     the parameter value is a function, it will be executed every time when a param value needs to
 *     be obtained for a request (unless the param was overridden).
 *   - **`url`** – {string} – action specific `url` override. The url templating is supported just
 *     like for the resource-level urls.
 *   - **`isArray`** – {boolean=} – If true then the returned object for this action is an array,
 *     see `returns` section.
 *   - **`transformRequest`** –
 *     `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
 *     transform function or an array of such functions. The transform function takes the http
 *     request body and headers and returns its transformed (typically serialized) version.
 *     By default, transformRequest will contain one function that checks if the request data is
 *     an object and serializes to using `angular.toJson`. To prevent this behavior, set
 *     `transformRequest` to an empty array: `transformRequest: []`
 *   - **`transformResponse`** –
 *     `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
 *     transform function or an array of such functions. The transform function takes the http
 *     response body and headers and returns its transformed (typically deserialized) version.
 *     By default, transformResponse will contain one function that checks if the response looks like
 *     a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior, set
 *     `transformResponse` to an empty array: `transformResponse: []`
 *   - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
 *     GET request, otherwise if a cache instance built with
 *     {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
 *     caching.
 *   - **`timeout`** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} that
 *     should abort the request when resolved.
 *   - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the
 *     XHR object. See
 *     [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5)
 *     for more information.
 *   - **`responseType`** - `{string}` - see
 *     [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
 *   - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -
 *     `response` and `responseError`. Both `response` and `responseError` interceptors get called
 *     with `http response` object. See {@link ng.$http $http interceptors}.
 *
 * @param {Object} options Hash with custom settings that should extend the
 *   default `$resourceProvider` behavior.  The only supported option is
 *
 *   Where:
 *
 *   - **`stripTrailingSlashes`** – {boolean} – If true then the trailing
 *   slashes from any calculated URL will be stripped. (Defaults to true.)
 *
 * @returns {Object} A resource "class" object with methods for the default set of resource actions
 *   optionally extended with custom `actions`. The default set contains these actions:
 *   ```js
 *   { 'get':    {method:'GET'},
 *     'save':   {method:'POST'},
 *     'query':  {method:'GET', isArray:true},
 *     'remove': {method:'DELETE'},
 *     'delete': {method:'DELETE'} };
 *   ```
 *
 *   Calling these methods invoke an {@link ng.$http} with the specified http method,
 *   destination and parameters. When the data is returned from the server then the object is an
 *   instance of the resource class. The actions `save`, `remove` and `delete` are available on it
 *   as  methods with the `$` prefix. This allows you to easily perform CRUD operations (create,
 *   read, update, delete) on server-side data like this:
 *   ```js
 *   var User = $resource('/user/:userId', {userId:'@id'});
 *   var user = User.get({userId:123}, function() {
 *     user.abc = true;
 *     user.$save();
 *   });
 *   ```
 *
 *   It is important to realize that invoking a $resource object method immediately returns an
 *   empty reference (object or array depending on `isArray`). Once the data is returned from the
 *   server the existing reference is populated with the actual data. This is a useful trick since
 *   usually the resource is assigned to a model which is then rendered by the view. Having an empty
 *   object results in no rendering, once the data arrives from the server then the object is
 *   populated with the data and the view automatically re-renders itself showing the new data. This
 *   means that in most cases one never has to write a callback function for the action methods.
 *
 *   The action methods on the class object or instance object can be invoked with the following
 *   parameters:
 *
 *   - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
 *   - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
 *   - non-GET instance actions:  `instance.$action([parameters], [success], [error])`
 *
 *
 *   Success callback is called with (value, responseHeaders) arguments, where the value is
 *   the populated resource instance or collection object. The error callback is called
 *   with (httpResponse) argument.
 *
 *   Class actions return empty instance (with additional properties below).
 *   Instance actions return promise of the action.
 *
 *   The Resource instances and collection have these additional properties:
 *
 *   - `$promise`: the {@link ng.$q promise} of the original server interaction that created this
 *     instance or collection.
 *
 *     On success, the promise is resolved with the same resource instance or collection object,
 *     updated with data from server. This makes it easy to use in
 *     {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view
 *     rendering until the resource(s) are loaded.
 *
 *     On failure, the promise is resolved with the {@link ng.$http http response} object, without
 *     the `resource` property.
 *
 *     If an interceptor object was provided, the promise will instead be resolved with the value
 *     returned by the interceptor.
 *
 *   - `$resolved`: `true` after first server interaction is completed (either with success or
 *      rejection), `false` before that. Knowing if the Resource has been resolved is useful in
 *      data-binding.
 *
 * @example
 *
 * # Credit card resource
 *
 * ```js
     // Define CreditCard class
     var CreditCard = $resource('/user/:userId/card/:cardId',
      {userId:123, cardId:'@id'}, {
       charge: {method:'POST', params:{charge:true}}
      });

     // We can retrieve a collection from the server
     var cards = CreditCard.query(function() {
       // GET: /user/123/card
       // server returns: [ {id:456, number:'1234', name:'Smith'} ];

       var card = cards[0];
       // each item is an instance of CreditCard
       expect(card instanceof CreditCard).toEqual(true);
       card.name = "J. Smith";
       // non GET methods are mapped onto the instances
       card.$save();
       // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
       // server returns: {id:456, number:'1234', name: 'J. Smith'};

       // our custom method is mapped as well.
       card.$charge({amount:9.99});
       // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
     });

     // we can create an instance as well
     var newCard = new CreditCard({number:'0123'});
     newCard.name = "Mike Smith";
     newCard.$save();
     // POST: /user/123/card {number:'0123', name:'Mike Smith'}
     // server returns: {id:789, number:'0123', name: 'Mike Smith'};
     expect(newCard.id).toEqual(789);
 * ```
 *
 * The object returned from this function execution is a resource "class" which has "static" method
 * for each action in the definition.
 *
 * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and
 * `headers`.
 * When the data is returned from the server then the object is an instance of the resource type and
 * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
 * operations (create, read, update, delete) on server-side data.

   ```js
     var User = $resource('/user/:userId', {userId:'@id'});
     User.get({userId:123}, function(user) {
       user.abc = true;
       user.$save();
     });
   ```
 *
 * It's worth noting that the success callback for `get`, `query` and other methods gets passed
 * in the response that came from the server as well as $http header getter function, so one
 * could rewrite the above example and get access to http headers as:
 *
   ```js
     var User = $resource('/user/:userId', {userId:'@id'});
     User.get({userId:123}, function(u, getResponseHeaders){
       u.abc = true;
       u.$save(function(u, putResponseHeaders) {
         //u => saved user object
         //putResponseHeaders => $http header getter
       });
     });
   ```
 *
 * You can also access the raw `$http` promise via the `$promise` property on the object returned
 *
   ```
     var User = $resource('/user/:userId', {userId:'@id'});
     User.get({userId:123})
         .$promise.then(function(user) {
           $scope.user = user;
         });
   ```

 * # Creating a custom 'PUT' request
 * In this example we create a custom method on our resource to make a PUT request
 * ```js
 *    var app = angular.module('app', ['ngResource', 'ngRoute']);
 *
 *    // Some APIs expect a PUT request in the format URL/object/ID
 *    // Here we are creating an 'update' method
 *    app.factory('Notes', ['$resource', function($resource) {
 *    return $resource('/notes/:id', null,
 *        {
 *            'update': { method:'PUT' }
 *        });
 *    }]);
 *
 *    // In our controller we get the ID from the URL using ngRoute and $routeParams
 *    // We pass in $routeParams and our Notes factory along with $scope
 *    app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
                                      function($scope, $routeParams, Notes) {
 *    // First get a note object from the factory
 *    var note = Notes.get({ id:$routeParams.id });
 *    $id = note.id;
 *
 *    // Now call update passing in the ID first then the object you are updating
 *    Notes.update({ id:$id }, note);
 *
 *    // This will PUT /notes/ID with the note object in the request payload
 *    }]);
 * ```
 */
angular.module('ngResource', ['ng']).
  provider('$resource', function() {
    var provider = this;

    this.defaults = {
      // Strip slashes by default
      stripTrailingSlashes: true,

      // Default actions configuration
      actions: {
        'get': {method: 'GET'},
        'save': {method: 'POST'},
        'query': {method: 'GET', isArray: true},
        'remove': {method: 'DELETE'},
        'delete': {method: 'DELETE'}
      }
    };

    this.$get = ['$http', '$q', function($http, $q) {

      var noop = angular.noop,
        forEach = angular.forEach,
        extend = angular.extend,
        copy = angular.copy,
        isFunction = angular.isFunction;

      /**
       * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
       * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set
       * (pchar) allowed in path segments:
       *    segment       = *pchar
       *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
       *    pct-encoded   = "%" HEXDIG HEXDIG
       *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
       *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
       *                     / "*" / "+" / "," / ";" / "="
       */
      function encodeUriSegment(val) {
        return encodeUriQuery(val, true).
          replace(/%26/gi, '&').
          replace(/%3D/gi, '=').
          replace(/%2B/gi, '+');
      }


      /**
       * This method is intended for encoding *key* or *value* parts of query component. We need a
       * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't
       * have to be encoded per http://tools.ietf.org/html/rfc3986:
       *    query       = *( pchar / "/" / "?" )
       *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
       *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
       *    pct-encoded   = "%" HEXDIG HEXDIG
       *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
       *                     / "*" / "+" / "," / ";" / "="
       */
      function encodeUriQuery(val, pctEncodeSpaces) {
        return encodeURIComponent(val).
          replace(/%40/gi, '@').
          replace(/%3A/gi, ':').
          replace(/%24/g, '$').
          replace(/%2C/gi, ',').
          replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
      }

      function Route(template, defaults) {
        this.template = template;
        this.defaults = extend({}, provider.defaults, defaults);
        this.urlParams = {};
      }

      Route.prototype = {
        setUrlParams: function(config, params, actionUrl) {
          var self = this,
            url = actionUrl || self.template,
            val,
            encodedVal;

          var urlParams = self.urlParams = {};
          forEach(url.split(/\W/), function(param) {
            if (param === 'hasOwnProperty') {
              throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name.");
            }
            if (!(new RegExp("^\\d+$").test(param)) && param &&
              (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) {
              urlParams[param] = true;
            }
          });
          url = url.replace(/\\:/g, ':');

          params = params || {};
          forEach(self.urlParams, function(_, urlParam) {
            val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
            if (angular.isDefined(val) && val !== null) {
              encodedVal = encodeUriSegment(val);
              url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) {
                return encodedVal + p1;
              });
            } else {
              url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match,
                  leadingSlashes, tail) {
                if (tail.charAt(0) == '/') {
                  return tail;
                } else {
                  return leadingSlashes + tail;
                }
              });
            }
          });

          // strip trailing slashes and set the url (unless this behavior is specifically disabled)
          if (self.defaults.stripTrailingSlashes) {
            url = url.replace(/\/+$/, '') || '/';
          }

          // then replace collapse `/.` if found in the last URL path segment before the query
          // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`
          url = url.replace(/\/\.(?=\w+($|\?))/, '.');
          // replace escaped `/\.` with `/.`
          config.url = url.replace(/\/\\\./, '/.');


          // set params - delegate param encoding to $http
          forEach(params, function(value, key) {
            if (!self.urlParams[key]) {
              config.params = config.params || {};
              config.params[key] = value;
            }
          });
        }
      };


      function resourceFactory(url, paramDefaults, actions, options) {
        var route = new Route(url, options);

        actions = extend({}, provider.defaults.actions, actions);

        function extractParams(data, actionParams) {
          var ids = {};
          actionParams = extend({}, paramDefaults, actionParams);
          forEach(actionParams, function(value, key) {
            if (isFunction(value)) { value = value(); }
            ids[key] = value && value.charAt && value.charAt(0) == '@' ?
              lookupDottedPath(data, value.substr(1)) : value;
          });
          return ids;
        }

        function defaultResponseInterceptor(response) {
          return response.resource;
        }

        function Resource(value) {
          shallowClearAndCopy(value || {}, this);
        }

        Resource.prototype.toJSON = function() {
          var data = extend({}, this);
          delete data.$promise;
          delete data.$resolved;
          return data;
        };

        forEach(actions, function(action, name) {
          var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);

          Resource[name] = function(a1, a2, a3, a4) {
            var params = {}, data, success, error;

            /* jshint -W086 */ /* (purposefully fall through case statements) */
            switch (arguments.length) {
              case 4:
                error = a4;
                success = a3;
              //fallthrough
              case 3:
              case 2:
                if (isFunction(a2)) {
                  if (isFunction(a1)) {
                    success = a1;
                    error = a2;
                    break;
                  }

                  success = a2;
                  error = a3;
                  //fallthrough
                } else {
                  params = a1;
                  data = a2;
                  success = a3;
                  break;
                }
              case 1:
                if (isFunction(a1)) success = a1;
                else if (hasBody) data = a1;
                else params = a1;
                break;
              case 0: break;
              default:
                throw $resourceMinErr('badargs',
                  "Expected up to 4 arguments [params, data, success, error], got {0} arguments",
                  arguments.length);
            }
            /* jshint +W086 */ /* (purposefully fall through case statements) */

            var isInstanceCall = this instanceof Resource;
            var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));
            var httpConfig = {};
            var responseInterceptor = action.interceptor && action.interceptor.response ||
              defaultResponseInterceptor;
            var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||
              undefined;

            forEach(action, function(value, key) {
              if (key != 'params' && key != 'isArray' && key != 'interceptor') {
                httpConfig[key] = copy(value);
              }
            });

            if (hasBody) httpConfig.data = data;
            route.setUrlParams(httpConfig,
              extend({}, extractParams(data, action.params || {}), params),
              action.url);

            var promise = $http(httpConfig).then(function(response) {
              var data = response.data,
                promise = value.$promise;

              if (data) {
                // Need to convert action.isArray to boolean in case it is undefined
                // jshint -W018
                if (angular.isArray(data) !== (!!action.isArray)) {
                  throw $resourceMinErr('badcfg',
                      'Error in resource configuration for action `{0}`. Expected response to ' +
                      'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object',
                    angular.isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url);
                }
                // jshint +W018
                if (action.isArray) {
                  value.length = 0;
                  forEach(data, function(item) {
                    if (typeof item === "object") {
                      value.push(new Resource(item));
                    } else {
                      // Valid JSON values may be string literals, and these should not be converted
                      // into objects. These items will not have access to the Resource prototype
                      // methods, but unfortunately there
                      value.push(item);
                    }
                  });
                } else {
                  shallowClearAndCopy(data, value);
                  value.$promise = promise;
                }
              }

              value.$resolved = true;

              response.resource = value;

              return response;
            }, function(response) {
              value.$resolved = true;

              (error || noop)(response);

              return $q.reject(response);
            });

            promise = promise.then(
              function(response) {
                var value = responseInterceptor(response);
                (success || noop)(value, response.headers);
                return value;
              },
              responseErrorInterceptor);

            if (!isInstanceCall) {
              // we are creating instance / collection
              // - set the initial promise
              // - return the instance / collection
              value.$promise = promise;
              value.$resolved = false;

              return value;
            }

            // instance call
            return promise;
          };


          Resource.prototype['$' + name] = function(params, success, error) {
            if (isFunction(params)) {
              error = success; success = params; params = {};
            }
            var result = Resource[name].call(this, params, this, success, error);
            return result.$promise || result;
          };
        });

        Resource.bind = function(additionalParamDefaults) {
          return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
        };

        return Resource;
      }

      return resourceFactory;
    }];
  });


})(window, window.angular);
/**
 * @license AngularJS v1.4.3
 * (c) 2010-2015 Google, Inc. http://angularjs.org
 * License: MIT
 */
(function(window, angular, undefined) {'use strict';

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *     Any commits to this file should be reviewed with security in mind.  *
 *   Changes to this file can potentially create security vulnerabilities. *
 *          An approval from 2 Core members with history of modifying      *
 *                         this file is required.                          *
 *                                                                         *
 *  Does the change somehow allow for arbitrary javascript to be executed? *
 *    Or allows for someone to change the prototype of built-in objects?   *
 *     Or gives undesired access to variables likes document or window?    *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

var $sanitizeMinErr = angular.$$minErr('$sanitize');

/**
 * @ngdoc module
 * @name ngSanitize
 * @description
 *
 * # ngSanitize
 *
 * The `ngSanitize` module provides functionality to sanitize HTML.
 *
 *
 * <div doc-module-components="ngSanitize"></div>
 *
 * See {@link ngSanitize.$sanitize `$sanitize`} for usage.
 */

/*
 * HTML Parser By Misko Hevery (misko@hevery.com)
 * based on:  HTML Parser By John Resig (ejohn.org)
 * Original code by Erik Arvidsson, Mozilla Public License
 * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
 *
 * // Use like so:
 * htmlParser(htmlString, {
 *     start: function(tag, attrs, unary) {},
 *     end: function(tag) {},
 *     chars: function(text) {},
 *     comment: function(text) {}
 * });
 *
 */


/**
 * @ngdoc service
 * @name $sanitize
 * @kind function
 *
 * @description
 *   The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are
 *   then serialized back to properly escaped html string. This means that no unsafe input can make
 *   it into the returned string, however, since our parser is more strict than a typical browser
 *   parser, it's possible that some obscure input, which would be recognized as valid HTML by a
 *   browser, won't make it through the sanitizer. The input may also contain SVG markup.
 *   The whitelist is configured using the functions `aHrefSanitizationWhitelist` and
 *   `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}.
 *
 * @param {string} html HTML input.
 * @returns {string} Sanitized HTML.
 *
 * @example
   <example module="sanitizeExample" deps="angular-sanitize.js">
   <file name="index.html">
     <script>
         angular.module('sanitizeExample', ['ngSanitize'])
           .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
             $scope.snippet =
               '<p style="color:blue">an html\n' +
               '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
               'snippet</p>';
             $scope.deliberatelyTrustDangerousSnippet = function() {
               return $sce.trustAsHtml($scope.snippet);
             };
           }]);
     </script>
     <div ng-controller="ExampleController">
        Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
       <table>
         <tr>
           <td>Directive</td>
           <td>How</td>
           <td>Source</td>
           <td>Rendered</td>
         </tr>
         <tr id="bind-html-with-sanitize">
           <td>ng-bind-html</td>
           <td>Automatically uses $sanitize</td>
           <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
           <td><div ng-bind-html="snippet"></div></td>
         </tr>
         <tr id="bind-html-with-trust">
           <td>ng-bind-html</td>
           <td>Bypass $sanitize by explicitly trusting the dangerous value</td>
           <td>
           <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt;
&lt;/div&gt;</pre>
           </td>
           <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
         </tr>
         <tr id="bind-default">
           <td>ng-bind</td>
           <td>Automatically escapes</td>
           <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
           <td><div ng-bind="snippet"></div></td>
         </tr>
       </table>
       </div>
   </file>
   <file name="protractor.js" type="protractor">
     it('should sanitize the html snippet by default', function() {
       expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
         toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
     });

     it('should inline raw snippet if bound to a trusted value', function() {
       expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
         toBe("<p style=\"color:blue\">an html\n" +
              "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
              "snippet</p>");
     });

     it('should escape snippet without any filter', function() {
       expect(element(by.css('#bind-default div')).getInnerHtml()).
         toBe("&lt;p style=\"color:blue\"&gt;an html\n" +
              "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" +
              "snippet&lt;/p&gt;");
     });

     it('should update', function() {
       element(by.model('snippet')).clear();
       element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
       expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
         toBe('new <b>text</b>');
       expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
         'new <b onclick="alert(1)">text</b>');
       expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
         "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;");
     });
   </file>
   </example>
 */
function $SanitizeProvider() {
  this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
    return function(html) {
      var buf = [];
      htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
        return !/^unsafe/.test($$sanitizeUri(uri, isImage));
      }));
      return buf.join('');
    };
  }];
}

function sanitizeText(chars) {
  var buf = [];
  var writer = htmlSanitizeWriter(buf, angular.noop);
  writer.chars(chars);
  return buf.join('');
}


// Regular Expressions for parsing tags and attributes
var START_TAG_REGEXP =
       /^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/,
  END_TAG_REGEXP = /^<\/\s*([\w:-]+)[^>]*>/,
  ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,
  BEGIN_TAG_REGEXP = /^</,
  BEGING_END_TAGE_REGEXP = /^<\//,
  COMMENT_REGEXP = /<!--(.*?)-->/g,
  DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i,
  CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g,
  SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
  // Match everything outside of normal chars and " (quote character)
  NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;


// Good source of info about elements and attributes
// http://dev.w3.org/html5/spec/Overview.html#semantics
// http://simon.html5.org/html-elements

// Safe Void Elements - HTML5
// http://dev.w3.org/html5/spec/Overview.html#void-elements
var voidElements = makeMap("area,br,col,hr,img,wbr");

// Elements that you can, intentionally, leave open (and which close themselves)
// http://dev.w3.org/html5/spec/Overview.html#optional-tags
var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
    optionalEndTagInlineElements = makeMap("rp,rt"),
    optionalEndTagElements = angular.extend({},
                                            optionalEndTagInlineElements,
                                            optionalEndTagBlockElements);

// Safe Block Elements - HTML5
var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," +
        "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," +
        "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul"));

// Inline Elements - HTML5
var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," +
        "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," +
        "samp,small,span,strike,strong,sub,sup,time,tt,u,var"));

// SVG Elements
// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
// Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted.
// They can potentially allow for arbitrary javascript to be executed. See #11290
var svgElements = makeMap("circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph," +
        "hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline," +
        "radialGradient,rect,stop,svg,switch,text,title,tspan,use");

// Special Elements (can contain anything)
var specialElements = makeMap("script,style");

var validElements = angular.extend({},
                                   voidElements,
                                   blockElements,
                                   inlineElements,
                                   optionalEndTagElements,
                                   svgElements);

//Attributes that have href and hence need to be sanitized
var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap,xlink:href");

var htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
    'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +
    'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +
    'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' +
    'valign,value,vspace,width');

// SVG attributes (without "id" and "name" attributes)
// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
var svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
    'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' +
    'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' +
    'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' +
    'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' +
    'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' +
    'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' +
    'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' +
    'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' +
    'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' +
    'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' +
    'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' +
    'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' +
    'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' +
    'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true);

var validAttrs = angular.extend({},
                                uriAttrs,
                                svgAttrs,
                                htmlAttrs);

function makeMap(str, lowercaseKeys) {
  var obj = {}, items = str.split(','), i;
  for (i = 0; i < items.length; i++) {
    obj[lowercaseKeys ? angular.lowercase(items[i]) : items[i]] = true;
  }
  return obj;
}


/**
 * @example
 * htmlParser(htmlString, {
 *     start: function(tag, attrs, unary) {},
 *     end: function(tag) {},
 *     chars: function(text) {},
 *     comment: function(text) {}
 * });
 *
 * @param {string} html string
 * @param {object} handler
 */
function htmlParser(html, handler) {
  if (typeof html !== 'string') {
    if (html === null || typeof html === 'undefined') {
      html = '';
    } else {
      html = '' + html;
    }
  }
  var index, chars, match, stack = [], last = html, text;
  stack.last = function() { return stack[stack.length - 1]; };

  while (html) {
    text = '';
    chars = true;

    // Make sure we're not in a script or style element
    if (!stack.last() || !specialElements[stack.last()]) {

      // Comment
      if (html.indexOf("<!--") === 0) {
        // comments containing -- are not allowed unless they terminate the comment
        index = html.indexOf("--", 4);

        if (index >= 0 && html.lastIndexOf("-->", index) === index) {
          if (handler.comment) handler.comment(html.substring(4, index));
          html = html.substring(index + 3);
          chars = false;
        }
      // DOCTYPE
      } else if (DOCTYPE_REGEXP.test(html)) {
        match = html.match(DOCTYPE_REGEXP);

        if (match) {
          html = html.replace(match[0], '');
          chars = false;
        }
      // end tag
      } else if (BEGING_END_TAGE_REGEXP.test(html)) {
        match = html.match(END_TAG_REGEXP);

        if (match) {
          html = html.substring(match[0].length);
          match[0].replace(END_TAG_REGEXP, parseEndTag);
          chars = false;
        }

      // start tag
      } else if (BEGIN_TAG_REGEXP.test(html)) {
        match = html.match(START_TAG_REGEXP);

        if (match) {
          // We only have a valid start-tag if there is a '>'.
          if (match[4]) {
            html = html.substring(match[0].length);
            match[0].replace(START_TAG_REGEXP, parseStartTag);
          }
          chars = false;
        } else {
          // no ending tag found --- this piece should be encoded as an entity.
          text += '<';
          html = html.substring(1);
        }
      }

      if (chars) {
        index = html.indexOf("<");

        text += index < 0 ? html : html.substring(0, index);
        html = index < 0 ? "" : html.substring(index);

        if (handler.chars) handler.chars(decodeEntities(text));
      }

    } else {
      // IE versions 9 and 10 do not understand the regex '[^]', so using a workaround with [\W\w].
      html = html.replace(new RegExp("([\\W\\w]*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'),
        function(all, text) {
          text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1");

          if (handler.chars) handler.chars(decodeEntities(text));

          return "";
      });

      parseEndTag("", stack.last());
    }

    if (html == last) {
      throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " +
                                        "of html: {0}", html);
    }
    last = html;
  }

  // Clean up any remaining tags
  parseEndTag();

  function parseStartTag(tag, tagName, rest, unary) {
    tagName = angular.lowercase(tagName);
    if (blockElements[tagName]) {
      while (stack.last() && inlineElements[stack.last()]) {
        parseEndTag("", stack.last());
      }
    }

    if (optionalEndTagElements[tagName] && stack.last() == tagName) {
      parseEndTag("", tagName);
    }

    unary = voidElements[tagName] || !!unary;

    if (!unary) {
      stack.push(tagName);
    }

    var attrs = {};

    rest.replace(ATTR_REGEXP,
      function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {
        var value = doubleQuotedValue
          || singleQuotedValue
          || unquotedValue
          || '';

        attrs[name] = decodeEntities(value);
    });
    if (handler.start) handler.start(tagName, attrs, unary);
  }

  function parseEndTag(tag, tagName) {
    var pos = 0, i;
    tagName = angular.lowercase(tagName);
    if (tagName) {
      // Find the closest opened tag of the same type
      for (pos = stack.length - 1; pos >= 0; pos--) {
        if (stack[pos] == tagName) break;
      }
    }

    if (pos >= 0) {
      // Close all the open elements, up the stack
      for (i = stack.length - 1; i >= pos; i--)
        if (handler.end) handler.end(stack[i]);

      // Remove the open elements from the stack
      stack.length = pos;
    }
  }
}

var hiddenPre=document.createElement("pre");
/**
 * decodes all entities into regular string
 * @param value
 * @returns {string} A string with decoded entities.
 */
function decodeEntities(value) {
  if (!value) { return ''; }

  hiddenPre.innerHTML = value.replace(/</g,"&lt;");
  // innerText depends on styling as it doesn't display hidden elements.
  // Therefore, it's better to use textContent not to cause unnecessary reflows.
  return hiddenPre.textContent;
}

/**
 * Escapes all potentially dangerous characters, so that the
 * resulting string can be safely inserted into attribute or
 * element text.
 * @param value
 * @returns {string} escaped text
 */
function encodeEntities(value) {
  return value.
    replace(/&/g, '&amp;').
    replace(SURROGATE_PAIR_REGEXP, function(value) {
      var hi = value.charCodeAt(0);
      var low = value.charCodeAt(1);
      return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
    }).
    replace(NON_ALPHANUMERIC_REGEXP, function(value) {
      return '&#' + value.charCodeAt(0) + ';';
    }).
    replace(/</g, '&lt;').
    replace(/>/g, '&gt;');
}

/**
 * create an HTML/XML writer which writes to buffer
 * @param {Array} buf use buf.jain('') to get out sanitized html string
 * @returns {object} in the form of {
 *     start: function(tag, attrs, unary) {},
 *     end: function(tag) {},
 *     chars: function(text) {},
 *     comment: function(text) {}
 * }
 */
function htmlSanitizeWriter(buf, uriValidator) {
  var ignore = false;
  var out = angular.bind(buf, buf.push);
  return {
    start: function(tag, attrs, unary) {
      tag = angular.lowercase(tag);
      if (!ignore && specialElements[tag]) {
        ignore = tag;
      }
      if (!ignore && validElements[tag] === true) {
        out('<');
        out(tag);
        angular.forEach(attrs, function(value, key) {
          var lkey=angular.lowercase(key);
          var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');
          if (validAttrs[lkey] === true &&
            (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
            out(' ');
            out(key);
            out('="');
            out(encodeEntities(value));
            out('"');
          }
        });
        out(unary ? '/>' : '>');
      }
    },
    end: function(tag) {
        tag = angular.lowercase(tag);
        if (!ignore && validElements[tag] === true) {
          out('</');
          out(tag);
          out('>');
        }
        if (tag == ignore) {
          ignore = false;
        }
      },
    chars: function(chars) {
        if (!ignore) {
          out(encodeEntities(chars));
        }
      }
  };
}


// define ngSanitize module and register $sanitize service
angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);

/* global sanitizeText: false */

/**
 * @ngdoc filter
 * @name linky
 * @kind function
 *
 * @description
 * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
 * plain email address links.
 *
 * Requires the {@link ngSanitize `ngSanitize`} module to be installed.
 *
 * @param {string} text Input text.
 * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.
 * @returns {string} Html-linkified text.
 *
 * @usage
   <span ng-bind-html="linky_expression | linky"></span>
 *
 * @example
   <example module="linkyExample" deps="angular-sanitize.js">
     <file name="index.html">
       <script>
         angular.module('linkyExample', ['ngSanitize'])
           .controller('ExampleController', ['$scope', function($scope) {
             $scope.snippet =
               'Pretty text with some links:\n'+
               'http://angularjs.org/,\n'+
               'mailto:us@somewhere.org,\n'+
               'another@somewhere.org,\n'+
               'and one more: ftp://127.0.0.1/.';
             $scope.snippetWithTarget = 'http://angularjs.org/';
           }]);
       </script>
       <div ng-controller="ExampleController">
       Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
       <table>
         <tr>
           <td>Filter</td>
           <td>Source</td>
           <td>Rendered</td>
         </tr>
         <tr id="linky-filter">
           <td>linky filter</td>
           <td>
             <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre>
           </td>
           <td>
             <div ng-bind-html="snippet | linky"></div>
           </td>
         </tr>
         <tr id="linky-target">
          <td>linky target</td>
          <td>
            <pre>&lt;div ng-bind-html="snippetWithTarget | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre>
          </td>
          <td>
            <div ng-bind-html="snippetWithTarget | linky:'_blank'"></div>
          </td>
         </tr>
         <tr id="escaped-html">
           <td>no filter</td>
           <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td>
           <td><div ng-bind="snippet"></div></td>
         </tr>
       </table>
     </file>
     <file name="protractor.js" type="protractor">
       it('should linkify the snippet with urls', function() {
         expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
             toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
                  'another@somewhere.org, and one more: ftp://127.0.0.1/.');
         expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
       });

       it('should not linkify snippet without the linky filter', function() {
         expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
             toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
                  'another@somewhere.org, and one more: ftp://127.0.0.1/.');
         expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
       });

       it('should update', function() {
         element(by.model('snippet')).clear();
         element(by.model('snippet')).sendKeys('new http://link.');
         expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
             toBe('new http://link.');
         expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
         expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
             .toBe('new http://link.');
       });

       it('should work with the target property', function() {
        expect(element(by.id('linky-target')).
            element(by.binding("snippetWithTarget | linky:'_blank'")).getText()).
            toBe('http://angularjs.org/');
        expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
       });
     </file>
   </example>
 */
angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
  var LINKY_URL_REGEXP =
        /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"”’]/i,
      MAILTO_REGEXP = /^mailto:/i;

  return function(text, target) {
    if (!text) return text;
    var match;
    var raw = text;
    var html = [];
    var url;
    var i;
    while ((match = raw.match(LINKY_URL_REGEXP))) {
      // We can not end in these as they are sometimes found at the end of the sentence
      url = match[0];
      // if we did not match ftp/http/www/mailto then assume mailto
      if (!match[2] && !match[4]) {
        url = (match[3] ? 'http://' : 'mailto:') + url;
      }
      i = match.index;
      addText(raw.substr(0, i));
      addLink(url, match[0].replace(MAILTO_REGEXP, ''));
      raw = raw.substring(i + match[0].length);
    }
    addText(raw);
    return $sanitize(html.join(''));

    function addText(text) {
      if (!text) {
        return;
      }
      html.push(sanitizeText(text));
    }

    function addLink(url, text) {
      html.push('<a ');
      if (angular.isDefined(target)) {
        html.push('target="',
                  target,
                  '" ');
      }
      html.push('href="',
                url.replace(/"/g, '&quot;'),
                '">');
      addText(text);
      html.push('</a>');
    }
  };
}]);


})(window, window.angular);
/**
 * @license AngularJS v1.4.3
 * (c) 2010-2015 Google, Inc. http://angularjs.org
 * License: MIT
 */
(function(window, angular, undefined) {'use strict';

/**
 * @ngdoc module
 * @name ngRoute
 * @description
 *
 * # ngRoute
 *
 * The `ngRoute` module provides routing and deeplinking services and directives for angular apps.
 *
 * ## Example
 * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
 *
 *
 * <div doc-module-components="ngRoute"></div>
 */
 /* global -ngRouteModule */
var ngRouteModule = angular.module('ngRoute', ['ng']).
                        provider('$route', $RouteProvider),
    $routeMinErr = angular.$$minErr('ngRoute');

/**
 * @ngdoc provider
 * @name $routeProvider
 *
 * @description
 *
 * Used for configuring routes.
 *
 * ## Example
 * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
 *
 * ## Dependencies
 * Requires the {@link ngRoute `ngRoute`} module to be installed.
 */
function $RouteProvider() {
  function inherit(parent, extra) {
    return angular.extend(Object.create(parent), extra);
  }

  var routes = {};

  /**
   * @ngdoc method
   * @name $routeProvider#when
   *
   * @param {string} path Route path (matched against `$location.path`). If `$location.path`
   *    contains redundant trailing slash or is missing one, the route will still match and the
   *    `$location.path` will be updated to add or drop the trailing slash to exactly match the
   *    route definition.
   *
   *    * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up
   *        to the next slash are matched and stored in `$routeParams` under the given `name`
   *        when the route matches.
   *    * `path` can contain named groups starting with a colon and ending with a star:
   *        e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name`
   *        when the route matches.
   *    * `path` can contain optional named groups with a question mark: e.g.`:name?`.
   *
   *    For example, routes like `/color/:color/largecode/:largecode*\/edit` will match
   *    `/color/brown/largecode/code/with/slashes/edit` and extract:
   *
   *    * `color: brown`
   *    * `largecode: code/with/slashes`.
   *
   *
   * @param {Object} route Mapping information to be assigned to `$route.current` on route
   *    match.
   *
   *    Object properties:
   *
   *    - `controller` – `{(string|function()=}` – Controller fn that should be associated with
   *      newly created scope or the name of a {@link angular.Module#controller registered
   *      controller} if passed as a string.
   *    - `controllerAs` – `{string=}` – An identifier name for a reference to the controller.
   *      If present, the controller will be published to scope under the `controllerAs` name.
   *    - `template` – `{string=|function()=}` – html template as a string or a function that
   *      returns an html template as a string which should be used by {@link
   *      ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives.
   *      This property takes precedence over `templateUrl`.
   *
   *      If `template` is a function, it will be called with the following parameters:
   *
   *      - `{Array.<Object>}` - route parameters extracted from the current
   *        `$location.path()` by applying the current route
   *
   *    - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
   *      template that should be used by {@link ngRoute.directive:ngView ngView}.
   *
   *      If `templateUrl` is a function, it will be called with the following parameters:
   *
   *      - `{Array.<Object>}` - route parameters extracted from the current
   *        `$location.path()` by applying the current route
   *
   *    - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
   *      be injected into the controller. If any of these dependencies are promises, the router
   *      will wait for them all to be resolved or one to be rejected before the controller is
   *      instantiated.
   *      If all the promises are resolved successfully, the values of the resolved promises are
   *      injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is
   *      fired. If any of the promises are rejected the
   *      {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object
   *      is:
   *
   *      - `key` – `{string}`: a name of a dependency to be injected into the controller.
   *      - `factory` - `{string|function}`: If `string` then it is an alias for a service.
   *        Otherwise if function, then it is {@link auto.$injector#invoke injected}
   *        and the return value is treated as the dependency. If the result is a promise, it is
   *        resolved before its value is injected into the controller. Be aware that
   *        `ngRoute.$routeParams` will still refer to the previous route within these resolve
   *        functions.  Use `$route.current.params` to access the new route parameters, instead.
   *
   *    - `redirectTo` – {(string|function())=} – value to update
   *      {@link ng.$location $location} path with and trigger route redirection.
   *
   *      If `redirectTo` is a function, it will be called with the following parameters:
   *
   *      - `{Object.<string>}` - route parameters extracted from the current
   *        `$location.path()` by applying the current route templateUrl.
   *      - `{string}` - current `$location.path()`
   *      - `{Object}` - current `$location.search()`
   *
   *      The custom `redirectTo` function is expected to return a string which will be used
   *      to update `$location.path()` and `$location.search()`.
   *
   *    - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()`
   *      or `$location.hash()` changes.
   *
   *      If the option is set to `false` and url in the browser changes, then
   *      `$routeUpdate` event is broadcasted on the root scope.
   *
   *    - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive
   *
   *      If the option is set to `true`, then the particular route can be matched without being
   *      case sensitive
   *
   * @returns {Object} self
   *
   * @description
   * Adds a new route definition to the `$route` service.
   */
  this.when = function(path, route) {
    //copy original route object to preserve params inherited from proto chain
    var routeCopy = angular.copy(route);
    if (angular.isUndefined(routeCopy.reloadOnSearch)) {
      routeCopy.reloadOnSearch = true;
    }
    if (angular.isUndefined(routeCopy.caseInsensitiveMatch)) {
      routeCopy.caseInsensitiveMatch = this.caseInsensitiveMatch;
    }
    routes[path] = angular.extend(
      routeCopy,
      path && pathRegExp(path, routeCopy)
    );

    // create redirection for trailing slashes
    if (path) {
      var redirectPath = (path[path.length - 1] == '/')
            ? path.substr(0, path.length - 1)
            : path + '/';

      routes[redirectPath] = angular.extend(
        {redirectTo: path},
        pathRegExp(redirectPath, routeCopy)
      );
    }

    return this;
  };

  /**
   * @ngdoc property
   * @name $routeProvider#caseInsensitiveMatch
   * @description
   *
   * A boolean property indicating if routes defined
   * using this provider should be matched using a case insensitive
   * algorithm. Defaults to `false`.
   */
  this.caseInsensitiveMatch = false;

   /**
    * @param path {string} path
    * @param opts {Object} options
    * @return {?Object}
    *
    * @description
    * Normalizes the given path, returning a regular expression
    * and the original path.
    *
    * Inspired by pathRexp in visionmedia/express/lib/utils.js.
    */
  function pathRegExp(path, opts) {
    var insensitive = opts.caseInsensitiveMatch,
        ret = {
          originalPath: path,
          regexp: path
        },
        keys = ret.keys = [];

    path = path
      .replace(/([().])/g, '\\$1')
      .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option) {
        var optional = option === '?' ? option : null;
        var star = option === '*' ? option : null;
        keys.push({ name: key, optional: !!optional });
        slash = slash || '';
        return ''
          + (optional ? '' : slash)
          + '(?:'
          + (optional ? slash : '')
          + (star && '(.+?)' || '([^/]+)')
          + (optional || '')
          + ')'
          + (optional || '');
      })
      .replace(/([\/$\*])/g, '\\$1');

    ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : '');
    return ret;
  }

  /**
   * @ngdoc method
   * @name $routeProvider#otherwise
   *
   * @description
   * Sets route definition that will be used on route change when no other route definition
   * is matched.
   *
   * @param {Object|string} params Mapping information to be assigned to `$route.current`.
   * If called with a string, the value maps to `redirectTo`.
   * @returns {Object} self
   */
  this.otherwise = function(params) {
    if (typeof params === 'string') {
      params = {redirectTo: params};
    }
    this.when(null, params);
    return this;
  };


  this.$get = ['$rootScope',
               '$location',
               '$routeParams',
               '$q',
               '$injector',
               '$templateRequest',
               '$sce',
      function($rootScope, $location, $routeParams, $q, $injector, $templateRequest, $sce) {

    /**
     * @ngdoc service
     * @name $route
     * @requires $location
     * @requires $routeParams
     *
     * @property {Object} current Reference to the current route definition.
     * The route definition contains:
     *
     *   - `controller`: The controller constructor as define in route definition.
     *   - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
     *     controller instantiation. The `locals` contain
     *     the resolved values of the `resolve` map. Additionally the `locals` also contain:
     *
     *     - `$scope` - The current route scope.
     *     - `$template` - The current route template HTML.
     *
     * @property {Object} routes Object with all route configuration Objects as its properties.
     *
     * @description
     * `$route` is used for deep-linking URLs to controllers and views (HTML partials).
     * It watches `$location.url()` and tries to map the path to an existing route definition.
     *
     * Requires the {@link ngRoute `ngRoute`} module to be installed.
     *
     * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API.
     *
     * The `$route` service is typically used in conjunction with the
     * {@link ngRoute.directive:ngView `ngView`} directive and the
     * {@link ngRoute.$routeParams `$routeParams`} service.
     *
     * @example
     * This example shows how changing the URL hash causes the `$route` to match a route against the
     * URL, and the `ngView` pulls in the partial.
     *
     * <example name="$route-service" module="ngRouteExample"
     *          deps="angular-route.js" fixBase="true">
     *   <file name="index.html">
     *     <div ng-controller="MainController">
     *       Choose:
     *       <a href="Book/Moby">Moby</a> |
     *       <a href="Book/Moby/ch/1">Moby: Ch1</a> |
     *       <a href="Book/Gatsby">Gatsby</a> |
     *       <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
     *       <a href="Book/Scarlet">Scarlet Letter</a><br/>
     *
     *       <div ng-view></div>
     *
     *       <hr />
     *
     *       <pre>$location.path() = {{$location.path()}}</pre>
     *       <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
     *       <pre>$route.current.params = {{$route.current.params}}</pre>
     *       <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
     *       <pre>$routeParams = {{$routeParams}}</pre>
     *     </div>
     *   </file>
     *
     *   <file name="book.html">
     *     controller: {{name}}<br />
     *     Book Id: {{params.bookId}}<br />
     *   </file>
     *
     *   <file name="chapter.html">
     *     controller: {{name}}<br />
     *     Book Id: {{params.bookId}}<br />
     *     Chapter Id: {{params.chapterId}}
     *   </file>
     *
     *   <file name="script.js">
     *     angular.module('ngRouteExample', ['ngRoute'])
     *
     *      .controller('MainController', function($scope, $route, $routeParams, $location) {
     *          $scope.$route = $route;
     *          $scope.$location = $location;
     *          $scope.$routeParams = $routeParams;
     *      })
     *
     *      .controller('BookController', function($scope, $routeParams) {
     *          $scope.name = "BookController";
     *          $scope.params = $routeParams;
     *      })
     *
     *      .controller('ChapterController', function($scope, $routeParams) {
     *          $scope.name = "ChapterController";
     *          $scope.params = $routeParams;
     *      })
     *
     *     .config(function($routeProvider, $locationProvider) {
     *       $routeProvider
     *        .when('/Book/:bookId', {
     *         templateUrl: 'book.html',
     *         controller: 'BookController',
     *         resolve: {
     *           // I will cause a 1 second delay
     *           delay: function($q, $timeout) {
     *             var delay = $q.defer();
     *             $timeout(delay.resolve, 1000);
     *             return delay.promise;
     *           }
     *         }
     *       })
     *       .when('/Book/:bookId/ch/:chapterId', {
     *         templateUrl: 'chapter.html',
     *         controller: 'ChapterController'
     *       });
     *
     *       // configure html5 to get links working on jsfiddle
     *       $locationProvider.html5Mode(true);
     *     });
     *
     *   </file>
     *
     *   <file name="protractor.js" type="protractor">
     *     it('should load and compile correct template', function() {
     *       element(by.linkText('Moby: Ch1')).click();
     *       var content = element(by.css('[ng-view]')).getText();
     *       expect(content).toMatch(/controller\: ChapterController/);
     *       expect(content).toMatch(/Book Id\: Moby/);
     *       expect(content).toMatch(/Chapter Id\: 1/);
     *
     *       element(by.partialLinkText('Scarlet')).click();
     *
     *       content = element(by.css('[ng-view]')).getText();
     *       expect(content).toMatch(/controller\: BookController/);
     *       expect(content).toMatch(/Book Id\: Scarlet/);
     *     });
     *   </file>
     * </example>
     */

    /**
     * @ngdoc event
     * @name $route#$routeChangeStart
     * @eventType broadcast on root scope
     * @description
     * Broadcasted before a route change. At this  point the route services starts
     * resolving all of the dependencies needed for the route change to occur.
     * Typically this involves fetching the view template as well as any dependencies
     * defined in `resolve` route property. Once  all of the dependencies are resolved
     * `$routeChangeSuccess` is fired.
     *
     * The route change (and the `$location` change that triggered it) can be prevented
     * by calling `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on}
     * for more details about event object.
     *
     * @param {Object} angularEvent Synthetic event object.
     * @param {Route} next Future route information.
     * @param {Route} current Current route information.
     */

    /**
     * @ngdoc event
     * @name $route#$routeChangeSuccess
     * @eventType broadcast on root scope
     * @description
     * Broadcasted after a route change has happened successfully.
     * The `resolve` dependencies are now available in the `current.locals` property.
     *
     * {@link ngRoute.directive:ngView ngView} listens for the directive
     * to instantiate the controller and render the view.
     *
     * @param {Object} angularEvent Synthetic event object.
     * @param {Route} current Current route information.
     * @param {Route|Undefined} previous Previous route information, or undefined if current is
     * first route entered.
     */

    /**
     * @ngdoc event
     * @name $route#$routeChangeError
     * @eventType broadcast on root scope
     * @description
     * Broadcasted if any of the resolve promises are rejected.
     *
     * @param {Object} angularEvent Synthetic event object
     * @param {Route} current Current route information.
     * @param {Route} previous Previous route information.
     * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
     */

    /**
     * @ngdoc event
     * @name $route#$routeUpdate
     * @eventType broadcast on root scope
     * @description
     * The `reloadOnSearch` property has been set to false, and we are reusing the same
     * instance of the Controller.
     *
     * @param {Object} angularEvent Synthetic event object
     * @param {Route} current Current/previous route information.
     */

    var forceReload = false,
        preparedRoute,
        preparedRouteIsUpdateOnly,
        $route = {
          routes: routes,

          /**
           * @ngdoc method
           * @name $route#reload
           *
           * @description
           * Causes `$route` service to reload the current route even if
           * {@link ng.$location $location} hasn't changed.
           *
           * As a result of that, {@link ngRoute.directive:ngView ngView}
           * creates new scope and reinstantiates the controller.
           */
          reload: function() {
            forceReload = true;
            $rootScope.$evalAsync(function() {
              // Don't support cancellation of a reload for now...
              prepareRoute();
              commitRoute();
            });
          },

          /**
           * @ngdoc method
           * @name $route#updateParams
           *
           * @description
           * Causes `$route` service to update the current URL, replacing
           * current route parameters with those specified in `newParams`.
           * Provided property names that match the route's path segment
           * definitions will be interpolated into the location's path, while
           * remaining properties will be treated as query params.
           *
           * @param {!Object<string, string>} newParams mapping of URL parameter names to values
           */
          updateParams: function(newParams) {
            if (this.current && this.current.$$route) {
              newParams = angular.extend({}, this.current.params, newParams);
              $location.path(interpolate(this.current.$$route.originalPath, newParams));
              // interpolate modifies newParams, only query params are left
              $location.search(newParams);
            } else {
              throw $routeMinErr('norout', 'Tried updating route when with no current route');
            }
          }
        };

    $rootScope.$on('$locationChangeStart', prepareRoute);
    $rootScope.$on('$locationChangeSuccess', commitRoute);

    return $route;

    /////////////////////////////////////////////////////

    /**
     * @param on {string} current url
     * @param route {Object} route regexp to match the url against
     * @return {?Object}
     *
     * @description
     * Check if the route matches the current url.
     *
     * Inspired by match in
     * visionmedia/express/lib/router/router.js.
     */
    function switchRouteMatcher(on, route) {
      var keys = route.keys,
          params = {};

      if (!route.regexp) return null;

      var m = route.regexp.exec(on);
      if (!m) return null;

      for (var i = 1, len = m.length; i < len; ++i) {
        var key = keys[i - 1];

        var val = m[i];

        if (key && val) {
          params[key.name] = val;
        }
      }
      return params;
    }

    function prepareRoute($locationEvent) {
      var lastRoute = $route.current;

      preparedRoute = parseRoute();
      preparedRouteIsUpdateOnly = preparedRoute && lastRoute && preparedRoute.$$route === lastRoute.$$route
          && angular.equals(preparedRoute.pathParams, lastRoute.pathParams)
          && !preparedRoute.reloadOnSearch && !forceReload;

      if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) {
        if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) {
          if ($locationEvent) {
            $locationEvent.preventDefault();
          }
        }
      }
    }

    function commitRoute() {
      var lastRoute = $route.current;
      var nextRoute = preparedRoute;

      if (preparedRouteIsUpdateOnly) {
        lastRoute.params = nextRoute.params;
        angular.copy(lastRoute.params, $routeParams);
        $rootScope.$broadcast('$routeUpdate', lastRoute);
      } else if (nextRoute || lastRoute) {
        forceReload = false;
        $route.current = nextRoute;
        if (nextRoute) {
          if (nextRoute.redirectTo) {
            if (angular.isString(nextRoute.redirectTo)) {
              $location.path(interpolate(nextRoute.redirectTo, nextRoute.params)).search(nextRoute.params)
                       .replace();
            } else {
              $location.url(nextRoute.redirectTo(nextRoute.pathParams, $location.path(), $location.search()))
                       .replace();
            }
          }
        }

        $q.when(nextRoute).
          then(function() {
            if (nextRoute) {
              var locals = angular.extend({}, nextRoute.resolve),
                  template, templateUrl;

              angular.forEach(locals, function(value, key) {
                locals[key] = angular.isString(value) ?
                    $injector.get(value) : $injector.invoke(value, null, null, key);
              });

              if (angular.isDefined(template = nextRoute.template)) {
                if (angular.isFunction(template)) {
                  template = template(nextRoute.params);
                }
              } else if (angular.isDefined(templateUrl = nextRoute.templateUrl)) {
                if (angular.isFunction(templateUrl)) {
                  templateUrl = templateUrl(nextRoute.params);
                }
                if (angular.isDefined(templateUrl)) {
                  nextRoute.loadedTemplateUrl = $sce.valueOf(templateUrl);
                  template = $templateRequest(templateUrl);
                }
              }
              if (angular.isDefined(template)) {
                locals['$template'] = template;
              }
              return $q.all(locals);
            }
          }).
          then(function(locals) {
            // after route change
            if (nextRoute == $route.current) {
              if (nextRoute) {
                nextRoute.locals = locals;
                angular.copy(nextRoute.params, $routeParams);
              }
              $rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute);
            }
          }, function(error) {
            if (nextRoute == $route.current) {
              $rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error);
            }
          });
      }
    }


    /**
     * @returns {Object} the current active route, by matching it against the URL
     */
    function parseRoute() {
      // Match a route
      var params, match;
      angular.forEach(routes, function(route, path) {
        if (!match && (params = switchRouteMatcher($location.path(), route))) {
          match = inherit(route, {
            params: angular.extend({}, $location.search(), params),
            pathParams: params});
          match.$$route = route;
        }
      });
      // No route matched; fallback to "otherwise" route
      return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
    }

    /**
     * @returns {string} interpolation of the redirect path with the parameters
     */
    function interpolate(string, params) {
      var result = [];
      angular.forEach((string || '').split(':'), function(segment, i) {
        if (i === 0) {
          result.push(segment);
        } else {
          var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/);
          var key = segmentMatch[1];
          result.push(params[key]);
          result.push(segmentMatch[2] || '');
          delete params[key];
        }
      });
      return result.join('');
    }
  }];
}

ngRouteModule.provider('$routeParams', $RouteParamsProvider);


/**
 * @ngdoc service
 * @name $routeParams
 * @requires $route
 *
 * @description
 * The `$routeParams` service allows you to retrieve the current set of route parameters.
 *
 * Requires the {@link ngRoute `ngRoute`} module to be installed.
 *
 * The route parameters are a combination of {@link ng.$location `$location`}'s
 * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}.
 * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched.
 *
 * In case of parameter name collision, `path` params take precedence over `search` params.
 *
 * The service guarantees that the identity of the `$routeParams` object will remain unchanged
 * (but its properties will likely change) even when a route change occurs.
 *
 * Note that the `$routeParams` are only updated *after* a route change completes successfully.
 * This means that you cannot rely on `$routeParams` being correct in route resolve functions.
 * Instead you can use `$route.current.params` to access the new route's parameters.
 *
 * @example
 * ```js
 *  // Given:
 *  // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
 *  // Route: /Chapter/:chapterId/Section/:sectionId
 *  //
 *  // Then
 *  $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
 * ```
 */
function $RouteParamsProvider() {
  this.$get = function() { return {}; };
}

ngRouteModule.directive('ngView', ngViewFactory);
ngRouteModule.directive('ngView', ngViewFillContentFactory);


/**
 * @ngdoc directive
 * @name ngView
 * @restrict ECA
 *
 * @description
 * # Overview
 * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by
 * including the rendered template of the current route into the main layout (`index.html`) file.
 * Every time the current route changes, the included view changes with it according to the
 * configuration of the `$route` service.
 *
 * Requires the {@link ngRoute `ngRoute`} module to be installed.
 *
 * @animations
 * enter - animation is used to bring new content into the browser.
 * leave - animation is used to animate existing content away.
 *
 * The enter and leave animation occur concurrently.
 *
 * @scope
 * @priority 400
 * @param {string=} onload Expression to evaluate whenever the view updates.
 *
 * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll
 *                  $anchorScroll} to scroll the viewport after the view is updated.
 *
 *                  - If the attribute is not set, disable scrolling.
 *                  - If the attribute is set without value, enable scrolling.
 *                  - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated
 *                    as an expression yields a truthy value.
 * @example
    <example name="ngView-directive" module="ngViewExample"
             deps="angular-route.js;angular-animate.js"
             animations="true" fixBase="true">
      <file name="index.html">
        <div ng-controller="MainCtrl as main">
          Choose:
          <a href="Book/Moby">Moby</a> |
          <a href="Book/Moby/ch/1">Moby: Ch1</a> |
          <a href="Book/Gatsby">Gatsby</a> |
          <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
          <a href="Book/Scarlet">Scarlet Letter</a><br/>

          <div class="view-animate-container">
            <div ng-view class="view-animate"></div>
          </div>
          <hr />

          <pre>$location.path() = {{main.$location.path()}}</pre>
          <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
          <pre>$route.current.params = {{main.$route.current.params}}</pre>
          <pre>$routeParams = {{main.$routeParams}}</pre>
        </div>
      </file>

      <file name="book.html">
        <div>
          controller: {{book.name}}<br />
          Book Id: {{book.params.bookId}}<br />
        </div>
      </file>

      <file name="chapter.html">
        <div>
          controller: {{chapter.name}}<br />
          Book Id: {{chapter.params.bookId}}<br />
          Chapter Id: {{chapter.params.chapterId}}
        </div>
      </file>

      <file name="animations.css">
        .view-animate-container {
          position:relative;
          height:100px!important;
          background:white;
          border:1px solid black;
          height:40px;
          overflow:hidden;
        }

        .view-animate {
          padding:10px;
        }

        .view-animate.ng-enter, .view-animate.ng-leave {
          -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
          transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;

          display:block;
          width:100%;
          border-left:1px solid black;

          position:absolute;
          top:0;
          left:0;
          right:0;
          bottom:0;
          padding:10px;
        }

        .view-animate.ng-enter {
          left:100%;
        }
        .view-animate.ng-enter.ng-enter-active {
          left:0;
        }
        .view-animate.ng-leave.ng-leave-active {
          left:-100%;
        }
      </file>

      <file name="script.js">
        angular.module('ngViewExample', ['ngRoute', 'ngAnimate'])
          .config(['$routeProvider', '$locationProvider',
            function($routeProvider, $locationProvider) {
              $routeProvider
                .when('/Book/:bookId', {
                  templateUrl: 'book.html',
                  controller: 'BookCtrl',
                  controllerAs: 'book'
                })
                .when('/Book/:bookId/ch/:chapterId', {
                  templateUrl: 'chapter.html',
                  controller: 'ChapterCtrl',
                  controllerAs: 'chapter'
                });

              $locationProvider.html5Mode(true);
          }])
          .controller('MainCtrl', ['$route', '$routeParams', '$location',
            function($route, $routeParams, $location) {
              this.$route = $route;
              this.$location = $location;
              this.$routeParams = $routeParams;
          }])
          .controller('BookCtrl', ['$routeParams', function($routeParams) {
            this.name = "BookCtrl";
            this.params = $routeParams;
          }])
          .controller('ChapterCtrl', ['$routeParams', function($routeParams) {
            this.name = "ChapterCtrl";
            this.params = $routeParams;
          }]);

      </file>

      <file name="protractor.js" type="protractor">
        it('should load and compile correct template', function() {
          element(by.linkText('Moby: Ch1')).click();
          var content = element(by.css('[ng-view]')).getText();
          expect(content).toMatch(/controller\: ChapterCtrl/);
          expect(content).toMatch(/Book Id\: Moby/);
          expect(content).toMatch(/Chapter Id\: 1/);

          element(by.partialLinkText('Scarlet')).click();

          content = element(by.css('[ng-view]')).getText();
          expect(content).toMatch(/controller\: BookCtrl/);
          expect(content).toMatch(/Book Id\: Scarlet/);
        });
      </file>
    </example>
 */


/**
 * @ngdoc event
 * @name ngView#$viewContentLoaded
 * @eventType emit on the current ngView scope
 * @description
 * Emitted every time the ngView content is reloaded.
 */
ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate'];
function ngViewFactory($route, $anchorScroll, $animate) {
  return {
    restrict: 'ECA',
    terminal: true,
    priority: 400,
    transclude: 'element',
    link: function(scope, $element, attr, ctrl, $transclude) {
        var currentScope,
            currentElement,
            previousLeaveAnimation,
            autoScrollExp = attr.autoscroll,
            onloadExp = attr.onload || '';

        scope.$on('$routeChangeSuccess', update);
        update();

        function cleanupLastView() {
          if (previousLeaveAnimation) {
            $animate.cancel(previousLeaveAnimation);
            previousLeaveAnimation = null;
          }

          if (currentScope) {
            currentScope.$destroy();
            currentScope = null;
          }
          if (currentElement) {
            previousLeaveAnimation = $animate.leave(currentElement);
            previousLeaveAnimation.then(function() {
              previousLeaveAnimation = null;
            });
            currentElement = null;
          }
        }

        function update() {
          var locals = $route.current && $route.current.locals,
              template = locals && locals.$template;

          if (angular.isDefined(template)) {
            var newScope = scope.$new();
            var current = $route.current;

            // Note: This will also link all children of ng-view that were contained in the original
            // html. If that content contains controllers, ... they could pollute/change the scope.
            // However, using ng-view on an element with additional content does not make sense...
            // Note: We can't remove them in the cloneAttchFn of $transclude as that
            // function is called before linking the content, which would apply child
            // directives to non existing elements.
            var clone = $transclude(newScope, function(clone) {
              $animate.enter(clone, null, currentElement || $element).then(function onNgViewEnter() {
                if (angular.isDefined(autoScrollExp)
                  && (!autoScrollExp || scope.$eval(autoScrollExp))) {
                  $anchorScroll();
                }
              });
              cleanupLastView();
            });

            currentElement = clone;
            currentScope = current.scope = newScope;
            currentScope.$emit('$viewContentLoaded');
            currentScope.$eval(onloadExp);
          } else {
            cleanupLastView();
          }
        }
    }
  };
}

// This directive is called during the $transclude call of the first `ngView` directive.
// It will replace and compile the content of the element with the loaded template.
// We need this directive so that the element content is already filled when
// the link function of another directive on the same element as ngView
// is called.
ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route'];
function ngViewFillContentFactory($compile, $controller, $route) {
  return {
    restrict: 'ECA',
    priority: -400,
    link: function(scope, $element) {
      var current = $route.current,
          locals = current.locals;

      $element.html(locals.$template);

      var link = $compile($element.contents());

      if (current.controller) {
        locals.$scope = scope;
        var controller = $controller(current.controller, locals);
        if (current.controllerAs) {
          scope[current.controllerAs] = controller;
        }
        $element.data('$ngControllerController', controller);
        $element.children().data('$ngControllerController', controller);
      }

      link(scope);
    }
  };
}


})(window, window.angular);
/*
 * angular-ui-bootstrap
 * http://angular-ui.github.io/bootstrap/

 * Version: 0.13.1-SNAPSHOT - 2015-07-23
 * License: MIT
 */
angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.collapse","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.bindHtml","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.position","ui.bootstrap.datepicker","ui.bootstrap.dropdown","ui.bootstrap.modal","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.transition","ui.bootstrap.typeahead"]);
angular.module("ui.bootstrap.tpls", ["template/accordion/accordion-group.html","template/accordion/accordion.html","template/alert/alert.html","template/carousel/carousel.html","template/carousel/slide.html","template/datepicker/datepicker.html","template/datepicker/day.html","template/datepicker/month.html","template/datepicker/popup.html","template/datepicker/year.html","template/modal/backdrop.html","template/modal/window.html","template/pagination/pager.html","template/pagination/pagination.html","template/tooltip/tooltip-html-popup.html","template/tooltip/tooltip-html-unsafe-popup.html","template/tooltip/tooltip-popup.html","template/tooltip/tooltip-template-popup.html","template/popover/popover-template.html","template/popover/popover.html","template/progressbar/bar.html","template/progressbar/progress.html","template/progressbar/progressbar.html","template/rating/rating.html","template/tabs/tab.html","template/tabs/tabset.html","template/timepicker/timepicker.html","template/typeahead/typeahead-match.html","template/typeahead/typeahead-popup.html"]);
angular.module('ui.bootstrap.collapse', [])

  .directive('collapse', ['$animate', function ($animate) {

    return {
      link: function (scope, element, attrs) {
        function expand() {
          element.removeClass('collapse')
            .addClass('collapsing')
            .attr('aria-expanded', true)
            .attr('aria-hidden', false);

          $animate.addClass(element, 'in', {
            to: { height: element[0].scrollHeight + 'px' }
          }).then(expandDone);
        }

        function expandDone() {
          element.removeClass('collapsing');
          element.css({height: 'auto'});
        }

        function collapse() {
          if(! element.hasClass('collapse') && ! element.hasClass('in')) {
            return collapseDone();
          }

          element
            // IMPORTANT: The height must be set before adding "collapsing" class.
            // Otherwise, the browser attempts to animate from height 0 (in
            // collapsing class) to the given height here.
            .css({height: element[0].scrollHeight + 'px'})
            // initially all panel collapse have the collapse class, this removal
            // prevents the animation from jumping to collapsed state
            .removeClass('collapse')
            .addClass('collapsing')
            .attr('aria-expanded', false)
            .attr('aria-hidden', true);

          $animate.removeClass(element, 'in', {
            to: {height: '0'}
          }).then(collapseDone);
        }

        function collapseDone() {
          element.css({height: '0'}); // Required so that collapse works when animation is disabled
          element.removeClass('collapsing');
          element.addClass('collapse');
        }

        scope.$watch(attrs.collapse, function (shouldCollapse) {
          if (shouldCollapse) {
            collapse();
          } else {
            expand();
          }
        });
      }
    };
  }]);

angular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse'])

.constant('accordionConfig', {
  closeOthers: true
})

.controller('AccordionController', ['$scope', '$attrs', 'accordionConfig', function ($scope, $attrs, accordionConfig) {

  // This array keeps track of the accordion groups
  this.groups = [];

  // Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to
  this.closeOthers = function(openGroup) {
    var closeOthers = angular.isDefined($attrs.closeOthers) ? $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers;
    if ( closeOthers ) {
      angular.forEach(this.groups, function (group) {
        if ( group !== openGroup ) {
          group.isOpen = false;
        }
      });
    }
  };

  // This is called from the accordion-group directive to add itself to the accordion
  this.addGroup = function(groupScope) {
    var that = this;
    this.groups.push(groupScope);

    groupScope.$on('$destroy', function (event) {
      that.removeGroup(groupScope);
    });
  };

  // This is called from the accordion-group directive when to remove itself
  this.removeGroup = function(group) {
    var index = this.groups.indexOf(group);
    if ( index !== -1 ) {
      this.groups.splice(index, 1);
    }
  };

}])

// The accordion directive simply sets up the directive controller
// and adds an accordion CSS class to itself element.
.directive('accordion', function () {
  return {
    restrict:'EA',
    controller:'AccordionController',
    transclude: true,
    replace: false,
    templateUrl: 'template/accordion/accordion.html'
  };
})

// The accordion-group directive indicates a block of html that will expand and collapse in an accordion
.directive('accordionGroup', function() {
  return {
    require:'^accordion',         // We need this directive to be inside an accordion
    restrict:'EA',
    transclude:true,              // It transcludes the contents of the directive into the template
    replace: true,                // The element containing the directive will be replaced with the template
    templateUrl:'template/accordion/accordion-group.html',
    scope: {
      heading: '@',               // Interpolate the heading attribute onto this scope
      isOpen: '=?',
      isDisabled: '=?'
    },
    controller: function() {
      this.setHeading = function(element) {
        this.heading = element;
      };
    },
    link: function(scope, element, attrs, accordionCtrl) {
      accordionCtrl.addGroup(scope);

      scope.$watch('isOpen', function(value) {
        if ( value ) {
          accordionCtrl.closeOthers(scope);
        }
      });

      scope.toggleOpen = function() {
        if ( !scope.isDisabled ) {
          scope.isOpen = !scope.isOpen;
        }
      };
    }
  };
})

// Use accordion-heading below an accordion-group to provide a heading containing HTML
// <accordion-group>
//   <accordion-heading>Heading containing HTML - <img src="..."></accordion-heading>
// </accordion-group>
.directive('accordionHeading', function() {
  return {
    restrict: 'EA',
    transclude: true,   // Grab the contents to be used as the heading
    template: '',       // In effect remove this element!
    replace: true,
    require: '^accordionGroup',
    link: function(scope, element, attr, accordionGroupCtrl, transclude) {
      // Pass the heading to the accordion-group controller
      // so that it can be transcluded into the right place in the template
      // [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat]
      accordionGroupCtrl.setHeading(transclude(scope, angular.noop));
    }
  };
})

// Use in the accordion-group template to indicate where you want the heading to be transcluded
// You must provide the property on the accordion-group controller that will hold the transcluded element
// <div class="accordion-group">
//   <div class="accordion-heading" ><a ... accordion-transclude="heading">...</a></div>
//   ...
// </div>
.directive('accordionTransclude', function() {
  return {
    require: '^accordionGroup',
    link: function(scope, element, attr, controller) {
      scope.$watch(function() { return controller[attr.accordionTransclude]; }, function(heading) {
        if ( heading ) {
          element.html('');
          element.append(heading);
        }
      });
    }
  };
})

;

angular.module('ui.bootstrap.alert', [])

.controller('AlertController', ['$scope', '$attrs', function ($scope, $attrs) {
  $scope.closeable = !!$attrs.close;
  this.close = $scope.close;
}])

.directive('alert', function () {
  return {
    restrict:'EA',
    controller:'AlertController',
    templateUrl:'template/alert/alert.html',
    transclude:true,
    replace:true,
    scope: {
      type: '@',
      close: '&'
    }
  };
})

.directive('dismissOnTimeout', ['$timeout', function($timeout) {
  return {
    require: 'alert',
    link: function(scope, element, attrs, alertCtrl) {
      $timeout(function(){
        alertCtrl.close();
      }, parseInt(attrs.dismissOnTimeout, 10));
    }
  };
}]);

angular.module('ui.bootstrap.bindHtml', [])

  .value('$bindHtmlUnsafeSuppressDeprecated', false)

  .directive('bindHtmlUnsafe', ['$log', '$bindHtmlUnsafeSuppressDeprecated', function ($log, $bindHtmlUnsafeSuppressDeprecated) {
    return function (scope, element, attr) {
      if (!$bindHtmlUnsafeSuppressDeprecated) {
        $log.warn('bindHtmlUnsafe is now deprecated. Use ngBindHtml instead');
      }
      element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe);
      scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) {
        element.html(value || '');
      });
    };
  }]);
angular.module('ui.bootstrap.buttons', [])

.constant('buttonConfig', {
  activeClass: 'active',
  toggleEvent: 'click'
})

.controller('ButtonsController', ['buttonConfig', function(buttonConfig) {
  this.activeClass = buttonConfig.activeClass || 'active';
  this.toggleEvent = buttonConfig.toggleEvent || 'click';
}])

.directive('btnRadio', function () {
  return {
    require: ['btnRadio', 'ngModel'],
    controller: 'ButtonsController',
    link: function (scope, element, attrs, ctrls) {
      var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];

      //model -> UI
      ngModelCtrl.$render = function () {
        element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio)));
      };

      //ui->model
      element.bind(buttonsCtrl.toggleEvent, function () {
        var isActive = element.hasClass(buttonsCtrl.activeClass);

        if (!isActive || angular.isDefined(attrs.uncheckable)) {
          scope.$apply(function () {
            ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.btnRadio));
            ngModelCtrl.$render();
          });
        }
      });
    }
  };
})

.directive('btnCheckbox', function () {
  return {
    require: ['btnCheckbox', 'ngModel'],
    controller: 'ButtonsController',
    link: function (scope, element, attrs, ctrls) {
      var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];

      function getTrueValue() {
        return getCheckboxValue(attrs.btnCheckboxTrue, true);
      }

      function getFalseValue() {
        return getCheckboxValue(attrs.btnCheckboxFalse, false);
      }

      function getCheckboxValue(attributeValue, defaultValue) {
        var val = scope.$eval(attributeValue);
        return angular.isDefined(val) ? val : defaultValue;
      }

      //model -> UI
      ngModelCtrl.$render = function () {
        element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue()));
      };

      //ui->model
      element.bind(buttonsCtrl.toggleEvent, function () {
        scope.$apply(function () {
          ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());
          ngModelCtrl.$render();
        });
      });
    }
  };
});

/**
* @ngdoc overview
* @name ui.bootstrap.carousel
*
* @description
* AngularJS version of an image carousel.
*
*/
angular.module('ui.bootstrap.carousel', [])
.controller('CarouselController', ['$scope', '$element', '$interval', '$animate', function ($scope, $element, $interval, $animate) {
  var self = this,
    slides = self.slides = $scope.slides = [],
    NO_TRANSITION = 'uib-noTransition',
    SLIDE_DIRECTION = 'uib-slideDirection',
    currentIndex = -1,
    currentInterval, isPlaying;
  self.currentSlide = null;

  var destroyed = false;
  /* direction: "prev" or "next" */
  self.select = $scope.select = function(nextSlide, direction) {
    var nextIndex = self.indexOfSlide(nextSlide);
    //Decide direction if it's not given
    if (direction === undefined) {
      direction = nextIndex > self.getCurrentIndex() ? 'next' : 'prev';
    }
    //Prevent this user-triggered transition from occurring if there is already one in progress
    if (nextSlide && nextSlide !== self.currentSlide && !$scope.$currentTransition) {
      goNext(nextSlide, nextIndex, direction);
    }
  };

  function goNext(slide, index, direction) {
    // Scope has been destroyed, stop here.
    if (destroyed) { return; }

    angular.extend(slide, {direction: direction, active: true});
    angular.extend(self.currentSlide || {}, {direction: direction, active: false});
    if ($animate.enabled() && !$scope.noTransition && !$scope.$currentTransition &&
      slide.$element) {
      slide.$element.data(SLIDE_DIRECTION, slide.direction);
      $scope.$currentTransition = true;
      slide.$element.one('$animate:close', function closeFn() {
        $scope.$currentTransition = null;
      });
    }

    self.currentSlide = slide;
    currentIndex = index;

    //every time you change slides, reset the timer
    restartTimer();
  }

  $scope.$on('$destroy', function () {
    destroyed = true;
  });

  function getSlideByIndex(index) {
    if (angular.isUndefined(slides[index].index)) {
      return slides[index];
    }
    var i, len = slides.length;
    for (i = 0; i < slides.length; ++i) {
      if (slides[i].index == index) {
        return slides[i];
      }
    }
  }

  self.getCurrentIndex = function() {
    if (self.currentSlide && angular.isDefined(self.currentSlide.index)) {
      return +self.currentSlide.index;
    }
    return currentIndex;
  };

  /* Allow outside people to call indexOf on slides array */
  self.indexOfSlide = function(slide) {
    return angular.isDefined(slide.index) ? +slide.index : slides.indexOf(slide);
  };

  $scope.next = function() {
    var newIndex = (self.getCurrentIndex() + 1) % slides.length;

    if (newIndex === 0 && $scope.noWrap()) {
      $scope.pause();
      return;
    }

    return self.select(getSlideByIndex(newIndex), 'next');
  };

  $scope.prev = function() {
    var newIndex = self.getCurrentIndex() - 1 < 0 ? slides.length - 1 : self.getCurrentIndex() - 1;

    if ($scope.noWrap() && newIndex === slides.length - 1){
      $scope.pause();
      return;
    }

    return self.select(getSlideByIndex(newIndex), 'prev');
  };

  $scope.isActive = function(slide) {
     return self.currentSlide === slide;
  };

  $scope.$watch('interval', restartTimer);
  $scope.$on('$destroy', resetTimer);

  function restartTimer() {
    resetTimer();
    var interval = +$scope.interval;
    if (!isNaN(interval) && interval > 0) {
      currentInterval = $interval(timerFn, interval);
    }
  }

  function resetTimer() {
    if (currentInterval) {
      $interval.cancel(currentInterval);
      currentInterval = null;
    }
  }

  function timerFn() {
    var interval = +$scope.interval;
    if (isPlaying && !isNaN(interval) && interval > 0 && slides.length) {
      $scope.next();
    } else {
      $scope.pause();
    }
  }

  $scope.play = function() {
    if (!isPlaying) {
      isPlaying = true;
      restartTimer();
    }
  };
  $scope.pause = function() {
    if (!$scope.noPause) {
      isPlaying = false;
      resetTimer();
    }
  };

  self.addSlide = function(slide, element) {
    slide.$element = element;
    slides.push(slide);
    //if this is the first slide or the slide is set to active, select it
    if(slides.length === 1 || slide.active) {
      self.select(slides[slides.length-1]);
      if (slides.length == 1) {
        $scope.play();
      }
    } else {
      slide.active = false;
    }
  };

  self.removeSlide = function(slide) {
    if (angular.isDefined(slide.index)) {
      slides.sort(function(a, b) {
        return +a.index > +b.index;
      });
    }
    //get the index of the slide inside the carousel
    var index = slides.indexOf(slide);
    slides.splice(index, 1);
    if (slides.length > 0 && slide.active) {
      if (index >= slides.length) {
        self.select(slides[index-1]);
      } else {
        self.select(slides[index]);
      }
    } else if (currentIndex > index) {
      currentIndex--;
    }
  };

  $scope.$watch('noTransition', function(noTransition) {
    $element.data(NO_TRANSITION, noTransition);
  });

}])

/**
 * @ngdoc directive
 * @name ui.bootstrap.carousel.directive:carousel
 * @restrict EA
 *
 * @description
 * Carousel is the outer container for a set of image 'slides' to showcase.
 *
 * @param {number=} interval The time, in milliseconds, that it will take the carousel to go to the next slide.
 * @param {boolean=} noTransition Whether to disable transitions on the carousel.
 * @param {boolean=} noPause Whether to disable pausing on the carousel (by default, the carousel interval pauses on hover).
 *
 * @example
<example module="ui.bootstrap">
  <file name="index.html">
    <carousel>
      <slide>
        <img src="http://placekitten.com/150/150" style="margin:auto;">
        <div class="carousel-caption">
          <p>Beautiful!</p>
        </div>
      </slide>
      <slide>
        <img src="http://placekitten.com/100/150" style="margin:auto;">
        <div class="carousel-caption">
          <p>D'aww!</p>
        </div>
      </slide>
    </carousel>
  </file>
  <file name="demo.css">
    .carousel-indicators {
      top: auto;
      bottom: 15px;
    }
  </file>
</example>
 */
.directive('carousel', [function() {
  return {
    restrict: 'EA',
    transclude: true,
    replace: true,
    controller: 'CarouselController',
    require: 'carousel',
    templateUrl: 'template/carousel/carousel.html',
    scope: {
      interval: '=',
      noTransition: '=',
      noPause: '=',
      noWrap: '&'
    }
  };
}])

/**
 * @ngdoc directive
 * @name ui.bootstrap.carousel.directive:slide
 * @restrict EA
 *
 * @description
 * Creates a slide inside a {@link ui.bootstrap.carousel.directive:carousel carousel}.  Must be placed as a child of a carousel element.
 *
 * @param {boolean=} active Model binding, whether or not this slide is currently active.
 * @param {number=} index The index of the slide. The slides will be sorted by this parameter.
 *
 * @example
<example module="ui.bootstrap">
  <file name="index.html">
<div ng-controller="CarouselDemoCtrl">
  <carousel>
    <slide ng-repeat="slide in slides" active="slide.active" index="$index">
      <img ng-src="{{slide.image}}" style="margin:auto;">
      <div class="carousel-caption">
        <h4>Slide {{$index}}</h4>
        <p>{{slide.text}}</p>
      </div>
    </slide>
  </carousel>
  Interval, in milliseconds: <input type="number" ng-model="myInterval">
  <br />Enter a negative number to stop the interval.
</div>
  </file>
  <file name="script.js">
function CarouselDemoCtrl($scope) {
  $scope.myInterval = 5000;
}
  </file>
  <file name="demo.css">
    .carousel-indicators {
      top: auto;
      bottom: 15px;
    }
  </file>
</example>
*/

.directive('slide', function() {
  return {
    require: '^carousel',
    restrict: 'EA',
    transclude: true,
    replace: true,
    templateUrl: 'template/carousel/slide.html',
    scope: {
      active: '=?',
      index: '=?'
    },
    link: function (scope, element, attrs, carouselCtrl) {
      carouselCtrl.addSlide(scope, element);
      //when the scope is destroyed then remove the slide from the current slides array
      scope.$on('$destroy', function() {
        carouselCtrl.removeSlide(scope);
      });

      scope.$watch('active', function(active) {
        if (active) {
          carouselCtrl.select(scope);
        }
      });
    }
  };
})

.animation('.item', [
         '$animate',
function ($animate) {
  var NO_TRANSITION = 'uib-noTransition',
    SLIDE_DIRECTION = 'uib-slideDirection';

  return {
    beforeAddClass: function (element, className, done) {
      // Due to transclusion, noTransition property is on parent's scope
      if (className == 'active' && element.parent() &&
          !element.parent().data(NO_TRANSITION)) {
        var stopped = false;
        var direction = element.data(SLIDE_DIRECTION);
        var directionClass = direction == 'next' ? 'left' : 'right';
        element.addClass(direction);
        $animate.addClass(element, directionClass).then(function () {
          if (!stopped) {
            element.removeClass(directionClass + ' ' + direction);
          }
          done();
        });

        return function () {
          stopped = true;
        };
      }
      done();
    },
    beforeRemoveClass: function (element, className, done) {
      // Due to transclusion, noTransition property is on parent's scope
      if (className == 'active' && element.parent() &&
          !element.parent().data(NO_TRANSITION)) {
        var stopped = false;
        var direction = element.data(SLIDE_DIRECTION);
        var directionClass = direction == 'next' ? 'left' : 'right';
        $animate.addClass(element, directionClass).then(function () {
          if (!stopped) {
            element.removeClass(directionClass);
          }
          done();
        });
        return function () {
          stopped = true;
        };
      }
      done();
    }
  };

}])


;

angular.module('ui.bootstrap.dateparser', [])

.service('dateParser', ['$locale', 'orderByFilter', function($locale, orderByFilter) {
  // Pulled from https://github.com/mbostock/d3/blob/master/src/format/requote.js
  var SPECIAL_CHARACTERS_REGEXP = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;

  this.parsers = {};

  var formatCodeToRegex = {
    'yyyy': {
      regex: '\\d{4}',
      apply: function(value) { this.year = +value; }
    },
    'yy': {
      regex: '\\d{2}',
      apply: function(value) { this.year = +value + 2000; }
    },
    'y': {
      regex: '\\d{1,4}',
      apply: function(value) { this.year = +value; }
    },
    'MMMM': {
      regex: $locale.DATETIME_FORMATS.MONTH.join('|'),
      apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); }
    },
    'MMM': {
      regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
      apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); }
    },
    'MM': {
      regex: '0[1-9]|1[0-2]',
      apply: function(value) { this.month = value - 1; }
    },
    'M': {
      regex: '[1-9]|1[0-2]',
      apply: function(value) { this.month = value - 1; }
    },
    'dd': {
      regex: '[0-2][0-9]{1}|3[0-1]{1}',
      apply: function(value) { this.date = +value; }
    },
    'd': {
      regex: '[1-2]?[0-9]{1}|3[0-1]{1}',
      apply: function(value) { this.date = +value; }
    },
    'EEEE': {
      regex: $locale.DATETIME_FORMATS.DAY.join('|')
    },
    'EEE': {
      regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|')
    },
    'HH': {
      regex: '(?:0|1)[0-9]|2[0-3]',
      apply: function(value) { this.hours = +value; }
    },
    'H': {
      regex: '1?[0-9]|2[0-3]',
      apply: function(value) { this.hours = +value; }
    },
    'mm': {
      regex: '[0-5][0-9]',
      apply: function(value) { this.minutes = +value; }
    },
    'm': {
      regex: '[0-9]|[1-5][0-9]',
      apply: function(value) { this.minutes = +value; }
    },
    'sss': {
      regex: '[0-9][0-9][0-9]',
      apply: function(value) { this.milliseconds = +value; }
    },
    'ss': {
      regex: '[0-5][0-9]',
      apply: function(value) { this.seconds = +value; }
    },
    's': {
      regex: '[0-9]|[1-5][0-9]',
      apply: function(value) { this.seconds = +value; }
    }
  };

  function createParser(format) {
    var map = [], regex = format.split('');

    angular.forEach(formatCodeToRegex, function(data, code) {
      var index = format.indexOf(code);

      if (index > -1) {
        format = format.split('');

        regex[index] = '(' + data.regex + ')';
        format[index] = '$'; // Custom symbol to define consumed part of format
        for (var i = index + 1, n = index + code.length; i < n; i++) {
          regex[i] = '';
          format[i] = '$';
        }
        format = format.join('');

        map.push({ index: index, apply: data.apply });
      }
    });

    return {
      regex: new RegExp('^' + regex.join('') + '$'),
      map: orderByFilter(map, 'index')
    };
  }

  this.parse = function(input, format, baseDate) {
    if ( !angular.isString(input) || !format ) {
      return input;
    }

    format = $locale.DATETIME_FORMATS[format] || format;
    format = format.replace(SPECIAL_CHARACTERS_REGEXP, '\\$&');

    if ( !this.parsers[format] ) {
      this.parsers[format] = createParser(format);
    }

    var parser = this.parsers[format],
        regex = parser.regex,
        map = parser.map,
        results = input.match(regex);

    if ( results && results.length ) {
      var fields, dt;
      if (baseDate) {
        fields = {
          year: baseDate.getFullYear(),
          month: baseDate.getMonth(),
          date: baseDate.getDate(),
          hours: baseDate.getHours(),
          minutes: baseDate.getMinutes(),
          seconds: baseDate.getSeconds(),
          milliseconds: baseDate.getMilliseconds()
        };
      } else {
        fields = { year: 1900, month: 0, date: 1, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 };
      }

      for( var i = 1, n = results.length; i < n; i++ ) {
        var mapper = map[i-1];
        if ( mapper.apply ) {
          mapper.apply.call(fields, results[i]);
        }
      }

      if ( isValid(fields.year, fields.month, fields.date) ) {
        dt = new Date(fields.year, fields.month, fields.date, fields.hours, fields.minutes, fields.seconds,
          fields.milliseconds || 0);
      }

      return dt;
    }
  };

  // Check if date is valid for specific month (and year for February).
  // Month: 0 = Jan, 1 = Feb, etc
  function isValid(year, month, date) {
    if (date < 1) {
      return false;
    }

    if ( month === 1 && date > 28) {
        return date === 29 && ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
    }

    if ( month === 3 || month === 5 || month === 8 || month === 10) {
        return date < 31;
    }

    return true;
  }
}]);

angular.module('ui.bootstrap.position', [])

/**
 * A set of utility methods that can be use to retrieve position of DOM elements.
 * It is meant to be used where we need to absolute-position DOM elements in
 * relation to other, existing elements (this is the case for tooltips, popovers,
 * typeahead suggestions etc.).
 */
  .factory('$position', ['$document', '$window', function ($document, $window) {

    function getStyle(el, cssprop) {
      if (el.currentStyle) { //IE
        return el.currentStyle[cssprop];
      } else if ($window.getComputedStyle) {
        return $window.getComputedStyle(el)[cssprop];
      }
      // finally try and get inline style
      return el.style[cssprop];
    }

    /**
     * Checks if a given element is statically positioned
     * @param element - raw DOM element
     */
    function isStaticPositioned(element) {
      return (getStyle(element, 'position') || 'static' ) === 'static';
    }

    /**
     * returns the closest, non-statically positioned parentOffset of a given element
     * @param element
     */
    var parentOffsetEl = function (element) {
      var docDomEl = $document[0];
      var offsetParent = element.offsetParent || docDomEl;
      while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) {
        offsetParent = offsetParent.offsetParent;
      }
      return offsetParent || docDomEl;
    };

    return {
      /**
       * Provides read-only equivalent of jQuery's position function:
       * http://api.jquery.com/position/
       */
      position: function (element) {
        var elBCR = this.offset(element);
        var offsetParentBCR = { top: 0, left: 0 };
        var offsetParentEl = parentOffsetEl(element[0]);
        if (offsetParentEl != $document[0]) {
          offsetParentBCR = this.offset(angular.element(offsetParentEl));
          offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;
          offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;
        }

        var boundingClientRect = element[0].getBoundingClientRect();
        return {
          width: boundingClientRect.width || element.prop('offsetWidth'),
          height: boundingClientRect.height || element.prop('offsetHeight'),
          top: elBCR.top - offsetParentBCR.top,
          left: elBCR.left - offsetParentBCR.left
        };
      },

      /**
       * Provides read-only equivalent of jQuery's offset function:
       * http://api.jquery.com/offset/
       */
      offset: function (element) {
        var boundingClientRect = element[0].getBoundingClientRect();
        return {
          width: boundingClientRect.width || element.prop('offsetWidth'),
          height: boundingClientRect.height || element.prop('offsetHeight'),
          top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
          left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
        };
      },

      /**
       * Provides coordinates for the targetEl in relation to hostEl
       */
      positionElements: function (hostEl, targetEl, positionStr, appendToBody) {

        var positionStrParts = positionStr.split('-');
        var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center';

        var hostElPos,
          targetElWidth,
          targetElHeight,
          targetElPos;

        hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl);

        targetElWidth = targetEl.prop('offsetWidth');
        targetElHeight = targetEl.prop('offsetHeight');

        var shiftWidth = {
          center: function () {
            return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2;
          },
          left: function () {
            return hostElPos.left;
          },
          right: function () {
            return hostElPos.left + hostElPos.width;
          }
        };

        var shiftHeight = {
          center: function () {
            return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2;
          },
          top: function () {
            return hostElPos.top;
          },
          bottom: function () {
            return hostElPos.top + hostElPos.height;
          }
        };

        switch (pos0) {
          case 'right':
            targetElPos = {
              top: shiftHeight[pos1](),
              left: shiftWidth[pos0]()
            };
            break;
          case 'left':
            targetElPos = {
              top: shiftHeight[pos1](),
              left: hostElPos.left - targetElWidth
            };
            break;
          case 'bottom':
            targetElPos = {
              top: shiftHeight[pos0](),
              left: shiftWidth[pos1]()
            };
            break;
          default:
            targetElPos = {
              top: hostElPos.top - targetElHeight,
              left: shiftWidth[pos1]()
            };
            break;
        }

        return targetElPos;
      }
    };
  }]);

angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.position'])

.constant('datepickerConfig', {
  formatDay: 'dd',
  formatMonth: 'MMMM',
  formatYear: 'yyyy',
  formatDayHeader: 'EEE',
  formatDayTitle: 'MMMM yyyy',
  formatMonthTitle: 'yyyy',
  datepickerMode: 'day',
  minMode: 'day',
  maxMode: 'year',
  showWeeks: true,
  startingDay: 0,
  yearRange: 20,
  minDate: null,
  maxDate: null,
  shortcutPropagation: false
})

.controller('DatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$log', 'dateFilter', 'datepickerConfig', function($scope, $attrs, $parse, $interpolate, $log, dateFilter, datepickerConfig) {
  var self = this,
      ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl;

  // Modes chain
  this.modes = ['day', 'month', 'year'];

  // Configuration attributes
  angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle',
                   'minMode', 'maxMode', 'showWeeks', 'startingDay', 'yearRange', 'shortcutPropagation'], function( key, index ) {
    self[key] = angular.isDefined($attrs[key]) ? (index < 8 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key];
  });

  // Watchable date attributes
  angular.forEach(['minDate', 'maxDate'], function( key ) {
    if ( $attrs[key] ) {
      $scope.$parent.$watch($parse($attrs[key]), function(value) {
        self[key] = value ? new Date(value) : null;
        self.refreshView();
      });
    } else {
      self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null;
    }
  });

  $scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode;
  $scope.maxMode = self.maxMode;
  $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000);

  if(angular.isDefined($attrs.initDate)) {
    this.activeDate = $scope.$parent.$eval($attrs.initDate) || new Date();
    $scope.$parent.$watch($attrs.initDate, function(initDate){
      if(initDate && (ngModelCtrl.$isEmpty(ngModelCtrl.$modelValue) || ngModelCtrl.$invalid)){
        self.activeDate = initDate;
        self.refreshView();
      }
    });
  } else {
    this.activeDate =  new Date();
  }

  $scope.isActive = function(dateObject) {
    if (self.compare(dateObject.date, self.activeDate) === 0) {
      $scope.activeDateId = dateObject.uid;
      return true;
    }
    return false;
  };

  this.init = function( ngModelCtrl_ ) {
    ngModelCtrl = ngModelCtrl_;

    ngModelCtrl.$render = function() {
      self.render();
    };
  };

  this.render = function() {
    if ( ngModelCtrl.$viewValue ) {
      var date = new Date( ngModelCtrl.$viewValue ),
          isValid = !isNaN(date);

      if ( isValid ) {
        this.activeDate = date;
      } else {
        $log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
      }
      ngModelCtrl.$setValidity('date', isValid);
    }
    this.refreshView();
  };

  this.refreshView = function() {
    if ( this.element ) {
      this._refreshView();

      var date = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;
      ngModelCtrl.$setValidity('date-disabled', !date || (this.element && !this.isDisabled(date)));
    }
  };

  this.createDateObject = function(date, format) {
    var model = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;
    return {
      date: date,
      label: dateFilter(date, format),
      selected: model && this.compare(date, model) === 0,
      disabled: this.isDisabled(date),
      current: this.compare(date, new Date()) === 0,
      customClass: this.customClass(date)
    };
  };

  this.isDisabled = function( date ) {
    return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode})));
  };

    this.customClass = function( date ) {
      return $scope.customClass({date: date, mode: $scope.datepickerMode});
    };

  // Split array into smaller arrays
  this.split = function(arr, size) {
    var arrays = [];
    while (arr.length > 0) {
      arrays.push(arr.splice(0, size));
    }
    return arrays;
  };

  // Fix a hard-reprodusible bug with timezones
  // The bug depends on OS, browser, current timezone and current date
  // i.e.
  // var date = new Date(2014, 0, 1);
  // console.log(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours());
  // can result in "2013 11 31 23" because of the bug.
  this.fixTimeZone = function(date) {
    var hours = date.getHours();
    date.setHours(hours === 23 ? hours + 2 : 0);
  };

  $scope.select = function( date ) {
    if ( $scope.datepickerMode === self.minMode ) {
      var dt = ngModelCtrl.$viewValue ? new Date( ngModelCtrl.$viewValue ) : new Date(0, 0, 0, 0, 0, 0, 0);
      dt.setFullYear( date.getFullYear(), date.getMonth(), date.getDate() );
      ngModelCtrl.$setViewValue( dt );
      ngModelCtrl.$render();
    } else {
      self.activeDate = date;
      $scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) - 1 ];
    }
  };

  $scope.move = function( direction ) {
    var year = self.activeDate.getFullYear() + direction * (self.step.years || 0),
        month = self.activeDate.getMonth() + direction * (self.step.months || 0);
    self.activeDate.setFullYear(year, month, 1);
    self.refreshView();
  };

  $scope.toggleMode = function( direction ) {
    direction = direction || 1;

    if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) {
      return;
    }

    $scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) + direction ];
  };

  // Key event mapper
  $scope.keys = { 13:'enter', 32:'space', 33:'pageup', 34:'pagedown', 35:'end', 36:'home', 37:'left', 38:'up', 39:'right', 40:'down' };

  var focusElement = function() {
    self.element[0].focus();
  };

  // Listen for focus requests from popup directive
  $scope.$on('datepicker.focus', focusElement);

  $scope.keydown = function( evt ) {
    var key = $scope.keys[evt.which];

    if ( !key || evt.shiftKey || evt.altKey ) {
      return;
    }

    evt.preventDefault();
    if(!self.shortcutPropagation){
        evt.stopPropagation();
    }

    if (key === 'enter' || key === 'space') {
      if ( self.isDisabled(self.activeDate)) {
        return; // do nothing
      }
      $scope.select(self.activeDate);
      focusElement();
    } else if (evt.ctrlKey && (key === 'up' || key === 'down')) {
      $scope.toggleMode(key === 'up' ? 1 : -1);
      focusElement();
    } else {
      self.handleKeyDown(key, evt);
      self.refreshView();
    }
  };
}])

.directive( 'datepicker', function () {
  return {
    restrict: 'EA',
    replace: true,
    templateUrl: 'template/datepicker/datepicker.html',
    scope: {
      datepickerMode: '=?',
      dateDisabled: '&',
      customClass: '&',
      shortcutPropagation: '&?'
    },
    require: ['datepicker', '?^ngModel'],
    controller: 'DatepickerController',
    link: function(scope, element, attrs, ctrls) {
      var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];

      if ( ngModelCtrl ) {
        datepickerCtrl.init( ngModelCtrl );
      }
    }
  };
})

.directive('daypicker', ['dateFilter', function (dateFilter) {
  return {
    restrict: 'EA',
    replace: true,
    templateUrl: 'template/datepicker/day.html',
    require: '^datepicker',
    link: function(scope, element, attrs, ctrl) {
      scope.showWeeks = ctrl.showWeeks;

      ctrl.step = { months: 1 };
      ctrl.element = element;

      var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
      function getDaysInMonth( year, month ) {
        return ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0))) ? 29 : DAYS_IN_MONTH[month];
      }

      function getDates(startDate, n) {
        var dates = new Array(n), current = new Date(startDate), i = 0, date;
        while ( i < n ) {
          date = new Date(current);
          ctrl.fixTimeZone(date);
          dates[i++] = date;
          current.setDate( current.getDate() + 1 );
        }
        return dates;
      }

      ctrl._refreshView = function() {
        var year = ctrl.activeDate.getFullYear(),
          month = ctrl.activeDate.getMonth(),
          firstDayOfMonth = new Date(year, month, 1),
          difference = ctrl.startingDay - firstDayOfMonth.getDay(),
          numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : - difference,
          firstDate = new Date(firstDayOfMonth);

        if ( numDisplayedFromPreviousMonth > 0 ) {
          firstDate.setDate( - numDisplayedFromPreviousMonth + 1 );
        }

        // 42 is the number of days on a six-month calendar
        var days = getDates(firstDate, 42);
        for (var i = 0; i < 42; i ++) {
          days[i] = angular.extend(ctrl.createDateObject(days[i], ctrl.formatDay), {
            secondary: days[i].getMonth() !== month,
            uid: scope.uniqueId + '-' + i
          });
        }

        scope.labels = new Array(7);
        for (var j = 0; j < 7; j++) {
          scope.labels[j] = {
            abbr: dateFilter(days[j].date, ctrl.formatDayHeader),
            full: dateFilter(days[j].date, 'EEEE')
          };
        }

        scope.title = dateFilter(ctrl.activeDate, ctrl.formatDayTitle);
        scope.rows = ctrl.split(days, 7);

        if ( scope.showWeeks ) {
          scope.weekNumbers = [];
          var thursdayIndex = (4 + 7 - ctrl.startingDay) % 7,
              numWeeks = scope.rows.length;
          for (var curWeek = 0; curWeek < numWeeks; curWeek++) {
            scope.weekNumbers.push(
              getISO8601WeekNumber( scope.rows[curWeek][thursdayIndex].date ));
          }
        }
      };

      ctrl.compare = function(date1, date2) {
        return (new Date( date1.getFullYear(), date1.getMonth(), date1.getDate() ) - new Date( date2.getFullYear(), date2.getMonth(), date2.getDate() ) );
      };

      function getISO8601WeekNumber(date) {
        var checkDate = new Date(date);
        checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday
        var time = checkDate.getTime();
        checkDate.setMonth(0); // Compare with Jan 1
        checkDate.setDate(1);
        return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
      }

      ctrl.handleKeyDown = function( key, evt ) {
        var date = ctrl.activeDate.getDate();

        if (key === 'left') {
          date = date - 1;   // up
        } else if (key === 'up') {
          date = date - 7;   // down
        } else if (key === 'right') {
          date = date + 1;   // down
        } else if (key === 'down') {
          date = date + 7;
        } else if (key === 'pageup' || key === 'pagedown') {
          var month = ctrl.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1);
          ctrl.activeDate.setMonth(month, 1);
          date = Math.min(getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth()), date);
        } else if (key === 'home') {
          date = 1;
        } else if (key === 'end') {
          date = getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth());
        }
        ctrl.activeDate.setDate(date);
      };

      ctrl.refreshView();
    }
  };
}])

.directive('monthpicker', ['dateFilter', function (dateFilter) {
  return {
    restrict: 'EA',
    replace: true,
    templateUrl: 'template/datepicker/month.html',
    require: '^datepicker',
    link: function(scope, element, attrs, ctrl) {
      ctrl.step = { years: 1 };
      ctrl.element = element;

      ctrl._refreshView = function() {
        var months = new Array(12),
            year = ctrl.activeDate.getFullYear(),
            date;

        for ( var i = 0; i < 12; i++ ) {
          date = new Date(year, i, 1);
          ctrl.fixTimeZone(date);
          months[i] = angular.extend(ctrl.createDateObject(date, ctrl.formatMonth), {
            uid: scope.uniqueId + '-' + i
          });
        }

        scope.title = dateFilter(ctrl.activeDate, ctrl.formatMonthTitle);
        scope.rows = ctrl.split(months, 3);
      };

      ctrl.compare = function(date1, date2) {
        return new Date( date1.getFullYear(), date1.getMonth() ) - new Date( date2.getFullYear(), date2.getMonth() );
      };

      ctrl.handleKeyDown = function( key, evt ) {
        var date = ctrl.activeDate.getMonth();

        if (key === 'left') {
          date = date - 1;   // up
        } else if (key === 'up') {
          date = date - 3;   // down
        } else if (key === 'right') {
          date = date + 1;   // down
        } else if (key === 'down') {
          date = date + 3;
        } else if (key === 'pageup' || key === 'pagedown') {
          var year = ctrl.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1);
          ctrl.activeDate.setFullYear(year);
        } else if (key === 'home') {
          date = 0;
        } else if (key === 'end') {
          date = 11;
        }
        ctrl.activeDate.setMonth(date);
      };

      ctrl.refreshView();
    }
  };
}])

.directive('yearpicker', ['dateFilter', function (dateFilter) {
  return {
    restrict: 'EA',
    replace: true,
    templateUrl: 'template/datepicker/year.html',
    require: '^datepicker',
    link: function(scope, element, attrs, ctrl) {
      var range = ctrl.yearRange;

      ctrl.step = { years: range };
      ctrl.element = element;

      function getStartingYear( year ) {
        return parseInt((year - 1) / range, 10) * range + 1;
      }

      ctrl._refreshView = function() {
        var years = new Array(range), date;

        for ( var i = 0, start = getStartingYear(ctrl.activeDate.getFullYear()); i < range; i++ ) {
          date = new Date(start + i, 0, 1);
          ctrl.fixTimeZone(date);
          years[i] = angular.extend(ctrl.createDateObject(date, ctrl.formatYear), {
            uid: scope.uniqueId + '-' + i
          });
        }

        scope.title = [years[0].label, years[range - 1].label].join(' - ');
        scope.rows = ctrl.split(years, 5);
      };

      ctrl.compare = function(date1, date2) {
        return date1.getFullYear() - date2.getFullYear();
      };

      ctrl.handleKeyDown = function( key, evt ) {
        var date = ctrl.activeDate.getFullYear();

        if (key === 'left') {
          date = date - 1;   // up
        } else if (key === 'up') {
          date = date - 5;   // down
        } else if (key === 'right') {
          date = date + 1;   // down
        } else if (key === 'down') {
          date = date + 5;
        } else if (key === 'pageup' || key === 'pagedown') {
          date += (key === 'pageup' ? - 1 : 1) * ctrl.step.years;
        } else if (key === 'home') {
          date = getStartingYear( ctrl.activeDate.getFullYear() );
        } else if (key === 'end') {
          date = getStartingYear( ctrl.activeDate.getFullYear() ) + range - 1;
        }
        ctrl.activeDate.setFullYear(date);
      };

      ctrl.refreshView();
    }
  };
}])

.constant('datepickerPopupConfig', {
  datepickerPopup: 'yyyy-MM-dd',
  html5Types: {
    date: 'yyyy-MM-dd',
    'datetime-local': 'yyyy-MM-ddTHH:mm:ss.sss',
    'month': 'yyyy-MM'
  },
  currentText: 'Today',
  clearText: 'Clear',
  closeText: 'Done',
  closeOnDateSelection: true,
  appendToBody: false,
  showButtonBar: true
})

.directive('datepickerPopup', ['$compile', '$parse', '$document', '$position', 'dateFilter', 'dateParser', 'datepickerPopupConfig', '$timeout',
function ($compile, $parse, $document, $position, dateFilter, dateParser, datepickerPopupConfig, $timeout) {
  return {
    restrict: 'EA',
    require: 'ngModel',
    scope: {
      isOpen: '=?',
      currentText: '@',
      clearText: '@',
      closeText: '@',
      dateDisabled: '&',
      customClass: '&'
    },
    link: function(scope, element, attrs, ngModel) {
      var dateFormat,
          closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? scope.$parent.$eval(attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection,
          appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? scope.$parent.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody;

      scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? scope.$parent.$eval(attrs.showButtonBar) : datepickerPopupConfig.showButtonBar;

      scope.getText = function( key ) {
        return scope[key + 'Text'] || datepickerPopupConfig[key + 'Text'];
      };

      var isHtml5DateInput = false;
      if (datepickerPopupConfig.html5Types[attrs.type]) {
        dateFormat = datepickerPopupConfig.html5Types[attrs.type];
        isHtml5DateInput = true;
      } else {
        dateFormat = attrs.datepickerPopup || datepickerPopupConfig.datepickerPopup;
        attrs.$observe('datepickerPopup', function(value, oldValue) {
            var newDateFormat = value || datepickerPopupConfig.datepickerPopup;
            // Invalidate the $modelValue to ensure that formatters re-run
            // FIXME: Refactor when PR is merged: https://github.com/angular/angular.js/pull/10764
            if (newDateFormat !== dateFormat) {
              dateFormat = newDateFormat;
              ngModel.$modelValue = null;

              if (!dateFormat) {
                throw new Error('datepickerPopup must have a date format specified.');
              }
            }
        });
      }

      if (!dateFormat) {
        throw new Error('datepickerPopup must have a date format specified.');
      }

      if (isHtml5DateInput && attrs.datepickerPopup) {
        throw new Error('HTML5 date input types do not support custom formats.');
      }

      // popup element used to display calendar
      var popupEl = angular.element('<div datepicker-popup-wrap><div datepicker></div></div>');
      popupEl.attr({
        'ng-model': 'date',
        'ng-change': 'dateSelection(date)'
      });

      function cameltoDash( string ){
        return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); });
      }

      // datepicker element
      var datepickerEl = angular.element(popupEl.children()[0]);
      if (isHtml5DateInput) {
        if (attrs.type == 'month') {
          datepickerEl.attr('datepicker-mode', '"month"');
          datepickerEl.attr('min-mode', 'month');
        }
      }

      if ( attrs.datepickerOptions ) {
        var options = scope.$parent.$eval(attrs.datepickerOptions);
        if(options.initDate) {
          scope.initDate = options.initDate;
          datepickerEl.attr( 'init-date', 'initDate' );
          delete options.initDate;
        }
        angular.forEach(options, function( value, option ) {
          datepickerEl.attr( cameltoDash(option), value );
        });
      }

      scope.watchData = {};
      angular.forEach(['minDate', 'maxDate', 'datepickerMode', 'initDate', 'shortcutPropagation'], function( key ) {
        if ( attrs[key] ) {
          var getAttribute = $parse(attrs[key]);
          scope.$parent.$watch(getAttribute, function(value){
            scope.watchData[key] = value;
          });
          datepickerEl.attr(cameltoDash(key), 'watchData.' + key);

          // Propagate changes from datepicker to outside
          if ( key === 'datepickerMode' ) {
            var setAttribute = getAttribute.assign;
            scope.$watch('watchData.' + key, function(value, oldvalue) {
              if ( angular.isFunction(setAttribute) && value !== oldvalue ) {
                setAttribute(scope.$parent, value);
              }
            });
          }
        }
      });
      if (attrs.dateDisabled) {
        datepickerEl.attr('date-disabled', 'dateDisabled({ date: date, mode: mode })');
      }

      if (attrs.showWeeks) {
        datepickerEl.attr('show-weeks', attrs.showWeeks);
      }

      if (attrs.customClass){
        datepickerEl.attr('custom-class', 'customClass({ date: date, mode: mode })');
      }

      function parseDate(viewValue) {
        if (angular.isNumber(viewValue)) {
          // presumably timestamp to date object
          viewValue = new Date(viewValue);
        }

        if (!viewValue) {
          return null;
        } else if (angular.isDate(viewValue) && !isNaN(viewValue)) {
          return viewValue;
        } else if (angular.isString(viewValue)) {
          var date = dateParser.parse(viewValue, dateFormat, scope.date) || new Date(viewValue);
          if (isNaN(date)) {
            return undefined;
          } else {
            return date;
          }
        } else {
          return undefined;
        }
      }

      function validator(modelValue, viewValue) {
        var value = modelValue || viewValue;
        if (angular.isNumber(value)) {
          value = new Date(value);
        }
        if (!value) {
          return true;
        } else if (angular.isDate(value) && !isNaN(value)) {
          return true;
        } else if (angular.isString(value)) {
          var date = dateParser.parse(value, dateFormat) || new Date(value);
          return !isNaN(date);
        } else {
          return false;
        }
      }

      if (!isHtml5DateInput) {
        // Internal API to maintain the correct ng-invalid-[key] class
        ngModel.$$parserName = 'date';
        ngModel.$validators.date = validator;
        ngModel.$parsers.unshift(parseDate);
        ngModel.$formatters.push(function (value) {
          scope.date = value;
          return ngModel.$isEmpty(value) ? value : dateFilter(value, dateFormat);
        });
      }
      else {
        ngModel.$formatters.push(function (value) {
          scope.date = value;
          return value;
        });
      }

      // Inner change
      scope.dateSelection = function(dt) {
        if (angular.isDefined(dt)) {
          scope.date = dt;
        }
        var date = scope.date ? dateFilter(scope.date, dateFormat) : '';
        element.val(date);
        ngModel.$setViewValue(date);

        if ( closeOnDateSelection ) {
          scope.isOpen = false;
          element[0].focus();
        }
      };

      // Detect changes in the view from the text box
      ngModel.$viewChangeListeners.push(function () {
        scope.date = dateParser.parse(ngModel.$viewValue, dateFormat, scope.date) || new Date(ngModel.$viewValue);
      });

      var documentClickBind = function(event) {
        if (scope.isOpen && event.target !== element[0]) {
          scope.$apply(function() {
            scope.isOpen = false;
          });
        }
      };

      var inputKeydownBind = function(evt) {
        if (evt.which === 27 && scope.isOpen) {
          evt.preventDefault();
          evt.stopPropagation();
          scope.$apply(function() {
            scope.isOpen = false;
          });
          element[0].focus();
        } else if (evt.which === 40 && !scope.isOpen) {
          evt.preventDefault();
          evt.stopPropagation();
          scope.$apply(function() {
            scope.isOpen = true;
          });
        }
      };
      element.bind('keydown', inputKeydownBind);

      scope.keydown = function(evt) {
        if (evt.which === 27) {
          scope.isOpen = false;
          element[0].focus();
        }
      };

      scope.$watch('isOpen', function(value) {
        if (value) {
          scope.position = appendToBody ? $position.offset(element) : $position.position(element);
          scope.position.top = scope.position.top + element.prop('offsetHeight');

          $document.bind('click', documentClickBind);

          $timeout(function() {
            scope.$broadcast('datepicker.focus');
          }, 0, false);
        } else {
          $document.unbind('click', documentClickBind);
        }
      });

      scope.select = function( date ) {
        if (date === 'today') {
          var today = new Date();
          if (angular.isDate(scope.date)) {
            date = new Date(scope.date);
            date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate());
          } else {
            date = new Date(today.setHours(0, 0, 0, 0));
          }
        }
        scope.dateSelection( date );
      };

      scope.close = function() {
        scope.isOpen = false;
        element[0].focus();
      };

      var $popup = $compile(popupEl)(scope);
      // Prevent jQuery cache memory leak (template is now redundant after linking)
      popupEl.remove();

      if ( appendToBody ) {
        $document.find('body').append($popup);
      } else {
        element.after($popup);
      }

      scope.$on('$destroy', function() {
        if (scope.isOpen === true) {
          scope.$apply(function() {
            scope.isOpen = false;
          });
        }

        $popup.remove();
        element.unbind('keydown', inputKeydownBind);
        $document.unbind('click', documentClickBind);
      });
    }
  };
}])

.directive('datepickerPopupWrap', function() {
  return {
    restrict:'EA',
    replace: true,
    transclude: true,
    templateUrl: 'template/datepicker/popup.html'
  };
});

angular.module('ui.bootstrap.dropdown', ['ui.bootstrap.position'])

.constant('dropdownConfig', {
  openClass: 'open'
})

.service('dropdownService', ['$document', '$rootScope', function($document, $rootScope) {
  var openScope = null;

  this.open = function( dropdownScope ) {
    if ( !openScope ) {
      $document.bind('click', closeDropdown);
      $document.bind('keydown', keybindFilter);
    }

    if ( openScope && openScope !== dropdownScope ) {
      openScope.isOpen = false;
    }

    openScope = dropdownScope;
  };

  this.close = function( dropdownScope ) {
    if ( openScope === dropdownScope ) {
      openScope = null;
      $document.unbind('click', closeDropdown);
      $document.unbind('keydown', keybindFilter);
    }
  };

  var closeDropdown = function( evt ) {
    // This method may still be called during the same mouse event that
    // unbound this event handler. So check openScope before proceeding.
    if (!openScope) { return; }

    if( evt && openScope.getAutoClose() === 'disabled' )  { return ; }

    var toggleElement = openScope.getToggleElement();
    if ( evt && toggleElement && toggleElement[0].contains(evt.target) ) {
      return;
    }

    var dropdownElement = openScope.getDropdownElement();
    if (evt && openScope.getAutoClose() === 'outsideClick' &&
      dropdownElement && dropdownElement[0].contains(evt.target)) {
      return;
    }

    openScope.isOpen = false;

    if (!$rootScope.$$phase) {
      openScope.$apply();
    }
  };

  var keybindFilter = function( evt ) {
    if ( evt.which === 27 ) {
      openScope.focusToggleElement();
      closeDropdown();
    }
    else if ( openScope.isKeynavEnabled() && /(38|40)/.test(evt.which) && openScope.isOpen ) {
      evt.preventDefault();
      evt.stopPropagation();
      openScope.focusDropdownEntry(evt.which);
    }
  };
}])

.controller('DropdownController', ['$scope', '$attrs', '$parse', 'dropdownConfig', 'dropdownService', '$animate', '$position', '$document', '$compile', '$templateRequest', function($scope, $attrs, $parse, dropdownConfig, dropdownService, $animate, $position, $document, $compile, $templateRequest) {
  var self = this,
    scope = $scope.$new(), // create a child scope so we are not polluting original one
	templateScope,
    openClass = dropdownConfig.openClass,
    getIsOpen,
    setIsOpen = angular.noop,
    toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop,
    appendToBody = false,
    keynavEnabled =false,
    selectedOption = null;

  this.init = function( element ) {
    self.$element = element;

    if ( $attrs.isOpen ) {
      getIsOpen = $parse($attrs.isOpen);
      setIsOpen = getIsOpen.assign;

      $scope.$watch(getIsOpen, function(value) {
        scope.isOpen = !!value;
      });
    }

    appendToBody = angular.isDefined($attrs.dropdownAppendToBody);
    keynavEnabled = angular.isDefined($attrs.keyboardNav);

    if ( appendToBody && self.dropdownMenu ) {
      $document.find('body').append( self.dropdownMenu );
      element.on('$destroy', function handleDestroyEvent() {
        self.dropdownMenu.remove();
      });
    }
  };

  this.toggle = function( open ) {
    return scope.isOpen = arguments.length ? !!open : !scope.isOpen;
  };

  // Allow other directives to watch status
  this.isOpen = function() {
    return scope.isOpen;
  };

  scope.getToggleElement = function() {
    return self.toggleElement;
  };

  scope.getAutoClose = function() {
    return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled'
  };

  scope.getElement = function() {
    return self.$element;
  };

  scope.isKeynavEnabled = function() {
    return keynavEnabled;
  };

  scope.focusDropdownEntry = function(keyCode) {
    var elems = self.dropdownMenu ? //If append to body is used.
      (angular.element(self.dropdownMenu).find('a')) :
      (angular.element(self.$element).find('ul').eq(0).find('a'));

    switch (keyCode) {
      case (40): {
        if ( !angular.isNumber(self.selectedOption)) {
          self.selectedOption = 0;
        } else {
          self.selectedOption = (self.selectedOption === elems.length -1 ?
            self.selectedOption :
            self.selectedOption + 1);
        }
        break;
      }
      case (38): {
        if ( !angular.isNumber(self.selectedOption)) {
          return;
        } else {
          self.selectedOption = (self.selectedOption === 0 ?
            0 :
            self.selectedOption - 1);
        }
        break;
      }
    }
    elems[self.selectedOption].focus();
  };

  scope.getDropdownElement = function() {
    return self.dropdownMenu;
  };

  scope.focusToggleElement = function() {
    if ( self.toggleElement ) {
      self.toggleElement[0].focus();
    }
  };

  scope.$watch('isOpen', function( isOpen, wasOpen ) {
    if (appendToBody && self.dropdownMenu) {
        var pos = $position.positionElements(self.$element, self.dropdownMenu, 'bottom-left', true);
        var css = {
            top: pos.top + 'px',
            display: isOpen ? 'block' : 'none'
        };

        var rightalign = self.dropdownMenu.hasClass('dropdown-menu-right');
        if (!rightalign) {
            css.left = pos.left + 'px';
            css.right = 'auto';
        } else {
            css.left = 'auto';
            css.right = (window.innerWidth - (pos.left + self.$element.prop('offsetWidth'))) + 'px';
        }

        self.dropdownMenu.css(css);
    }

    $animate[isOpen ? 'addClass' : 'removeClass'](self.$element, openClass).then(function() {
        if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
           toggleInvoker($scope, { open: !!isOpen });
        }
    });

    if ( isOpen ) {
      if (self.dropdownMenuTemplateUrl) {
        $templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) {
          templateScope = scope.$new();
          $compile(tplContent.trim())(templateScope, function(dropdownElement) {
            var newEl = dropdownElement;
            self.dropdownMenu.replaceWith(newEl);
            self.dropdownMenu = newEl;
          });
        });
      }

      scope.focusToggleElement();
      dropdownService.open( scope );
    } else {
      if (self.dropdownMenuTemplateUrl) {
        if (templateScope) {
          templateScope.$destroy();
        }
        var newEl = angular.element('<ul class="dropdown-menu"></ul>');
        self.dropdownMenu.replaceWith(newEl);
        self.dropdownMenu = newEl;
      }

      dropdownService.close( scope );
      self.selectedOption = null;
    }

    setIsOpen($scope, isOpen);
  });

  $scope.$on('$locationChangeSuccess', function() {
    if (scope.getAutoClose() !== 'disabled') {
      scope.isOpen = false;
    }
  });

  $scope.$on('$destroy', function() {
    scope.$destroy();
  });
}])

.directive('dropdown', function() {
  return {
    controller: 'DropdownController',
    link: function(scope, element, attrs, dropdownCtrl) {
      dropdownCtrl.init( element );
      element.addClass('dropdown');
    }
  };
})

.directive('dropdownMenu', function() {
  return {
    restrict: 'AC',
    require: '?^dropdown',
    link: function(scope, element, attrs, dropdownCtrl) {
      if (!dropdownCtrl) {
        return;
      }
      var tplUrl = attrs.templateUrl;
      if (tplUrl) {
        dropdownCtrl.dropdownMenuTemplateUrl = tplUrl;
      }
      if (!dropdownCtrl.dropdownMenu) {
        dropdownCtrl.dropdownMenu = element;
      }
    }
  };
})

.directive('keyboardNav', function() {
  return {
    restrict: 'A',
    require: '?^dropdown',
    link: function (scope, element, attrs, dropdownCtrl) {

      element.bind('keydown', function(e) {

        if ([38, 40].indexOf(e.which) !== -1) {

          e.preventDefault();
          e.stopPropagation();

          var elems = angular.element(element).find('a');

          switch (e.keyCode) {
            case (40): { // Down
              if ( !angular.isNumber(dropdownCtrl.selectedOption)) {
                dropdownCtrl.selectedOption = 0;
              } else {
                dropdownCtrl.selectedOption = (dropdownCtrl.selectedOption === elems.length -1 ? dropdownCtrl.selectedOption : dropdownCtrl.selectedOption+1);
              }

            }
            break;
            case (38): { // Up
              dropdownCtrl.selectedOption = (dropdownCtrl.selectedOption === 0 ? 0 : dropdownCtrl.selectedOption-1);
            }
            break;
          }
          elems[dropdownCtrl.selectedOption].focus();
        }
      });
    }

  };
})

.directive('dropdownToggle', function() {
  return {
    require: '?^dropdown',
    link: function(scope, element, attrs, dropdownCtrl) {
      if ( !dropdownCtrl ) {
        return;
      }

      element.addClass('dropdown-toggle');

      dropdownCtrl.toggleElement = element;

      var toggleDropdown = function(event) {
        event.preventDefault();

        if ( !element.hasClass('disabled') && !attrs.disabled ) {
          scope.$apply(function() {
            dropdownCtrl.toggle();
          });
        }
      };

      element.bind('click', toggleDropdown);

      // WAI-ARIA
      element.attr({ 'aria-haspopup': true, 'aria-expanded': false });
      scope.$watch(dropdownCtrl.isOpen, function( isOpen ) {
        element.attr('aria-expanded', !!isOpen);
      });

      scope.$on('$destroy', function() {
        element.unbind('click', toggleDropdown);
      });
    }
  };
});

angular.module('ui.bootstrap.modal', [])

/**
 * A helper, internal data structure that acts as a map but also allows getting / removing
 * elements in the LIFO order
 */
  .factory('$$stackedMap', function () {
    return {
      createNew: function () {
        var stack = [];

        return {
          add: function (key, value) {
            stack.push({
              key: key,
              value: value
            });
          },
          get: function (key) {
            for (var i = 0; i < stack.length; i++) {
              if (key == stack[i].key) {
                return stack[i];
              }
            }
          },
          keys: function() {
            var keys = [];
            for (var i = 0; i < stack.length; i++) {
              keys.push(stack[i].key);
            }
            return keys;
          },
          top: function () {
            return stack[stack.length - 1];
          },
          remove: function (key) {
            var idx = -1;
            for (var i = 0; i < stack.length; i++) {
              if (key == stack[i].key) {
                idx = i;
                break;
              }
            }
            return stack.splice(idx, 1)[0];
          },
          removeTop: function () {
            return stack.splice(stack.length - 1, 1)[0];
          },
          length: function () {
            return stack.length;
          }
        };
      }
    };
  })

/**
 * A helper directive for the $modal service. It creates a backdrop element.
 */
  .directive('modalBackdrop', [
           '$animate', '$modalStack',
  function ($animate ,  $modalStack) {
    return {
      restrict: 'EA',
      replace: true,
      templateUrl: 'template/modal/backdrop.html',
      compile: function (tElement, tAttrs) {
        tElement.addClass(tAttrs.backdropClass);
        return linkFn;
      }
    };

    function linkFn(scope, element, attrs) {
      if (attrs.modalInClass) {
        $animate.addClass(element, attrs.modalInClass);

        scope.$on($modalStack.NOW_CLOSING_EVENT, function (e, setIsAsync) {
          var done = setIsAsync();
          $animate.removeClass(element, attrs.modalInClass).then(done);
        });
      }
    }
  }])

  .directive('modalWindow', [
           '$modalStack', '$q', '$animate',
  function ($modalStack ,  $q ,  $animate) {
    return {
      restrict: 'EA',
      scope: {
        index: '@'
      },
      replace: true,
      transclude: true,
      templateUrl: function(tElement, tAttrs) {
        return tAttrs.templateUrl || 'template/modal/window.html';
      },
      link: function (scope, element, attrs) {
        element.addClass(attrs.windowClass || '');
        scope.size = attrs.size;

        scope.close = function (evt) {
          var modal = $modalStack.getTop();
          if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) {
            evt.preventDefault();
            evt.stopPropagation();
            $modalStack.dismiss(modal.key, 'backdrop click');
          }
        };

        // This property is only added to the scope for the purpose of detecting when this directive is rendered.
        // We can detect that by using this property in the template associated with this directive and then use
        // {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}.
        scope.$isRendered = true;

        // Deferred object that will be resolved when this modal is render.
        var modalRenderDeferObj = $q.defer();
        // Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready.
        // In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template.
        attrs.$observe('modalRender', function (value) {
          if (value == 'true') {
            modalRenderDeferObj.resolve();
          }
        });

        modalRenderDeferObj.promise.then(function () {
          if (attrs.modalInClass) {
            $animate.addClass(element, attrs.modalInClass);

            scope.$on($modalStack.NOW_CLOSING_EVENT, function (e, setIsAsync) {
              var done = setIsAsync();
              $animate.removeClass(element, attrs.modalInClass).then(done);
            });
          }

          var inputsWithAutofocus = element[0].querySelectorAll('[autofocus]');
          /**
           * Auto-focusing of a freshly-opened modal element causes any child elements
           * with the autofocus attribute to lose focus. This is an issue on touch
           * based devices which will show and then hide the onscreen keyboard.
           * Attempts to refocus the autofocus element via JavaScript will not reopen
           * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus
           * the modal element if the modal does not contain an autofocus element.
           */
          if (inputsWithAutofocus.length) {
            inputsWithAutofocus[0].focus();
          } else {
            element[0].focus();
          }

          // Notify {@link $modalStack} that modal is rendered.
          var modal = $modalStack.getTop();
          if (modal) {
            $modalStack.modalRendered(modal.key);
          }
        });
      }
    };
  }])

  .directive('modalAnimationClass', [
    function () {
      return {
        compile: function (tElement, tAttrs) {
          if (tAttrs.modalAnimation) {
            tElement.addClass(tAttrs.modalAnimationClass);
          }
        }
      };
    }])

  .directive('modalTransclude', function () {
    return {
      link: function($scope, $element, $attrs, controller, $transclude) {
        $transclude($scope.$parent, function(clone) {
          $element.empty();
          $element.append(clone);
        });
      }
    };
  })

  .factory('$modalStack', [
             '$animate', '$timeout', '$document', '$compile', '$rootScope',
             '$q',
             '$$stackedMap',
    function ($animate ,  $timeout ,  $document ,  $compile ,  $rootScope ,
              $q,
              $$stackedMap) {

      var OPENED_MODAL_CLASS = 'modal-open';

      var backdropDomEl, backdropScope;
      var openedWindows = $$stackedMap.createNew();
      var $modalStack = {
        NOW_CLOSING_EVENT: 'modal.stack.now-closing'
      };

      function backdropIndex() {
        var topBackdropIndex = -1;
        var opened = openedWindows.keys();
        for (var i = 0; i < opened.length; i++) {
          if (openedWindows.get(opened[i]).value.backdrop) {
            topBackdropIndex = i;
          }
        }
        return topBackdropIndex;
      }

      $rootScope.$watch(backdropIndex, function(newBackdropIndex){
        if (backdropScope) {
          backdropScope.index = newBackdropIndex;
        }
      });

      function removeModalWindow(modalInstance, elementToReceiveFocus) {

        var body = $document.find('body').eq(0);
        var modalWindow = openedWindows.get(modalInstance).value;

        //clean up the stack
        openedWindows.remove(modalInstance);

        removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, function() {
          body.toggleClass(OPENED_MODAL_CLASS, openedWindows.length() > 0);
          checkRemoveBackdrop();
        });

        //move focus to specified element if available, or else to body
        if (elementToReceiveFocus && elementToReceiveFocus.focus) {
          elementToReceiveFocus.focus();
        } else {
          body.focus();
        }
      }

      function checkRemoveBackdrop() {
          //remove backdrop if no longer needed
          if (backdropDomEl && backdropIndex() == -1) {
            var backdropScopeRef = backdropScope;
            removeAfterAnimate(backdropDomEl, backdropScope, function () {
              backdropScopeRef = null;
            });
            backdropDomEl = undefined;
            backdropScope = undefined;
          }
      }

      function removeAfterAnimate(domEl, scope, done) {
        var asyncDeferred;
        var asyncPromise = null;
        var setIsAsync = function () {
          if (!asyncDeferred) {
            asyncDeferred = $q.defer();
            asyncPromise = asyncDeferred.promise;
          }

          return function asyncDone() {
            asyncDeferred.resolve();
          };
        };
        scope.$broadcast($modalStack.NOW_CLOSING_EVENT, setIsAsync);

        // Note that it's intentional that asyncPromise might be null.
        // That's when setIsAsync has not been called during the
        // NOW_CLOSING_EVENT broadcast.
        return $q.when(asyncPromise).then(afterAnimating);

        function afterAnimating() {
          if (afterAnimating.done) {
            return;
          }
          afterAnimating.done = true;

          domEl.remove();
          scope.$destroy();
          if (done) {
            done();
          }
        }
      }

      $document.bind('keydown', function (evt) {
        var modal;

        if (evt.which === 27) {
          modal = openedWindows.top();
          if (modal && modal.value.keyboard) {
            evt.preventDefault();
            $rootScope.$apply(function () {
              $modalStack.dismiss(modal.key, 'escape key press');
            });
          }
        }
      });

      $modalStack.open = function (modalInstance, modal) {

        var modalOpener = $document[0].activeElement;

        openedWindows.add(modalInstance, {
          deferred: modal.deferred,
          renderDeferred: modal.renderDeferred,
          modalScope: modal.scope,
          backdrop: modal.backdrop,
          keyboard: modal.keyboard
        });

        var body = $document.find('body').eq(0),
            currBackdropIndex = backdropIndex();

        if (currBackdropIndex >= 0 && !backdropDomEl) {
          backdropScope = $rootScope.$new(true);
          backdropScope.index = currBackdropIndex;
          var angularBackgroundDomEl = angular.element('<div modal-backdrop="modal-backdrop"></div>');
          angularBackgroundDomEl.attr('backdrop-class', modal.backdropClass);
          if (modal.animation) {
            angularBackgroundDomEl.attr('modal-animation', 'true');
          }
          backdropDomEl = $compile(angularBackgroundDomEl)(backdropScope);
          body.append(backdropDomEl);
        }

        var angularDomEl = angular.element('<div modal-window="modal-window"></div>');
        angularDomEl.attr({
          'template-url': modal.windowTemplateUrl,
          'window-class': modal.windowClass,
          'size': modal.size,
          'index': openedWindows.length() - 1,
          'animate': 'animate'
        }).html(modal.content);
        if (modal.animation) {
          angularDomEl.attr('modal-animation', 'true');
        }

        var modalDomEl = $compile(angularDomEl)(modal.scope);
        openedWindows.top().value.modalDomEl = modalDomEl;
        openedWindows.top().value.modalOpener = modalOpener;
        body.append(modalDomEl);
        body.addClass(OPENED_MODAL_CLASS);
      };

      function broadcastClosing(modalWindow, resultOrReason, closing) {
          return !modalWindow.value.modalScope.$broadcast('modal.closing', resultOrReason, closing).defaultPrevented;
      }

      $modalStack.close = function (modalInstance, result) {
        var modalWindow = openedWindows.get(modalInstance);
        if (modalWindow && broadcastClosing(modalWindow, result, true)) {
          modalWindow.value.deferred.resolve(result);
          removeModalWindow(modalInstance, modalWindow.value.modalOpener);
          return true;
        }
        return !modalWindow;
      };

      $modalStack.dismiss = function (modalInstance, reason) {
        var modalWindow = openedWindows.get(modalInstance);
        if (modalWindow && broadcastClosing(modalWindow, reason, false)) {
          modalWindow.value.deferred.reject(reason);
          removeModalWindow(modalInstance, modalWindow.value.modalOpener);
          return true;
        }
        return !modalWindow;
      };

      $modalStack.dismissAll = function (reason) {
        var topModal = this.getTop();
        while (topModal && this.dismiss(topModal.key, reason)) {
          topModal = this.getTop();
        }
      };

      $modalStack.getTop = function () {
        return openedWindows.top();
      };

      $modalStack.modalRendered = function (modalInstance) {
        var modalWindow = openedWindows.get(modalInstance);
        if (modalWindow) {
          modalWindow.value.renderDeferred.resolve();
        }
      };

      return $modalStack;
    }])

  .provider('$modal', function () {

    var $modalProvider = {
      options: {
        animation: true,
        backdrop: true, //can also be false or 'static'
        keyboard: true
      },
      $get: ['$injector', '$rootScope', '$q', '$templateRequest', '$controller', '$modalStack',
        function ($injector, $rootScope, $q, $templateRequest, $controller, $modalStack) {

          var $modal = {};

          function getTemplatePromise(options) {
            return options.template ? $q.when(options.template) :
              $templateRequest(angular.isFunction(options.templateUrl) ? (options.templateUrl)() : options.templateUrl);
          }

          function getResolvePromises(resolves) {
            var promisesArr = [];
            angular.forEach(resolves, function (value) {
              if (angular.isFunction(value) || angular.isArray(value)) {
                promisesArr.push($q.when($injector.invoke(value)));
              }
            });
            return promisesArr;
          }

          $modal.open = function (modalOptions) {

            var modalResultDeferred = $q.defer();
            var modalOpenedDeferred = $q.defer();
            var modalRenderDeferred = $q.defer();

            //prepare an instance of a modal to be injected into controllers and returned to a caller
            var modalInstance = {
              result: modalResultDeferred.promise,
              opened: modalOpenedDeferred.promise,
              rendered: modalRenderDeferred.promise,
              close: function (result) {
                return $modalStack.close(modalInstance, result);
              },
              dismiss: function (reason) {
                return $modalStack.dismiss(modalInstance, reason);
              }
            };

            //merge and clean up options
            modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
            modalOptions.resolve = modalOptions.resolve || {};

            //verify options
            if (!modalOptions.template && !modalOptions.templateUrl) {
              throw new Error('One of template or templateUrl options is required.');
            }

            var templateAndResolvePromise =
              $q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));


            templateAndResolvePromise.then(function resolveSuccess(tplAndVars) {

              var modalScope = (modalOptions.scope || $rootScope).$new();
              modalScope.$close = modalInstance.close;
              modalScope.$dismiss = modalInstance.dismiss;

              var ctrlInstance, ctrlLocals = {};
              var resolveIter = 1;

              //controllers
              if (modalOptions.controller) {
                ctrlLocals.$scope = modalScope;
                ctrlLocals.$modalInstance = modalInstance;
                angular.forEach(modalOptions.resolve, function (value, key) {
                  ctrlLocals[key] = tplAndVars[resolveIter++];
                });

                ctrlInstance = $controller(modalOptions.controller, ctrlLocals);
                if (modalOptions.controllerAs) {
                  if (modalOptions.bindToController) {
                    angular.extend(modalScope, ctrlInstance);
                  } else {
                    modalScope[modalOptions.controllerAs] = ctrlInstance;
                  }
                }
              }

              $modalStack.open(modalInstance, {
                scope: modalScope,
                deferred: modalResultDeferred,
                renderDeferred: modalRenderDeferred,
                content: tplAndVars[0],
                animation: modalOptions.animation,
                backdrop: modalOptions.backdrop,
                keyboard: modalOptions.keyboard,
                backdropClass: modalOptions.backdropClass,
                windowClass: modalOptions.windowClass,
                windowTemplateUrl: modalOptions.windowTemplateUrl,
                size: modalOptions.size
              });

            }, function resolveError(reason) {
              modalResultDeferred.reject(reason);
            });

            templateAndResolvePromise.then(function () {
              modalOpenedDeferred.resolve(true);
            }, function (reason) {
              modalOpenedDeferred.reject(reason);
            });

            return modalInstance;
          };

          return $modal;
        }]
    };

    return $modalProvider;
  });

angular.module('ui.bootstrap.pagination', [])
.controller('PaginationController', ['$scope', '$attrs', '$parse', function ($scope, $attrs, $parse) {
  var self = this,
      ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
      setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop;

  this.init = function(ngModelCtrl_, config) {
    ngModelCtrl = ngModelCtrl_;
    this.config = config;

    ngModelCtrl.$render = function() {
      self.render();
    };

    if ($attrs.itemsPerPage) {
      $scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) {
        self.itemsPerPage = parseInt(value, 10);
        $scope.totalPages = self.calculateTotalPages();
      });
    } else {
      this.itemsPerPage = config.itemsPerPage;
    }

    $scope.$watch('totalItems', function() {
      $scope.totalPages = self.calculateTotalPages();
    });

    $scope.$watch('totalPages', function(value) {
      setNumPages($scope.$parent, value); // Readonly variable

      if ( $scope.page > value ) {
        $scope.selectPage(value);
      } else {
        ngModelCtrl.$render();
      }
    });
  };

  this.calculateTotalPages = function() {
    var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage);
    return Math.max(totalPages || 0, 1);
  };

  this.render = function() {
    $scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1;
  };

  $scope.selectPage = function(page, evt) {
    var clickAllowed = !$scope.ngDisabled || !evt;
    if (clickAllowed && $scope.page !== page && page > 0 && page <= $scope.totalPages) {
      if (evt && evt.target) {
        evt.target.blur();
      }
      ngModelCtrl.$setViewValue(page);
      ngModelCtrl.$render();
    }
  };

  $scope.getText = function( key ) {
    return $scope[key + 'Text'] || self.config[key + 'Text'];
  };
  $scope.noPrevious = function() {
    return $scope.page === 1;
  };
  $scope.noNext = function() {
    return $scope.page === $scope.totalPages;
  };
}])

.constant('paginationConfig', {
  itemsPerPage: 10,
  boundaryLinks: false,
  directionLinks: true,
  firstText: 'First',
  previousText: 'Previous',
  nextText: 'Next',
  lastText: 'Last',
  rotate: true
})

.directive('pagination', ['$parse', 'paginationConfig', function($parse, paginationConfig) {
  return {
    restrict: 'EA',
    scope: {
      totalItems: '=',
      firstText: '@',
      previousText: '@',
      nextText: '@',
      lastText: '@',
      ngDisabled:'='
    },
    require: ['pagination', '?ngModel'],
    controller: 'PaginationController',
    templateUrl: 'template/pagination/pagination.html',
    replace: true,
    link: function(scope, element, attrs, ctrls) {
      var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];

      if (!ngModelCtrl) {
         return; // do nothing if no ng-model
      }

      // Setup configuration parameters
      var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize,
          rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate;
      scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks;
      scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks;

      paginationCtrl.init(ngModelCtrl, paginationConfig);

      if (attrs.maxSize) {
        scope.$parent.$watch($parse(attrs.maxSize), function(value) {
          maxSize = parseInt(value, 10);
          paginationCtrl.render();
        });
      }

      // Create page object used in template
      function makePage(number, text, isActive) {
        return {
          number: number,
          text: text,
          active: isActive
        };
      }

      function getPages(currentPage, totalPages) {
        var pages = [];

        // Default page limits
        var startPage = 1, endPage = totalPages;
        var isMaxSized = ( angular.isDefined(maxSize) && maxSize < totalPages );

        // recompute if maxSize
        if ( isMaxSized ) {
          if ( rotate ) {
            // Current page is displayed in the middle of the visible ones
            startPage = Math.max(currentPage - Math.floor(maxSize/2), 1);
            endPage   = startPage + maxSize - 1;

            // Adjust if limit is exceeded
            if (endPage > totalPages) {
              endPage   = totalPages;
              startPage = endPage - maxSize + 1;
            }
          } else {
            // Visible pages are paginated with maxSize
            startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1;

            // Adjust last page if limit is exceeded
            endPage = Math.min(startPage + maxSize - 1, totalPages);
          }
        }

        // Add page number links
        for (var number = startPage; number <= endPage; number++) {
          var page = makePage(number, number, number === currentPage);
          pages.push(page);
        }

        // Add links to move between page sets
        if ( isMaxSized && ! rotate ) {
          if ( startPage > 1 ) {
            var previousPageSet = makePage(startPage - 1, '...', false);
            pages.unshift(previousPageSet);
          }

          if ( endPage < totalPages ) {
            var nextPageSet = makePage(endPage + 1, '...', false);
            pages.push(nextPageSet);
          }
        }

        return pages;
      }

      var originalRender = paginationCtrl.render;
      paginationCtrl.render = function() {
        originalRender();
        if (scope.page > 0 && scope.page <= scope.totalPages) {
          scope.pages = getPages(scope.page, scope.totalPages);
        }
      };
    }
  };
}])

.constant('pagerConfig', {
  itemsPerPage: 10,
  previousText: '« Previous',
  nextText: 'Next »',
  align: true
})

.directive('pager', ['pagerConfig', function(pagerConfig) {
  return {
    restrict: 'EA',
    scope: {
      totalItems: '=',
      previousText: '@',
      nextText: '@'
    },
    require: ['pager', '?ngModel'],
    controller: 'PaginationController',
    templateUrl: 'template/pagination/pager.html',
    replace: true,
    link: function(scope, element, attrs, ctrls) {
      var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];

      if (!ngModelCtrl) {
         return; // do nothing if no ng-model
      }

      scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align;
      paginationCtrl.init(ngModelCtrl, pagerConfig);
    }
  };
}]);

/**
 * The following features are still outstanding: animation as a
 * function, placement as a function, inside, support for more triggers than
 * just mouse enter/leave, html tooltips, and selector delegation.
 */
angular.module( 'ui.bootstrap.tooltip', [ 'ui.bootstrap.position', 'ui.bootstrap.bindHtml' ] )

/**
 * The $tooltip service creates tooltip- and popover-like directives as well as
 * houses global options for them.
 */
.provider( '$tooltip', function () {
  // The default options tooltip and popover.
  var defaultOptions = {
    placement: 'top',
    animation: true,
    popupDelay: 0,
    useContentExp: false
  };

  // Default hide triggers for each show trigger
  var triggerMap = {
    'mouseenter': 'mouseleave',
    'click': 'click',
    'focus': 'blur'
  };

  // The options specified to the provider globally.
  var globalOptions = {};

  /**
   * `options({})` allows global configuration of all tooltips in the
   * application.
   *
   *   var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) {
   *     // place tooltips left instead of top by default
   *     $tooltipProvider.options( { placement: 'left' } );
   *   });
   */
	this.options = function( value ) {
		angular.extend( globalOptions, value );
	};

  /**
   * This allows you to extend the set of trigger mappings available. E.g.:
   *
   *   $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' );
   */
  this.setTriggers = function setTriggers ( triggers ) {
    angular.extend( triggerMap, triggers );
  };

  /**
   * This is a helper function for translating camel-case to snake-case.
   */
  function snake_case(name){
    var regexp = /[A-Z]/g;
    var separator = '-';
    return name.replace(regexp, function(letter, pos) {
      return (pos ? separator : '') + letter.toLowerCase();
    });
  }

  /**
   * Returns the actual instance of the $tooltip service.
   * TODO support multiple triggers
   */
  this.$get = [ '$window', '$compile', '$timeout', '$document', '$position', '$interpolate', function ( $window, $compile, $timeout, $document, $position, $interpolate ) {
    return function $tooltip ( type, prefix, defaultTriggerShow, options ) {
      options = angular.extend( {}, defaultOptions, globalOptions, options );

      /**
       * Returns an object of show and hide triggers.
       *
       * If a trigger is supplied,
       * it is used to show the tooltip; otherwise, it will use the `trigger`
       * option passed to the `$tooltipProvider.options` method; else it will
       * default to the trigger supplied to this directive factory.
       *
       * The hide trigger is based on the show trigger. If the `trigger` option
       * was passed to the `$tooltipProvider.options` method, it will use the
       * mapped trigger from `triggerMap` or the passed trigger if the map is
       * undefined; otherwise, it uses the `triggerMap` value of the show
       * trigger; else it will just use the show trigger.
       */
      function getTriggers ( trigger ) {
        var show = trigger || options.trigger || defaultTriggerShow;
        var hide = triggerMap[show] || show;
        return {
          show: show,
          hide: hide
        };
      }

      var directiveName = snake_case( type );

      var startSym = $interpolate.startSymbol();
      var endSym = $interpolate.endSymbol();
      var template =
        '<div '+ directiveName +'-popup '+
          'title="'+startSym+'title'+endSym+'" '+
          (options.useContentExp ?
            'content-exp="contentExp()" ' :
            'content="'+startSym+'content'+endSym+'" ') +
          'placement="'+startSym+'placement'+endSym+'" '+
          'popup-class="'+startSym+'popupClass'+endSym+'" '+
          'animation="animation" '+
          'is-open="isOpen"'+
          'origin-scope="origScope" '+
          '>'+
        '</div>';

      return {
        restrict: 'EA',
        compile: function (tElem, tAttrs) {
          var tooltipLinker = $compile( template );

          return function link ( scope, element, attrs, tooltipCtrl ) {
            var tooltip;
            var tooltipLinkedScope;
            var transitionTimeout;
            var popupTimeout;
            var appendToBody = angular.isDefined( options.appendToBody ) ? options.appendToBody : false;
            var triggers = getTriggers( undefined );
            var hasEnableExp = angular.isDefined(attrs[prefix+'Enable']);
            var ttScope = scope.$new(true);

            var positionTooltip = function () {
              if (!tooltip) { return; }

              var ttPosition = $position.positionElements(element, tooltip, ttScope.placement, appendToBody);
              ttPosition.top += 'px';
              ttPosition.left += 'px';

              // Now set the calculated positioning.
              tooltip.css( ttPosition );
            };

            // Set up the correct scope to allow transclusion later
            ttScope.origScope = scope;

            // By default, the tooltip is not open.
            // TODO add ability to start tooltip opened
            ttScope.isOpen = false;

            function toggleTooltipBind () {
              if ( ! ttScope.isOpen ) {
                showTooltipBind();
              } else {
                hideTooltipBind();
              }
            }

            // Show the tooltip with delay if specified, otherwise show it immediately
            function showTooltipBind() {
              if(hasEnableExp && !scope.$eval(attrs[prefix+'Enable'])) {
                return;
              }

              prepareTooltip();

              if ( ttScope.popupDelay ) {
                // Do nothing if the tooltip was already scheduled to pop-up.
                // This happens if show is triggered multiple times before any hide is triggered.
                if (!popupTimeout) {
                  popupTimeout = $timeout( show, ttScope.popupDelay, false );
                  popupTimeout.then(function(reposition){reposition();});
                }
              } else {
                show()();
              }
            }

            function hideTooltipBind () {
              scope.$apply(function () {
                hide();
              });
            }

            // Show the tooltip popup element.
            function show() {

              popupTimeout = null;

              // If there is a pending remove transition, we must cancel it, lest the
              // tooltip be mysteriously removed.
              if ( transitionTimeout ) {
                $timeout.cancel( transitionTimeout );
                transitionTimeout = null;
              }

              // Don't show empty tooltips.
              if ( !(options.useContentExp ? ttScope.contentExp() : ttScope.content) ) {
                return angular.noop;
              }

              createTooltip();

              // Set the initial positioning.
              tooltip.css({ top: 0, left: 0, display: 'block' });
              ttScope.$digest();

              positionTooltip();

              // And show the tooltip.
              ttScope.isOpen = true;
              ttScope.$apply(); // digest required as $apply is not called

              // Return positioning function as promise callback for correct
              // positioning after draw.
              return positionTooltip;
            }

            // Hide the tooltip popup element.
            function hide() {
              // First things first: we don't show it anymore.
              ttScope.isOpen = false;

              //if tooltip is going to be shown after delay, we must cancel this
              $timeout.cancel( popupTimeout );
              popupTimeout = null;

              // And now we remove it from the DOM. However, if we have animation, we
              // need to wait for it to expire beforehand.
              // FIXME: this is a placeholder for a port of the transitions library.
              if ( ttScope.animation ) {
                if (!transitionTimeout) {
                  transitionTimeout = $timeout(removeTooltip, 500);
                }
              } else {
                removeTooltip();
              }
            }

            function createTooltip() {
              // There can only be one tooltip element per directive shown at once.
              if (tooltip) {
                removeTooltip();
              }
              tooltipLinkedScope = ttScope.$new();
              tooltip = tooltipLinker(tooltipLinkedScope, function (tooltip) {
                if ( appendToBody ) {
                  $document.find( 'body' ).append( tooltip );
                } else {
                  element.after( tooltip );
                }
              });

              tooltipLinkedScope.$watch(function () {
                $timeout(positionTooltip, 0, false);
              });

              if (options.useContentExp) {
                tooltipLinkedScope.$watch('contentExp()', function (val) {
                  if (!val && ttScope.isOpen ) {
                    hide();
                  }
                });
              }
            }

            function removeTooltip() {
              transitionTimeout = null;
              if (tooltip) {
                tooltip.remove();
                tooltip = null;
              }
              if (tooltipLinkedScope) {
                tooltipLinkedScope.$destroy();
                tooltipLinkedScope = null;
              }
            }

            function prepareTooltip() {
              prepPopupClass();
              prepPlacement();
              prepPopupDelay();
            }

            ttScope.contentExp = function () {
              return scope.$eval(attrs[type]);
            };

            /**
             * Observe the relevant attributes.
             */
            if (!options.useContentExp) {
              attrs.$observe( type, function ( val ) {
                ttScope.content = val;

                if (!val && ttScope.isOpen ) {
                  hide();
                }
              });
            }

            attrs.$observe( 'disabled', function ( val ) {
              if (val && ttScope.isOpen ) {
                hide();
              }
            });

            attrs.$observe( prefix+'Title', function ( val ) {
              ttScope.title = val;
            });

            function prepPopupClass() {
              ttScope.popupClass = attrs[prefix + 'Class'];
            }

            function prepPlacement() {
              var val = attrs[ prefix + 'Placement' ];
              ttScope.placement = angular.isDefined( val ) ? val : options.placement;
            }

            function prepPopupDelay() {
              var val = attrs[ prefix + 'PopupDelay' ];
              var delay = parseInt( val, 10 );
              ttScope.popupDelay = ! isNaN(delay) ? delay : options.popupDelay;
            }

            var unregisterTriggers = function () {
              element.unbind(triggers.show, showTooltipBind);
              element.unbind(triggers.hide, hideTooltipBind);
            };

            function prepTriggers() {
              var val = attrs[ prefix + 'Trigger' ];
              unregisterTriggers();

              triggers = getTriggers( val );

              if ( triggers.show === triggers.hide ) {
                element.bind( triggers.show, toggleTooltipBind );
              } else {
                element.bind( triggers.show, showTooltipBind );
                element.bind( triggers.hide, hideTooltipBind );
              }
            }
            prepTriggers();

            var animation = scope.$eval(attrs[prefix + 'Animation']);
            ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation;

            var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']);
            appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody;

            // if a tooltip is attached to <body> we need to remove it on
            // location change as its parent scope will probably not be destroyed
            // by the change.
            if ( appendToBody ) {
              scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess () {
              if ( ttScope.isOpen ) {
                hide();
              }
            });
            }

            // Make sure tooltip is destroyed and removed.
            scope.$on('$destroy', function onDestroyTooltip() {
              $timeout.cancel( transitionTimeout );
              $timeout.cancel( popupTimeout );
              unregisterTriggers();
              removeTooltip();
              ttScope = null;
            });
          };
        }
      };
    };
  }];
})

// This is mostly ngInclude code but with a custom scope
.directive( 'tooltipTemplateTransclude', [
         '$animate', '$sce', '$compile', '$templateRequest',
function ($animate ,  $sce ,  $compile ,  $templateRequest) {
  return {
    link: function ( scope, elem, attrs ) {
      var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope);

      var changeCounter = 0,
        currentScope,
        previousElement,
        currentElement;

      var cleanupLastIncludeContent = function() {
        if (previousElement) {
          previousElement.remove();
          previousElement = null;
        }
        if (currentScope) {
          currentScope.$destroy();
          currentScope = null;
        }
        if (currentElement) {
          $animate.leave(currentElement).then(function() {
            previousElement = null;
          });
          previousElement = currentElement;
          currentElement = null;
        }
      };

      scope.$watch($sce.parseAsResourceUrl(attrs.tooltipTemplateTransclude), function (src) {
        var thisChangeId = ++changeCounter;

        if (src) {
          //set the 2nd param to true to ignore the template request error so that the inner
          //contents and scope can be cleaned up.
          $templateRequest(src, true).then(function(response) {
            if (thisChangeId !== changeCounter) { return; }
            var newScope = origScope.$new();
            var template = response;

            var clone = $compile(template)(newScope, function(clone) {
              cleanupLastIncludeContent();
              $animate.enter(clone, elem);
            });

            currentScope = newScope;
            currentElement = clone;

            currentScope.$emit('$includeContentLoaded', src);
          }, function() {
            if (thisChangeId === changeCounter) {
              cleanupLastIncludeContent();
              scope.$emit('$includeContentError', src);
            }
          });
          scope.$emit('$includeContentRequested', src);
        } else {
          cleanupLastIncludeContent();
        }
      });

      scope.$on('$destroy', cleanupLastIncludeContent);
    }
  };
}])

/**
 * Note that it's intentional that these classes are *not* applied through $animate.
 * They must not be animated as they're expected to be present on the tooltip on
 * initialization.
 */
.directive('tooltipClasses', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      if (scope.placement) {
        element.addClass(scope.placement);
      }
      if (scope.popupClass) {
        element.addClass(scope.popupClass);
      }
      if (scope.animation()) {
        element.addClass(attrs.tooltipAnimationClass);
      }
    }
  };
})

.directive( 'tooltipPopup', function () {
  return {
    restrict: 'EA',
    replace: true,
    scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
    templateUrl: 'template/tooltip/tooltip-popup.html'
  };
})

.directive( 'tooltip', [ '$tooltip', function ( $tooltip ) {
  return $tooltip( 'tooltip', 'tooltip', 'mouseenter' );
}])

.directive( 'tooltipTemplatePopup', function () {
  return {
    restrict: 'EA',
    replace: true,
    scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&',
      originScope: '&' },
    templateUrl: 'template/tooltip/tooltip-template-popup.html'
  };
})

.directive( 'tooltipTemplate', [ '$tooltip', function ( $tooltip ) {
  return $tooltip('tooltipTemplate', 'tooltip', 'mouseenter', {
    useContentExp: true
  });
}])

.directive( 'tooltipHtmlPopup', function () {
  return {
    restrict: 'EA',
    replace: true,
    scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
    templateUrl: 'template/tooltip/tooltip-html-popup.html'
  };
})

.directive( 'tooltipHtml', [ '$tooltip', function ( $tooltip ) {
  return $tooltip('tooltipHtml', 'tooltip', 'mouseenter', {
    useContentExp: true
  });
}])

/*
Deprecated
*/
.directive( 'tooltipHtmlUnsafePopup', function () {
  return {
    restrict: 'EA',
    replace: true,
    scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
    templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html'
  };
})

.value('tooltipHtmlUnsafeSuppressDeprecated', false)
.directive( 'tooltipHtmlUnsafe', [
          '$tooltip', 'tooltipHtmlUnsafeSuppressDeprecated', '$log',
function ( $tooltip ,  tooltipHtmlUnsafeSuppressDeprecated ,  $log) {
  if (!tooltipHtmlUnsafeSuppressDeprecated) {
    $log.warn('tooltip-html-unsafe is now deprecated. Use tooltip-html or tooltip-template instead.');
  }
  return $tooltip( 'tooltipHtmlUnsafe', 'tooltip', 'mouseenter' );
}]);

/**
 * The following features are still outstanding: popup delay, animation as a
 * function, placement as a function, inside, support for more triggers than
 * just mouse enter/leave, html popovers, and selector delegatation.
 */
angular.module( 'ui.bootstrap.popover', [ 'ui.bootstrap.tooltip' ] )

.directive( 'popoverTemplatePopup', function () {
  return {
    restrict: 'EA',
    replace: true,
    scope: { title: '@', contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&',
      originScope: '&' },
    templateUrl: 'template/popover/popover-template.html'
  };
})

.directive( 'popoverTemplate', [ '$tooltip', function ( $tooltip ) {
  return $tooltip( 'popoverTemplate', 'popover', 'click', {
    useContentExp: true
  } );
}])

.directive( 'popoverPopup', function () {
  return {
    restrict: 'EA',
    replace: true,
    scope: { title: '@', content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
    templateUrl: 'template/popover/popover.html'
  };
})

.directive( 'popover', [ '$tooltip', function ( $tooltip ) {
  return $tooltip( 'popover', 'popover', 'click' );
}]);

angular.module('ui.bootstrap.progressbar', [])

.constant('progressConfig', {
  animate: true,
  max: 100
})

.controller('ProgressController', ['$scope', '$attrs', 'progressConfig', function($scope, $attrs, progressConfig) {
    var self = this,
        animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate;

    this.bars = [];
    $scope.max = angular.isDefined($scope.max) ? $scope.max : progressConfig.max;

    this.addBar = function(bar, element) {
        if ( !animate ) {
            element.css({'transition': 'none'});
        }

        this.bars.push(bar);

        bar.max = $scope.max;

        bar.$watch('value', function( value ) {
            bar.recalculatePercentage();
        });

        bar.recalculatePercentage = function() {
            bar.percent = +(100 * bar.value / bar.max).toFixed(2);
        };

        bar.$on('$destroy', function() {
            element = null;
            self.removeBar(bar);
        });
    };

    this.removeBar = function(bar) {
        this.bars.splice(this.bars.indexOf(bar), 1);
    };

    $scope.$watch('max', function(max) {
        self.bars.forEach(function (bar) {
            bar.max = $scope.max;
            bar.recalculatePercentage();
        });
    });
}])

.directive('progress', function() {
    return {
        restrict: 'EA',
        replace: true,
        transclude: true,
        controller: 'ProgressController',
        require: 'progress',
        scope: {
          max: '=?'
        },
        templateUrl: 'template/progressbar/progress.html'
    };
})

.directive('bar', function() {
    return {
        restrict: 'EA',
        replace: true,
        transclude: true,
        require: '^progress',
        scope: {
            value: '=',
            type: '@'
        },
        templateUrl: 'template/progressbar/bar.html',
        link: function(scope, element, attrs, progressCtrl) {
            progressCtrl.addBar(scope, element);
        }
    };
})

.directive('progressbar', function() {
    return {
        restrict: 'EA',
        replace: true,
        transclude: true,
        controller: 'ProgressController',
        scope: {
            value: '=',
            max: '=?',
            type: '@'
        },
        templateUrl: 'template/progressbar/progressbar.html',
        link: function(scope, element, attrs, progressCtrl) {
            progressCtrl.addBar(scope, angular.element(element.children()[0]));
        }
    };
});

angular.module('ui.bootstrap.rating', [])

.constant('ratingConfig', {
  max: 5,
  stateOn: null,
  stateOff: null
})

.controller('RatingController', ['$scope', '$attrs', 'ratingConfig', function($scope, $attrs, ratingConfig) {
  var ngModelCtrl  = { $setViewValue: angular.noop };

  this.init = function(ngModelCtrl_) {
    ngModelCtrl = ngModelCtrl_;
    ngModelCtrl.$render = this.render;

    ngModelCtrl.$formatters.push(function(value) {
      if (angular.isNumber(value) && value << 0 !== value) {
        value = Math.round(value);
      }
      return value;
    });

    this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn;
    this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff;

    var ratingStates = angular.isDefined($attrs.ratingStates) ? $scope.$parent.$eval($attrs.ratingStates) :
                        new Array( angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max );
    $scope.range = this.buildTemplateObjects(ratingStates);
  };

  this.buildTemplateObjects = function(states) {
    for (var i = 0, n = states.length; i < n; i++) {
      states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff }, states[i]);
    }
    return states;
  };

  $scope.rate = function(value) {
    if ( !$scope.readonly && value >= 0 && value <= $scope.range.length ) {
      ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue === value ? 0 : value);
      ngModelCtrl.$render();
    }
  };

  $scope.enter = function(value) {
    if ( !$scope.readonly ) {
      $scope.value = value;
    }
    $scope.onHover({value: value});
  };

  $scope.reset = function() {
    $scope.value = ngModelCtrl.$viewValue;
    $scope.onLeave();
  };

  $scope.onKeydown = function(evt) {
    if (/(37|38|39|40)/.test(evt.which)) {
      evt.preventDefault();
      evt.stopPropagation();
      $scope.rate( $scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1) );
    }
  };

  this.render = function() {
    $scope.value = ngModelCtrl.$viewValue;
  };
}])

.directive('rating', function() {
  return {
    restrict: 'EA',
    require: ['rating', 'ngModel'],
    scope: {
      readonly: '=?',
      onHover: '&',
      onLeave: '&'
    },
    controller: 'RatingController',
    templateUrl: 'template/rating/rating.html',
    replace: true,
    link: function(scope, element, attrs, ctrls) {
      var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1];
      ratingCtrl.init( ngModelCtrl );
    }
  };
});

/**
 * @ngdoc overview
 * @name ui.bootstrap.tabs
 *
 * @description
 * AngularJS version of the tabs directive.
 */

angular.module('ui.bootstrap.tabs', [])

.controller('TabsetController', ['$scope', function TabsetCtrl($scope) {
  var ctrl = this,
      tabs = ctrl.tabs = $scope.tabs = [];

  ctrl.select = function(selectedTab) {
    angular.forEach(tabs, function(tab) {
      if (tab.active && tab !== selectedTab) {
        tab.active = false;
        tab.onDeselect();
      }
    });
    selectedTab.active = true;
    selectedTab.onSelect();
  };

  ctrl.addTab = function addTab(tab) {
    tabs.push(tab);
    // we can't run the select function on the first tab
    // since that would select it twice
    if (tabs.length === 1 && tab.active !== false) {
      tab.active = true;
    } else if (tab.active) {
      ctrl.select(tab);
    }
    else {
      tab.active = false;
    }
  };

  ctrl.removeTab = function removeTab(tab) {
    var index = tabs.indexOf(tab);
    //Select a new tab if the tab to be removed is selected and not destroyed
    if (tab.active && tabs.length > 1 && !destroyed) {
      //If this is the last tab, select the previous tab. else, the next tab.
      var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1;
      ctrl.select(tabs[newActiveIndex]);
    }
    tabs.splice(index, 1);
  };

  var destroyed;
  $scope.$on('$destroy', function() {
    destroyed = true;
  });
}])

/**
 * @ngdoc directive
 * @name ui.bootstrap.tabs.directive:tabset
 * @restrict EA
 *
 * @description
 * Tabset is the outer container for the tabs directive
 *
 * @param {boolean=} vertical Whether or not to use vertical styling for the tabs.
 * @param {boolean=} justified Whether or not to use justified styling for the tabs.
 *
 * @example
<example module="ui.bootstrap">
  <file name="index.html">
    <tabset>
      <tab heading="Tab 1"><b>First</b> Content!</tab>
      <tab heading="Tab 2"><i>Second</i> Content!</tab>
    </tabset>
    <hr />
    <tabset vertical="true">
      <tab heading="Vertical Tab 1"><b>First</b> Vertical Content!</tab>
      <tab heading="Vertical Tab 2"><i>Second</i> Vertical Content!</tab>
    </tabset>
    <tabset justified="true">
      <tab heading="Justified Tab 1"><b>First</b> Justified Content!</tab>
      <tab heading="Justified Tab 2"><i>Second</i> Justified Content!</tab>
    </tabset>
  </file>
</example>
 */
.directive('tabset', function() {
  return {
    restrict: 'EA',
    transclude: true,
    replace: true,
    scope: {
      type: '@'
    },
    controller: 'TabsetController',
    templateUrl: 'template/tabs/tabset.html',
    link: function(scope, element, attrs) {
      scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;
      scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false;
    }
  };
})

/**
 * @ngdoc directive
 * @name ui.bootstrap.tabs.directive:tab
 * @restrict EA
 *
 * @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}.
 * @param {string=} select An expression to evaluate when the tab is selected.
 * @param {boolean=} active A binding, telling whether or not this tab is selected.
 * @param {boolean=} disabled A binding, telling whether or not this tab is disabled.
 *
 * @description
 * Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}.
 *
 * @example
<example module="ui.bootstrap">
  <file name="index.html">
    <div ng-controller="TabsDemoCtrl">
      <button class="btn btn-small" ng-click="items[0].active = true">
        Select item 1, using active binding
      </button>
      <button class="btn btn-small" ng-click="items[1].disabled = !items[1].disabled">
        Enable/disable item 2, using disabled binding
      </button>
      <br />
      <tabset>
        <tab heading="Tab 1">First Tab</tab>
        <tab select="alertMe()">
          <tab-heading><i class="icon-bell"></i> Alert me!</tab-heading>
          Second Tab, with alert callback and html heading!
        </tab>
        <tab ng-repeat="item in items"
          heading="{{item.title}}"
          disabled="item.disabled"
          active="item.active">
          {{item.content}}
        </tab>
      </tabset>
    </div>
  </file>
  <file name="script.js">
    function TabsDemoCtrl($scope) {
      $scope.items = [
        { title:"Dynamic Title 1", content:"Dynamic Item 0" },
        { title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true }
      ];

      $scope.alertMe = function() {
        setTimeout(function() {
          alert("You've selected the alert tab!");
        });
      };
    };
  </file>
</example>
 */

/**
 * @ngdoc directive
 * @name ui.bootstrap.tabs.directive:tabHeading
 * @restrict EA
 *
 * @description
 * Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element.
 *
 * @example
<example module="ui.bootstrap">
  <file name="index.html">
    <tabset>
      <tab>
        <tab-heading><b>HTML</b> in my titles?!</tab-heading>
        And some content, too!
      </tab>
      <tab>
        <tab-heading><i class="icon-heart"></i> Icon heading?!?</tab-heading>
        That's right.
      </tab>
    </tabset>
  </file>
</example>
 */
.directive('tab', ['$parse', '$log', function($parse, $log) {
  return {
    require: '^tabset',
    restrict: 'EA',
    replace: true,
    templateUrl: 'template/tabs/tab.html',
    transclude: true,
    scope: {
      active: '=?',
      heading: '@',
      onSelect: '&select', //This callback is called in contentHeadingTransclude
                          //once it inserts the tab's content into the dom
      onDeselect: '&deselect'
    },
    controller: function() {
      //Empty controller so other directives can require being 'under' a tab
    },
    compile: function(elm, attrs, transclude) {
      return function postLink(scope, elm, attrs, tabsetCtrl) {
        scope.$watch('active', function(active) {
          if (active) {
            tabsetCtrl.select(scope);
          }
        });

        scope.disabled = false;
        if ( attrs.disable ) {
          scope.$parent.$watch($parse(attrs.disable), function(value) {
            scope.disabled = !! value;
          });
        }

        // Deprecation support of "disabled" parameter
        // fix(tab): IE9 disabled attr renders grey text on enabled tab #2677
        // This code is duplicated from the lines above to make it easy to remove once
        // the feature has been completely deprecated
        if ( attrs.disabled ) {
          $log.warn('Use of "disabled" attribute has been deprecated, please use "disable"');
          scope.$parent.$watch($parse(attrs.disabled), function(value) {
            scope.disabled = !! value;
          });
        }

        scope.select = function() {
          if ( !scope.disabled ) {
            scope.active = true;
          }
        };

        tabsetCtrl.addTab(scope);
        scope.$on('$destroy', function() {
          tabsetCtrl.removeTab(scope);
        });

        //We need to transclude later, once the content container is ready.
        //when this link happens, we're inside a tab heading.
        scope.$transcludeFn = transclude;
      };
    }
  };
}])

.directive('tabHeadingTransclude', [function() {
  return {
    restrict: 'A',
    require: '^tab',
    link: function(scope, elm, attrs, tabCtrl) {
      scope.$watch('headingElement', function updateHeadingElement(heading) {
        if (heading) {
          elm.html('');
          elm.append(heading);
        }
      });
    }
  };
}])

.directive('tabContentTransclude', function() {
  return {
    restrict: 'A',
    require: '^tabset',
    link: function(scope, elm, attrs) {
      var tab = scope.$eval(attrs.tabContentTransclude);

      //Now our tab is ready to be transcluded: both the tab heading area
      //and the tab content area are loaded.  Transclude 'em both.
      tab.$transcludeFn(tab.$parent, function(contents) {
        angular.forEach(contents, function(node) {
          if (isTabHeading(node)) {
            //Let tabHeadingTransclude know.
            tab.headingElement = node;
          } else {
            elm.append(node);
          }
        });
      });
    }
  };
  function isTabHeading(node) {
    return node.tagName &&  (
      node.hasAttribute('tab-heading') ||
      node.hasAttribute('data-tab-heading') ||
      node.tagName.toLowerCase() === 'tab-heading' ||
      node.tagName.toLowerCase() === 'data-tab-heading'
    );
  }
})

;

angular.module('ui.bootstrap.timepicker', [])

.constant('timepickerConfig', {
  hourStep: 1,
  minuteStep: 1,
  showMeridian: true,
  meridians: null,
  readonlyInput: false,
  mousewheel: true,
  arrowkeys: true,
  showSpinners: true
})

.controller('TimepickerController', ['$scope', '$attrs', '$parse', '$log', '$locale', 'timepickerConfig', function($scope, $attrs, $parse, $log, $locale, timepickerConfig) {
  var selected = new Date(),
      ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
      meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS;

  this.init = function( ngModelCtrl_, inputs ) {
    ngModelCtrl = ngModelCtrl_;
    ngModelCtrl.$render = this.render;

    ngModelCtrl.$formatters.unshift(function (modelValue) {
      return modelValue ? new Date( modelValue ) : null;
    });

    var hoursInputEl = inputs.eq(0),
        minutesInputEl = inputs.eq(1);

    var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel;
    if ( mousewheel ) {
      this.setupMousewheelEvents( hoursInputEl, minutesInputEl );
    }

    var arrowkeys = angular.isDefined($attrs.arrowkeys) ? $scope.$parent.$eval($attrs.arrowkeys) : timepickerConfig.arrowkeys;
    if (arrowkeys) {
      this.setupArrowkeyEvents( hoursInputEl, minutesInputEl );
    }

    $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput;
    this.setupInputEvents( hoursInputEl, minutesInputEl );
  };

  var hourStep = timepickerConfig.hourStep;
  if ($attrs.hourStep) {
    $scope.$parent.$watch($parse($attrs.hourStep), function(value) {
      hourStep = parseInt(value, 10);
    });
  }

  var minuteStep = timepickerConfig.minuteStep;
  if ($attrs.minuteStep) {
    $scope.$parent.$watch($parse($attrs.minuteStep), function(value) {
      minuteStep = parseInt(value, 10);
    });
  }

  // 12H / 24H mode
  $scope.showMeridian = timepickerConfig.showMeridian;
  if ($attrs.showMeridian) {
    $scope.$parent.$watch($parse($attrs.showMeridian), function(value) {
      $scope.showMeridian = !!value;

      if ( ngModelCtrl.$error.time ) {
        // Evaluate from template
        var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate();
        if (angular.isDefined( hours ) && angular.isDefined( minutes )) {
          selected.setHours( hours );
          refresh();
        }
      } else {
        updateTemplate();
      }
    });
  }

  // Get $scope.hours in 24H mode if valid
  function getHoursFromTemplate ( ) {
    var hours = parseInt( $scope.hours, 10 );
    var valid = ( $scope.showMeridian ) ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);
    if ( !valid ) {
      return undefined;
    }

    if ( $scope.showMeridian ) {
      if ( hours === 12 ) {
        hours = 0;
      }
      if ( $scope.meridian === meridians[1] ) {
        hours = hours + 12;
      }
    }
    return hours;
  }

  function getMinutesFromTemplate() {
    var minutes = parseInt($scope.minutes, 10);
    return ( minutes >= 0 && minutes < 60 ) ? minutes : undefined;
  }

  function pad( value ) {
    return ( angular.isDefined(value) && value.toString().length < 2 ) ? '0' + value : value.toString();
  }

  // Respond on mousewheel spin
  this.setupMousewheelEvents = function( hoursInputEl, minutesInputEl ) {
    var isScrollingUp = function(e) {
      if (e.originalEvent) {
        e = e.originalEvent;
      }
      //pick correct delta variable depending on event
      var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY;
      return (e.detail || delta > 0);
    };

    hoursInputEl.bind('mousewheel wheel', function(e) {
      $scope.$apply( (isScrollingUp(e)) ? $scope.incrementHours() : $scope.decrementHours() );
      e.preventDefault();
    });

    minutesInputEl.bind('mousewheel wheel', function(e) {
      $scope.$apply( (isScrollingUp(e)) ? $scope.incrementMinutes() : $scope.decrementMinutes() );
      e.preventDefault();
    });

  };

  // Respond on up/down arrowkeys
  this.setupArrowkeyEvents = function( hoursInputEl, minutesInputEl ) {
    hoursInputEl.bind('keydown', function(e) {
      if ( e.which === 38 ) { // up
        e.preventDefault();
        $scope.incrementHours();
        $scope.$apply();
      }
      else if ( e.which === 40 ) { // down
        e.preventDefault();
        $scope.decrementHours();
        $scope.$apply();
      }
    });

    minutesInputEl.bind('keydown', function(e) {
      if ( e.which === 38 ) { // up
        e.preventDefault();
        $scope.incrementMinutes();
        $scope.$apply();
      }
      else if ( e.which === 40 ) { // down
        e.preventDefault();
        $scope.decrementMinutes();
        $scope.$apply();
      }
    });
  };

  this.setupInputEvents = function( hoursInputEl, minutesInputEl ) {
    if ( $scope.readonlyInput ) {
      $scope.updateHours = angular.noop;
      $scope.updateMinutes = angular.noop;
      return;
    }

    var invalidate = function(invalidHours, invalidMinutes) {
      ngModelCtrl.$setViewValue( null );
      ngModelCtrl.$setValidity('time', false);
      if (angular.isDefined(invalidHours)) {
        $scope.invalidHours = invalidHours;
      }
      if (angular.isDefined(invalidMinutes)) {
        $scope.invalidMinutes = invalidMinutes;
      }
    };

    $scope.updateHours = function() {
      var hours = getHoursFromTemplate();

      if ( angular.isDefined(hours) ) {
        selected.setHours( hours );
        refresh( 'h' );
      } else {
        invalidate(true);
      }
    };

    hoursInputEl.bind('blur', function(e) {
      if ( !$scope.invalidHours && $scope.hours < 10) {
        $scope.$apply( function() {
          $scope.hours = pad( $scope.hours );
        });
      }
    });

    $scope.updateMinutes = function() {
      var minutes = getMinutesFromTemplate();

      if ( angular.isDefined(minutes) ) {
        selected.setMinutes( minutes );
        refresh( 'm' );
      } else {
        invalidate(undefined, true);
      }
    };

    minutesInputEl.bind('blur', function(e) {
      if ( !$scope.invalidMinutes && $scope.minutes < 10 ) {
        $scope.$apply( function() {
          $scope.minutes = pad( $scope.minutes );
        });
      }
    });

  };

  this.render = function() {
    var date = ngModelCtrl.$viewValue;

    if ( isNaN(date) ) {
      ngModelCtrl.$setValidity('time', false);
      $log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
    } else {
      if ( date ) {
        selected = date;
      }
      makeValid();
      updateTemplate();
    }
  };

  // Call internally when we know that model is valid.
  function refresh( keyboardChange ) {
    makeValid();
    ngModelCtrl.$setViewValue( new Date(selected) );
    updateTemplate( keyboardChange );
  }

  function makeValid() {
    ngModelCtrl.$setValidity('time', true);
    $scope.invalidHours = false;
    $scope.invalidMinutes = false;
  }

  function updateTemplate( keyboardChange ) {
    var hours = selected.getHours(), minutes = selected.getMinutes();

    if ( $scope.showMeridian ) {
      hours = ( hours === 0 || hours === 12 ) ? 12 : hours % 12; // Convert 24 to 12 hour system
    }

    $scope.hours = keyboardChange === 'h' ? hours : pad(hours);
    if (keyboardChange !== 'm') {
      $scope.minutes = pad(minutes);
    }
    $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];
  }

  function addMinutes( minutes ) {
    var dt = new Date( selected.getTime() + minutes * 60000 );
    selected.setHours( dt.getHours(), dt.getMinutes() );
    refresh();
  }
  
  $scope.showSpinners = angular.isDefined($attrs.showSpinners) ?
    $scope.$parent.$eval($attrs.showSpinners) : timepickerConfig.showSpinners;
  
  $scope.incrementHours = function() {
    addMinutes( hourStep * 60 );
  };
  $scope.decrementHours = function() {
    addMinutes( - hourStep * 60 );
  };
  $scope.incrementMinutes = function() {
    addMinutes( minuteStep );
  };
  $scope.decrementMinutes = function() {
    addMinutes( - minuteStep );
  };
  $scope.toggleMeridian = function() {
    addMinutes( 12 * 60 * (( selected.getHours() < 12 ) ? 1 : -1) );
  };
}])

.directive('timepicker', function () {
  return {
    restrict: 'EA',
    require: ['timepicker', '?^ngModel'],
    controller:'TimepickerController',
    replace: true,
    scope: {},
    templateUrl: 'template/timepicker/timepicker.html',
    link: function(scope, element, attrs, ctrls) {
      var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];

      if ( ngModelCtrl ) {
        timepickerCtrl.init( ngModelCtrl, element.find('input') );
      }
    }
  };
});

angular.module('ui.bootstrap.transition', [])

.value('$transitionSuppressDeprecated', false)
/**
 * $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete.
 * @param  {DOMElement} element  The DOMElement that will be animated.
 * @param  {string|object|function} trigger  The thing that will cause the transition to start:
 *   - As a string, it represents the css class to be added to the element.
 *   - As an object, it represents a hash of style attributes to be applied to the element.
 *   - As a function, it represents a function to be called that will cause the transition to occur.
 * @return {Promise}  A promise that is resolved when the transition finishes.
 */
.factory('$transition', [
        '$q', '$timeout', '$rootScope', '$log', '$transitionSuppressDeprecated',
function($q ,  $timeout ,  $rootScope ,  $log ,  $transitionSuppressDeprecated) {

  if (!$transitionSuppressDeprecated) {
    $log.warn('$transition is now deprecated. Use $animate from ngAnimate instead.');
  }

  var $transition = function(element, trigger, options) {
    options = options || {};
    var deferred = $q.defer();
    var endEventName = $transition[options.animation ? 'animationEndEventName' : 'transitionEndEventName'];

    var transitionEndHandler = function(event) {
      $rootScope.$apply(function() {
        element.unbind(endEventName, transitionEndHandler);
        deferred.resolve(element);
      });
    };

    if (endEventName) {
      element.bind(endEventName, transitionEndHandler);
    }

    // Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur
    $timeout(function() {
      if ( angular.isString(trigger) ) {
        element.addClass(trigger);
      } else if ( angular.isFunction(trigger) ) {
        trigger(element);
      } else if ( angular.isObject(trigger) ) {
        element.css(trigger);
      }
      //If browser does not support transitions, instantly resolve
      if ( !endEventName ) {
        deferred.resolve(element);
      }
    });

    // Add our custom cancel function to the promise that is returned
    // We can call this if we are about to run a new transition, which we know will prevent this transition from ending,
    // i.e. it will therefore never raise a transitionEnd event for that transition
    deferred.promise.cancel = function() {
      if ( endEventName ) {
        element.unbind(endEventName, transitionEndHandler);
      }
      deferred.reject('Transition cancelled');
    };

    return deferred.promise;
  };

  // Work out the name of the transitionEnd event
  var transElement = document.createElement('trans');
  var transitionEndEventNames = {
    'WebkitTransition': 'webkitTransitionEnd',
    'MozTransition': 'transitionend',
    'OTransition': 'oTransitionEnd',
    'transition': 'transitionend'
  };
  var animationEndEventNames = {
    'WebkitTransition': 'webkitAnimationEnd',
    'MozTransition': 'animationend',
    'OTransition': 'oAnimationEnd',
    'transition': 'animationend'
  };
  function findEndEventName(endEventNames) {
    for (var name in endEventNames){
      if (transElement.style[name] !== undefined) {
        return endEventNames[name];
      }
    }
  }
  $transition.transitionEndEventName = findEndEventName(transitionEndEventNames);
  $transition.animationEndEventName = findEndEventName(animationEndEventNames);
  return $transition;
}]);

angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position', 'ui.bootstrap.bindHtml'])

/**
 * A helper service that can parse typeahead's syntax (string provided by users)
 * Extracted to a separate service for ease of unit testing
 */
  .factory('typeaheadParser', ['$parse', function ($parse) {

  //                      00000111000000000000022200000000000000003333333333333330000000000044000
  var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/;

  return {
    parse:function (input) {

      var match = input.match(TYPEAHEAD_REGEXP);
      if (!match) {
        throw new Error(
          'Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' +
            ' but got "' + input + '".');
      }

      return {
        itemName:match[3],
        source:$parse(match[4]),
        viewMapper:$parse(match[2] || match[1]),
        modelMapper:$parse(match[1])
      };
    }
  };
}])

  .directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$window', '$rootScope', '$position', 'typeaheadParser',
       function ($compile, $parse, $q, $timeout, $document, $window, $rootScope, $position, typeaheadParser) {

  var HOT_KEYS = [9, 13, 27, 38, 40];
  var eventDebounceTime = 200;

  return {
    require:'ngModel',
    link:function (originalScope, element, attrs, modelCtrl) {

      //SUPPORTED ATTRIBUTES (OPTIONS)

      //minimal no of characters that needs to be entered before typeahead kicks-in
      var minLength = originalScope.$eval(attrs.typeaheadMinLength);
      if (!minLength && minLength !== 0) {
        minLength = 1;
      }

      //minimal wait time after last character typed before typeahead kicks-in
      var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0;

      //should it restrict model values to the ones selected from the popup only?
      var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false;

      //binding to a variable that indicates if matches are being retrieved asynchronously
      var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;

      //a callback executed when a match is selected
      var onSelectCallback = $parse(attrs.typeaheadOnSelect);

      //should it select highlighted popup value when losing focus?
      var isSelectOnBlur = angular.isDefined(attrs.typeaheadSelectOnBlur) ? originalScope.$eval(attrs.typeaheadSelectOnBlur) : false;

      var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;

      var appendToBody =  attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false;

      var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false;

      //INTERNAL VARIABLES

      //model setter executed upon match selection
      var $setModelValue = $parse(attrs.ngModel).assign;

      //expressions used by typeahead
      var parserResult = typeaheadParser.parse(attrs.typeahead);

      var hasFocus;

      //Used to avoid bug in iOS webview where iOS keyboard does not fire
      //mousedown & mouseup events
      //Issue #3699
      var selected;

      //create a child scope for the typeahead directive so we are not polluting original scope
      //with typeahead-specific data (matches, query etc.)
      var scope = originalScope.$new();
      originalScope.$on('$destroy', function(){
        scope.$destroy();
      });

      // WAI-ARIA
      var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000);
      element.attr({
        'aria-autocomplete': 'list',
        'aria-expanded': false,
        'aria-owns': popupId
      });

      //pop-up element used to display matches
      var popUpEl = angular.element('<div typeahead-popup></div>');
      popUpEl.attr({
        id: popupId,
        matches: 'matches',
        active: 'activeIdx',
        select: 'select(activeIdx)',
        'move-in-progress': 'moveInProgress',
        query: 'query',
        position: 'position'
      });
      //custom item template
      if (angular.isDefined(attrs.typeaheadTemplateUrl)) {
        popUpEl.attr('template-url', attrs.typeaheadTemplateUrl);
      }

      var resetMatches = function() {
        scope.matches = [];
        scope.activeIdx = -1;
        element.attr('aria-expanded', false);
      };

      var getMatchId = function(index) {
        return popupId + '-option-' + index;
      };

      // Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead.
      // This attribute is added or removed automatically when the `activeIdx` changes.
      scope.$watch('activeIdx', function(index) {
        if (index < 0) {
          element.removeAttr('aria-activedescendant');
        } else {
          element.attr('aria-activedescendant', getMatchId(index));
        }
      });

      var getMatchesAsync = function(inputValue) {

        var locals = {$viewValue: inputValue};
        isLoadingSetter(originalScope, true);
        $q.when(parserResult.source(originalScope, locals)).then(function(matches) {

          //it might happen that several async queries were in progress if a user were typing fast
          //but we are interested only in responses that correspond to the current view value
          var onCurrentRequest = (inputValue === modelCtrl.$viewValue);
          if (onCurrentRequest && hasFocus) {
            if (matches && matches.length > 0) {

              scope.activeIdx = focusFirst ? 0 : -1;
              scope.matches.length = 0;

              //transform labels
              for(var i=0; i<matches.length; i++) {
                locals[parserResult.itemName] = matches[i];
                scope.matches.push({
                  id: getMatchId(i),
                  label: parserResult.viewMapper(scope, locals),
                  model: matches[i]
                });
              }

              scope.query = inputValue;
              //position pop-up with matches - we need to re-calculate its position each time we are opening a window
              //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
              //due to other elements being rendered
              recalculatePosition();

              element.attr('aria-expanded', true);
            } else {
              resetMatches();
            }
          }
          if (onCurrentRequest) {
            isLoadingSetter(originalScope, false);
          }
        }, function(){
          resetMatches();
          isLoadingSetter(originalScope, false);
        });
      };

      // bind events only if appendToBody params exist - performance feature
      if (appendToBody) {
        angular.element($window).bind('resize', fireRecalculating);
        $document.find('body').bind('scroll', fireRecalculating);
      }

      // Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
      var timeoutEventPromise;

      // Default progress type
      scope.moveInProgress = false;

      function fireRecalculating() {
        if(!scope.moveInProgress){
          scope.moveInProgress = true;
          scope.$digest();
        }

        // Cancel previous timeout
        if (timeoutEventPromise) {
          $timeout.cancel(timeoutEventPromise);
        }

        // Debounced executing recalculate after events fired
        timeoutEventPromise = $timeout(function () {
          // if popup is visible
          if (scope.matches.length) {
            recalculatePosition();
          }

          scope.moveInProgress = false;
          scope.$digest();
        }, eventDebounceTime);
      }

      // recalculate actual position and set new values to scope
      // after digest loop is popup in right position
      function recalculatePosition() {
        scope.position = appendToBody ? $position.offset(element) : $position.position(element);
        scope.position.top += element.prop('offsetHeight');
      }

      resetMatches();

      //we need to propagate user's query so we can higlight matches
      scope.query = undefined;

      //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
      var timeoutPromise;

      var scheduleSearchWithTimeout = function(inputValue) {
        timeoutPromise = $timeout(function () {
          getMatchesAsync(inputValue);
        }, waitTime);
      };

      var cancelPreviousTimeout = function() {
        if (timeoutPromise) {
          $timeout.cancel(timeoutPromise);
        }
      };

      //plug into $parsers pipeline to open a typeahead on view changes initiated from DOM
      //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
      modelCtrl.$parsers.unshift(function (inputValue) {

        hasFocus = true;

        if (minLength === 0 || inputValue && inputValue.length >= minLength) {
          if (waitTime > 0) {
            cancelPreviousTimeout();
            scheduleSearchWithTimeout(inputValue);
          } else {
            getMatchesAsync(inputValue);
          }
        } else {
          isLoadingSetter(originalScope, false);
          cancelPreviousTimeout();
          resetMatches();
        }

        if (isEditable) {
          return inputValue;
        } else {
          if (!inputValue) {
            // Reset in case user had typed something previously.
            modelCtrl.$setValidity('editable', true);
            return inputValue;
          } else {
            modelCtrl.$setValidity('editable', false);
            return undefined;
          }
        }
      });

      modelCtrl.$formatters.push(function (modelValue) {

        var candidateViewValue, emptyViewValue;
        var locals = {};

        // The validity may be set to false via $parsers (see above) if
        // the model is restricted to selected values. If the model
        // is set manually it is considered to be valid.
        if (!isEditable) {
          modelCtrl.$setValidity('editable', true);
        }

        if (inputFormatter) {

          locals.$model = modelValue;
          return inputFormatter(originalScope, locals);

        } else {

          //it might happen that we don't have enough info to properly render input value
          //we need to check for this situation and simply return model value if we can't apply custom formatting
          locals[parserResult.itemName] = modelValue;
          candidateViewValue = parserResult.viewMapper(originalScope, locals);
          locals[parserResult.itemName] = undefined;
          emptyViewValue = parserResult.viewMapper(originalScope, locals);

          return candidateViewValue!== emptyViewValue ? candidateViewValue : modelValue;
        }
      });

      scope.select = function (activeIdx) {
        //called from within the $digest() cycle
        var locals = {};
        var model, item;

        selected = true;
        locals[parserResult.itemName] = item = scope.matches[activeIdx].model;
        model = parserResult.modelMapper(originalScope, locals);
        $setModelValue(originalScope, model);
        modelCtrl.$setValidity('editable', true);
        modelCtrl.$setValidity('parse', true);

        onSelectCallback(originalScope, {
          $item: item,
          $model: model,
          $label: parserResult.viewMapper(originalScope, locals)
        });

        resetMatches();

        //return focus to the input element if a match was selected via a mouse click event
        // use timeout to avoid $rootScope:inprog error
        $timeout(function() { element[0].focus(); }, 0, false);
      };

      //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
      element.bind('keydown', function (evt) {

        //typeahead is open and an "interesting" key was pressed
        if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
          return;
        }

        // if there's nothing selected (i.e. focusFirst) and enter is hit, don't do anything
        if (scope.activeIdx === -1 && evt.which === 13) {
          return;
        }

        // if there's nothing selected (i.e. focusFirst) and tab is hit, clear the results
        if (scope.activeIdx === -1 && evt.which === 9) {
          resetMatches();
          scope.$digest();
          return;
        }

        evt.preventDefault();

        if (evt.which === 40) {
          scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
          scope.$digest();

        } else if (evt.which === 38) {
          scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1;
          scope.$digest();

        } else if (evt.which === 13 || evt.which === 9) {
          scope.$apply(function () {
            scope.select(scope.activeIdx);
          });

        } else if (evt.which === 27) {
          evt.stopPropagation();

          resetMatches();
          scope.$digest();
        }
      });

      element.bind('blur', function () {
        if (isSelectOnBlur && scope.matches.length && scope.activeIdx !== -1 && !selected) {
          selected = true;
          scope.$apply(function () {
            scope.select(scope.activeIdx);
          });
        }
        hasFocus = false;
        selected = false;
      });

      // Keep reference to click handler to unbind it.
      var dismissClickHandler = function (evt) {
        // Issue #3973
        // Firefox treats right click as a click on document
        if (element[0] !== evt.target && evt.which !== 3) {
          resetMatches();
          if (!$rootScope.$$phase) {
            scope.$digest();
          }
        }
      };

      $document.bind('click', dismissClickHandler);

      originalScope.$on('$destroy', function(){
        $document.unbind('click', dismissClickHandler);
        if (appendToBody) {
          $popup.remove();
        }
        // Prevent jQuery cache memory leak
        popUpEl.remove();
      });

      var $popup = $compile(popUpEl)(scope);

      if (appendToBody) {
        $document.find('body').append($popup);
      } else {
        element.after($popup);
      }
    }
  };

}])

  .directive('typeaheadPopup', function () {
    return {
      restrict:'EA',
      scope:{
        matches:'=',
        query:'=',
        active:'=',
        position:'&',
        moveInProgress:'=',
        select:'&'
      },
      replace:true,
      templateUrl:'template/typeahead/typeahead-popup.html',
      link:function (scope, element, attrs) {

        scope.templateUrl = attrs.templateUrl;

        scope.isOpen = function () {
          return scope.matches.length > 0;
        };

        scope.isActive = function (matchIdx) {
          return scope.active == matchIdx;
        };

        scope.selectActive = function (matchIdx) {
          scope.active = matchIdx;
        };

        scope.selectMatch = function (activeIdx) {
          scope.select({activeIdx:activeIdx});
        };
      }
    };
  })

  .directive('typeaheadMatch', ['$templateRequest', '$compile', '$parse', function ($templateRequest, $compile, $parse) {
    return {
      restrict:'EA',
      scope:{
        index:'=',
        match:'=',
        query:'='
      },
      link:function (scope, element, attrs) {
        var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html';
        $templateRequest(tplUrl).then(function(tplContent) {
          $compile(tplContent.trim())(scope, function(clonedElement){
            element.replaceWith(clonedElement);
          });
        });
      }
    };
  }])

  .filter('typeaheadHighlight', function() {

    function escapeRegexp(queryToEscape) {
      return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
    }

    return function(matchItem, query) {
      return query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem;
    };
  });

angular.module("template/accordion/accordion-group.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/accordion/accordion-group.html",
    "<div class=\"panel panel-default\">\n" +
    "  <div class=\"panel-heading\">\n" +
    "    <h4 class=\"panel-title\">\n" +
    "      <a href=\"#\" tabindex=\"0\" class=\"accordion-toggle\" ng-click=\"$event.preventDefault(); toggleOpen()\" accordion-transclude=\"heading\"><span ng-class=\"{'text-muted': isDisabled}\">{{heading}}</span></a>\n" +
    "    </h4>\n" +
    "  </div>\n" +
    "  <div class=\"panel-collapse collapse\" collapse=\"!isOpen\">\n" +
    "	  <div class=\"panel-body\" ng-transclude></div>\n" +
    "  </div>\n" +
    "</div>\n" +
    "");
}]);

angular.module("template/accordion/accordion.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/accordion/accordion.html",
    "<div class=\"panel-group\" ng-transclude></div>");
}]);

angular.module("template/alert/alert.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/alert/alert.html",
    "<div class=\"alert\" ng-class=\"['alert-' + (type || 'warning'), closeable ? 'alert-dismissible' : null]\" role=\"alert\">\n" +
    "    <button ng-show=\"closeable\" type=\"button\" class=\"close\" ng-click=\"close($event)\">\n" +
    "        <span aria-hidden=\"true\">&times;</span>\n" +
    "        <span class=\"sr-only\">Close</span>\n" +
    "    </button>\n" +
    "    <div ng-transclude></div>\n" +
    "</div>\n" +
    "");
}]);

angular.module("template/carousel/carousel.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/carousel/carousel.html",
    "<div ng-mouseenter=\"pause()\" ng-mouseleave=\"play()\" class=\"carousel\" ng-swipe-right=\"prev()\" ng-swipe-left=\"next()\">\n" +
    "    <ol class=\"carousel-indicators\" ng-show=\"slides.length > 1\">\n" +
    "        <li ng-repeat=\"slide in slides | orderBy:'index' track by $index\" ng-class=\"{active: isActive(slide)}\" ng-click=\"select(slide)\"></li>\n" +
    "    </ol>\n" +
    "    <div class=\"carousel-inner\" ng-transclude></div>\n" +
    "    <a class=\"left carousel-control\" ng-click=\"prev()\" ng-show=\"slides.length > 1\"><span class=\"glyphicon glyphicon-chevron-left\"></span></a>\n" +
    "    <a class=\"right carousel-control\" ng-click=\"next()\" ng-show=\"slides.length > 1\"><span class=\"glyphicon glyphicon-chevron-right\"></span></a>\n" +
    "</div>\n" +
    "");
}]);

angular.module("template/carousel/slide.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/carousel/slide.html",
    "<div ng-class=\"{\n" +
    "    'active': active\n" +
    "  }\" class=\"item text-center\" ng-transclude></div>\n" +
    "");
}]);

angular.module("template/datepicker/datepicker.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/datepicker/datepicker.html",
    "<div ng-switch=\"datepickerMode\" role=\"application\" ng-keydown=\"keydown($event)\">\n" +
    "  <daypicker ng-switch-when=\"day\" tabindex=\"0\"></daypicker>\n" +
    "  <monthpicker ng-switch-when=\"month\" tabindex=\"0\"></monthpicker>\n" +
    "  <yearpicker ng-switch-when=\"year\" tabindex=\"0\"></yearpicker>\n" +
    "</div>");
}]);

angular.module("template/datepicker/day.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/datepicker/day.html",
    "<table role=\"grid\" aria-labelledby=\"{{::uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" +
    "  <thead>\n" +
    "    <tr>\n" +
    "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" +
    "      <th colspan=\"{{::5 + showWeeks}}\"><button id=\"{{::uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" ng-disabled=\"datepickerMode === maxMode\" tabindex=\"-1\" style=\"width:100%;\"><strong>{{title}}</strong></button></th>\n" +
    "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" +
    "    </tr>\n" +
    "    <tr>\n" +
    "      <th ng-if=\"showWeeks\" class=\"text-center\"></th>\n" +
    "      <th ng-repeat=\"label in ::labels track by $index\" class=\"text-center\"><small aria-label=\"{{::label.full}}\">{{::label.abbr}}</small></th>\n" +
    "    </tr>\n" +
    "  </thead>\n" +
    "  <tbody>\n" +
    "    <tr ng-repeat=\"row in rows track by $index\">\n" +
    "      <td ng-if=\"showWeeks\" class=\"text-center h6\"><em>{{ weekNumbers[$index] }}</em></td>\n" +
    "      <td ng-repeat=\"dt in row track by dt.date\" class=\"text-center\" role=\"gridcell\" id=\"{{::dt.uid}}\" ng-class=\"::dt.customClass\">\n" +
    "        <button type=\"button\" style=\"min-width:100%;\" class=\"btn btn-default btn-sm\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"dt.disabled\" tabindex=\"-1\"><span ng-class=\"::{'text-muted': dt.secondary, 'text-info': dt.current}\">{{::dt.label}}</span></button>\n" +
    "      </td>\n" +
    "    </tr>\n" +
    "  </tbody>\n" +
    "</table>\n" +
    "");
}]);

angular.module("template/datepicker/month.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/datepicker/month.html",
    "<table role=\"grid\" aria-labelledby=\"{{::uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" +
    "  <thead>\n" +
    "    <tr>\n" +
    "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" +
    "      <th><button id=\"{{::uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" ng-disabled=\"datepickerMode === maxMode\" tabindex=\"-1\" style=\"width:100%;\"><strong>{{title}}</strong></button></th>\n" +
    "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" +
    "    </tr>\n" +
    "  </thead>\n" +
    "  <tbody>\n" +
    "    <tr ng-repeat=\"row in rows track by $index\">\n" +
    "      <td ng-repeat=\"dt in row track by dt.date\" class=\"text-center\" role=\"gridcell\" id=\"{{::dt.uid}}\" ng-class=\"::dt.customClass\">\n" +
    "        <button type=\"button\" style=\"min-width:100%;\" class=\"btn btn-default\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"dt.disabled\" tabindex=\"-1\"><span ng-class=\"::{'text-info': dt.current}\">{{::dt.label}}</span></button>\n" +
    "      </td>\n" +
    "    </tr>\n" +
    "  </tbody>\n" +
    "</table>\n" +
    "");
}]);

angular.module("template/datepicker/popup.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/datepicker/popup.html",
    "<ul class=\"dropdown-menu\" ng-if=\"isOpen\" style=\"display: block\" ng-style=\"{top: position.top+'px', left: position.left+'px'}\" ng-keydown=\"keydown($event)\" ng-click=\"$event.stopPropagation()\">\n" +
    "	<li ng-transclude></li>\n" +
    "	<li ng-if=\"showButtonBar\" style=\"padding:10px 9px 2px\">\n" +
    "		<span class=\"btn-group pull-left\">\n" +
    "			<button type=\"button\" class=\"btn btn-sm btn-info\" ng-click=\"select('today')\">{{ getText('current') }}</button>\n" +
    "			<button type=\"button\" class=\"btn btn-sm btn-danger\" ng-click=\"select(null)\">{{ getText('clear') }}</button>\n" +
    "		</span>\n" +
    "		<button type=\"button\" class=\"btn btn-sm btn-success pull-right\" ng-click=\"close()\">{{ getText('close') }}</button>\n" +
    "	</li>\n" +
    "</ul>\n" +
    "");
}]);

angular.module("template/datepicker/year.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/datepicker/year.html",
    "<table role=\"grid\" aria-labelledby=\"{{::uniqueId}}-title\" aria-activedescendant=\"{{activeDateId}}\">\n" +
    "  <thead>\n" +
    "    <tr>\n" +
    "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" +
    "      <th colspan=\"3\"><button id=\"{{::uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" ng-disabled=\"datepickerMode === maxMode\" tabindex=\"-1\" style=\"width:100%;\"><strong>{{title}}</strong></button></th>\n" +
    "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" +
    "    </tr>\n" +
    "  </thead>\n" +
    "  <tbody>\n" +
    "    <tr ng-repeat=\"row in rows track by $index\">\n" +
    "      <td ng-repeat=\"dt in row track by dt.date\" class=\"text-center\" role=\"gridcell\" id=\"{{::dt.uid}}\">\n" +
    "        <button type=\"button\" style=\"min-width:100%;\" class=\"btn btn-default\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"dt.disabled\" tabindex=\"-1\"><span ng-class=\"::{'text-info': dt.current}\">{{::dt.label}}</span></button>\n" +
    "      </td>\n" +
    "    </tr>\n" +
    "  </tbody>\n" +
    "</table>\n" +
    "");
}]);

angular.module("template/modal/backdrop.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/modal/backdrop.html",
    "<div class=\"modal-backdrop\"\n" +
    "     modal-animation-class=\"fade\"\n" +
    "     modal-in-class=\"in\"\n" +
    "     ng-style=\"{'z-index': 1040 + (index && 1 || 0) + index*10}\"\n" +
    "></div>\n" +
    "");
}]);

angular.module("template/modal/window.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/modal/window.html",
    "<div modal-render=\"{{$isRendered}}\" tabindex=\"-1\" role=\"dialog\" class=\"modal\"\n" +
    "    modal-animation-class=\"fade\"\n" +
    "    modal-in-class=\"in\"\n" +
    "	ng-style=\"{'z-index': 1050 + index*10, display: 'block'}\" ng-click=\"close($event)\">\n" +
    "    <div class=\"modal-dialog\" ng-class=\"size ? 'modal-' + size : ''\"><div class=\"modal-content\" modal-transclude></div></div>\n" +
    "</div>\n" +
    "");
}]);

angular.module("template/pagination/pager.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/pagination/pager.html",
    "<ul class=\"pager\">\n" +
    "  <li ng-class=\"{disabled: noPrevious(), previous: align}\"><a href ng-click=\"selectPage(page - 1, $event)\">{{::getText('previous')}}</a></li>\n" +
    "  <li ng-class=\"{disabled: noNext(), next: align}\"><a href ng-click=\"selectPage(page + 1, $event)\">{{::getText('next')}}</a></li>\n" +
    "</ul>");
}]);

angular.module("template/pagination/pagination.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/pagination/pagination.html",
    "<ul class=\"pagination\">\n" +
    "  <li ng-if=\"::boundaryLinks\" ng-class=\"{disabled: noPrevious()||ngDisabled}\"><a href ng-click=\"selectPage(1, $event)\">{{::getText('first')}}</a></li>\n" +
    "  <li ng-if=\"::directionLinks\" ng-class=\"{disabled: noPrevious()||ngDisabled}\"><a href ng-click=\"selectPage(page - 1, $event)\">{{::getText('previous')}}</a></li>\n" +
    "  <li ng-repeat=\"page in pages track by $index\" ng-class=\"{active: page.active,disabled: ngDisabled&&!page.active}\"><a href ng-click=\"selectPage(page.number, $event)\">{{page.text}}</a></li>\n" +
    "  <li ng-if=\"::directionLinks\" ng-class=\"{disabled: noNext()||ngDisabled}\"><a href ng-click=\"selectPage(page + 1, $event)\">{{::getText('next')}}</a></li>\n" +
    "  <li ng-if=\"::boundaryLinks\" ng-class=\"{disabled: noNext()||ngDisabled}\"><a href ng-click=\"selectPage(totalPages, $event)\">{{::getText('last')}}</a></li>\n" +
    "</ul>\n" +
    "");
}]);

angular.module("template/tooltip/tooltip-html-popup.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/tooltip/tooltip-html-popup.html",
    "<div class=\"tooltip\"\n" +
    "  tooltip-animation-class=\"fade\"\n" +
    "  tooltip-classes\n" +
    "  ng-class=\"{ in: isOpen() }\">\n" +
    "  <div class=\"tooltip-arrow\"></div>\n" +
    "  <div class=\"tooltip-inner\" ng-bind-html=\"contentExp()\"></div>\n" +
    "</div>\n" +
    "");
}]);

angular.module("template/tooltip/tooltip-html-unsafe-popup.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/tooltip/tooltip-html-unsafe-popup.html",
    "<div class=\"tooltip\"\n" +
    "  tooltip-animation-class=\"fade\"\n" +
    "  tooltip-classes\n" +
    "  ng-class=\"{ in: isOpen() }\">\n" +
    "  <div class=\"tooltip-arrow\"></div>\n" +
    "  <div class=\"tooltip-inner\" bind-html-unsafe=\"content\"></div>\n" +
    "</div>\n" +
    "");
}]);

angular.module("template/tooltip/tooltip-popup.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/tooltip/tooltip-popup.html",
    "<div class=\"tooltip\"\n" +
    "  tooltip-animation-class=\"fade\"\n" +
    "  tooltip-classes\n" +
    "  ng-class=\"{ in: isOpen() }\">\n" +
    "  <div class=\"tooltip-arrow\"></div>\n" +
    "  <div class=\"tooltip-inner\" ng-bind=\"content\"></div>\n" +
    "</div>\n" +
    "");
}]);

angular.module("template/tooltip/tooltip-template-popup.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/tooltip/tooltip-template-popup.html",
    "<div class=\"tooltip\"\n" +
    "  tooltip-animation-class=\"fade\"\n" +
    "  tooltip-classes\n" +
    "  ng-class=\"{ in: isOpen() }\">\n" +
    "  <div class=\"tooltip-arrow\"></div>\n" +
    "  <div class=\"tooltip-inner\"\n" +
    "    tooltip-template-transclude=\"contentExp()\"\n" +
    "    tooltip-template-transclude-scope=\"originScope()\"></div>\n" +
    "</div>\n" +
    "");
}]);

angular.module("template/popover/popover-template.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/popover/popover-template.html",
    "<div class=\"popover\"\n" +
    "  tooltip-animation-class=\"fade\"\n" +
    "  tooltip-classes\n" +
    "  ng-class=\"{ in: isOpen() }\">\n" +
    "  <div class=\"arrow\"></div>\n" +
    "\n" +
    "  <div class=\"popover-inner\">\n" +
    "      <h3 class=\"popover-title\" ng-bind=\"title\" ng-if=\"title\"></h3>\n" +
    "      <div class=\"popover-content\"\n" +
    "        tooltip-template-transclude=\"contentExp()\"\n" +
    "        tooltip-template-transclude-scope=\"originScope()\"></div>\n" +
    "  </div>\n" +
    "</div>\n" +
    "");
}]);

angular.module("template/popover/popover.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/popover/popover.html",
    "<div class=\"popover\"\n" +
    "  tooltip-animation-class=\"fade\"\n" +
    "  tooltip-classes\n" +
    "  ng-class=\"{ in: isOpen() }\">\n" +
    "  <div class=\"arrow\"></div>\n" +
    "\n" +
    "  <div class=\"popover-inner\">\n" +
    "      <h3 class=\"popover-title\" ng-bind=\"title\" ng-if=\"title\"></h3>\n" +
    "      <div class=\"popover-content\" ng-bind=\"content\"></div>\n" +
    "  </div>\n" +
    "</div>\n" +
    "");
}]);

angular.module("template/progressbar/bar.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/progressbar/bar.html",
    "<div class=\"progress-bar\" ng-class=\"type && 'progress-bar-' + type\" role=\"progressbar\" aria-valuenow=\"{{value}}\" aria-valuemin=\"0\" aria-valuemax=\"{{max}}\" ng-style=\"{width: (percent < 100 ? percent : 100) + '%'}\" aria-valuetext=\"{{percent | number:0}}%\" ng-transclude></div>\n" +
    "");
}]);

angular.module("template/progressbar/progress.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/progressbar/progress.html",
    "<div class=\"progress\" ng-transclude></div>");
}]);

angular.module("template/progressbar/progressbar.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/progressbar/progressbar.html",
    "<div class=\"progress\">\n" +
    "  <div class=\"progress-bar\" ng-class=\"type && 'progress-bar-' + type\" role=\"progressbar\" aria-valuenow=\"{{value}}\" aria-valuemin=\"0\" aria-valuemax=\"{{max}}\" ng-style=\"{width: (percent < 100 ? percent : 100) + '%'}\" aria-valuetext=\"{{percent | number:0}}%\" ng-transclude></div>\n" +
    "</div>\n" +
    "");
}]);

angular.module("template/rating/rating.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/rating/rating.html",
    "<span ng-mouseleave=\"reset()\" ng-keydown=\"onKeydown($event)\" tabindex=\"0\" role=\"slider\" aria-valuemin=\"0\" aria-valuemax=\"{{range.length}}\" aria-valuenow=\"{{value}}\">\n" +
    "    <i ng-repeat=\"r in range track by $index\" ng-mouseenter=\"enter($index + 1)\" ng-click=\"rate($index + 1)\" class=\"glyphicon\" ng-class=\"$index < value && (r.stateOn || 'glyphicon-star') || (r.stateOff || 'glyphicon-star-empty')\">\n" +
    "        <span class=\"sr-only\">({{ $index < value ? '*' : ' ' }})</span>\n" +
    "    </i>\n" +
    "</span>");
}]);

angular.module("template/tabs/tab.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/tabs/tab.html",
    "<li ng-class=\"{active: active, disabled: disabled}\">\n" +
    "  <a href=\"#\" ng-click=\"$event.preventDefault(); select()\" tab-heading-transclude>{{heading}}</a>\n" +
    "</li>\n" +
    "");
}]);

angular.module("template/tabs/tabset.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/tabs/tabset.html",
    "<div>\n" +
    "  <ul class=\"nav nav-{{type || 'tabs'}}\" ng-class=\"{'nav-stacked': vertical, 'nav-justified': justified}\" ng-transclude></ul>\n" +
    "  <div class=\"tab-content\">\n" +
    "    <div class=\"tab-pane\" \n" +
    "         ng-repeat=\"tab in tabs\" \n" +
    "         ng-class=\"{active: tab.active}\"\n" +
    "         tab-content-transclude=\"tab\">\n" +
    "    </div>\n" +
    "  </div>\n" +
    "</div>\n" +
    "");
}]);

angular.module("template/timepicker/timepicker.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/timepicker/timepicker.html",
    "<table>\n" +
    "  <tbody>\n" +
    "    <tr class=\"text-center\" ng-show=\"::showSpinners\">\n" +
    "      <td><a ng-click=\"incrementHours()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" +
    "      <td>&nbsp;</td>\n" +
    "      <td><a ng-click=\"incrementMinutes()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-up\"></span></a></td>\n" +
    "      <td ng-show=\"showMeridian\"></td>\n" +
    "    </tr>\n" +
    "    <tr>\n" +
    "      <td class=\"form-group\" ng-class=\"{'has-error': invalidHours}\">\n" +
    "        <input style=\"width:50px;\" type=\"text\" ng-model=\"hours\" ng-change=\"updateHours()\" class=\"form-control text-center\" ng-readonly=\"::readonlyInput\" maxlength=\"2\">\n" +
    "      </td>\n" +
    "      <td>:</td>\n" +
    "      <td class=\"form-group\" ng-class=\"{'has-error': invalidMinutes}\">\n" +
    "        <input style=\"width:50px;\" type=\"text\" ng-model=\"minutes\" ng-change=\"updateMinutes()\" class=\"form-control text-center\" ng-readonly=\"::readonlyInput\" maxlength=\"2\">\n" +
    "      </td>\n" +
    "      <td ng-show=\"showMeridian\"><button type=\"button\" class=\"btn btn-default text-center\" ng-click=\"toggleMeridian()\">{{meridian}}</button></td>\n" +
    "    </tr>\n" +
    "    <tr class=\"text-center\" ng-show=\"::showSpinners\">\n" +
    "      <td><a ng-click=\"decrementHours()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" +
    "      <td>&nbsp;</td>\n" +
    "      <td><a ng-click=\"decrementMinutes()\" class=\"btn btn-link\"><span class=\"glyphicon glyphicon-chevron-down\"></span></a></td>\n" +
    "      <td ng-show=\"showMeridian\"></td>\n" +
    "    </tr>\n" +
    "  </tbody>\n" +
    "</table>\n" +
    "");
}]);

angular.module("template/typeahead/typeahead-match.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/typeahead/typeahead-match.html",
    "<a href=\"#\" ng-click=\"$event.preventDefault()\" tabindex=\"-1\" bind-html-unsafe=\"match.label | typeaheadHighlight:query\"></a>\n" +
    "");
}]);

angular.module("template/typeahead/typeahead-popup.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/typeahead/typeahead-popup.html",
    "<ul class=\"dropdown-menu\" ng-show=\"isOpen() && !moveInProgress\" ng-style=\"{top: position().top+'px', left: position().left+'px'}\" style=\"display: block;\" role=\"listbox\" aria-hidden=\"{{!isOpen()}}\">\n" +
    "    <li ng-repeat=\"match in matches track by $index\" ng-class=\"{active: isActive($index) }\" ng-mouseenter=\"selectActive($index)\" ng-click=\"selectMatch($index)\" role=\"option\" id=\"{{::match.id}}\">\n" +
    "        <div typeahead-match index=\"$index\" match=\"match\" query=\"query\" template-url=\"templateUrl\"></div>\n" +
    "    </li>\n" +
    "</ul>\n" +
    "");
}]);
!angular.$$csp() && angular.element(document).find('head').prepend('<style type="text/css">.ng-animate.item:not(.left):not(.right){-webkit-transition:0s ease-in-out left;transition:0s ease-in-out left}</style>');/*!
* @license EaselJS
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2011-2015 gskinner.com, inc.
*
* Distributed under the terms of the MIT license.
* http://www.opensource.org/licenses/mit-license.html
*
* This notice shall be included in all copies or substantial portions of the Software.
*/
this.createjs=this.createjs||{},createjs.extend=function(a,b){"use strict";function c(){this.constructor=a}return c.prototype=b.prototype,a.prototype=new c},this.createjs=this.createjs||{},createjs.promote=function(a,b){"use strict";var c=a.prototype,d=Object.getPrototypeOf&&Object.getPrototypeOf(c)||c.__proto__;if(d){c[(b+="_")+"constructor"]=d.constructor;for(var e in d)c.hasOwnProperty(e)&&"function"==typeof d[e]&&(c[b+e]=d[e])}return a},this.createjs=this.createjs||{},createjs.indexOf=function(a,b){"use strict";for(var c=0,d=a.length;d>c;c++)if(b===a[c])return c;return-1},this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c){this.type=a,this.target=null,this.currentTarget=null,this.eventPhase=0,this.bubbles=!!b,this.cancelable=!!c,this.timeStamp=(new Date).getTime(),this.defaultPrevented=!1,this.propagationStopped=!1,this.immediatePropagationStopped=!1,this.removed=!1}var b=a.prototype;b.preventDefault=function(){this.defaultPrevented=this.cancelable&&!0},b.stopPropagation=function(){this.propagationStopped=!0},b.stopImmediatePropagation=function(){this.immediatePropagationStopped=this.propagationStopped=!0},b.remove=function(){this.removed=!0},b.clone=function(){return new a(this.type,this.bubbles,this.cancelable)},b.set=function(a){for(var b in a)this[b]=a[b];return this},b.toString=function(){return"[Event (type="+this.type+")]"},createjs.Event=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(){this._listeners=null,this._captureListeners=null}var b=a.prototype;a.initialize=function(a){a.addEventListener=b.addEventListener,a.on=b.on,a.removeEventListener=a.off=b.removeEventListener,a.removeAllEventListeners=b.removeAllEventListeners,a.hasEventListener=b.hasEventListener,a.dispatchEvent=b.dispatchEvent,a._dispatchEvent=b._dispatchEvent,a.willTrigger=b.willTrigger},b.addEventListener=function(a,b,c){var d;d=c?this._captureListeners=this._captureListeners||{}:this._listeners=this._listeners||{};var e=d[a];return e&&this.removeEventListener(a,b,c),e=d[a],e?e.push(b):d[a]=[b],b},b.on=function(a,b,c,d,e,f){return b.handleEvent&&(c=c||b,b=b.handleEvent),c=c||this,this.addEventListener(a,function(a){b.call(c,a,e),d&&a.remove()},f)},b.removeEventListener=function(a,b,c){var d=c?this._captureListeners:this._listeners;if(d){var e=d[a];if(e)for(var f=0,g=e.length;g>f;f++)if(e[f]==b){1==g?delete d[a]:e.splice(f,1);break}}},b.off=b.removeEventListener,b.removeAllEventListeners=function(a){a?(this._listeners&&delete this._listeners[a],this._captureListeners&&delete this._captureListeners[a]):this._listeners=this._captureListeners=null},b.dispatchEvent=function(a,b,c){if("string"==typeof a){var d=this._listeners;if(!(b||d&&d[a]))return!0;a=new createjs.Event(a,b,c)}else a.target&&a.clone&&(a=a.clone());try{a.target=this}catch(e){}if(a.bubbles&&this.parent){for(var f=this,g=[f];f.parent;)g.push(f=f.parent);var h,i=g.length;for(h=i-1;h>=0&&!a.propagationStopped;h--)g[h]._dispatchEvent(a,1+(0==h));for(h=1;i>h&&!a.propagationStopped;h++)g[h]._dispatchEvent(a,3)}else this._dispatchEvent(a,2);return!a.defaultPrevented},b.hasEventListener=function(a){var b=this._listeners,c=this._captureListeners;return!!(b&&b[a]||c&&c[a])},b.willTrigger=function(a){for(var b=this;b;){if(b.hasEventListener(a))return!0;b=b.parent}return!1},b.toString=function(){return"[EventDispatcher]"},b._dispatchEvent=function(a,b){var c,d=1==b?this._captureListeners:this._listeners;if(a&&d){var e=d[a.type];if(!e||!(c=e.length))return;try{a.currentTarget=this}catch(f){}try{a.eventPhase=b}catch(f){}a.removed=!1,e=e.slice();for(var g=0;c>g&&!a.immediatePropagationStopped;g++){var h=e[g];h.handleEvent?h.handleEvent(a):h(a),a.removed&&(this.off(a.type,h,1==b),a.removed=!1)}}},createjs.EventDispatcher=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(){throw"Ticker cannot be instantiated."}a.RAF_SYNCHED="synched",a.RAF="raf",a.TIMEOUT="timeout",a.useRAF=!1,a.timingMode=null,a.maxDelta=0,a.paused=!1,a.removeEventListener=null,a.removeAllEventListeners=null,a.dispatchEvent=null,a.hasEventListener=null,a._listeners=null,createjs.EventDispatcher.initialize(a),a._addEventListener=a.addEventListener,a.addEventListener=function(){return!a._inited&&a.init(),a._addEventListener.apply(a,arguments)},a._inited=!1,a._startTime=0,a._pausedTime=0,a._ticks=0,a._pausedTicks=0,a._interval=50,a._lastTime=0,a._times=null,a._tickTimes=null,a._timerId=null,a._raf=!0,a.setInterval=function(b){a._interval=b,a._inited&&a._setupTick()},a.getInterval=function(){return a._interval},a.setFPS=function(b){a.setInterval(1e3/b)},a.getFPS=function(){return 1e3/a._interval};try{Object.defineProperties(a,{interval:{get:a.getInterval,set:a.setInterval},framerate:{get:a.getFPS,set:a.setFPS}})}catch(b){console.log(b)}a.init=function(){a._inited||(a._inited=!0,a._times=[],a._tickTimes=[],a._startTime=a._getTime(),a._times.push(a._lastTime=0),a.interval=a._interval)},a.reset=function(){if(a._raf){var b=window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame;b&&b(a._timerId)}else clearTimeout(a._timerId);a.removeAllEventListeners("tick"),a._timerId=a._times=a._tickTimes=null,a._startTime=a._lastTime=a._ticks=0,a._inited=!1},a.getMeasuredTickTime=function(b){var c=0,d=a._tickTimes;if(!d||d.length<1)return-1;b=Math.min(d.length,b||0|a.getFPS());for(var e=0;b>e;e++)c+=d[e];return c/b},a.getMeasuredFPS=function(b){var c=a._times;return!c||c.length<2?-1:(b=Math.min(c.length-1,b||0|a.getFPS()),1e3/((c[0]-c[b])/b))},a.setPaused=function(b){a.paused=b},a.getPaused=function(){return a.paused},a.getTime=function(b){return a._startTime?a._getTime()-(b?a._pausedTime:0):-1},a.getEventTime=function(b){return a._startTime?(a._lastTime||a._startTime)-(b?a._pausedTime:0):-1},a.getTicks=function(b){return a._ticks-(b?a._pausedTicks:0)},a._handleSynch=function(){a._timerId=null,a._setupTick(),a._getTime()-a._lastTime>=.97*(a._interval-1)&&a._tick()},a._handleRAF=function(){a._timerId=null,a._setupTick(),a._tick()},a._handleTimeout=function(){a._timerId=null,a._setupTick(),a._tick()},a._setupTick=function(){if(null==a._timerId){var b=a.timingMode||a.useRAF&&a.RAF_SYNCHED;if(b==a.RAF_SYNCHED||b==a.RAF){var c=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame;if(c)return a._timerId=c(b==a.RAF?a._handleRAF:a._handleSynch),void(a._raf=!0)}a._raf=!1,a._timerId=setTimeout(a._handleTimeout,a._interval)}},a._tick=function(){var b=a.paused,c=a._getTime(),d=c-a._lastTime;if(a._lastTime=c,a._ticks++,b&&(a._pausedTicks++,a._pausedTime+=d),a.hasEventListener("tick")){var e=new createjs.Event("tick"),f=a.maxDelta;e.delta=f&&d>f?f:d,e.paused=b,e.time=c,e.runTime=c-a._pausedTime,a.dispatchEvent(e)}for(a._tickTimes.unshift(a._getTime()-c);a._tickTimes.length>100;)a._tickTimes.pop();for(a._times.unshift(c);a._times.length>100;)a._times.pop()};var c=window.performance&&(performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow);a._getTime=function(){return(c&&c.call(performance)||(new Date).getTime())-a._startTime},createjs.Ticker=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(){throw"UID cannot be instantiated"}a._nextID=0,a.get=function(){return a._nextID++},createjs.UID=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k){this.Event_constructor(a,b,c),this.stageX=d,this.stageY=e,this.rawX=null==i?d:i,this.rawY=null==j?e:j,this.nativeEvent=f,this.pointerID=g,this.primary=!!h,this.relatedTarget=k}var b=createjs.extend(a,createjs.Event);b._get_localX=function(){return this.currentTarget.globalToLocal(this.rawX,this.rawY).x},b._get_localY=function(){return this.currentTarget.globalToLocal(this.rawX,this.rawY).y},b._get_isTouch=function(){return-1!==this.pointerID};try{Object.defineProperties(b,{localX:{get:b._get_localX},localY:{get:b._get_localY},isTouch:{get:b._get_isTouch}})}catch(c){}b.clone=function(){return new a(this.type,this.bubbles,this.cancelable,this.stageX,this.stageY,this.nativeEvent,this.pointerID,this.primary,this.rawX,this.rawY)},b.toString=function(){return"[MouseEvent (type="+this.type+" stageX="+this.stageX+" stageY="+this.stageY+")]"},createjs.MouseEvent=createjs.promote(a,"Event")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d,e,f){this.setValues(a,b,c,d,e,f)}var b=a.prototype;a.DEG_TO_RAD=Math.PI/180,a.identity=null,b.setValues=function(a,b,c,d,e,f){return this.a=null==a?1:a,this.b=b||0,this.c=c||0,this.d=null==d?1:d,this.tx=e||0,this.ty=f||0,this},b.append=function(a,b,c,d,e,f){var g=this.a,h=this.b,i=this.c,j=this.d;return(1!=a||0!=b||0!=c||1!=d)&&(this.a=g*a+i*b,this.b=h*a+j*b,this.c=g*c+i*d,this.d=h*c+j*d),this.tx=g*e+i*f+this.tx,this.ty=h*e+j*f+this.ty,this},b.prepend=function(a,b,c,d,e,f){var g=this.a,h=this.c,i=this.tx;return this.a=a*g+c*this.b,this.b=b*g+d*this.b,this.c=a*h+c*this.d,this.d=b*h+d*this.d,this.tx=a*i+c*this.ty+e,this.ty=b*i+d*this.ty+f,this},b.appendMatrix=function(a){return this.append(a.a,a.b,a.c,a.d,a.tx,a.ty)},b.prependMatrix=function(a){return this.prepend(a.a,a.b,a.c,a.d,a.tx,a.ty)},b.appendTransform=function(b,c,d,e,f,g,h,i,j){if(f%360)var k=f*a.DEG_TO_RAD,l=Math.cos(k),m=Math.sin(k);else l=1,m=0;return g||h?(g*=a.DEG_TO_RAD,h*=a.DEG_TO_RAD,this.append(Math.cos(h),Math.sin(h),-Math.sin(g),Math.cos(g),b,c),this.append(l*d,m*d,-m*e,l*e,0,0)):this.append(l*d,m*d,-m*e,l*e,b,c),(i||j)&&(this.tx-=i*this.a+j*this.c,this.ty-=i*this.b+j*this.d),this},b.prependTransform=function(b,c,d,e,f,g,h,i,j){if(f%360)var k=f*a.DEG_TO_RAD,l=Math.cos(k),m=Math.sin(k);else l=1,m=0;return(i||j)&&(this.tx-=i,this.ty-=j),g||h?(g*=a.DEG_TO_RAD,h*=a.DEG_TO_RAD,this.prepend(l*d,m*d,-m*e,l*e,0,0),this.prepend(Math.cos(h),Math.sin(h),-Math.sin(g),Math.cos(g),b,c)):this.prepend(l*d,m*d,-m*e,l*e,b,c),this},b.rotate=function(b){b*=a.DEG_TO_RAD;var c=Math.cos(b),d=Math.sin(b),e=this.a,f=this.b;return this.a=e*c+this.c*d,this.b=f*c+this.d*d,this.c=-e*d+this.c*c,this.d=-f*d+this.d*c,this},b.skew=function(b,c){return b*=a.DEG_TO_RAD,c*=a.DEG_TO_RAD,this.append(Math.cos(c),Math.sin(c),-Math.sin(b),Math.cos(b),0,0),this},b.scale=function(a,b){return this.a*=a,this.b*=a,this.c*=b,this.d*=b,this},b.translate=function(a,b){return this.tx+=this.a*a+this.c*b,this.ty+=this.b*a+this.d*b,this},b.identity=function(){return this.a=this.d=1,this.b=this.c=this.tx=this.ty=0,this},b.invert=function(){var a=this.a,b=this.b,c=this.c,d=this.d,e=this.tx,f=a*d-b*c;return this.a=d/f,this.b=-b/f,this.c=-c/f,this.d=a/f,this.tx=(c*this.ty-d*e)/f,this.ty=-(a*this.ty-b*e)/f,this},b.isIdentity=function(){return 0===this.tx&&0===this.ty&&1===this.a&&0===this.b&&0===this.c&&1===this.d},b.equals=function(a){return this.tx===a.tx&&this.ty===a.ty&&this.a===a.a&&this.b===a.b&&this.c===a.c&&this.d===a.d},b.transformPoint=function(a,b,c){return c=c||{},c.x=a*this.a+b*this.c+this.tx,c.y=a*this.b+b*this.d+this.ty,c},b.decompose=function(b){null==b&&(b={}),b.x=this.tx,b.y=this.ty,b.scaleX=Math.sqrt(this.a*this.a+this.b*this.b),b.scaleY=Math.sqrt(this.c*this.c+this.d*this.d);var c=Math.atan2(-this.c,this.d),d=Math.atan2(this.b,this.a),e=Math.abs(1-c/d);return 1e-5>e?(b.rotation=d/a.DEG_TO_RAD,this.a<0&&this.d>=0&&(b.rotation+=b.rotation<=0?180:-180),b.skewX=b.skewY=0):(b.skewX=c/a.DEG_TO_RAD,b.skewY=d/a.DEG_TO_RAD),b},b.copy=function(a){return this.setValues(a.a,a.b,a.c,a.d,a.tx,a.ty)},b.clone=function(){return new a(this.a,this.b,this.c,this.d,this.tx,this.ty)},b.toString=function(){return"[Matrix2D (a="+this.a+" b="+this.b+" c="+this.c+" d="+this.d+" tx="+this.tx+" ty="+this.ty+")]"},a.identity=new a,createjs.Matrix2D=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d,e){this.setValues(a,b,c,d,e)}var b=a.prototype;b.setValues=function(a,b,c,d,e){return this.visible=null==a?!0:!!a,this.alpha=null==b?1:b,this.shadow=c,this.compositeOperation=d,this.matrix=e||this.matrix&&this.matrix.identity()||new createjs.Matrix2D,this},b.append=function(a,b,c,d,e){return this.alpha*=b,this.shadow=c||this.shadow,this.compositeOperation=d||this.compositeOperation,this.visible=this.visible&&a,e&&this.matrix.appendMatrix(e),this},b.prepend=function(a,b,c,d,e){return this.alpha*=b,this.shadow=this.shadow||c,this.compositeOperation=this.compositeOperation||d,this.visible=this.visible&&a,e&&this.matrix.prependMatrix(e),this},b.identity=function(){return this.visible=!0,this.alpha=1,this.shadow=this.compositeOperation=null,this.matrix.identity(),this},b.clone=function(){return new a(this.alpha,this.shadow,this.compositeOperation,this.visible,this.matrix.clone())},createjs.DisplayProps=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b){this.setValues(a,b)}var b=a.prototype;b.setValues=function(a,b){return this.x=a||0,this.y=b||0,this},b.copy=function(a){return this.x=a.x,this.y=a.y,this},b.clone=function(){return new a(this.x,this.y)},b.toString=function(){return"[Point (x="+this.x+" y="+this.y+")]"},createjs.Point=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d){this.setValues(a,b,c,d)}var b=a.prototype;b.setValues=function(a,b,c,d){return this.x=a||0,this.y=b||0,this.width=c||0,this.height=d||0,this},b.extend=function(a,b,c,d){return c=c||0,d=d||0,a+c>this.x+this.width&&(this.width=a+c-this.x),b+d>this.y+this.height&&(this.height=b+d-this.y),a<this.x&&(this.width+=this.x-a,this.x=a),b<this.y&&(this.height+=this.y-b,this.y=b),this},b.pad=function(a,b,c,d){return this.x-=b,this.y-=a,this.width+=b+d,this.height+=a+c,this},b.copy=function(a){return this.setValues(a.x,a.y,a.width,a.height)},b.contains=function(a,b,c,d){return c=c||0,d=d||0,a>=this.x&&a+c<=this.x+this.width&&b>=this.y&&b+d<=this.y+this.height},b.union=function(a){return this.clone().extend(a.x,a.y,a.width,a.height)},b.intersection=function(b){var c=b.x,d=b.y,e=c+b.width,f=d+b.height;return this.x>c&&(c=this.x),this.y>d&&(d=this.y),this.x+this.width<e&&(e=this.x+this.width),this.y+this.height<f&&(f=this.y+this.height),c>=e||d>=f?null:new a(c,d,e-c,f-d)},b.intersects=function(a){return a.x<=this.x+this.width&&this.x<=a.x+a.width&&a.y<=this.y+this.height&&this.y<=a.y+a.height},b.isEmpty=function(){return this.width<=0||this.height<=0},b.clone=function(){return new a(this.x,this.y,this.width,this.height)},b.toString=function(){return"[Rectangle (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")]"},createjs.Rectangle=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d,e,f,g){a.addEventListener&&(this.target=a,this.overLabel=null==c?"over":c,this.outLabel=null==b?"out":b,this.downLabel=null==d?"down":d,this.play=e,this._isPressed=!1,this._isOver=!1,this._enabled=!1,a.mouseChildren=!1,this.enabled=!0,this.handleEvent({}),f&&(g&&(f.actionsEnabled=!1,f.gotoAndStop&&f.gotoAndStop(g)),a.hitArea=f))}var b=a.prototype;b.setEnabled=function(a){if(a!=this._enabled){var b=this.target;this._enabled=a,a?(b.cursor="pointer",b.addEventListener("rollover",this),b.addEventListener("rollout",this),b.addEventListener("mousedown",this),b.addEventListener("pressup",this),b._reset&&(b.__reset=b._reset,b._reset=this._reset)):(b.cursor=null,b.removeEventListener("rollover",this),b.removeEventListener("rollout",this),b.removeEventListener("mousedown",this),b.removeEventListener("pressup",this),b.__reset&&(b._reset=b.__reset,delete b.__reset))}},b.getEnabled=function(){return this._enabled};try{Object.defineProperties(b,{enabled:{get:b.getEnabled,set:b.setEnabled}})}catch(c){}b.toString=function(){return"[ButtonHelper]"},b.handleEvent=function(a){var b,c=this.target,d=a.type;"mousedown"==d?(this._isPressed=!0,b=this.downLabel):"pressup"==d?(this._isPressed=!1,b=this._isOver?this.overLabel:this.outLabel):"rollover"==d?(this._isOver=!0,b=this._isPressed?this.downLabel:this.overLabel):(this._isOver=!1,b=this._isPressed?this.overLabel:this.outLabel),this.play?c.gotoAndPlay&&c.gotoAndPlay(b):c.gotoAndStop&&c.gotoAndStop(b)},b._reset=function(){var a=this.paused;this.__reset(),this.paused=a},createjs.ButtonHelper=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d){this.color=a||"black",this.offsetX=b||0,this.offsetY=c||0,this.blur=d||0}var b=a.prototype;a.identity=new a("transparent",0,0,0),b.toString=function(){return"[Shadow]"},b.clone=function(){return new a(this.color,this.offsetX,this.offsetY,this.blur)},createjs.Shadow=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.EventDispatcher_constructor(),this.complete=!0,this.framerate=0,this._animations=null,this._frames=null,this._images=null,this._data=null,this._loadCount=0,this._frameHeight=0,this._frameWidth=0,this._numFrames=0,this._regX=0,this._regY=0,this._spacing=0,this._margin=0,this._parseData(a)}var b=createjs.extend(a,createjs.EventDispatcher);b.getAnimations=function(){return this._animations.slice()};try{Object.defineProperties(b,{animations:{get:b.getAnimations}})}catch(c){}b.getNumFrames=function(a){if(null==a)return this._frames?this._frames.length:this._numFrames||0;var b=this._data[a];return null==b?0:b.frames.length},b.getAnimation=function(a){return this._data[a]},b.getFrame=function(a){var b;return this._frames&&(b=this._frames[a])?b:null},b.getFrameBounds=function(a,b){var c=this.getFrame(a);return c?(b||new createjs.Rectangle).setValues(-c.regX,-c.regY,c.rect.width,c.rect.height):null},b.toString=function(){return"[SpriteSheet]"},b.clone=function(){throw"SpriteSheet cannot be cloned."},b._parseData=function(a){var b,c,d,e;if(null!=a){if(this.framerate=a.framerate||0,a.images&&(c=a.images.length)>0)for(e=this._images=[],b=0;c>b;b++){var f=a.images[b];if("string"==typeof f){var g=f;f=document.createElement("img"),f.src=g}e.push(f),f.getContext||f.naturalWidth||(this._loadCount++,this.complete=!1,function(a,b){f.onload=function(){a._handleImageLoad(b)}}(this,g),function(a,b){f.onerror=function(){a._handleImageError(b)}}(this,g))}if(null==a.frames);else if(Array.isArray(a.frames))for(this._frames=[],e=a.frames,b=0,c=e.length;c>b;b++){var h=e[b];this._frames.push({image:this._images[h[4]?h[4]:0],rect:new createjs.Rectangle(h[0],h[1],h[2],h[3]),regX:h[5]||0,regY:h[6]||0})}else d=a.frames,this._frameWidth=d.width,this._frameHeight=d.height,this._regX=d.regX||0,this._regY=d.regY||0,this._spacing=d.spacing||0,this._margin=d.margin||0,this._numFrames=d.count,0==this._loadCount&&this._calculateFrames();if(this._animations=[],null!=(d=a.animations)){this._data={};var i;for(i in d){var j={name:i},k=d[i];if("number"==typeof k)e=j.frames=[k];else if(Array.isArray(k))if(1==k.length)j.frames=[k[0]];else for(j.speed=k[3],j.next=k[2],e=j.frames=[],b=k[0];b<=k[1];b++)e.push(b);else{j.speed=k.speed,j.next=k.next;var l=k.frames;e=j.frames="number"==typeof l?[l]:l.slice(0)}(j.next===!0||void 0===j.next)&&(j.next=i),(j.next===!1||e.length<2&&j.next==i)&&(j.next=null),j.speed||(j.speed=1),this._animations.push(i),this._data[i]=j}}}},b._handleImageLoad=function(){0==--this._loadCount&&(this._calculateFrames(),this.complete=!0,this.dispatchEvent("complete"))},b._handleImageError=function(a){var b=new createjs.Event("error");b.src=a,this.dispatchEvent(b),0==--this._loadCount&&this.dispatchEvent("complete")},b._calculateFrames=function(){if(!this._frames&&0!=this._frameWidth){this._frames=[];var a=this._numFrames||1e5,b=0,c=this._frameWidth,d=this._frameHeight,e=this._spacing,f=this._margin;a:for(var g=0,h=this._images;g<h.length;g++)for(var i=h[g],j=i.width,k=i.height,l=f;k-f-d>=l;){for(var m=f;j-f-c>=m;){if(b>=a)break a;b++,this._frames.push({image:i,rect:new createjs.Rectangle(m,l,c,d),regX:this._regX,regY:this._regY}),m+=c+e}l+=d+e}this._numFrames=b}},createjs.SpriteSheet=createjs.promote(a,"EventDispatcher")}(),this.createjs=this.createjs||{},function(){"use strict";function a(){this.command=null,this._stroke=null,this._strokeStyle=null,this._oldStrokeStyle=null,this._strokeDash=null,this._oldStrokeDash=null,this._strokeIgnoreScale=!1,this._fill=null,this._instructions=[],this._commitIndex=0,this._activeInstructions=[],this._dirty=!1,this._storeIndex=0,this.clear()}var b=a.prototype,c=a;a.getRGB=function(a,b,c,d){return null!=a&&null==c&&(d=b,c=255&a,b=a>>8&255,a=a>>16&255),null==d?"rgb("+a+","+b+","+c+")":"rgba("+a+","+b+","+c+","+d+")"},a.getHSL=function(a,b,c,d){return null==d?"hsl("+a%360+","+b+"%,"+c+"%)":"hsla("+a%360+","+b+"%,"+c+"%,"+d+")"},a.BASE_64={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,a:26,b:27,c:28,d:29,e:30,f:31,g:32,h:33,i:34,j:35,k:36,l:37,m:38,n:39,o:40,p:41,q:42,r:43,s:44,t:45,u:46,v:47,w:48,x:49,y:50,z:51,0:52,1:53,2:54,3:55,4:56,5:57,6:58,7:59,8:60,9:61,"+":62,"/":63},a.STROKE_CAPS_MAP=["butt","round","square"],a.STROKE_JOINTS_MAP=["miter","round","bevel"];var d=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");d.getContext&&(a._ctx=d.getContext("2d"),d.width=d.height=1),b.getInstructions=function(){return this._updateInstructions(),this._instructions};try{Object.defineProperties(b,{instructions:{get:b.getInstructions}})}catch(e){}b.isEmpty=function(){return!(this._instructions.length||this._activeInstructions.length)},b.draw=function(a,b){this._updateInstructions();for(var c=this._instructions,d=this._storeIndex,e=c.length;e>d;d++)c[d].exec(a,b)},b.drawAsPath=function(a){this._updateInstructions();for(var b,c=this._instructions,d=this._storeIndex,e=c.length;e>d;d++)(b=c[d]).path!==!1&&b.exec(a)},b.moveTo=function(a,b){return this.append(new c.MoveTo(a,b),!0)},b.lineTo=function(a,b){return this.append(new c.LineTo(a,b))},b.arcTo=function(a,b,d,e,f){return this.append(new c.ArcTo(a,b,d,e,f))},b.arc=function(a,b,d,e,f,g){return this.append(new c.Arc(a,b,d,e,f,g))},b.quadraticCurveTo=function(a,b,d,e){return this.append(new c.QuadraticCurveTo(a,b,d,e))},b.bezierCurveTo=function(a,b,d,e,f,g){return this.append(new c.BezierCurveTo(a,b,d,e,f,g))},b.rect=function(a,b,d,e){return this.append(new c.Rect(a,b,d,e))},b.closePath=function(){return this._activeInstructions.length?this.append(new c.ClosePath):this},b.clear=function(){return this._instructions.length=this._activeInstructions.length=this._commitIndex=0,this._strokeStyle=this._oldStrokeStyle=this._stroke=this._fill=this._strokeDash=this._oldStrokeDash=null,this._dirty=this._strokeIgnoreScale=!1,this},b.beginFill=function(a){return this._setFill(a?new c.Fill(a):null)},b.beginLinearGradientFill=function(a,b,d,e,f,g){return this._setFill((new c.Fill).linearGradient(a,b,d,e,f,g))},b.beginRadialGradientFill=function(a,b,d,e,f,g,h,i){return this._setFill((new c.Fill).radialGradient(a,b,d,e,f,g,h,i))},b.beginBitmapFill=function(a,b,d){return this._setFill(new c.Fill(null,d).bitmap(a,b))},b.endFill=function(){return this.beginFill()},b.setStrokeStyle=function(a,b,d,e,f){return this._updateInstructions(!0),this._strokeStyle=this.command=new c.StrokeStyle(a,b,d,e,f),this._stroke&&(this._stroke.ignoreScale=f),this._strokeIgnoreScale=f,this},b.setStrokeDash=function(a,b){return this._updateInstructions(!0),this._strokeDash=this.command=new c.StrokeDash(a,b),this},b.beginStroke=function(a){return this._setStroke(a?new c.Stroke(a):null)},b.beginLinearGradientStroke=function(a,b,d,e,f,g){return this._setStroke((new c.Stroke).linearGradient(a,b,d,e,f,g))},b.beginRadialGradientStroke=function(a,b,d,e,f,g,h,i){return this._setStroke((new c.Stroke).radialGradient(a,b,d,e,f,g,h,i))},b.beginBitmapStroke=function(a,b){return this._setStroke((new c.Stroke).bitmap(a,b))},b.endStroke=function(){return this.beginStroke()},b.curveTo=b.quadraticCurveTo,b.drawRect=b.rect,b.drawRoundRect=function(a,b,c,d,e){return this.drawRoundRectComplex(a,b,c,d,e,e,e,e)},b.drawRoundRectComplex=function(a,b,d,e,f,g,h,i){return this.append(new c.RoundRect(a,b,d,e,f,g,h,i))},b.drawCircle=function(a,b,d){return this.append(new c.Circle(a,b,d))},b.drawEllipse=function(a,b,d,e){return this.append(new c.Ellipse(a,b,d,e))},b.drawPolyStar=function(a,b,d,e,f,g){return this.append(new c.PolyStar(a,b,d,e,f,g))},b.append=function(a,b){return this._activeInstructions.push(a),this.command=a,b||(this._dirty=!0),this},b.decodePath=function(b){for(var c=[this.moveTo,this.lineTo,this.quadraticCurveTo,this.bezierCurveTo,this.closePath],d=[2,2,4,6,0],e=0,f=b.length,g=[],h=0,i=0,j=a.BASE_64;f>e;){var k=b.charAt(e),l=j[k],m=l>>3,n=c[m];if(!n||3&l)throw"bad path data (@"+e+"): "+k;var o=d[m];m||(h=i=0),g.length=0,e++;for(var p=(l>>2&1)+2,q=0;o>q;q++){var r=j[b.charAt(e)],s=r>>5?-1:1;r=(31&r)<<6|j[b.charAt(e+1)],3==p&&(r=r<<6|j[b.charAt(e+2)]),r=s*r/10,q%2?h=r+=h:i=r+=i,g[q]=r,e+=p}n.apply(this,g)}return this},b.store=function(){return this._updateInstructions(!0),this._storeIndex=this._instructions.length,this},b.unstore=function(){return this._storeIndex=0,this},b.clone=function(){var b=new a;return b.command=this.command,b._stroke=this._stroke,b._strokeStyle=this._strokeStyle,b._strokeDash=this._strokeDash,b._strokeIgnoreScale=this._strokeIgnoreScale,b._fill=this._fill,b._instructions=this._instructions.slice(),b._commitIndex=this._commitIndex,b._activeInstructions=this._activeInstructions.slice(),b._dirty=this._dirty,b._storeIndex=this._storeIndex,b},b.toString=function(){return"[Graphics]"},b.mt=b.moveTo,b.lt=b.lineTo,b.at=b.arcTo,b.bt=b.bezierCurveTo,b.qt=b.quadraticCurveTo,b.a=b.arc,b.r=b.rect,b.cp=b.closePath,b.c=b.clear,b.f=b.beginFill,b.lf=b.beginLinearGradientFill,b.rf=b.beginRadialGradientFill,b.bf=b.beginBitmapFill,b.ef=b.endFill,b.ss=b.setStrokeStyle,b.sd=b.setStrokeDash,b.s=b.beginStroke,b.ls=b.beginLinearGradientStroke,b.rs=b.beginRadialGradientStroke,b.bs=b.beginBitmapStroke,b.es=b.endStroke,b.dr=b.drawRect,b.rr=b.drawRoundRect,b.rc=b.drawRoundRectComplex,b.dc=b.drawCircle,b.de=b.drawEllipse,b.dp=b.drawPolyStar,b.p=b.decodePath,b._updateInstructions=function(b){var c=this._instructions,d=this._activeInstructions,e=this._commitIndex;if(this._dirty&&d.length){c.length=e,c.push(a.beginCmd);var f=d.length,g=c.length;c.length=g+f;for(var h=0;f>h;h++)c[h+g]=d[h];this._fill&&c.push(this._fill),this._stroke&&(this._strokeDash!==this._oldStrokeDash&&(this._oldStrokeDash=this._strokeDash,c.push(this._strokeDash)),this._strokeStyle!==this._oldStrokeStyle&&(this._oldStrokeStyle=this._strokeStyle,c.push(this._strokeStyle)),c.push(this._stroke)),this._dirty=!1}b&&(d.length=0,this._commitIndex=c.length)},b._setFill=function(a){return this._updateInstructions(!0),this.command=this._fill=a,this},b._setStroke=function(a){return this._updateInstructions(!0),(this.command=this._stroke=a)&&(a.ignoreScale=this._strokeIgnoreScale),this},(c.LineTo=function(a,b){this.x=a,this.y=b}).prototype.exec=function(a){a.lineTo(this.x,this.y)},(c.MoveTo=function(a,b){this.x=a,this.y=b}).prototype.exec=function(a){a.moveTo(this.x,this.y)},(c.ArcTo=function(a,b,c,d,e){this.x1=a,this.y1=b,this.x2=c,this.y2=d,this.radius=e}).prototype.exec=function(a){a.arcTo(this.x1,this.y1,this.x2,this.y2,this.radius)},(c.Arc=function(a,b,c,d,e,f){this.x=a,this.y=b,this.radius=c,this.startAngle=d,this.endAngle=e,this.anticlockwise=!!f}).prototype.exec=function(a){a.arc(this.x,this.y,this.radius,this.startAngle,this.endAngle,this.anticlockwise)},(c.QuadraticCurveTo=function(a,b,c,d){this.cpx=a,this.cpy=b,this.x=c,this.y=d}).prototype.exec=function(a){a.quadraticCurveTo(this.cpx,this.cpy,this.x,this.y)},(c.BezierCurveTo=function(a,b,c,d,e,f){this.cp1x=a,this.cp1y=b,this.cp2x=c,this.cp2y=d,this.x=e,this.y=f}).prototype.exec=function(a){a.bezierCurveTo(this.cp1x,this.cp1y,this.cp2x,this.cp2y,this.x,this.y)},(c.Rect=function(a,b,c,d){this.x=a,this.y=b,this.w=c,this.h=d}).prototype.exec=function(a){a.rect(this.x,this.y,this.w,this.h)},(c.ClosePath=function(){}).prototype.exec=function(a){a.closePath()},(c.BeginPath=function(){}).prototype.exec=function(a){a.beginPath()},b=(c.Fill=function(a,b){this.style=a,this.matrix=b}).prototype,b.exec=function(a){if(this.style){a.fillStyle=this.style;var b=this.matrix;b&&(a.save(),a.transform(b.a,b.b,b.c,b.d,b.tx,b.ty)),a.fill(),b&&a.restore()}},b.linearGradient=function(b,c,d,e,f,g){for(var h=this.style=a._ctx.createLinearGradient(d,e,f,g),i=0,j=b.length;j>i;i++)h.addColorStop(c[i],b[i]);return h.props={colors:b,ratios:c,x0:d,y0:e,x1:f,y1:g,type:"linear"},this},b.radialGradient=function(b,c,d,e,f,g,h,i){for(var j=this.style=a._ctx.createRadialGradient(d,e,f,g,h,i),k=0,l=b.length;l>k;k++)j.addColorStop(c[k],b[k]);return j.props={colors:b,ratios:c,x0:d,y0:e,r0:f,x1:g,y1:h,r1:i,type:"radial"},this},b.bitmap=function(b,c){if(b.naturalWidth||b.getContext||b.readyState>=2){var d=this.style=a._ctx.createPattern(b,c||"");d.props={image:b,repetition:c,type:"bitmap"}}return this},b.path=!1,b=(c.Stroke=function(a,b){this.style=a,this.ignoreScale=b}).prototype,b.exec=function(a){this.style&&(a.strokeStyle=this.style,this.ignoreScale&&(a.save(),a.setTransform(1,0,0,1,0,0)),a.stroke(),this.ignoreScale&&a.restore())},b.linearGradient=c.Fill.prototype.linearGradient,b.radialGradient=c.Fill.prototype.radialGradient,b.bitmap=c.Fill.prototype.bitmap,b.path=!1,b=(c.StrokeStyle=function(a,b,c,d,e){this.width=a,this.caps=b,this.joints=c,this.miterLimit=d,this.ignoreScale=e}).prototype,b.exec=function(b){b.lineWidth=null==this.width?"1":this.width,b.lineCap=null==this.caps?"butt":isNaN(this.caps)?this.caps:a.STROKE_CAPS_MAP[this.caps],b.lineJoin=null==this.joints?"miter":isNaN(this.joints)?this.joints:a.STROKE_JOINTS_MAP[this.joints],b.miterLimit=null==this.miterLimit?"10":this.miterLimit,b.ignoreScale=null==this.ignoreScale?!1:this.ignoreScale},b.path=!1,(c.StrokeDash=function(a,b){this.segments=a,this.offset=b||0}).prototype.exec=function(a){a.setLineDash&&(a.setLineDash(this.segments||c.StrokeDash.EMPTY_SEGMENTS),a.lineDashOffset=this.offset||0)},c.StrokeDash.EMPTY_SEGMENTS=[],(c.RoundRect=function(a,b,c,d,e,f,g,h){this.x=a,this.y=b,this.w=c,this.h=d,this.radiusTL=e,this.radiusTR=f,this.radiusBR=g,this.radiusBL=h}).prototype.exec=function(a){var b=(j>i?i:j)/2,c=0,d=0,e=0,f=0,g=this.x,h=this.y,i=this.w,j=this.h,k=this.radiusTL,l=this.radiusTR,m=this.radiusBR,n=this.radiusBL;0>k&&(k*=c=-1),k>b&&(k=b),0>l&&(l*=d=-1),l>b&&(l=b),0>m&&(m*=e=-1),m>b&&(m=b),0>n&&(n*=f=-1),n>b&&(n=b),a.moveTo(g+i-l,h),a.arcTo(g+i+l*d,h-l*d,g+i,h+l,l),a.lineTo(g+i,h+j-m),a.arcTo(g+i+m*e,h+j+m*e,g+i-m,h+j,m),a.lineTo(g+n,h+j),a.arcTo(g-n*f,h+j+n*f,g,h+j-n,n),a.lineTo(g,h+k),a.arcTo(g-k*c,h-k*c,g+k,h,k),a.closePath()},(c.Circle=function(a,b,c){this.x=a,this.y=b,this.radius=c}).prototype.exec=function(a){a.arc(this.x,this.y,this.radius,0,2*Math.PI)},(c.Ellipse=function(a,b,c,d){this.x=a,this.y=b,this.w=c,this.h=d}).prototype.exec=function(a){var b=this.x,c=this.y,d=this.w,e=this.h,f=.5522848,g=d/2*f,h=e/2*f,i=b+d,j=c+e,k=b+d/2,l=c+e/2;a.moveTo(b,l),a.bezierCurveTo(b,l-h,k-g,c,k,c),a.bezierCurveTo(k+g,c,i,l-h,i,l),a.bezierCurveTo(i,l+h,k+g,j,k,j),a.bezierCurveTo(k-g,j,b,l+h,b,l)},(c.PolyStar=function(a,b,c,d,e,f){this.x=a,this.y=b,this.radius=c,this.sides=d,this.pointSize=e,this.angle=f}).prototype.exec=function(a){var b=this.x,c=this.y,d=this.radius,e=(this.angle||0)/180*Math.PI,f=this.sides,g=1-(this.pointSize||0),h=Math.PI/f;a.moveTo(b+Math.cos(e)*d,c+Math.sin(e)*d);for(var i=0;f>i;i++)e+=h,1!=g&&a.lineTo(b+Math.cos(e)*d*g,c+Math.sin(e)*d*g),e+=h,a.lineTo(b+Math.cos(e)*d,c+Math.sin(e)*d);a.closePath()},a.beginCmd=new c.BeginPath,createjs.Graphics=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(){this.EventDispatcher_constructor(),this.alpha=1,this.cacheCanvas=null,this.cacheID=0,this.id=createjs.UID.get(),this.mouseEnabled=!0,this.tickEnabled=!0,this.name=null,this.parent=null,this.regX=0,this.regY=0,this.rotation=0,this.scaleX=1,this.scaleY=1,this.skewX=0,this.skewY=0,this.shadow=null,this.visible=!0,this.x=0,this.y=0,this.transformMatrix=null,this.compositeOperation=null,this.snapToPixel=!0,this.filters=null,this.mask=null,this.hitArea=null,this.cursor=null,this._cacheOffsetX=0,this._cacheOffsetY=0,this._filterOffsetX=0,this._filterOffsetY=0,this._cacheScale=1,this._cacheDataURLID=0,this._cacheDataURL=null,this._props=new createjs.DisplayProps,this._rectangle=new createjs.Rectangle,this._bounds=null
}var b=createjs.extend(a,createjs.EventDispatcher);a._MOUSE_EVENTS=["click","dblclick","mousedown","mouseout","mouseover","pressmove","pressup","rollout","rollover"],a.suppressCrossDomainErrors=!1,a._snapToPixelEnabled=!1;var c=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");c.getContext&&(a._hitTestCanvas=c,a._hitTestContext=c.getContext("2d"),c.width=c.height=1),a._nextCacheID=1,b.getStage=function(){for(var a=this,b=createjs.Stage;a.parent;)a=a.parent;return a instanceof b?a:null};try{Object.defineProperties(b,{stage:{get:b.getStage}})}catch(d){}b.isVisible=function(){return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY)},b.draw=function(a,b){var c=this.cacheCanvas;if(b||!c)return!1;var d=this._cacheScale;return a.drawImage(c,this._cacheOffsetX+this._filterOffsetX,this._cacheOffsetY+this._filterOffsetY,c.width/d,c.height/d),!0},b.updateContext=function(b){var c=this,d=c.mask,e=c._props.matrix;d&&d.graphics&&!d.graphics.isEmpty()&&(d.getMatrix(e),b.transform(e.a,e.b,e.c,e.d,e.tx,e.ty),d.graphics.drawAsPath(b),b.clip(),e.invert(),b.transform(e.a,e.b,e.c,e.d,e.tx,e.ty)),this.getMatrix(e);var f=e.tx,g=e.ty;a._snapToPixelEnabled&&c.snapToPixel&&(f=f+(0>f?-.5:.5)|0,g=g+(0>g?-.5:.5)|0),b.transform(e.a,e.b,e.c,e.d,f,g),b.globalAlpha*=c.alpha,c.compositeOperation&&(b.globalCompositeOperation=c.compositeOperation),c.shadow&&this._applyShadow(b,c.shadow)},b.cache=function(a,b,c,d,e){e=e||1,this.cacheCanvas||(this.cacheCanvas=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")),this._cacheWidth=c,this._cacheHeight=d,this._cacheOffsetX=a,this._cacheOffsetY=b,this._cacheScale=e,this.updateCache()},b.updateCache=function(b){var c=this.cacheCanvas;if(!c)throw"cache() must be called before updateCache()";var d=this._cacheScale,e=this._cacheOffsetX*d,f=this._cacheOffsetY*d,g=this._cacheWidth,h=this._cacheHeight,i=c.getContext("2d"),j=this._getFilterBounds();e+=this._filterOffsetX=j.x,f+=this._filterOffsetY=j.y,g=Math.ceil(g*d)+j.width,h=Math.ceil(h*d)+j.height,g!=c.width||h!=c.height?(c.width=g,c.height=h):b||i.clearRect(0,0,g+1,h+1),i.save(),i.globalCompositeOperation=b,i.setTransform(d,0,0,d,-e,-f),this.draw(i,!0),this._applyFilters(),i.restore(),this.cacheID=a._nextCacheID++},b.uncache=function(){this._cacheDataURL=this.cacheCanvas=null,this.cacheID=this._cacheOffsetX=this._cacheOffsetY=this._filterOffsetX=this._filterOffsetY=0,this._cacheScale=1},b.getCacheDataURL=function(){return this.cacheCanvas?(this.cacheID!=this._cacheDataURLID&&(this._cacheDataURL=this.cacheCanvas.toDataURL()),this._cacheDataURL):null},b.localToGlobal=function(a,b,c){return this.getConcatenatedMatrix(this._props.matrix).transformPoint(a,b,c||new createjs.Point)},b.globalToLocal=function(a,b,c){return this.getConcatenatedMatrix(this._props.matrix).invert().transformPoint(a,b,c||new createjs.Point)},b.localToLocal=function(a,b,c,d){return d=this.localToGlobal(a,b,d),c.globalToLocal(d.x,d.y,d)},b.setTransform=function(a,b,c,d,e,f,g,h,i){return this.x=a||0,this.y=b||0,this.scaleX=null==c?1:c,this.scaleY=null==d?1:d,this.rotation=e||0,this.skewX=f||0,this.skewY=g||0,this.regX=h||0,this.regY=i||0,this},b.getMatrix=function(a){var b=this,c=a&&a.identity()||new createjs.Matrix2D;return b.transformMatrix?c.copy(b.transformMatrix):c.appendTransform(b.x,b.y,b.scaleX,b.scaleY,b.rotation,b.skewX,b.skewY,b.regX,b.regY)},b.getConcatenatedMatrix=function(a){for(var b=this,c=this.getMatrix(a);b=b.parent;)c.prependMatrix(b.getMatrix(b._props.matrix));return c},b.getConcatenatedDisplayProps=function(a){a=a?a.identity():new createjs.DisplayProps;var b=this,c=b.getMatrix(a.matrix);do a.prepend(b.visible,b.alpha,b.shadow,b.compositeOperation),b!=this&&c.prependMatrix(b.getMatrix(b._props.matrix));while(b=b.parent);return a},b.hitTest=function(b,c){var d=a._hitTestContext;d.setTransform(1,0,0,1,-b,-c),this.draw(d);var e=this._testHit(d);return d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,2,2),e},b.set=function(a){for(var b in a)this[b]=a[b];return this},b.getBounds=function(){if(this._bounds)return this._rectangle.copy(this._bounds);var a=this.cacheCanvas;if(a){var b=this._cacheScale;return this._rectangle.setValues(this._cacheOffsetX,this._cacheOffsetY,a.width/b,a.height/b)}return null},b.getTransformedBounds=function(){return this._getBounds()},b.setBounds=function(a,b,c,d){null==a&&(this._bounds=a),this._bounds=(this._bounds||new createjs.Rectangle).setValues(a,b,c,d)},b.clone=function(){return this._cloneProps(new a)},b.toString=function(){return"[DisplayObject (name="+this.name+")]"},b._cloneProps=function(a){return a.alpha=this.alpha,a.mouseEnabled=this.mouseEnabled,a.tickEnabled=this.tickEnabled,a.name=this.name,a.regX=this.regX,a.regY=this.regY,a.rotation=this.rotation,a.scaleX=this.scaleX,a.scaleY=this.scaleY,a.shadow=this.shadow,a.skewX=this.skewX,a.skewY=this.skewY,a.visible=this.visible,a.x=this.x,a.y=this.y,a.compositeOperation=this.compositeOperation,a.snapToPixel=this.snapToPixel,a.filters=null==this.filters?null:this.filters.slice(0),a.mask=this.mask,a.hitArea=this.hitArea,a.cursor=this.cursor,a._bounds=this._bounds,a},b._applyShadow=function(a,b){b=b||Shadow.identity,a.shadowColor=b.color,a.shadowOffsetX=b.offsetX,a.shadowOffsetY=b.offsetY,a.shadowBlur=b.blur},b._tick=function(a){var b=this._listeners;b&&b.tick&&(a.target=null,a.propagationStopped=a.immediatePropagationStopped=!1,this.dispatchEvent(a))},b._testHit=function(b){try{var c=b.getImageData(0,0,1,1).data[3]>1}catch(d){if(!a.suppressCrossDomainErrors)throw"An error has occurred. This is most likely due to security restrictions on reading canvas pixel data with local or cross-domain images."}return c},b._applyFilters=function(){if(this.filters&&0!=this.filters.length&&this.cacheCanvas)for(var a=this.filters.length,b=this.cacheCanvas.getContext("2d"),c=this.cacheCanvas.width,d=this.cacheCanvas.height,e=0;a>e;e++)this.filters[e].applyFilter(b,0,0,c,d)},b._getFilterBounds=function(){var a,b=this.filters,c=this._rectangle.setValues(0,0,0,0);if(!b||!(a=b.length))return c;for(var d=0;a>d;d++){var e=this.filters[d];e.getBounds&&e.getBounds(c)}return c},b._getBounds=function(a,b){return this._transformBounds(this.getBounds(),a,b)},b._transformBounds=function(a,b,c){if(!a)return a;var d=a.x,e=a.y,f=a.width,g=a.height,h=this._props.matrix;h=c?h.identity():this.getMatrix(h),(d||e)&&h.appendTransform(0,0,1,1,0,0,0,-d,-e),b&&h.prependMatrix(b);var i=f*h.a,j=f*h.b,k=g*h.c,l=g*h.d,m=h.tx,n=h.ty,o=m,p=m,q=n,r=n;return(d=i+m)<o?o=d:d>p&&(p=d),(d=i+k+m)<o?o=d:d>p&&(p=d),(d=k+m)<o?o=d:d>p&&(p=d),(e=j+n)<q?q=e:e>r&&(r=e),(e=j+l+n)<q?q=e:e>r&&(r=e),(e=l+n)<q?q=e:e>r&&(r=e),a.setValues(o,q,p-o,r-q)},b._hasMouseEventListener=function(){for(var b=a._MOUSE_EVENTS,c=0,d=b.length;d>c;c++)if(this.hasEventListener(b[c]))return!0;return!!this.cursor},createjs.DisplayObject=createjs.promote(a,"EventDispatcher")}(),this.createjs=this.createjs||{},function(){"use strict";function a(){this.DisplayObject_constructor(),this.children=[],this.mouseChildren=!0,this.tickChildren=!0}var b=createjs.extend(a,createjs.DisplayObject);b.getNumChildren=function(){return this.children.length};try{Object.defineProperties(b,{numChildren:{get:b.getNumChildren}})}catch(c){}b.initialize=a,b.isVisible=function(){var a=this.cacheCanvas||this.children.length;return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&a)},b.draw=function(a,b){if(this.DisplayObject_draw(a,b))return!0;for(var c=this.children.slice(),d=0,e=c.length;e>d;d++){var f=c[d];f.isVisible()&&(a.save(),f.updateContext(a),f.draw(a),a.restore())}return!0},b.addChild=function(a){if(null==a)return a;var b=arguments.length;if(b>1){for(var c=0;b>c;c++)this.addChild(arguments[c]);return arguments[b-1]}return a.parent&&a.parent.removeChild(a),a.parent=this,this.children.push(a),a.dispatchEvent("added"),a},b.addChildAt=function(a,b){var c=arguments.length,d=arguments[c-1];if(0>d||d>this.children.length)return arguments[c-2];if(c>2){for(var e=0;c-1>e;e++)this.addChildAt(arguments[e],d+e);return arguments[c-2]}return a.parent&&a.parent.removeChild(a),a.parent=this,this.children.splice(b,0,a),a.dispatchEvent("added"),a},b.removeChild=function(a){var b=arguments.length;if(b>1){for(var c=!0,d=0;b>d;d++)c=c&&this.removeChild(arguments[d]);return c}return this.removeChildAt(createjs.indexOf(this.children,a))},b.removeChildAt=function(a){var b=arguments.length;if(b>1){for(var c=[],d=0;b>d;d++)c[d]=arguments[d];c.sort(function(a,b){return b-a});for(var e=!0,d=0;b>d;d++)e=e&&this.removeChildAt(c[d]);return e}if(0>a||a>this.children.length-1)return!1;var f=this.children[a];return f&&(f.parent=null),this.children.splice(a,1),f.dispatchEvent("removed"),!0},b.removeAllChildren=function(){for(var a=this.children;a.length;)this.removeChildAt(0)},b.getChildAt=function(a){return this.children[a]},b.getChildByName=function(a){for(var b=this.children,c=0,d=b.length;d>c;c++)if(b[c].name==a)return b[c];return null},b.sortChildren=function(a){this.children.sort(a)},b.getChildIndex=function(a){return createjs.indexOf(this.children,a)},b.swapChildrenAt=function(a,b){var c=this.children,d=c[a],e=c[b];d&&e&&(c[a]=e,c[b]=d)},b.swapChildren=function(a,b){for(var c,d,e=this.children,f=0,g=e.length;g>f&&(e[f]==a&&(c=f),e[f]==b&&(d=f),null==c||null==d);f++);f!=g&&(e[c]=b,e[d]=a)},b.setChildIndex=function(a,b){var c=this.children,d=c.length;if(!(a.parent!=this||0>b||b>=d)){for(var e=0;d>e&&c[e]!=a;e++);e!=d&&e!=b&&(c.splice(e,1),c.splice(b,0,a))}},b.contains=function(a){for(;a;){if(a==this)return!0;a=a.parent}return!1},b.hitTest=function(a,b){return null!=this.getObjectUnderPoint(a,b)},b.getObjectsUnderPoint=function(a,b,c){var d=[],e=this.localToGlobal(a,b);return this._getObjectsUnderPoint(e.x,e.y,d,c>0,1==c),d},b.getObjectUnderPoint=function(a,b,c){var d=this.localToGlobal(a,b);return this._getObjectsUnderPoint(d.x,d.y,null,c>0,1==c)},b.getBounds=function(){return this._getBounds(null,!0)},b.getTransformedBounds=function(){return this._getBounds()},b.clone=function(b){var c=this._cloneProps(new a);return b&&this._cloneChildren(c),c},b.toString=function(){return"[Container (name="+this.name+")]"},b._tick=function(a){if(this.tickChildren)for(var b=this.children.length-1;b>=0;b--){var c=this.children[b];c.tickEnabled&&c._tick&&c._tick(a)}this.DisplayObject__tick(a)},b._cloneChildren=function(a){a.children.length&&a.removeAllChildren();for(var b=a.children,c=0,d=this.children.length;d>c;c++){var e=this.children[c].clone(!0);e.parent=a,b.push(e)}},b._getObjectsUnderPoint=function(b,c,d,e,f,g){if(g=g||0,!g&&!this._testMask(this,b,c))return null;var h,i=createjs.DisplayObject._hitTestContext;f=f||e&&this._hasMouseEventListener();for(var j=this.children,k=j.length,l=k-1;l>=0;l--){var m=j[l],n=m.hitArea;if(m.visible&&(n||m.isVisible())&&(!e||m.mouseEnabled)&&(n||this._testMask(m,b,c)))if(!n&&m instanceof a){var o=m._getObjectsUnderPoint(b,c,d,e,f,g+1);if(!d&&o)return e&&!this.mouseChildren?this:o}else{if(e&&!f&&!m._hasMouseEventListener())continue;var p=m.getConcatenatedDisplayProps(m._props);if(h=p.matrix,n&&(h.appendMatrix(n.getMatrix(n._props.matrix)),p.alpha=n.alpha),i.globalAlpha=p.alpha,i.setTransform(h.a,h.b,h.c,h.d,h.tx-b,h.ty-c),(n||m).draw(i),!this._testHit(i))continue;if(i.setTransform(1,0,0,1,0,0),i.clearRect(0,0,2,2),!d)return e&&!this.mouseChildren?this:m;d.push(m)}}return null},b._testMask=function(a,b,c){var d=a.mask;if(!d||!d.graphics||d.graphics.isEmpty())return!0;var e=this._props.matrix,f=a.parent;e=f?f.getConcatenatedMatrix(e):e.identity(),e=d.getMatrix(d._props.matrix).prependMatrix(e);var g=createjs.DisplayObject._hitTestContext;return g.setTransform(e.a,e.b,e.c,e.d,e.tx-b,e.ty-c),d.graphics.drawAsPath(g),g.fillStyle="#000",g.fill(),this._testHit(g)?(g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,2,2),!0):!1},b._getBounds=function(a,b){var c=this.DisplayObject_getBounds();if(c)return this._transformBounds(c,a,b);var d=this._props.matrix;d=b?d.identity():this.getMatrix(d),a&&d.prependMatrix(a);for(var e=this.children.length,f=null,g=0;e>g;g++){var h=this.children[g];h.visible&&(c=h._getBounds(d))&&(f?f.extend(c.x,c.y,c.width,c.height):f=c.clone())}return f},createjs.Container=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.Container_constructor(),this.autoClear=!0,this.canvas="string"==typeof a?document.getElementById(a):a,this.mouseX=0,this.mouseY=0,this.drawRect=null,this.snapToPixelEnabled=!1,this.mouseInBounds=!1,this.tickOnUpdate=!0,this.mouseMoveOutside=!1,this.preventSelection=!0,this._pointerData={},this._pointerCount=0,this._primaryPointerID=null,this._mouseOverIntervalID=null,this._nextStage=null,this._prevStage=null,this.enableDOMEvents(!0)}var b=createjs.extend(a,createjs.Container);b._get_nextStage=function(){return this._nextStage},b._set_nextStage=function(a){this._nextStage&&(this._nextStage._prevStage=null),a&&(a._prevStage=this),this._nextStage=a};try{Object.defineProperties(b,{nextStage:{get:b._get_nextStage,set:b._set_nextStage}})}catch(c){}b.update=function(a){if(this.canvas&&(this.tickOnUpdate&&this.tick(a),this.dispatchEvent("drawstart",!1,!0)!==!1)){createjs.DisplayObject._snapToPixelEnabled=this.snapToPixelEnabled;var b=this.drawRect,c=this.canvas.getContext("2d");c.setTransform(1,0,0,1,0,0),this.autoClear&&(b?c.clearRect(b.x,b.y,b.width,b.height):c.clearRect(0,0,this.canvas.width+1,this.canvas.height+1)),c.save(),this.drawRect&&(c.beginPath(),c.rect(b.x,b.y,b.width,b.height),c.clip()),this.updateContext(c),this.draw(c,!1),c.restore(),this.dispatchEvent("drawend")}},b.tick=function(a){if(this.tickEnabled&&this.dispatchEvent("tickstart",!1,!0)!==!1){var b=new createjs.Event("tick");if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);this._tick(b),this.dispatchEvent("tickend")}},b.handleEvent=function(a){"tick"==a.type&&this.update(a)},b.clear=function(){if(this.canvas){var a=this.canvas.getContext("2d");a.setTransform(1,0,0,1,0,0),a.clearRect(0,0,this.canvas.width+1,this.canvas.height+1)}},b.toDataURL=function(a,b){var c,d=this.canvas.getContext("2d"),e=this.canvas.width,f=this.canvas.height;if(a){c=d.getImageData(0,0,e,f);var g=d.globalCompositeOperation;d.globalCompositeOperation="destination-over",d.fillStyle=a,d.fillRect(0,0,e,f)}var h=this.canvas.toDataURL(b||"image/png");return a&&(d.putImageData(c,0,0),d.globalCompositeOperation=g),h},b.enableMouseOver=function(a){if(this._mouseOverIntervalID&&(clearInterval(this._mouseOverIntervalID),this._mouseOverIntervalID=null,0==a&&this._testMouseOver(!0)),null==a)a=20;else if(0>=a)return;var b=this;this._mouseOverIntervalID=setInterval(function(){b._testMouseOver()},1e3/Math.min(50,a))},b.enableDOMEvents=function(a){null==a&&(a=!0);var b,c,d=this._eventListeners;if(!a&&d){for(b in d)c=d[b],c.t.removeEventListener(b,c.f,!1);this._eventListeners=null}else if(a&&!d&&this.canvas){var e=window.addEventListener?window:document,f=this;d=this._eventListeners={},d.mouseup={t:e,f:function(a){f._handleMouseUp(a)}},d.mousemove={t:e,f:function(a){f._handleMouseMove(a)}},d.dblclick={t:this.canvas,f:function(a){f._handleDoubleClick(a)}},d.mousedown={t:this.canvas,f:function(a){f._handleMouseDown(a)}};for(b in d)c=d[b],c.t.addEventListener(b,c.f,!1)}},b.clone=function(){throw"Stage cannot be cloned."},b.toString=function(){return"[Stage (name="+this.name+")]"},b._getElementRect=function(a){var b;try{b=a.getBoundingClientRect()}catch(c){b={top:a.offsetTop,left:a.offsetLeft,width:a.offsetWidth,height:a.offsetHeight}}var d=(window.pageXOffset||document.scrollLeft||0)-(document.clientLeft||document.body.clientLeft||0),e=(window.pageYOffset||document.scrollTop||0)-(document.clientTop||document.body.clientTop||0),f=window.getComputedStyle?getComputedStyle(a,null):a.currentStyle,g=parseInt(f.paddingLeft)+parseInt(f.borderLeftWidth),h=parseInt(f.paddingTop)+parseInt(f.borderTopWidth),i=parseInt(f.paddingRight)+parseInt(f.borderRightWidth),j=parseInt(f.paddingBottom)+parseInt(f.borderBottomWidth);return{left:b.left+d+g,right:b.right+d-i,top:b.top+e+h,bottom:b.bottom+e-j}},b._getPointerData=function(a){var b=this._pointerData[a];return b||(b=this._pointerData[a]={x:0,y:0}),b},b._handleMouseMove=function(a){a||(a=window.event),this._handlePointerMove(-1,a,a.pageX,a.pageY)},b._handlePointerMove=function(a,b,c,d,e){if((!this._prevStage||void 0!==e)&&this.canvas){var f=this._nextStage,g=this._getPointerData(a),h=g.inBounds;this._updatePointerPosition(a,b,c,d),(h||g.inBounds||this.mouseMoveOutside)&&(-1===a&&g.inBounds==!h&&this._dispatchMouseEvent(this,h?"mouseleave":"mouseenter",!1,a,g,b),this._dispatchMouseEvent(this,"stagemousemove",!1,a,g,b),this._dispatchMouseEvent(g.target,"pressmove",!0,a,g,b)),f&&f._handlePointerMove(a,b,c,d,null)}},b._updatePointerPosition=function(a,b,c,d){var e=this._getElementRect(this.canvas);c-=e.left,d-=e.top;var f=this.canvas.width,g=this.canvas.height;c/=(e.right-e.left)/f,d/=(e.bottom-e.top)/g;var h=this._getPointerData(a);(h.inBounds=c>=0&&d>=0&&f-1>=c&&g-1>=d)?(h.x=c,h.y=d):this.mouseMoveOutside&&(h.x=0>c?0:c>f-1?f-1:c,h.y=0>d?0:d>g-1?g-1:d),h.posEvtObj=b,h.rawX=c,h.rawY=d,(a===this._primaryPointerID||-1===a)&&(this.mouseX=h.x,this.mouseY=h.y,this.mouseInBounds=h.inBounds)},b._handleMouseUp=function(a){this._handlePointerUp(-1,a,!1)},b._handlePointerUp=function(a,b,c,d){var e=this._nextStage,f=this._getPointerData(a);if(!this._prevStage||void 0!==d){var g=null,h=f.target;d||!h&&!e||(g=this._getObjectsUnderPoint(f.x,f.y,null,!0)),f.down&&(this._dispatchMouseEvent(this,"stagemouseup",!1,a,f,b,g),f.down=!1),g==h&&this._dispatchMouseEvent(h,"click",!0,a,f,b),this._dispatchMouseEvent(h,"pressup",!0,a,f,b),c?(a==this._primaryPointerID&&(this._primaryPointerID=null),delete this._pointerData[a]):f.target=null,e&&e._handlePointerUp(a,b,c,d||g&&this)}},b._handleMouseDown=function(a){this._handlePointerDown(-1,a,a.pageX,a.pageY)},b._handlePointerDown=function(a,b,c,d,e){this.preventSelection&&b.preventDefault(),(null==this._primaryPointerID||-1===a)&&(this._primaryPointerID=a),null!=d&&this._updatePointerPosition(a,b,c,d);var f=null,g=this._nextStage,h=this._getPointerData(a);e||(f=h.target=this._getObjectsUnderPoint(h.x,h.y,null,!0)),h.inBounds&&(this._dispatchMouseEvent(this,"stagemousedown",!1,a,h,b,f),h.down=!0),this._dispatchMouseEvent(f,"mousedown",!0,a,h,b),g&&g._handlePointerDown(a,b,c,d,e||f&&this)},b._testMouseOver=function(a,b,c){if(!this._prevStage||void 0!==b){var d=this._nextStage;if(!this._mouseOverIntervalID)return void(d&&d._testMouseOver(a,b,c));var e=this._getPointerData(-1);if(e&&(a||this.mouseX!=this._mouseOverX||this.mouseY!=this._mouseOverY||!this.mouseInBounds)){var f,g,h,i=e.posEvtObj,j=c||i&&i.target==this.canvas,k=null,l=-1,m="";!b&&(a||this.mouseInBounds&&j)&&(k=this._getObjectsUnderPoint(this.mouseX,this.mouseY,null,!0),this._mouseOverX=this.mouseX,this._mouseOverY=this.mouseY);var n=this._mouseOverTarget||[],o=n[n.length-1],p=this._mouseOverTarget=[];for(f=k;f;)p.unshift(f),m||(m=f.cursor),f=f.parent;for(this.canvas.style.cursor=m,!b&&c&&(c.canvas.style.cursor=m),g=0,h=p.length;h>g&&p[g]==n[g];g++)l=g;for(o!=k&&this._dispatchMouseEvent(o,"mouseout",!0,-1,e,i,k),g=n.length-1;g>l;g--)this._dispatchMouseEvent(n[g],"rollout",!1,-1,e,i,k);for(g=p.length-1;g>l;g--)this._dispatchMouseEvent(p[g],"rollover",!1,-1,e,i,o);o!=k&&this._dispatchMouseEvent(k,"mouseover",!0,-1,e,i,o),d&&d._testMouseOver(a,b||k&&this,c||j&&this)}}},b._handleDoubleClick=function(a,b){var c=null,d=this._nextStage,e=this._getPointerData(-1);b||(c=this._getObjectsUnderPoint(e.x,e.y,null,!0),this._dispatchMouseEvent(c,"dblclick",!0,-1,e,a)),d&&d._handleDoubleClick(a,b||c&&this)},b._dispatchMouseEvent=function(a,b,c,d,e,f,g){if(a&&(c||a.hasEventListener(b))){var h=new createjs.MouseEvent(b,c,!1,e.x,e.y,f,d,d===this._primaryPointerID||-1===d,e.rawX,e.rawY,g);a.dispatchEvent(h)}},createjs.Stage=createjs.promote(a,"Container")}(),this.createjs=this.createjs||{},function(){function a(a){this.DisplayObject_constructor(),"string"==typeof a?(this.image=document.createElement("img"),this.image.src=a):this.image=a,this.sourceRect=null}var b=createjs.extend(a,createjs.DisplayObject);b.initialize=a,b.isVisible=function(){var a=this.image,b=this.cacheCanvas||a&&(a.naturalWidth||a.getContext||a.readyState>=2);return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&b)},b.draw=function(a,b){if(this.DisplayObject_draw(a,b)||!this.image)return!0;var c=this.image,d=this.sourceRect;if(d){var e=d.x,f=d.y,g=e+d.width,h=f+d.height,i=0,j=0,k=c.width,l=c.height;0>e&&(i-=e,e=0),g>k&&(g=k),0>f&&(j-=f,f=0),h>l&&(h=l),a.drawImage(c,e,f,g-e,h-f,i,j,g-e,h-f)}else a.drawImage(c,0,0);return!0},b.getBounds=function(){var a=this.DisplayObject_getBounds();if(a)return a;var b=this.image,c=this.sourceRect||b,d=b&&(b.naturalWidth||b.getContext||b.readyState>=2);return d?this._rectangle.setValues(0,0,c.width,c.height):null},b.clone=function(){var b=new a(this.image);return this.sourceRect&&(b.sourceRect=this.sourceRect.clone()),this._cloneProps(b),b},b.toString=function(){return"[Bitmap (name="+this.name+")]"},createjs.Bitmap=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b){this.DisplayObject_constructor(),this.currentFrame=0,this.currentAnimation=null,this.paused=!0,this.spriteSheet=a,this.currentAnimationFrame=0,this.framerate=0,this._animation=null,this._currentFrame=null,this._skipAdvance=!1,null!=b&&this.gotoAndPlay(b)}var b=createjs.extend(a,createjs.DisplayObject);b.initialize=a,b.isVisible=function(){var a=this.cacheCanvas||this.spriteSheet.complete;return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&a)},b.draw=function(a,b){if(this.DisplayObject_draw(a,b))return!0;this._normalizeFrame();var c=this.spriteSheet.getFrame(0|this._currentFrame);if(!c)return!1;var d=c.rect;return d.width&&d.height&&a.drawImage(c.image,d.x,d.y,d.width,d.height,-c.regX,-c.regY,d.width,d.height),!0},b.play=function(){this.paused=!1},b.stop=function(){this.paused=!0},b.gotoAndPlay=function(a){this.paused=!1,this._skipAdvance=!0,this._goto(a)},b.gotoAndStop=function(a){this.paused=!0,this._goto(a)},b.advance=function(a){var b=this.framerate||this.spriteSheet.framerate,c=b&&null!=a?a/(1e3/b):1;this._normalizeFrame(c)},b.getBounds=function(){return this.DisplayObject_getBounds()||this.spriteSheet.getFrameBounds(this.currentFrame,this._rectangle)},b.clone=function(){return this._cloneProps(new a(this.spriteSheet))},b.toString=function(){return"[Sprite (name="+this.name+")]"},b._cloneProps=function(a){return this.DisplayObject__cloneProps(a),a.currentFrame=this.currentFrame,a.currentAnimation=this.currentAnimation,a.paused=this.paused,a.currentAnimationFrame=this.currentAnimationFrame,a.framerate=this.framerate,a._animation=this._animation,a._currentFrame=this._currentFrame,a._skipAdvance=this._skipAdvance,a},b._tick=function(a){this.paused||(this._skipAdvance||this.advance(a&&a.delta),this._skipAdvance=!1),this.DisplayObject__tick(a)},b._normalizeFrame=function(a){a=a||0;var b,c=this._animation,d=this.paused,e=this._currentFrame;if(c){var f=c.speed||1,g=this.currentAnimationFrame;if(b=c.frames.length,g+a*f>=b){var h=c.next;if(this._dispatchAnimationEnd(c,e,d,h,b-1))return;if(h)return this._goto(h,a-(b-g)/f);this.paused=!0,g=c.frames.length-1}else g+=a*f;this.currentAnimationFrame=g,this._currentFrame=c.frames[0|g]}else if(e=this._currentFrame+=a,b=this.spriteSheet.getNumFrames(),e>=b&&b>0&&!this._dispatchAnimationEnd(c,e,d,b-1)&&(this._currentFrame-=b)>=b)return this._normalizeFrame();e=0|this._currentFrame,this.currentFrame!=e&&(this.currentFrame=e,this.dispatchEvent("change"))},b._dispatchAnimationEnd=function(a,b,c,d,e){var f=a?a.name:null;if(this.hasEventListener("animationend")){var g=new createjs.Event("animationend");g.name=f,g.next=d,this.dispatchEvent(g)}var h=this._animation!=a||this._currentFrame!=b;return h||c||!this.paused||(this.currentAnimationFrame=e,h=!0),h},b._goto=function(a,b){if(this.currentAnimationFrame=0,isNaN(a)){var c=this.spriteSheet.getAnimation(a);c&&(this._animation=c,this.currentAnimation=a,this._normalizeFrame(b))}else this.currentAnimation=this._animation=null,this._currentFrame=a,this._normalizeFrame()},createjs.Sprite=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.DisplayObject_constructor(),this.graphics=a?a:new createjs.Graphics}var b=createjs.extend(a,createjs.DisplayObject);b.isVisible=function(){var a=this.cacheCanvas||this.graphics&&!this.graphics.isEmpty();return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&a)},b.draw=function(a,b){return this.DisplayObject_draw(a,b)?!0:(this.graphics.draw(a,this),!0)},b.clone=function(b){var c=b&&this.graphics?this.graphics.clone():this.graphics;return this._cloneProps(new a(c))},b.toString=function(){return"[Shape (name="+this.name+")]"},createjs.Shape=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c){this.DisplayObject_constructor(),this.text=a,this.font=b,this.color=c,this.textAlign="left",this.textBaseline="top",this.maxWidth=null,this.outline=0,this.lineHeight=0,this.lineWidth=null}var b=createjs.extend(a,createjs.DisplayObject),c=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");c.getContext&&(a._workingContext=c.getContext("2d"),c.width=c.height=1),a.H_OFFSETS={start:0,left:0,center:-.5,end:-1,right:-1},a.V_OFFSETS={top:0,hanging:-.01,middle:-.4,alphabetic:-.8,ideographic:-.85,bottom:-1},b.isVisible=function(){var a=this.cacheCanvas||null!=this.text&&""!==this.text;return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&a)},b.draw=function(a,b){if(this.DisplayObject_draw(a,b))return!0;var c=this.color||"#000";return this.outline?(a.strokeStyle=c,a.lineWidth=1*this.outline):a.fillStyle=c,this._drawText(this._prepContext(a)),!0},b.getMeasuredWidth=function(){return this._getMeasuredWidth(this.text)},b.getMeasuredLineHeight=function(){return 1.2*this._getMeasuredWidth("M")},b.getMeasuredHeight=function(){return this._drawText(null,{}).height},b.getBounds=function(){var b=this.DisplayObject_getBounds();if(b)return b;if(null==this.text||""===this.text)return null;var c=this._drawText(null,{}),d=this.maxWidth&&this.maxWidth<c.width?this.maxWidth:c.width,e=d*a.H_OFFSETS[this.textAlign||"left"],f=this.lineHeight||this.getMeasuredLineHeight(),g=f*a.V_OFFSETS[this.textBaseline||"top"];return this._rectangle.setValues(e,g,d,c.height)},b.getMetrics=function(){var b={lines:[]};return b.lineHeight=this.lineHeight||this.getMeasuredLineHeight(),b.vOffset=b.lineHeight*a.V_OFFSETS[this.textBaseline||"top"],this._drawText(null,b,b.lines)},b.clone=function(){return this._cloneProps(new a(this.text,this.font,this.color))},b.toString=function(){return"[Text (text="+(this.text.length>20?this.text.substr(0,17)+"...":this.text)+")]"},b._cloneProps=function(a){return this.DisplayObject__cloneProps(a),a.textAlign=this.textAlign,a.textBaseline=this.textBaseline,a.maxWidth=this.maxWidth,a.outline=this.outline,a.lineHeight=this.lineHeight,a.lineWidth=this.lineWidth,a},b._prepContext=function(a){return a.font=this.font||"10px sans-serif",a.textAlign=this.textAlign||"left",a.textBaseline=this.textBaseline||"top",a},b._drawText=function(b,c,d){var e=!!b;e||(b=a._workingContext,b.save(),this._prepContext(b));for(var f=this.lineHeight||this.getMeasuredLineHeight(),g=0,h=0,i=String(this.text).split(/(?:\r\n|\r|\n)/),j=0,k=i.length;k>j;j++){var l=i[j],m=null;if(null!=this.lineWidth&&(m=b.measureText(l).width)>this.lineWidth){var n=l.split(/(\s)/);l=n[0],m=b.measureText(l).width;for(var o=1,p=n.length;p>o;o+=2){var q=b.measureText(n[o]+n[o+1]).width;m+q>this.lineWidth?(e&&this._drawTextLine(b,l,h*f),d&&d.push(l),m>g&&(g=m),l=n[o+1],m=b.measureText(l).width,h++):(l+=n[o]+n[o+1],m+=q)}}e&&this._drawTextLine(b,l,h*f),d&&d.push(l),c&&null==m&&(m=b.measureText(l).width),m>g&&(g=m),h++}return c&&(c.width=g,c.height=h*f),e||b.restore(),c},b._drawTextLine=function(a,b,c){this.outline?a.strokeText(b,0,c,this.maxWidth||65535):a.fillText(b,0,c,this.maxWidth||65535)},b._getMeasuredWidth=function(b){var c=a._workingContext;c.save();var d=this._prepContext(c).measureText(b).width;return c.restore(),d},createjs.Text=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b){this.Container_constructor(),this.text=a||"",this.spriteSheet=b,this.lineHeight=0,this.letterSpacing=0,this.spaceWidth=0,this._oldProps={text:0,spriteSheet:0,lineHeight:0,letterSpacing:0,spaceWidth:0}}var b=createjs.extend(a,createjs.Container);a.maxPoolSize=100,a._spritePool=[],b.draw=function(a,b){this.DisplayObject_draw(a,b)||(this._updateText(),this.Container_draw(a,b))},b.getBounds=function(){return this._updateText(),this.Container_getBounds()},b.isVisible=function(){var a=this.cacheCanvas||this.spriteSheet&&this.spriteSheet.complete&&this.text;return!!(this.visible&&this.alpha>0&&0!==this.scaleX&&0!==this.scaleY&&a)},b.clone=function(){return this._cloneProps(new a(this.text,this.spriteSheet))},b.addChild=b.addChildAt=b.removeChild=b.removeChildAt=b.removeAllChildren=function(){},b._cloneProps=function(a){return this.Container__cloneProps(a),a.lineHeight=this.lineHeight,a.letterSpacing=this.letterSpacing,a.spaceWidth=this.spaceWidth,a},b._getFrameIndex=function(a,b){var c,d=b.getAnimation(a);return d||(a!=(c=a.toUpperCase())||a!=(c=a.toLowerCase())||(c=null),c&&(d=b.getAnimation(c))),d&&d.frames[0]},b._getFrame=function(a,b){var c=this._getFrameIndex(a,b);return null==c?c:b.getFrame(c)},b._getLineHeight=function(a){var b=this._getFrame("1",a)||this._getFrame("T",a)||this._getFrame("L",a)||a.getFrame(0);return b?b.rect.height:1},b._getSpaceWidth=function(a){var b=this._getFrame("1",a)||this._getFrame("l",a)||this._getFrame("e",a)||this._getFrame("a",a)||a.getFrame(0);return b?b.rect.width:1},b._updateText=function(){var b,c=0,d=0,e=this._oldProps,f=!1,g=this.spaceWidth,h=this.lineHeight,i=this.spriteSheet,j=a._spritePool,k=this.children,l=0,m=k.length;for(var n in e)e[n]!=this[n]&&(e[n]=this[n],f=!0);if(f){var o=!!this._getFrame(" ",i);o||g||(g=this._getSpaceWidth(i)),h||(h=this._getLineHeight(i));for(var p=0,q=this.text.length;q>p;p++){var r=this.text.charAt(p);if(" "!=r||o)if("\n"!=r&&"\r"!=r){var s=this._getFrameIndex(r,i);null!=s&&(m>l?b=k[l]:(k.push(b=j.length?j.pop():new createjs.Sprite),b.parent=this,m++),b.spriteSheet=i,b.gotoAndStop(s),b.x=c,b.y=d,l++,c+=b.getBounds().width+this.letterSpacing)}else"\r"==r&&"\n"==this.text.charAt(p+1)&&p++,c=0,d+=h;else c+=g}for(;m>l;)j.push(b=k.pop()),b.parent=null,m--;j.length>a.maxPoolSize&&(j.length=a.maxPoolSize)}},createjs.BitmapText=createjs.promote(a,"Container")}(),this.createjs=this.createjs||{},function(){"use strict";function a(b,c,d,e){this.Container_constructor(),!a.inited&&a.init(),this.mode=b||a.INDEPENDENT,this.startPosition=c||0,this.loop=d,this.currentFrame=0,this.timeline=new createjs.Timeline(null,e,{paused:!0,position:c,useTicks:!0}),this.paused=!1,this.actionsEnabled=!0,this.autoReset=!0,this.frameBounds=this.frameBounds||null,this.framerate=null,this._synchOffset=0,this._prevPos=-1,this._prevPosition=0,this._t=0,this._managed={}}function b(){throw"MovieClipPlugin cannot be instantiated."}var c=createjs.extend(a,createjs.Container);a.INDEPENDENT="independent",a.SINGLE_FRAME="single",a.SYNCHED="synched",a.inited=!1,a.init=function(){a.inited||(b.install(),a.inited=!0)},c.getLabels=function(){return this.timeline.getLabels()},c.getCurrentLabel=function(){return this._updateTimeline(),this.timeline.getCurrentLabel()},c.getDuration=function(){return this.timeline.duration};try{Object.defineProperties(c,{labels:{get:c.getLabels},currentLabel:{get:c.getCurrentLabel},totalFrames:{get:c.getDuration},duration:{get:c.getDuration}})}catch(d){}c.initialize=a,c.isVisible=function(){return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY)},c.draw=function(a,b){return this.DisplayObject_draw(a,b)?!0:(this._updateTimeline(),this.Container_draw(a,b),!0)
},c.play=function(){this.paused=!1},c.stop=function(){this.paused=!0},c.gotoAndPlay=function(a){this.paused=!1,this._goto(a)},c.gotoAndStop=function(a){this.paused=!0,this._goto(a)},c.advance=function(b){var c=a.INDEPENDENT;if(this.mode==c){for(var d=this,e=d.framerate;(d=d.parent)&&null==e;)d.mode==c&&(e=d._framerate);this._framerate=e;var f=null!=e&&-1!=e&&null!=b?b/(1e3/e)+this._t:1,g=0|f;for(this._t=f-g;!this.paused&&g--;)this._prevPosition=this._prevPos<0?0:this._prevPosition+1,this._updateTimeline()}},c.clone=function(){throw"MovieClip cannot be cloned."},c.toString=function(){return"[MovieClip (name="+this.name+")]"},c._tick=function(a){this.advance(a&&a.delta),this.Container__tick(a)},c._goto=function(a){var b=this.timeline.resolve(a);null!=b&&(-1==this._prevPos&&(this._prevPos=0/0),this._prevPosition=b,this._t=0,this._updateTimeline())},c._reset=function(){this._prevPos=-1,this._t=this.currentFrame=0,this.paused=!1},c._updateTimeline=function(){var b=this.timeline,c=this.mode!=a.INDEPENDENT;b.loop=null==this.loop?!0:this.loop;var d=c?this.startPosition+(this.mode==a.SINGLE_FRAME?0:this._synchOffset):this._prevPos<0?0:this._prevPosition,e=c||!this.actionsEnabled?createjs.Tween.NONE:null;if(this.currentFrame=b._calcPosition(d),b.setPosition(d,e),this._prevPosition=b._prevPosition,this._prevPos!=b._prevPos){this.currentFrame=this._prevPos=b._prevPos;for(var f in this._managed)this._managed[f]=1;for(var g=b._tweens,h=0,i=g.length;i>h;h++){var j=g[h],k=j._target;if(k!=this&&!j.passive){var l=j._stepPosition;k instanceof createjs.DisplayObject?this._addManagedChild(k,l):this._setState(k.state,l)}}var m=this.children;for(h=m.length-1;h>=0;h--){var n=m[h].id;1==this._managed[n]&&(this.removeChildAt(h),delete this._managed[n])}}},c._setState=function(a,b){if(a)for(var c=a.length-1;c>=0;c--){var d=a[c],e=d.t,f=d.p;for(var g in f)e[g]=f[g];this._addManagedChild(e,b)}},c._addManagedChild=function(b,c){b._off||(this.addChildAt(b,0),b instanceof a&&(b._synchOffset=c,b.mode==a.INDEPENDENT&&b.autoReset&&!this._managed[b.id]&&b._reset()),this._managed[b.id]=2)},c._getBounds=function(a,b){var c=this.DisplayObject_getBounds();return c||(this._updateTimeline(),this.frameBounds&&(c=this._rectangle.copy(this.frameBounds[this.currentFrame]))),c?this._transformBounds(c,a,b):this.Container__getBounds(a,b)},createjs.MovieClip=createjs.promote(a,"Container"),b.priority=100,b.install=function(){createjs.Tween.installPlugin(b,["startPosition"])},b.init=function(a,b,c){return c},b.step=function(){},b.tween=function(b,c,d,e,f,g){return b.target instanceof a?1==g?f[c]:e[c]:d}}(),this.createjs=this.createjs||{},function(){"use strict";function a(){throw"SpriteSheetUtils cannot be instantiated"}var b=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");b.getContext&&(a._workingCanvas=b,a._workingContext=b.getContext("2d"),b.width=b.height=1),a.addFlippedFrames=function(b,c,d,e){if(c||d||e){var f=0;c&&a._flip(b,++f,!0,!1),d&&a._flip(b,++f,!1,!0),e&&a._flip(b,++f,!0,!0)}},a.extractFrame=function(b,c){isNaN(c)&&(c=b.getAnimation(c).frames[0]);var d=b.getFrame(c);if(!d)return null;var e=d.rect,f=a._workingCanvas;f.width=e.width,f.height=e.height,a._workingContext.drawImage(d.image,e.x,e.y,e.width,e.height,0,0,e.width,e.height);var g=document.createElement("img");return g.src=f.toDataURL("image/png"),g},a.mergeAlpha=function(a,b,c){c||(c=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")),c.width=Math.max(b.width,a.width),c.height=Math.max(b.height,a.height);var d=c.getContext("2d");return d.save(),d.drawImage(a,0,0),d.globalCompositeOperation="destination-in",d.drawImage(b,0,0),d.restore(),c},a._flip=function(b,c,d,e){for(var f=b._images,g=a._workingCanvas,h=a._workingContext,i=f.length/c,j=0;i>j;j++){var k=f[j];k.__tmp=j,h.setTransform(1,0,0,1,0,0),h.clearRect(0,0,g.width+1,g.height+1),g.width=k.width,g.height=k.height,h.setTransform(d?-1:1,0,0,e?-1:1,d?k.width:0,e?k.height:0),h.drawImage(k,0,0);var l=document.createElement("img");l.src=g.toDataURL("image/png"),l.width=k.width,l.height=k.height,f.push(l)}var m=b._frames,n=m.length/c;for(j=0;n>j;j++){k=m[j];var o=k.rect.clone();l=f[k.image.__tmp+i*c];var p={image:l,rect:o,regX:k.regX,regY:k.regY};d&&(o.x=l.width-o.x-o.width,p.regX=o.width-k.regX),e&&(o.y=l.height-o.y-o.height,p.regY=o.height-k.regY),m.push(p)}var q="_"+(d?"h":"")+(e?"v":""),r=b._animations,s=b._data,t=r.length/c;for(j=0;t>j;j++){var u=r[j];k=s[u];var v={name:u+q,speed:k.speed,next:k.next,frames:[]};k.next&&(v.next+=q),m=k.frames;for(var w=0,x=m.length;x>w;w++)v.frames.push(m[w]+n*c);s[v.name]=v,r.push(v.name)}},createjs.SpriteSheetUtils=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.EventDispatcher_constructor(),this.maxWidth=2048,this.maxHeight=2048,this.spriteSheet=null,this.scale=1,this.padding=1,this.timeSlice=.3,this.progress=-1,this.framerate=a||0,this._frames=[],this._animations={},this._data=null,this._nextFrameIndex=0,this._index=0,this._timerID=null,this._scale=1}var b=createjs.extend(a,createjs.EventDispatcher);a.ERR_DIMENSIONS="frame dimensions exceed max spritesheet dimensions",a.ERR_RUNNING="a build is already running",b.addFrame=function(b,c,d,e,f){if(this._data)throw a.ERR_RUNNING;var g=c||b.bounds||b.nominalBounds;return!g&&b.getBounds&&(g=b.getBounds()),g?(d=d||1,this._frames.push({source:b,sourceRect:g,scale:d,funct:e,data:f,index:this._frames.length,height:g.height*d})-1):null},b.addAnimation=function(b,c,d,e){if(this._data)throw a.ERR_RUNNING;this._animations[b]={frames:c,next:d,speed:e}},b.addMovieClip=function(b,c,d,e,f,g){if(this._data)throw a.ERR_RUNNING;var h=b.frameBounds,i=c||b.bounds||b.nominalBounds;if(!i&&b.getBounds&&(i=b.getBounds()),i||h){var j,k,l=this._frames.length,m=b.timeline.duration;for(j=0;m>j;j++){var n=h&&h[j]?h[j]:i;this.addFrame(b,n,d,this._setupMovieClipFrame,{i:j,f:e,d:f})}var o=b.timeline._labels,p=[];for(var q in o)p.push({index:o[q],label:q});if(p.length)for(p.sort(function(a,b){return a.index-b.index}),j=0,k=p.length;k>j;j++){for(var r=p[j].label,s=l+p[j].index,t=l+(j==k-1?m:p[j+1].index),u=[],v=s;t>v;v++)u.push(v);(!g||(r=g(r,b,s,t)))&&this.addAnimation(r,u,!0)}}},b.build=function(){if(this._data)throw a.ERR_RUNNING;for(this._startBuild();this._drawNext(););return this._endBuild(),this.spriteSheet},b.buildAsync=function(b){if(this._data)throw a.ERR_RUNNING;this.timeSlice=b,this._startBuild();var c=this;this._timerID=setTimeout(function(){c._run()},50-50*Math.max(.01,Math.min(.99,this.timeSlice||.3)))},b.stopAsync=function(){clearTimeout(this._timerID),this._data=null},b.clone=function(){throw"SpriteSheetBuilder cannot be cloned."},b.toString=function(){return"[SpriteSheetBuilder]"},b._startBuild=function(){var b=this.padding||0;this.progress=0,this.spriteSheet=null,this._index=0,this._scale=this.scale;var c=[];this._data={images:[],frames:c,framerate:this.framerate,animations:this._animations};var d=this._frames.slice();if(d.sort(function(a,b){return a.height<=b.height?-1:1}),d[d.length-1].height+2*b>this.maxHeight)throw a.ERR_DIMENSIONS;for(var e=0,f=0,g=0;d.length;){var h=this._fillRow(d,e,g,c,b);if(h.w>f&&(f=h.w),e+=h.h,!h.h||!d.length){var i=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");i.width=this._getSize(f,this.maxWidth),i.height=this._getSize(e,this.maxHeight),this._data.images[g]=i,h.h||(f=e=0,g++)}}},b._setupMovieClipFrame=function(a,b){var c=a.actionsEnabled;a.actionsEnabled=!1,a.gotoAndStop(b.i),a.actionsEnabled=c,b.f&&b.f(a,b.d,b.i)},b._getSize=function(a,b){for(var c=4;Math.pow(2,++c)<a;);return Math.min(b,Math.pow(2,c))},b._fillRow=function(b,c,d,e,f){var g=this.maxWidth,h=this.maxHeight;c+=f;for(var i=h-c,j=f,k=0,l=b.length-1;l>=0;l--){var m=b[l],n=this._scale*m.scale,o=m.sourceRect,p=m.source,q=Math.floor(n*o.x-f),r=Math.floor(n*o.y-f),s=Math.ceil(n*o.height+2*f),t=Math.ceil(n*o.width+2*f);if(t>g)throw a.ERR_DIMENSIONS;s>i||j+t>g||(m.img=d,m.rect=new createjs.Rectangle(j,c,t,s),k=k||s,b.splice(l,1),e[m.index]=[j,c,t,s,d,Math.round(-q+n*p.regX-f),Math.round(-r+n*p.regY-f)],j+=t)}return{w:j,h:k}},b._endBuild=function(){this.spriteSheet=new createjs.SpriteSheet(this._data),this._data=null,this.progress=1,this.dispatchEvent("complete")},b._run=function(){for(var a=50*Math.max(.01,Math.min(.99,this.timeSlice||.3)),b=(new Date).getTime()+a,c=!1;b>(new Date).getTime();)if(!this._drawNext()){c=!0;break}if(c)this._endBuild();else{var d=this;this._timerID=setTimeout(function(){d._run()},50-a)}var e=this.progress=this._index/this._frames.length;if(this.hasEventListener("progress")){var f=new createjs.Event("progress");f.progress=e,this.dispatchEvent(f)}},b._drawNext=function(){var a=this._frames[this._index],b=a.scale*this._scale,c=a.rect,d=a.sourceRect,e=this._data.images[a.img],f=e.getContext("2d");return a.funct&&a.funct(a.source,a.data),f.save(),f.beginPath(),f.rect(c.x,c.y,c.width,c.height),f.clip(),f.translate(Math.ceil(c.x-d.x*b),Math.ceil(c.y-d.y*b)),f.scale(b,b),a.source.draw(f),f.restore(),++this._index<this._frames.length},createjs.SpriteSheetBuilder=createjs.promote(a,"EventDispatcher")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.DisplayObject_constructor(),"string"==typeof a&&(a=document.getElementById(a)),this.mouseEnabled=!1;var b=a.style;b.position="absolute",b.transformOrigin=b.WebkitTransformOrigin=b.msTransformOrigin=b.MozTransformOrigin=b.OTransformOrigin="0% 0%",this.htmlElement=a,this._oldProps=null}var b=createjs.extend(a,createjs.DisplayObject);b.isVisible=function(){return null!=this.htmlElement},b.draw=function(){return!0},b.cache=function(){},b.uncache=function(){},b.updateCache=function(){},b.hitTest=function(){},b.localToGlobal=function(){},b.globalToLocal=function(){},b.localToLocal=function(){},b.clone=function(){throw"DOMElement cannot be cloned."},b.toString=function(){return"[DOMElement (name="+this.name+")]"},b._tick=function(a){var b=this.getStage();b&&b.on("drawend",this._handleDrawEnd,this,!0),this.DisplayObject__tick(a)},b._handleDrawEnd=function(){var a=this.htmlElement;if(a){var b=a.style,c=this.getConcatenatedDisplayProps(this._props),d=c.matrix,e=c.visible?"visible":"hidden";if(e!=b.visibility&&(b.visibility=e),c.visible){var f=this._oldProps,g=f&&f.matrix,h=1e4;if(!g||!g.equals(d)){var i="matrix("+(d.a*h|0)/h+","+(d.b*h|0)/h+","+(d.c*h|0)/h+","+(d.d*h|0)/h+","+(d.tx+.5|0);b.transform=b.WebkitTransform=b.OTransform=b.msTransform=i+","+(d.ty+.5|0)+")",b.MozTransform=i+"px,"+(d.ty+.5|0)+"px)",f||(f=this._oldProps=new createjs.DisplayProps(!0,0/0)),f.matrix.copy(d)}f.alpha!=c.alpha&&(b.opacity=""+(c.alpha*h|0)/h,f.alpha=c.alpha)}}},createjs.DOMElement=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(){}var b=a.prototype;b.getBounds=function(a){return a},b.applyFilter=function(a,b,c,d,e,f,g,h){f=f||a,null==g&&(g=b),null==h&&(h=c);try{var i=a.getImageData(b,c,d,e)}catch(j){return!1}return this._applyFilter(i)?(f.putImageData(i,g,h),!0):!1},b.toString=function(){return"[Filter]"},b.clone=function(){return new a},b._applyFilter=function(){return!0},createjs.Filter=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c){(isNaN(a)||0>a)&&(a=0),(isNaN(b)||0>b)&&(b=0),(isNaN(c)||1>c)&&(c=1),this.blurX=0|a,this.blurY=0|b,this.quality=0|c}var b=createjs.extend(a,createjs.Filter);a.MUL_TABLE=[1,171,205,293,57,373,79,137,241,27,391,357,41,19,283,265,497,469,443,421,25,191,365,349,335,161,155,149,9,278,269,261,505,245,475,231,449,437,213,415,405,395,193,377,369,361,353,345,169,331,325,319,313,307,301,37,145,285,281,69,271,267,263,259,509,501,493,243,479,118,465,459,113,446,55,435,429,423,209,413,51,403,199,393,97,3,379,375,371,367,363,359,355,351,347,43,85,337,333,165,327,323,5,317,157,311,77,305,303,75,297,294,73,289,287,71,141,279,277,275,68,135,67,133,33,262,260,129,511,507,503,499,495,491,61,121,481,477,237,235,467,232,115,457,227,451,7,445,221,439,218,433,215,427,425,211,419,417,207,411,409,203,202,401,399,396,197,49,389,387,385,383,95,189,47,187,93,185,23,183,91,181,45,179,89,177,11,175,87,173,345,343,341,339,337,21,167,83,331,329,327,163,81,323,321,319,159,79,315,313,39,155,309,307,153,305,303,151,75,299,149,37,295,147,73,291,145,289,287,143,285,71,141,281,35,279,139,69,275,137,273,17,271,135,269,267,133,265,33,263,131,261,130,259,129,257,1],a.SHG_TABLE=[0,9,10,11,9,12,10,11,12,9,13,13,10,9,13,13,14,14,14,14,10,13,14,14,14,13,13,13,9,14,14,14,15,14,15,14,15,15,14,15,15,15,14,15,15,15,15,15,14,15,15,15,15,15,15,12,14,15,15,13,15,15,15,15,16,16,16,15,16,14,16,16,14,16,13,16,16,16,15,16,13,16,15,16,14,9,16,16,16,16,16,16,16,16,16,13,14,16,16,15,16,16,10,16,15,16,14,16,16,14,16,16,14,16,16,14,15,16,16,16,14,15,14,15,13,16,16,15,17,17,17,17,17,17,14,15,17,17,16,16,17,16,15,17,16,17,11,17,16,17,16,17,16,17,17,16,17,17,16,17,17,16,16,17,17,17,16,14,17,17,17,17,15,16,14,16,15,16,13,16,15,16,14,16,15,16,12,16,15,16,17,17,17,17,17,13,16,15,17,17,17,16,15,17,17,17,16,15,17,17,14,16,17,17,16,17,17,16,15,17,16,14,17,16,15,17,16,17,17,16,17,15,16,17,14,17,16,15,17,16,17,13,17,16,17,17,16,17,14,17,16,17,16,17,16,17,9],b.getBounds=function(a){var b=0|this.blurX,c=0|this.blurY;if(0>=b&&0>=c)return a;var d=Math.pow(this.quality,.2);return(a||new createjs.Rectangle).pad(b*d+1,c*d+1,b*d+1,c*d+1)},b.clone=function(){return new a(this.blurX,this.blurY,this.quality)},b.toString=function(){return"[BlurFilter]"},b._applyFilter=function(b){var c=this.blurX>>1;if(isNaN(c)||0>c)return!1;var d=this.blurY>>1;if(isNaN(d)||0>d)return!1;if(0==c&&0==d)return!1;var e=this.quality;(isNaN(e)||1>e)&&(e=1),e|=0,e>3&&(e=3),1>e&&(e=1);var f=b.data,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=c+c+1|0,w=d+d+1|0,x=0|b.width,y=0|b.height,z=x-1|0,A=y-1|0,B=c+1|0,C=d+1|0,D={r:0,b:0,g:0,a:0},E=D;for(i=1;v>i;i++)E=E.n={r:0,b:0,g:0,a:0};E.n=D;var F={r:0,b:0,g:0,a:0},G=F;for(i=1;w>i;i++)G=G.n={r:0,b:0,g:0,a:0};G.n=F;for(var H=null,I=0|a.MUL_TABLE[c],J=0|a.SHG_TABLE[c],K=0|a.MUL_TABLE[d],L=0|a.SHG_TABLE[d];e-->0;){m=l=0;var M=I,N=J;for(h=y;--h>-1;){for(n=B*(r=f[0|l]),o=B*(s=f[l+1|0]),p=B*(t=f[l+2|0]),q=B*(u=f[l+3|0]),E=D,i=B;--i>-1;)E.r=r,E.g=s,E.b=t,E.a=u,E=E.n;for(i=1;B>i;i++)j=l+((i>z?z:i)<<2)|0,n+=E.r=f[j],o+=E.g=f[j+1],p+=E.b=f[j+2],q+=E.a=f[j+3],E=E.n;for(H=D,g=0;x>g;g++)f[l++]=n*M>>>N,f[l++]=o*M>>>N,f[l++]=p*M>>>N,f[l++]=q*M>>>N,j=m+((j=g+c+1)<z?j:z)<<2,n-=H.r-(H.r=f[j]),o-=H.g-(H.g=f[j+1]),p-=H.b-(H.b=f[j+2]),q-=H.a-(H.a=f[j+3]),H=H.n;m+=x}for(M=K,N=L,g=0;x>g;g++){for(l=g<<2|0,n=C*(r=f[l])|0,o=C*(s=f[l+1|0])|0,p=C*(t=f[l+2|0])|0,q=C*(u=f[l+3|0])|0,G=F,i=0;C>i;i++)G.r=r,G.g=s,G.b=t,G.a=u,G=G.n;for(k=x,i=1;d>=i;i++)l=k+g<<2,n+=G.r=f[l],o+=G.g=f[l+1],p+=G.b=f[l+2],q+=G.a=f[l+3],G=G.n,A>i&&(k+=x);if(l=g,H=F,e>0)for(h=0;y>h;h++)j=l<<2,f[j+3]=u=q*M>>>N,u>0?(f[j]=n*M>>>N,f[j+1]=o*M>>>N,f[j+2]=p*M>>>N):f[j]=f[j+1]=f[j+2]=0,j=g+((j=h+C)<A?j:A)*x<<2,n-=H.r-(H.r=f[j]),o-=H.g-(H.g=f[j+1]),p-=H.b-(H.b=f[j+2]),q-=H.a-(H.a=f[j+3]),H=H.n,l+=x;else for(h=0;y>h;h++)j=l<<2,f[j+3]=u=q*M>>>N,u>0?(u=255/u,f[j]=(n*M>>>N)*u,f[j+1]=(o*M>>>N)*u,f[j+2]=(p*M>>>N)*u):f[j]=f[j+1]=f[j+2]=0,j=g+((j=h+C)<A?j:A)*x<<2,n-=H.r-(H.r=f[j]),o-=H.g-(H.g=f[j+1]),p-=H.b-(H.b=f[j+2]),q-=H.a-(H.a=f[j+3]),H=H.n,l+=x}}return!0},createjs.BlurFilter=createjs.promote(a,"Filter")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.alphaMap=a,this._alphaMap=null,this._mapData=null}var b=createjs.extend(a,createjs.Filter);b.clone=function(){var b=new a(this.alphaMap);return b._alphaMap=this._alphaMap,b._mapData=this._mapData,b},b.toString=function(){return"[AlphaMapFilter]"},b._applyFilter=function(a){if(!this.alphaMap)return!0;if(!this._prepAlphaMap())return!1;for(var b=a.data,c=this._mapData,d=0,e=b.length;e>d;d+=4)b[d+3]=c[d]||0;return!0},b._prepAlphaMap=function(){if(!this.alphaMap)return!1;if(this.alphaMap==this._alphaMap&&this._mapData)return!0;this._mapData=null;var a,b=this._alphaMap=this.alphaMap,c=b;b instanceof HTMLCanvasElement?a=c.getContext("2d"):(c=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"),c.width=b.width,c.height=b.height,a=c.getContext("2d"),a.drawImage(b,0,0));try{var d=a.getImageData(0,0,b.width,b.height)}catch(e){return!1}return this._mapData=d.data,!0},createjs.AlphaMapFilter=createjs.promote(a,"Filter")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.mask=a}var b=createjs.extend(a,createjs.Filter);b.applyFilter=function(a,b,c,d,e,f,g,h){return this.mask?(f=f||a,null==g&&(g=b),null==h&&(h=c),f.save(),a!=f?!1:(f.globalCompositeOperation="destination-in",f.drawImage(this.mask,g,h),f.restore(),!0)):!0},b.clone=function(){return new a(this.mask)},b.toString=function(){return"[AlphaMaskFilter]"},createjs.AlphaMaskFilter=createjs.promote(a,"Filter")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d,e,f,g,h){this.redMultiplier=null!=a?a:1,this.greenMultiplier=null!=b?b:1,this.blueMultiplier=null!=c?c:1,this.alphaMultiplier=null!=d?d:1,this.redOffset=e||0,this.greenOffset=f||0,this.blueOffset=g||0,this.alphaOffset=h||0}var b=createjs.extend(a,createjs.Filter);b.toString=function(){return"[ColorFilter]"},b.clone=function(){return new a(this.redMultiplier,this.greenMultiplier,this.blueMultiplier,this.alphaMultiplier,this.redOffset,this.greenOffset,this.blueOffset,this.alphaOffset)},b._applyFilter=function(a){for(var b=a.data,c=b.length,d=0;c>d;d+=4)b[d]=b[d]*this.redMultiplier+this.redOffset,b[d+1]=b[d+1]*this.greenMultiplier+this.greenOffset,b[d+2]=b[d+2]*this.blueMultiplier+this.blueOffset,b[d+3]=b[d+3]*this.alphaMultiplier+this.alphaOffset;return!0},createjs.ColorFilter=createjs.promote(a,"Filter")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d){this.setColor(a,b,c,d)}var b=a.prototype;a.DELTA_INDEX=[0,.01,.02,.04,.05,.06,.07,.08,.1,.11,.12,.14,.15,.16,.17,.18,.2,.21,.22,.24,.25,.27,.28,.3,.32,.34,.36,.38,.4,.42,.44,.46,.48,.5,.53,.56,.59,.62,.65,.68,.71,.74,.77,.8,.83,.86,.89,.92,.95,.98,1,1.06,1.12,1.18,1.24,1.3,1.36,1.42,1.48,1.54,1.6,1.66,1.72,1.78,1.84,1.9,1.96,2,2.12,2.25,2.37,2.5,2.62,2.75,2.87,3,3.2,3.4,3.6,3.8,4,4.3,4.7,4.9,5,5.5,6,6.5,6.8,7,7.3,7.5,7.8,8,8.4,8.7,9,9.4,9.6,9.8,10],a.IDENTITY_MATRIX=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1],a.LENGTH=a.IDENTITY_MATRIX.length,b.setColor=function(a,b,c,d){return this.reset().adjustColor(a,b,c,d)},b.reset=function(){return this.copy(a.IDENTITY_MATRIX)},b.adjustColor=function(a,b,c,d){return this.adjustHue(d),this.adjustContrast(b),this.adjustBrightness(a),this.adjustSaturation(c)},b.adjustBrightness=function(a){return 0==a||isNaN(a)?this:(a=this._cleanValue(a,255),this._multiplyMatrix([1,0,0,0,a,0,1,0,0,a,0,0,1,0,a,0,0,0,1,0,0,0,0,0,1]),this)},b.adjustContrast=function(b){if(0==b||isNaN(b))return this;b=this._cleanValue(b,100);var c;return 0>b?c=127+b/100*127:(c=b%1,c=0==c?a.DELTA_INDEX[b]:a.DELTA_INDEX[b<<0]*(1-c)+a.DELTA_INDEX[(b<<0)+1]*c,c=127*c+127),this._multiplyMatrix([c/127,0,0,0,.5*(127-c),0,c/127,0,0,.5*(127-c),0,0,c/127,0,.5*(127-c),0,0,0,1,0,0,0,0,0,1]),this},b.adjustSaturation=function(a){if(0==a||isNaN(a))return this;a=this._cleanValue(a,100);var b=1+(a>0?3*a/100:a/100),c=.3086,d=.6094,e=.082;return this._multiplyMatrix([c*(1-b)+b,d*(1-b),e*(1-b),0,0,c*(1-b),d*(1-b)+b,e*(1-b),0,0,c*(1-b),d*(1-b),e*(1-b)+b,0,0,0,0,0,1,0,0,0,0,0,1]),this},b.adjustHue=function(a){if(0==a||isNaN(a))return this;a=this._cleanValue(a,180)/180*Math.PI;var b=Math.cos(a),c=Math.sin(a),d=.213,e=.715,f=.072;return this._multiplyMatrix([d+b*(1-d)+c*-d,e+b*-e+c*-e,f+b*-f+c*(1-f),0,0,d+b*-d+.143*c,e+b*(1-e)+.14*c,f+b*-f+c*-.283,0,0,d+b*-d+c*-(1-d),e+b*-e+c*e,f+b*(1-f)+c*f,0,0,0,0,0,1,0,0,0,0,0,1]),this},b.concat=function(b){return b=this._fixMatrix(b),b.length!=a.LENGTH?this:(this._multiplyMatrix(b),this)},b.clone=function(){return(new a).copy(this)},b.toArray=function(){for(var b=[],c=0,d=a.LENGTH;d>c;c++)b[c]=this[c];return b},b.copy=function(b){for(var c=a.LENGTH,d=0;c>d;d++)this[d]=b[d];return this},b.toString=function(){return"[ColorMatrix]"},b._multiplyMatrix=function(a){var b,c,d,e=[];for(b=0;5>b;b++){for(c=0;5>c;c++)e[c]=this[c+5*b];for(c=0;5>c;c++){var f=0;for(d=0;5>d;d++)f+=a[c+5*d]*e[d];this[c+5*b]=f}}},b._cleanValue=function(a,b){return Math.min(b,Math.max(-b,a))},b._fixMatrix=function(b){return b instanceof a&&(b=b.toArray()),b.length<a.LENGTH?b=b.slice(0,b.length).concat(a.IDENTITY_MATRIX.slice(b.length,a.LENGTH)):b.length>a.LENGTH&&(b=b.slice(0,a.LENGTH)),b},createjs.ColorMatrix=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.matrix=a}var b=createjs.extend(a,createjs.Filter);b.toString=function(){return"[ColorMatrixFilter]"},b.clone=function(){return new a(this.matrix)},b._applyFilter=function(a){for(var b,c,d,e,f=a.data,g=f.length,h=this.matrix,i=h[0],j=h[1],k=h[2],l=h[3],m=h[4],n=h[5],o=h[6],p=h[7],q=h[8],r=h[9],s=h[10],t=h[11],u=h[12],v=h[13],w=h[14],x=h[15],y=h[16],z=h[17],A=h[18],B=h[19],C=0;g>C;C+=4)b=f[C],c=f[C+1],d=f[C+2],e=f[C+3],f[C]=b*i+c*j+d*k+e*l+m,f[C+1]=b*n+c*o+d*p+e*q+r,f[C+2]=b*s+c*t+d*u+e*v+w,f[C+3]=b*x+c*y+d*z+e*A+B;return!0},createjs.ColorMatrixFilter=createjs.promote(a,"Filter")}(),this.createjs=this.createjs||{},function(){"use strict";function a(){throw"Touch cannot be instantiated"}a.isSupported=function(){return!!("ontouchstart"in window||window.navigator.msPointerEnabled&&window.navigator.msMaxTouchPoints>0||window.navigator.pointerEnabled&&window.navigator.maxTouchPoints>0)},a.enable=function(b,c,d){return b&&b.canvas&&a.isSupported()?b.__touch?!0:(b.__touch={pointers:{},multitouch:!c,preventDefault:!d,count:0},"ontouchstart"in window?a._IOS_enable(b):(window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&a._IE_enable(b),!0):!1},a.disable=function(b){b&&("ontouchstart"in window?a._IOS_disable(b):(window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&a._IE_disable(b),delete b.__touch)},a._IOS_enable=function(b){var c=b.canvas,d=b.__touch.f=function(c){a._IOS_handleEvent(b,c)};c.addEventListener("touchstart",d,!1),c.addEventListener("touchmove",d,!1),c.addEventListener("touchend",d,!1),c.addEventListener("touchcancel",d,!1)},a._IOS_disable=function(a){var b=a.canvas;if(b){var c=a.__touch.f;b.removeEventListener("touchstart",c,!1),b.removeEventListener("touchmove",c,!1),b.removeEventListener("touchend",c,!1),b.removeEventListener("touchcancel",c,!1)}},a._IOS_handleEvent=function(a,b){if(a){a.__touch.preventDefault&&b.preventDefault&&b.preventDefault();for(var c=b.changedTouches,d=b.type,e=0,f=c.length;f>e;e++){var g=c[e],h=g.identifier;g.target==a.canvas&&("touchstart"==d?this._handleStart(a,h,b,g.pageX,g.pageY):"touchmove"==d?this._handleMove(a,h,b,g.pageX,g.pageY):("touchend"==d||"touchcancel"==d)&&this._handleEnd(a,h,b))}}},a._IE_enable=function(b){var c=b.canvas,d=b.__touch.f=function(c){a._IE_handleEvent(b,c)};void 0===window.navigator.pointerEnabled?(c.addEventListener("MSPointerDown",d,!1),window.addEventListener("MSPointerMove",d,!1),window.addEventListener("MSPointerUp",d,!1),window.addEventListener("MSPointerCancel",d,!1),b.__touch.preventDefault&&(c.style.msTouchAction="none")):(c.addEventListener("pointerdown",d,!1),window.addEventListener("pointermove",d,!1),window.addEventListener("pointerup",d,!1),window.addEventListener("pointercancel",d,!1),b.__touch.preventDefault&&(c.style.touchAction="none")),b.__touch.activeIDs={}},a._IE_disable=function(a){var b=a.__touch.f;void 0===window.navigator.pointerEnabled?(window.removeEventListener("MSPointerMove",b,!1),window.removeEventListener("MSPointerUp",b,!1),window.removeEventListener("MSPointerCancel",b,!1),a.canvas&&a.canvas.removeEventListener("MSPointerDown",b,!1)):(window.removeEventListener("pointermove",b,!1),window.removeEventListener("pointerup",b,!1),window.removeEventListener("pointercancel",b,!1),a.canvas&&a.canvas.removeEventListener("pointerdown",b,!1))},a._IE_handleEvent=function(a,b){if(a){a.__touch.preventDefault&&b.preventDefault&&b.preventDefault();var c=b.type,d=b.pointerId,e=a.__touch.activeIDs;if("MSPointerDown"==c||"pointerdown"==c){if(b.srcElement!=a.canvas)return;e[d]=!0,this._handleStart(a,d,b,b.pageX,b.pageY)}else e[d]&&("MSPointerMove"==c||"pointermove"==c?this._handleMove(a,d,b,b.pageX,b.pageY):("MSPointerUp"==c||"MSPointerCancel"==c||"pointerup"==c||"pointercancel"==c)&&(delete e[d],this._handleEnd(a,d,b)))}},a._handleStart=function(a,b,c,d,e){var f=a.__touch;if(f.multitouch||!f.count){var g=f.pointers;g[b]||(g[b]=!0,f.count++,a._handlePointerDown(b,c,d,e))}},a._handleMove=function(a,b,c,d,e){a.__touch.pointers[b]&&a._handlePointerMove(b,c,d,e)},a._handleEnd=function(a,b,c){var d=a.__touch,e=d.pointers;e[b]&&(d.count--,a._handlePointerUp(b,c,!0),delete e[b])},createjs.Touch=a}(),this.createjs=this.createjs||{},function(){"use strict";var a=createjs.EaselJS=createjs.EaselJS||{};a.version="0.8.2",a.buildDate="Thu, 26 Nov 2015 20:44:34 GMT"}();/*!
* @license TweenJS
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2011-2015 gskinner.com, inc.
*
* Distributed under the terms of the MIT license.
* http://www.opensource.org/licenses/mit-license.html
*
* This notice shall be included in all copies or substantial portions of the Software.
*/
this.createjs=this.createjs||{},createjs.extend=function(a,b){"use strict";function c(){this.constructor=a}return c.prototype=b.prototype,a.prototype=new c},this.createjs=this.createjs||{},createjs.promote=function(a,b){"use strict";var c=a.prototype,d=Object.getPrototypeOf&&Object.getPrototypeOf(c)||c.__proto__;if(d){c[(b+="_")+"constructor"]=d.constructor;for(var e in d)c.hasOwnProperty(e)&&"function"==typeof d[e]&&(c[b+e]=d[e])}return a},this.createjs=this.createjs||{},function(){"use strict";function Event(a,b,c){this.type=a,this.target=null,this.currentTarget=null,this.eventPhase=0,this.bubbles=!!b,this.cancelable=!!c,this.timeStamp=(new Date).getTime(),this.defaultPrevented=!1,this.propagationStopped=!1,this.immediatePropagationStopped=!1,this.removed=!1}var a=Event.prototype;a.preventDefault=function(){this.defaultPrevented=this.cancelable&&!0},a.stopPropagation=function(){this.propagationStopped=!0},a.stopImmediatePropagation=function(){this.immediatePropagationStopped=this.propagationStopped=!0},a.remove=function(){this.removed=!0},a.clone=function(){return new Event(this.type,this.bubbles,this.cancelable)},a.set=function(a){for(var b in a)this[b]=a[b];return this},a.toString=function(){return"[Event (type="+this.type+")]"},createjs.Event=Event}(),this.createjs=this.createjs||{},function(){"use strict";function EventDispatcher(){this._listeners=null,this._captureListeners=null}var a=EventDispatcher.prototype;EventDispatcher.initialize=function(b){b.addEventListener=a.addEventListener,b.on=a.on,b.removeEventListener=b.off=a.removeEventListener,b.removeAllEventListeners=a.removeAllEventListeners,b.hasEventListener=a.hasEventListener,b.dispatchEvent=a.dispatchEvent,b._dispatchEvent=a._dispatchEvent,b.willTrigger=a.willTrigger},a.addEventListener=function(a,b,c){var d;d=c?this._captureListeners=this._captureListeners||{}:this._listeners=this._listeners||{};var e=d[a];return e&&this.removeEventListener(a,b,c),e=d[a],e?e.push(b):d[a]=[b],b},a.on=function(a,b,c,d,e,f){return b.handleEvent&&(c=c||b,b=b.handleEvent),c=c||this,this.addEventListener(a,function(a){b.call(c,a,e),d&&a.remove()},f)},a.removeEventListener=function(a,b,c){var d=c?this._captureListeners:this._listeners;if(d){var e=d[a];if(e)for(var f=0,g=e.length;g>f;f++)if(e[f]==b){1==g?delete d[a]:e.splice(f,1);break}}},a.off=a.removeEventListener,a.removeAllEventListeners=function(a){a?(this._listeners&&delete this._listeners[a],this._captureListeners&&delete this._captureListeners[a]):this._listeners=this._captureListeners=null},a.dispatchEvent=function(a,b,c){if("string"==typeof a){var d=this._listeners;if(!(b||d&&d[a]))return!0;a=new createjs.Event(a,b,c)}else a.target&&a.clone&&(a=a.clone());try{a.target=this}catch(e){}if(a.bubbles&&this.parent){for(var f=this,g=[f];f.parent;)g.push(f=f.parent);var h,i=g.length;for(h=i-1;h>=0&&!a.propagationStopped;h--)g[h]._dispatchEvent(a,1+(0==h));for(h=1;i>h&&!a.propagationStopped;h++)g[h]._dispatchEvent(a,3)}else this._dispatchEvent(a,2);return!a.defaultPrevented},a.hasEventListener=function(a){var b=this._listeners,c=this._captureListeners;return!!(b&&b[a]||c&&c[a])},a.willTrigger=function(a){for(var b=this;b;){if(b.hasEventListener(a))return!0;b=b.parent}return!1},a.toString=function(){return"[EventDispatcher]"},a._dispatchEvent=function(a,b){var c,d=1==b?this._captureListeners:this._listeners;if(a&&d){var e=d[a.type];if(!e||!(c=e.length))return;try{a.currentTarget=this}catch(f){}try{a.eventPhase=b}catch(f){}a.removed=!1,e=e.slice();for(var g=0;c>g&&!a.immediatePropagationStopped;g++){var h=e[g];h.handleEvent?h.handleEvent(a):h(a),a.removed&&(this.off(a.type,h,1==b),a.removed=!1)}}},createjs.EventDispatcher=EventDispatcher}(),this.createjs=this.createjs||{},function(){"use strict";function Ticker(){throw"Ticker cannot be instantiated."}Ticker.RAF_SYNCHED="synched",Ticker.RAF="raf",Ticker.TIMEOUT="timeout",Ticker.useRAF=!1,Ticker.timingMode=null,Ticker.maxDelta=0,Ticker.paused=!1,Ticker.removeEventListener=null,Ticker.removeAllEventListeners=null,Ticker.dispatchEvent=null,Ticker.hasEventListener=null,Ticker._listeners=null,createjs.EventDispatcher.initialize(Ticker),Ticker._addEventListener=Ticker.addEventListener,Ticker.addEventListener=function(){return!Ticker._inited&&Ticker.init(),Ticker._addEventListener.apply(Ticker,arguments)},Ticker._inited=!1,Ticker._startTime=0,Ticker._pausedTime=0,Ticker._ticks=0,Ticker._pausedTicks=0,Ticker._interval=50,Ticker._lastTime=0,Ticker._times=null,Ticker._tickTimes=null,Ticker._timerId=null,Ticker._raf=!0,Ticker.setInterval=function(a){Ticker._interval=a,Ticker._inited&&Ticker._setupTick()},Ticker.getInterval=function(){return Ticker._interval},Ticker.setFPS=function(a){Ticker.setInterval(1e3/a)},Ticker.getFPS=function(){return 1e3/Ticker._interval};try{Object.defineProperties(Ticker,{interval:{get:Ticker.getInterval,set:Ticker.setInterval},framerate:{get:Ticker.getFPS,set:Ticker.setFPS}})}catch(a){console.log(a)}Ticker.init=function(){Ticker._inited||(Ticker._inited=!0,Ticker._times=[],Ticker._tickTimes=[],Ticker._startTime=Ticker._getTime(),Ticker._times.push(Ticker._lastTime=0),Ticker.interval=Ticker._interval)},Ticker.reset=function(){if(Ticker._raf){var a=window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame;a&&a(Ticker._timerId)}else clearTimeout(Ticker._timerId);Ticker.removeAllEventListeners("tick"),Ticker._timerId=Ticker._times=Ticker._tickTimes=null,Ticker._startTime=Ticker._lastTime=Ticker._ticks=0,Ticker._inited=!1},Ticker.getMeasuredTickTime=function(a){var b=0,c=Ticker._tickTimes;if(!c||c.length<1)return-1;a=Math.min(c.length,a||0|Ticker.getFPS());for(var d=0;a>d;d++)b+=c[d];return b/a},Ticker.getMeasuredFPS=function(a){var b=Ticker._times;return!b||b.length<2?-1:(a=Math.min(b.length-1,a||0|Ticker.getFPS()),1e3/((b[0]-b[a])/a))},Ticker.setPaused=function(a){Ticker.paused=a},Ticker.getPaused=function(){return Ticker.paused},Ticker.getTime=function(a){return Ticker._startTime?Ticker._getTime()-(a?Ticker._pausedTime:0):-1},Ticker.getEventTime=function(a){return Ticker._startTime?(Ticker._lastTime||Ticker._startTime)-(a?Ticker._pausedTime:0):-1},Ticker.getTicks=function(a){return Ticker._ticks-(a?Ticker._pausedTicks:0)},Ticker._handleSynch=function(){Ticker._timerId=null,Ticker._setupTick(),Ticker._getTime()-Ticker._lastTime>=.97*(Ticker._interval-1)&&Ticker._tick()},Ticker._handleRAF=function(){Ticker._timerId=null,Ticker._setupTick(),Ticker._tick()},Ticker._handleTimeout=function(){Ticker._timerId=null,Ticker._setupTick(),Ticker._tick()},Ticker._setupTick=function(){if(null==Ticker._timerId){var a=Ticker.timingMode||Ticker.useRAF&&Ticker.RAF_SYNCHED;if(a==Ticker.RAF_SYNCHED||a==Ticker.RAF){var b=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame;if(b)return Ticker._timerId=b(a==Ticker.RAF?Ticker._handleRAF:Ticker._handleSynch),void(Ticker._raf=!0)}Ticker._raf=!1,Ticker._timerId=setTimeout(Ticker._handleTimeout,Ticker._interval)}},Ticker._tick=function(){var a=Ticker.paused,b=Ticker._getTime(),c=b-Ticker._lastTime;if(Ticker._lastTime=b,Ticker._ticks++,a&&(Ticker._pausedTicks++,Ticker._pausedTime+=c),Ticker.hasEventListener("tick")){var d=new createjs.Event("tick"),e=Ticker.maxDelta;d.delta=e&&c>e?e:c,d.paused=a,d.time=b,d.runTime=b-Ticker._pausedTime,Ticker.dispatchEvent(d)}for(Ticker._tickTimes.unshift(Ticker._getTime()-b);Ticker._tickTimes.length>100;)Ticker._tickTimes.pop();for(Ticker._times.unshift(b);Ticker._times.length>100;)Ticker._times.pop()};var b=window.performance&&(performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow);Ticker._getTime=function(){return(b&&b.call(performance)||(new Date).getTime())-Ticker._startTime},createjs.Ticker=Ticker}(),this.createjs=this.createjs||{},function(){"use strict";function Tween(a,b,c){this.ignoreGlobalPause=!1,this.loop=!1,this.duration=0,this.pluginData=c||{},this.target=a,this.position=null,this.passive=!1,this._paused=!1,this._curQueueProps={},this._initQueueProps={},this._steps=[],this._actions=[],this._prevPosition=0,this._stepPosition=0,this._prevPos=-1,this._target=a,this._useTicks=!1,this._inited=!1,this._registered=!1,b&&(this._useTicks=b.useTicks,this.ignoreGlobalPause=b.ignoreGlobalPause,this.loop=b.loop,b.onChange&&this.addEventListener("change",b.onChange),b.override&&Tween.removeTweens(a)),b&&b.paused?this._paused=!0:createjs.Tween._register(this,!0),b&&null!=b.position&&this.setPosition(b.position,Tween.NONE)}var a=createjs.extend(Tween,createjs.EventDispatcher);Tween.NONE=0,Tween.LOOP=1,Tween.REVERSE=2,Tween.IGNORE={},Tween._tweens=[],Tween._plugins={},Tween.get=function(a,b,c,d){return d&&Tween.removeTweens(a),new Tween(a,b,c)},Tween.tick=function(a,b){for(var c=Tween._tweens.slice(),d=c.length-1;d>=0;d--){var e=c[d];b&&!e.ignoreGlobalPause||e._paused||e.tick(e._useTicks?1:a)}},Tween.handleEvent=function(a){"tick"==a.type&&this.tick(a.delta,a.paused)},Tween.removeTweens=function(a){if(a.tweenjs_count){for(var b=Tween._tweens,c=b.length-1;c>=0;c--){var d=b[c];d._target==a&&(d._paused=!0,b.splice(c,1))}a.tweenjs_count=0}},Tween.removeAllTweens=function(){for(var a=Tween._tweens,b=0,c=a.length;c>b;b++){var d=a[b];d._paused=!0,d.target&&(d.target.tweenjs_count=0)}a.length=0},Tween.hasActiveTweens=function(a){return a?null!=a.tweenjs_count&&!!a.tweenjs_count:Tween._tweens&&!!Tween._tweens.length},Tween.installPlugin=function(a,b){var c=a.priority;null==c&&(a.priority=c=0);for(var d=0,e=b.length,f=Tween._plugins;e>d;d++){var g=b[d];if(f[g]){for(var h=f[g],i=0,j=h.length;j>i&&!(c<h[i].priority);i++);f[g].splice(i,0,a)}else f[g]=[a]}},Tween._register=function(a,b){var c=a._target,d=Tween._tweens;if(b&&!a._registered)c&&(c.tweenjs_count=c.tweenjs_count?c.tweenjs_count+1:1),d.push(a),!Tween._inited&&createjs.Ticker&&(createjs.Ticker.addEventListener("tick",Tween),Tween._inited=!0);else if(!b&&a._registered){c&&c.tweenjs_count--;for(var e=d.length;e--;)if(d[e]==a){d.splice(e,1);break}}a._registered=b},a.wait=function(a,b){if(null==a||0>=a)return this;var c=this._cloneProps(this._curQueueProps);return this._addStep({d:a,p0:c,e:this._linearEase,p1:c,v:b})},a.to=function(a,b,c){return(isNaN(b)||0>b)&&(b=0),this._addStep({d:b||0,p0:this._cloneProps(this._curQueueProps),e:c,p1:this._cloneProps(this._appendQueueProps(a))})},a.call=function(a,b,c){return this._addAction({f:a,p:b?b:[this],o:c?c:this._target})},a.set=function(a,b){return this._addAction({f:this._set,o:this,p:[a,b?b:this._target]})},a.play=function(a){return a||(a=this),this.call(a.setPaused,[!1],a)},a.pause=function(a){return a||(a=this),this.call(a.setPaused,[!0],a)},a.setPosition=function(a,b){0>a&&(a=0),null==b&&(b=1);var c=a,d=!1;if(c>=this.duration&&(this.loop?c%=this.duration:(c=this.duration,d=!0)),c==this._prevPos)return d;var e=this._prevPos;if(this.position=this._prevPos=c,this._prevPosition=a,this._target)if(d)this._updateTargetProps(null,1);else if(this._steps.length>0){for(var f=0,g=this._steps.length;g>f&&!(this._steps[f].t>c);f++);var h=this._steps[f-1];this._updateTargetProps(h,(this._stepPosition=c-h.t)/h.d)}return 0!=b&&this._actions.length>0&&(this._useTicks?this._runActions(c,c):1==b&&e>c?(e!=this.duration&&this._runActions(e,this.duration),this._runActions(0,c,!0)):this._runActions(e,c)),d&&this.setPaused(!0),this.dispatchEvent("change"),d},a.tick=function(a){this._paused||this.setPosition(this._prevPosition+a)},a.setPaused=function(a){return this._paused===!!a?this:(this._paused=!!a,Tween._register(this,!a),this)},a.w=a.wait,a.t=a.to,a.c=a.call,a.s=a.set,a.toString=function(){return"[Tween]"},a.clone=function(){throw"Tween can not be cloned."},a._updateTargetProps=function(a,b){var c,d,e,f,g,h;if(a||1!=b){if(this.passive=!!a.v,this.passive)return;a.e&&(b=a.e(b,0,1,1)),c=a.p0,d=a.p1}else this.passive=!1,c=d=this._curQueueProps;for(var i in this._initQueueProps){null==(f=c[i])&&(c[i]=f=this._initQueueProps[i]),null==(g=d[i])&&(d[i]=g=f),e=f==g||0==b||1==b||"number"!=typeof f?1==b?g:f:f+(g-f)*b;var j=!1;if(h=Tween._plugins[i])for(var k=0,l=h.length;l>k;k++){var m=h[k].tween(this,i,e,c,d,b,!!a&&c==d,!a);m==Tween.IGNORE?j=!0:e=m}j||(this._target[i]=e)}},a._runActions=function(a,b,c){var d=a,e=b,f=-1,g=this._actions.length,h=1;for(a>b&&(d=b,e=a,f=g,g=h=-1);(f+=h)!=g;){var i=this._actions[f],j=i.t;(j==e||j>d&&e>j||c&&j==a)&&i.f.apply(i.o,i.p)}},a._appendQueueProps=function(a){var b,c,d,e,f;for(var g in a)if(void 0===this._initQueueProps[g]){if(c=this._target[g],b=Tween._plugins[g])for(d=0,e=b.length;e>d;d++)c=b[d].init(this,g,c);this._initQueueProps[g]=this._curQueueProps[g]=void 0===c?null:c}else c=this._curQueueProps[g];for(var g in a){if(c=this._curQueueProps[g],b=Tween._plugins[g])for(f=f||{},d=0,e=b.length;e>d;d++)b[d].step&&b[d].step(this,g,c,a[g],f);this._curQueueProps[g]=a[g]}return f&&this._appendQueueProps(f),this._curQueueProps},a._cloneProps=function(a){var b={};for(var c in a)b[c]=a[c];return b},a._addStep=function(a){return a.d>0&&(this._steps.push(a),a.t=this.duration,this.duration+=a.d),this},a._addAction=function(a){return a.t=this.duration,this._actions.push(a),this},a._set=function(a,b){for(var c in a)b[c]=a[c]},createjs.Tween=createjs.promote(Tween,"EventDispatcher")}(),this.createjs=this.createjs||{},function(){"use strict";function Timeline(a,b,c){this.EventDispatcher_constructor(),this.ignoreGlobalPause=!1,this.duration=0,this.loop=!1,this.position=null,this._paused=!1,this._tweens=[],this._labels=null,this._labelList=null,this._prevPosition=0,this._prevPos=-1,this._useTicks=!1,this._registered=!1,c&&(this._useTicks=c.useTicks,this.loop=c.loop,this.ignoreGlobalPause=c.ignoreGlobalPause,c.onChange&&this.addEventListener("change",c.onChange)),a&&this.addTween.apply(this,a),this.setLabels(b),c&&c.paused?this._paused=!0:createjs.Tween._register(this,!0),c&&null!=c.position&&this.setPosition(c.position,createjs.Tween.NONE)}var a=createjs.extend(Timeline,createjs.EventDispatcher);a.addTween=function(a){var b=arguments.length;if(b>1){for(var c=0;b>c;c++)this.addTween(arguments[c]);return arguments[0]}return 0==b?null:(this.removeTween(a),this._tweens.push(a),a.setPaused(!0),a._paused=!1,a._useTicks=this._useTicks,a.duration>this.duration&&(this.duration=a.duration),this._prevPos>=0&&a.setPosition(this._prevPos,createjs.Tween.NONE),a)},a.removeTween=function(a){var b=arguments.length;if(b>1){for(var c=!0,d=0;b>d;d++)c=c&&this.removeTween(arguments[d]);return c}if(0==b)return!1;for(var e=this._tweens,d=e.length;d--;)if(e[d]==a)return e.splice(d,1),a.duration>=this.duration&&this.updateDuration(),!0;return!1},a.addLabel=function(a,b){this._labels[a]=b;var c=this._labelList;if(c){for(var d=0,e=c.length;e>d&&!(b<c[d].position);d++);c.splice(d,0,{label:a,position:b})}},a.setLabels=function(a){this._labels=a?a:{}},a.getLabels=function(){var a=this._labelList;if(!a){a=this._labelList=[];var b=this._labels;for(var c in b)a.push({label:c,position:b[c]});a.sort(function(a,b){return a.position-b.position})}return a},a.getCurrentLabel=function(){var a=this.getLabels(),b=this.position,c=a.length;if(c){for(var d=0;c>d&&!(b<a[d].position);d++);return 0==d?null:a[d-1].label}return null},a.gotoAndPlay=function(a){this.setPaused(!1),this._goto(a)},a.gotoAndStop=function(a){this.setPaused(!0),this._goto(a)},a.setPosition=function(a,b){var c=this._calcPosition(a),d=!this.loop&&a>=this.duration;if(c==this._prevPos)return d;this._prevPosition=a,this.position=this._prevPos=c;for(var e=0,f=this._tweens.length;f>e;e++)if(this._tweens[e].setPosition(c,b),c!=this._prevPos)return!1;return d&&this.setPaused(!0),this.dispatchEvent("change"),d},a.setPaused=function(a){this._paused=!!a,createjs.Tween._register(this,!a)},a.updateDuration=function(){this.duration=0;for(var a=0,b=this._tweens.length;b>a;a++){var c=this._tweens[a];c.duration>this.duration&&(this.duration=c.duration)}},a.tick=function(a){this.setPosition(this._prevPosition+a)},a.resolve=function(a){var b=Number(a);return isNaN(b)&&(b=this._labels[a]),b},a.toString=function(){return"[Timeline]"},a.clone=function(){throw"Timeline can not be cloned."},a._goto=function(a){var b=this.resolve(a);null!=b&&this.setPosition(b)},a._calcPosition=function(a){return 0>a?0:a<this.duration?a:this.loop?a%this.duration:this.duration},createjs.Timeline=createjs.promote(Timeline,"EventDispatcher")}(),this.createjs=this.createjs||{},function(){"use strict";function Ease(){throw"Ease cannot be instantiated."}Ease.linear=function(a){return a},Ease.none=Ease.linear,Ease.get=function(a){return-1>a&&(a=-1),a>1&&(a=1),function(b){return 0==a?b:0>a?b*(b*-a+1+a):b*((2-b)*a+(1-a))}},Ease.getPowIn=function(a){return function(b){return Math.pow(b,a)}},Ease.getPowOut=function(a){return function(b){return 1-Math.pow(1-b,a)}},Ease.getPowInOut=function(a){return function(b){return(b*=2)<1?.5*Math.pow(b,a):1-.5*Math.abs(Math.pow(2-b,a))}},Ease.quadIn=Ease.getPowIn(2),Ease.quadOut=Ease.getPowOut(2),Ease.quadInOut=Ease.getPowInOut(2),Ease.cubicIn=Ease.getPowIn(3),Ease.cubicOut=Ease.getPowOut(3),Ease.cubicInOut=Ease.getPowInOut(3),Ease.quartIn=Ease.getPowIn(4),Ease.quartOut=Ease.getPowOut(4),Ease.quartInOut=Ease.getPowInOut(4),Ease.quintIn=Ease.getPowIn(5),Ease.quintOut=Ease.getPowOut(5),Ease.quintInOut=Ease.getPowInOut(5),Ease.sineIn=function(a){return 1-Math.cos(a*Math.PI/2)},Ease.sineOut=function(a){return Math.sin(a*Math.PI/2)},Ease.sineInOut=function(a){return-.5*(Math.cos(Math.PI*a)-1)},Ease.getBackIn=function(a){return function(b){return b*b*((a+1)*b-a)}},Ease.backIn=Ease.getBackIn(1.7),Ease.getBackOut=function(a){return function(b){return--b*b*((a+1)*b+a)+1}},Ease.backOut=Ease.getBackOut(1.7),Ease.getBackInOut=function(a){return a*=1.525,function(b){return(b*=2)<1?.5*b*b*((a+1)*b-a):.5*((b-=2)*b*((a+1)*b+a)+2)}},Ease.backInOut=Ease.getBackInOut(1.7),Ease.circIn=function(a){return-(Math.sqrt(1-a*a)-1)},Ease.circOut=function(a){return Math.sqrt(1- --a*a)},Ease.circInOut=function(a){return(a*=2)<1?-.5*(Math.sqrt(1-a*a)-1):.5*(Math.sqrt(1-(a-=2)*a)+1)},Ease.bounceIn=function(a){return 1-Ease.bounceOut(1-a)},Ease.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},Ease.bounceInOut=function(a){return.5>a?.5*Ease.bounceIn(2*a):.5*Ease.bounceOut(2*a-1)+.5},Ease.getElasticIn=function(a,b){var c=2*Math.PI;return function(d){if(0==d||1==d)return d;var e=b/c*Math.asin(1/a);return-(a*Math.pow(2,10*(d-=1))*Math.sin((d-e)*c/b))}},Ease.elasticIn=Ease.getElasticIn(1,.3),Ease.getElasticOut=function(a,b){var c=2*Math.PI;return function(d){if(0==d||1==d)return d;var e=b/c*Math.asin(1/a);return a*Math.pow(2,-10*d)*Math.sin((d-e)*c/b)+1}},Ease.elasticOut=Ease.getElasticOut(1,.3),Ease.getElasticInOut=function(a,b){var c=2*Math.PI;return function(d){var e=b/c*Math.asin(1/a);return(d*=2)<1?-.5*a*Math.pow(2,10*(d-=1))*Math.sin((d-e)*c/b):a*Math.pow(2,-10*(d-=1))*Math.sin((d-e)*c/b)*.5+1}},Ease.elasticInOut=Ease.getElasticInOut(1,.3*1.5),createjs.Ease=Ease}(),this.createjs=this.createjs||{},function(){"use strict";function MotionGuidePlugin(){throw"MotionGuidePlugin cannot be instantiated."}MotionGuidePlugin.priority=0,MotionGuidePlugin._rotOffS,MotionGuidePlugin._rotOffE,MotionGuidePlugin._rotNormS,MotionGuidePlugin._rotNormE,MotionGuidePlugin.install=function(){return createjs.Tween.installPlugin(MotionGuidePlugin,["guide","x","y","rotation"]),createjs.Tween.IGNORE},MotionGuidePlugin.init=function(a,b,c){var d=a.target;return d.hasOwnProperty("x")||(d.x=0),d.hasOwnProperty("y")||(d.y=0),d.hasOwnProperty("rotation")||(d.rotation=0),"rotation"==b&&(a.__needsRot=!0),"guide"==b?null:c},MotionGuidePlugin.step=function(a,b,c,d,e){if("rotation"==b&&(a.__rotGlobalS=c,a.__rotGlobalE=d,MotionGuidePlugin.testRotData(a,e)),"guide"!=b)return d;var f,g=d;g.hasOwnProperty("path")||(g.path=[]);var h=g.path;if(g.hasOwnProperty("end")||(g.end=1),g.hasOwnProperty("start")||(g.start=c&&c.hasOwnProperty("end")&&c.path===h?c.end:0),g.hasOwnProperty("_segments")&&g._length)return d;var i=h.length,j=10;if(!(i>=6&&(i-2)%4==0))throw"invalid 'path' data, please see documentation for valid paths";g._segments=[],g._length=0;for(var k=2;i>k;k+=4){for(var l,m,n=h[k-2],o=h[k-1],p=h[k+0],q=h[k+1],r=h[k+2],s=h[k+3],t=n,u=o,v=0,w=[],x=1;j>=x;x++){var y=x/j,z=1-y;l=z*z*n+2*z*y*p+y*y*r,m=z*z*o+2*z*y*q+y*y*s,v+=w[w.push(Math.sqrt((f=l-t)*f+(f=m-u)*f))-1],t=l,u=m}g._segments.push(v),g._segments.push(w),g._length+=v}f=g.orient,g.orient=!0;var A={};return MotionGuidePlugin.calc(g,g.start,A),a.__rotPathS=Number(A.rotation.toFixed(5)),MotionGuidePlugin.calc(g,g.end,A),a.__rotPathE=Number(A.rotation.toFixed(5)),g.orient=!1,MotionGuidePlugin.calc(g,g.end,e),g.orient=f,g.orient?(a.__guideData=g,MotionGuidePlugin.testRotData(a,e),d):d},MotionGuidePlugin.testRotData=function(a,b){if(void 0===a.__rotGlobalS||void 0===a.__rotGlobalE){if(a.__needsRot)return;a.__rotGlobalS=a.__rotGlobalE=void 0!==a._curQueueProps.rotation?a._curQueueProps.rotation:b.rotation=a.target.rotation||0}if(void 0!==a.__guideData){var c=a.__guideData,d=a.__rotGlobalE-a.__rotGlobalS,e=a.__rotPathE-a.__rotPathS,f=d-e;if("auto"==c.orient)f>180?f-=360:-180>f&&(f+=360);else if("cw"==c.orient){for(;0>f;)f+=360;0==f&&d>0&&180!=d&&(f+=360)}else if("ccw"==c.orient){for(f=d-(e>180?360-e:e);f>0;)f-=360;0==f&&0>d&&-180!=d&&(f-=360)}c.rotDelta=f,c.rotOffS=a.__rotGlobalS-a.__rotPathS,a.__rotGlobalS=a.__rotGlobalE=a.__guideData=a.__needsRot=void 0}},MotionGuidePlugin.tween=function(a,b,c,d,e,f,g){var h=e.guide;if(void 0==h||h===d.guide)return c;if(h.lastRatio!=f){var i=(h.end-h.start)*(g?h.end:f)+h.start;switch(MotionGuidePlugin.calc(h,i,a.target),h.orient){case"cw":case"ccw":case"auto":a.target.rotation+=h.rotOffS+h.rotDelta*f;break;case"fixed":default:a.target.rotation+=h.rotOffS}h.lastRatio=f}return"rotation"!=b||h.orient&&"false"!=h.orient?a.target[b]:c},MotionGuidePlugin.calc=function(a,b,c){if(void 0==a._segments)throw"Missing critical pre-calculated information, please file a bug";void 0==c&&(c={x:0,y:0,rotation:0});for(var d=a._segments,e=a.path,f=a._length*b,g=d.length-2,h=0;f>d[h]&&g>h;)f-=d[h],h+=2;var i=d[h+1],j=0;for(g=i.length-1;f>i[j]&&g>j;)f-=i[j],j++;var k=j/++g+f/(g*i[j]);h=2*h+2;var l=1-k;return c.x=l*l*e[h-2]+2*l*k*e[h+0]+k*k*e[h+2],c.y=l*l*e[h-1]+2*l*k*e[h+1]+k*k*e[h+3],a.orient&&(c.rotation=57.2957795*Math.atan2((e[h+1]-e[h-1])*l+(e[h+3]-e[h+1])*k,(e[h+0]-e[h-2])*l+(e[h+2]-e[h+0])*k)),c},createjs.MotionGuidePlugin=MotionGuidePlugin}(),this.createjs=this.createjs||{},function(){"use strict";var a=createjs.TweenJS=createjs.TweenJS||{};a.version="0.6.2",a.buildDate="Thu, 26 Nov 2015 20:44:31 GMT"}();/*
 *
 * https://github.com/fatlinesofcode/ngDraggable
 */
angular.module("ngDraggable", [])
        .directive('ngDrag', ['$rootScope', '$parse', function ($rootScope, $parse) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    scope.value = attrs.ngDrag;
                 //   console.log("ngDraggable", "link", "", scope.value);
                  //  return;
                    var offset,_mx,_my,_tx,_ty;
                    var _hasTouch = ('ontouchstart' in document.documentElement);
                    var _pressEvents = 'touchstart mousedown';
                    var _moveEvents = 'touchmove mousemove';
                    var _releaseEvents = 'touchend mouseup';

                    var $document = $(document);
                    var $window = $(window);
                    var _data = null;

                    var _dragEnabled = false;

                    var _moveHistory = [];

                    var _pressTimer=null;

                    var onDragSuccessCallback = $parse(attrs.ngDragSuccess) || null;

                    var initialize = function () {
                        element.attr('draggable', 'false'); // prevent native drag
                        toggleListeners(true);
                    };


                    var toggleListeners = function (enable) {
                        // remove listeners

                        if (!enable)return;
                        // add listeners.

                        scope.$on('$destroy', onDestroy);
                        attrs.$observe("ngDrag", onEnableChange);
                        scope.$watch(attrs.ngDragData, onDragDataChange);
                        element.on(_pressEvents, onpress);
                        if(! _hasTouch){
                            element.on('mousedown', function(){ return false;}); // prevent native drag
                        }
                    };
                    var onDestroy = function (enable) {
                        toggleListeners(false);
                    };
                    var onDragDataChange = function (newVal, oldVal) {
                        _data = newVal;
                     //   console.log("69","onDragDataChange","data", _data);
                    }
                    var onEnableChange = function (newVal, oldVal) {
                        _dragEnabled=scope.$eval(newVal);

                    }
                    /*
                     * When the element is clicked start the drag behaviour
                     * On touch devices as a small delay so as not to prevent native window scrolling
                     */
                    var onpress = function(evt) {
                        if(! _dragEnabled)return;


                        if(_hasTouch){
                            cancelPress();
                            _pressTimer = setTimeout(function(){
                                cancelPress();
                                onlongpress(evt);
                            }, 0);
                            $document.on(_moveEvents, cancelPress);
                            $document.on(_releaseEvents, cancelPress);
                        }else{
                            onlongpress(evt);
                        }

                    }
                    var cancelPress = function() {
                        clearTimeout(_pressTimer);
                        $document.off(_moveEvents, cancelPress);
                        $document.off(_releaseEvents, cancelPress);
                      _moveHistory = [];
                    }
                    var onlongpress = function(evt) {
                        if(! _dragEnabled)return;
                        //evt.preventDefault();

                        offset = element.offset();
                        element.centerX = (element.width()/2);
                        element.centerY = (element.height()/2);
                        element.addClass('dragging');
                        _mx = (evt.pageX || evt.originalEvent.touches[evt.originalEvent.which].pageX);
                        _my = (evt.pageY || evt.originalEvent.touches[evt.originalEvent.which].pageY);

                      // the commented out block was the original implementation
                        //_tx=_mx-element.centerX-$window.scrollLeft();
                        //_ty=_my -element.centerY-$window.scrollTop();

                      // the next two lines were changes made by CEWE to avoid centering of the image on the mouse position even if we were only
                      // clicking on the draggable element. We want centering only as soon as the element is being moved.
                      _tx=_mx-element.x-$window.scrollLeft();
                      _ty=_my -element.y-$window.scrollTop();

                        //moveElement(_tx, _ty);
                        $document.on(_moveEvents, onmove);
                        $document.on(_releaseEvents, onrelease);
                        $rootScope.$broadcast('draggable:start', {x:_mx, y:_my, tx:_tx, ty:_ty, element:element, data:_data, nativeEvent: evt.originalEvent});

                    }
                    var onmove = function(evt) {
                        if(! _dragEnabled)return;

                        _mx = (evt.pageX || evt.originalEvent.touches[evt.originalEvent.which].pageX);
                        _my = (evt.pageY || evt.originalEvent.touches[evt.originalEvent.which].pageY);
                        _tx=_mx-element.centerX-$window.scrollLeft();
                        _ty=_my -element.centerY-$window.scrollTop();

                        if (_moveHistory.length === 0) {
                          evt.preventDefault();
                        }

                        _moveHistory.push( {x: _mx, y: _my});


                        if (_moveHistory.length > 1) {
                          var startXY = _moveHistory[0];
                          var currentXY = _moveHistory[_moveHistory.length - 1];

                          if (currentXY.y - startXY.y > 40) { // only move the element if it has been moved at least a certain amount of pixels downwards
                            evt.preventDefault();
                            moveElement(_tx, _ty);
                          }
                        }

                        //$rootScope.$broadcast('draggable:move', {x:_mx, y:_my, tx:_tx, ty:_ty, element:element, data:_data});

                    }
                    var onrelease = function(evt) {
                        if(! _dragEnabled)return;
                        //evt.preventDefault();
                        $rootScope.$broadcast('draggable:end', {x:_mx, y:_my, tx:_tx, ty:_ty, element:element,data:_data, nativeEvent: evt.originalEvent, callback:onDragComplete});
                        element.removeClass('dragging');
                        reset();
                        $document.off(_moveEvents, onmove);
                        $document.off(_releaseEvents, onrelease);

                    }
                    var onDragComplete = function(evt) {

                        if(! onDragSuccessCallback)return;

                        scope.$apply(function () {
                            onDragSuccessCallback(scope, {$data: _data, $event: evt});
                        });
                    }
                    var reset = function() {
                        element.css({left:'',top:'', position:'', 'z-index':''});
                        _moveHistory = [];
                    }
                    var moveElement = function(x,y) {
                        element.css({left:x,top:y, position:'fixed', 'z-index':99999});
                    }
                    initialize();
                }
            }
        }])
        .directive('ngDrop', ['$parse', '$timeout', function ($parse, $timeout) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    scope.value = attrs.ngDrop;

                    var _dropEnabled=false;

                    var onDropCallback = $parse(attrs.ngDropSuccess);// || function(){};
                    var initialize = function () {
                        toggleListeners(true);
                    };


                    var toggleListeners = function (enable) {
                        // remove listeners

                        if (!enable)return;
                        // add listeners.
                        attrs.$observe("ngDrop", onEnableChange);
                        scope.$on('$destroy', onDestroy);
                        //scope.$watch(attrs.uiDraggable, onDraggableChange);
                        scope.$on('draggable:start', onDragStart);
                        scope.$on('draggable:move', onDragMove);
                        scope.$on('draggable:end', onDragEnd);
                    };
                    var onDestroy = function (enable) {
                        toggleListeners(false);
                    };
                    var onEnableChange = function (newVal, oldVal) {
                        _dropEnabled=scope.$eval(newVal);
                    }
                    var onDragStart = function(evt, obj) {
                        if(! _dropEnabled)return;
                        isTouching(obj.x,obj.y,obj.element);
                    }
                    var onDragMove = function(evt, obj) {
                        if(! _dropEnabled)return;
                        isTouching(obj.x,obj.y,obj.element);
                    }
                    var onDragEnd = function(evt, obj) {
                        if(! _dropEnabled)return;
                        if(isTouching(obj.x,obj.y,obj.element)){
                            // call the ngDraggable element callback
                           if(obj.callback){
                                obj.callback(evt);
                            }

                            // call the ngDrop element callback
                         //   scope.$apply(function () {
                         //       onDropCallback(scope, {$data: obj.data, $event: evt});
                         //   });
                            $timeout(function(){
                                onDropCallback(scope, {$data: obj.data, $event: obj});
                            });


                        }
                        updateDragStyles(false, obj.element);
                    }
                    var isTouching = function(mouseX, mouseY, dragElement) {
                        var touching= hitTest(mouseX, mouseY);
                        updateDragStyles(touching, dragElement);
                        return touching;
                    }
                    var updateDragStyles = function(touching, dragElement) {
                        if(touching){
                            element.addClass('drag-enter');
                            dragElement.addClass('drag-over');
                        }else{
                            element.removeClass('drag-enter');
                            dragElement.removeClass('drag-over');
                        }
                    }
                    var hitTest = function(x, y) {
                        var bounds = element.offset();
                        bounds.right = bounds.left + element.outerWidth();
                        bounds.bottom = bounds.top + element.outerHeight();
                        return x >= bounds.left
                                && x <= bounds.right
                                && y <= bounds.bottom
                                && y >= bounds.top;
                    }

                    initialize();
                }
            }
        }])
        .directive('ngDragClone', ['$parse', '$timeout', function ($parse, $timeout) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    var img;
                    scope.clonedData = {};
                    var initialize = function () {

                        img = $(element.find('img'));
                        element.attr('draggable', 'false');
                        img.attr('draggable', 'false');
                        //log("243","initialize","img", img);
                        reset();
                        toggleListeners(true);
                    };


                    var toggleListeners = function (enable) {
                        // remove listeners

                        if (!enable)return;
                        // add listeners.
                        scope.$on('draggable:start', onDragStart);
                        scope.$on('draggable:move', onDragMove);
                        scope.$on('draggable:end', onDragEnd);
                        preventContextMenu();

                    };
                    var preventContextMenu = function() {
                      //  element.off('mousedown touchstart touchmove touchend touchcancel', absorbEvent_);
                        img.off('mousedown touchstart touchmove touchend touchcancel', absorbEvent_);
                      //  element.on('mousedown touchstart touchmove touchend touchcancel', absorbEvent_);
                        img.on('mousedown touchstart touchmove touchend touchcancel', absorbEvent_);
                    }
                    var onDragStart = function(evt, obj) {
                        scope.$apply(function(){
                            scope.clonedData = obj.data;
                         //   preventContextMenu();
                        });
                        //log("259","onDragStart","onDragStart", obj.element.width());
                        element.width(obj.element.width())
                        element.height(obj.element.height())
                        moveElement(obj.tx,obj.ty);
                    }
                    var onDragMove = function(evt, obj) {
                        moveElement(obj.tx,obj.ty);
                    }
                    var onDragEnd = function(evt, obj) {
                        //moveElement(obj.tx,obj.ty);
                        reset();
                    }

                    var reset = function() {
                        element.css({left:0,top:0, position:'fixed', 'z-index':-1, visibility:'hidden'});
                    }
                    var moveElement = function(x,y) {
                        element.css({left:x,top:y, position:'fixed', 'z-index':99999, visibility:'visible'});
                    }

                    var absorbEvent_ = function (event) {
                        var e = event.originalEvent;
                        e.preventDefault && e.preventDefault();
                        e.stopPropagation && e.stopPropagation();
                        e.cancelBubble = true;
                        e.returnValue = false;
                        return false;
                    }

                    initialize();
                }
            }
        }])
        .directive('ngPreventDrag', ['$parse', '$timeout', function ($parse, $timeout) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    var initialize = function () {

                        element.attr('draggable', 'false');
                        toggleListeners(true);
                    };


                    var toggleListeners = function (enable) {
                        // remove listeners

                        if (!enable)return;
                        // add listeners.
                        element.on('mousedown touchstart touchmove touchend touchcancel', absorbEvent_);
                    };


                    var absorbEvent_ = function (event) {
                        var e = event.originalEvent;
                        e.preventDefault && e.preventDefault();
                        e.stopPropagation && e.stopPropagation();
                        e.cancelBubble = true;
                        e.returnValue = false;
                        return false;
                    }

                    initialize();
                }
            }
        }]);/**
 * @license AngularJS v1.4.3
 * (c) 2010-2015 Google, Inc. http://angularjs.org
 * License: MIT
 */
(function(window, angular, undefined) {'use strict';

/* jshint ignore:start */
var noop        = angular.noop;
var extend      = angular.extend;
var jqLite      = angular.element;
var forEach     = angular.forEach;
var isArray     = angular.isArray;
var isString    = angular.isString;
var isObject    = angular.isObject;
var isUndefined = angular.isUndefined;
var isDefined   = angular.isDefined;
var isFunction  = angular.isFunction;
var isElement   = angular.isElement;

var ELEMENT_NODE = 1;
var COMMENT_NODE = 8;

var NG_ANIMATE_CLASSNAME = 'ng-animate';
var NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren';

var isPromiseLike = function(p) {
  return p && p.then ? true : false;
}

function assertArg(arg, name, reason) {
  if (!arg) {
    throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  }
  return arg;
}

function mergeClasses(a,b) {
  if (!a && !b) return '';
  if (!a) return b;
  if (!b) return a;
  if (isArray(a)) a = a.join(' ');
  if (isArray(b)) b = b.join(' ');
  return a + ' ' + b;
}

function packageStyles(options) {
  var styles = {};
  if (options && (options.to || options.from)) {
    styles.to = options.to;
    styles.from = options.from;
  }
  return styles;
}

function pendClasses(classes, fix, isPrefix) {
  var className = '';
  classes = isArray(classes)
      ? classes
      : classes && isString(classes) && classes.length
          ? classes.split(/\s+/)
          : [];
  forEach(classes, function(klass, i) {
    if (klass && klass.length > 0) {
      className += (i > 0) ? ' ' : '';
      className += isPrefix ? fix + klass
                            : klass + fix;
    }
  });
  return className;
}

function removeFromArray(arr, val) {
  var index = arr.indexOf(val);
  if (val >= 0) {
    arr.splice(index, 1);
  }
}

function stripCommentsFromElement(element) {
  if (element instanceof jqLite) {
    switch (element.length) {
      case 0:
        return [];
        break;

      case 1:
        // there is no point of stripping anything if the element
        // is the only element within the jqLite wrapper.
        // (it's important that we retain the element instance.)
        if (element[0].nodeType === ELEMENT_NODE) {
          return element;
        }
        break;

      default:
        return jqLite(extractElementNode(element));
        break;
    }
  }

  if (element.nodeType === ELEMENT_NODE) {
    return jqLite(element);
  }
}

function extractElementNode(element) {
  if (!element[0]) return element;
  for (var i = 0; i < element.length; i++) {
    var elm = element[i];
    if (elm.nodeType == ELEMENT_NODE) {
      return elm;
    }
  }
}

function $$addClass($$jqLite, element, className) {
  forEach(element, function(elm) {
    $$jqLite.addClass(elm, className);
  });
}

function $$removeClass($$jqLite, element, className) {
  forEach(element, function(elm) {
    $$jqLite.removeClass(elm, className);
  });
}

function applyAnimationClassesFactory($$jqLite) {
  return function(element, options) {
    if (options.addClass) {
      $$addClass($$jqLite, element, options.addClass);
      options.addClass = null;
    }
    if (options.removeClass) {
      $$removeClass($$jqLite, element, options.removeClass);
      options.removeClass = null;
    }
  }
}

function prepareAnimationOptions(options) {
  options = options || {};
  if (!options.$$prepared) {
    var domOperation = options.domOperation || noop;
    options.domOperation = function() {
      options.$$domOperationFired = true;
      domOperation();
      domOperation = noop;
    };
    options.$$prepared = true;
  }
  return options;
}

function applyAnimationStyles(element, options) {
  applyAnimationFromStyles(element, options);
  applyAnimationToStyles(element, options);
}

function applyAnimationFromStyles(element, options) {
  if (options.from) {
    element.css(options.from);
    options.from = null;
  }
}

function applyAnimationToStyles(element, options) {
  if (options.to) {
    element.css(options.to);
    options.to = null;
  }
}

function mergeAnimationOptions(element, target, newOptions) {
  var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || '');
  var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || '');
  var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove);

  extend(target, newOptions);

  if (classes.addClass) {
    target.addClass = classes.addClass;
  } else {
    target.addClass = null;
  }

  if (classes.removeClass) {
    target.removeClass = classes.removeClass;
  } else {
    target.removeClass = null;
  }

  return target;
}

function resolveElementClasses(existing, toAdd, toRemove) {
  var ADD_CLASS = 1;
  var REMOVE_CLASS = -1;

  var flags = {};
  existing = splitClassesToLookup(existing);

  toAdd = splitClassesToLookup(toAdd);
  forEach(toAdd, function(value, key) {
    flags[key] = ADD_CLASS;
  });

  toRemove = splitClassesToLookup(toRemove);
  forEach(toRemove, function(value, key) {
    flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS;
  });

  var classes = {
    addClass: '',
    removeClass: ''
  };

  forEach(flags, function(val, klass) {
    var prop, allow;
    if (val === ADD_CLASS) {
      prop = 'addClass';
      allow = !existing[klass];
    } else if (val === REMOVE_CLASS) {
      prop = 'removeClass';
      allow = existing[klass];
    }
    if (allow) {
      if (classes[prop].length) {
        classes[prop] += ' ';
      }
      classes[prop] += klass;
    }
  });

  function splitClassesToLookup(classes) {
    if (isString(classes)) {
      classes = classes.split(' ');
    }

    var obj = {};
    forEach(classes, function(klass) {
      // sometimes the split leaves empty string values
      // incase extra spaces were applied to the options
      if (klass.length) {
        obj[klass] = true;
      }
    });
    return obj;
  }

  return classes;
}

function getDomNode(element) {
  return (element instanceof angular.element) ? element[0] : element;
}

var $$rAFSchedulerFactory = ['$$rAF', function($$rAF) {
  var tickQueue = [];
  var cancelFn;

  function scheduler(tasks) {
    // we make a copy since RAFScheduler mutates the state
    // of the passed in array variable and this would be difficult
    // to track down on the outside code
    tickQueue.push([].concat(tasks));
    nextTick();
  }

  /* waitUntilQuiet does two things:
   * 1. It will run the FINAL `fn` value only when an uncancelled RAF has passed through
   * 2. It will delay the next wave of tasks from running until the quiet `fn` has run.
   *
   * The motivation here is that animation code can request more time from the scheduler
   * before the next wave runs. This allows for certain DOM properties such as classes to
   * be resolved in time for the next animation to run.
   */
  scheduler.waitUntilQuiet = function(fn) {
    if (cancelFn) cancelFn();

    cancelFn = $$rAF(function() {
      cancelFn = null;
      fn();
      nextTick();
    });
  };

  return scheduler;

  function nextTick() {
    if (!tickQueue.length) return;

    var updatedQueue = [];
    for (var i = 0; i < tickQueue.length; i++) {
      var innerQueue = tickQueue[i];
      runNextTask(innerQueue);
      if (innerQueue.length) {
        updatedQueue.push(innerQueue);
      }
    }
    tickQueue = updatedQueue;

    if (!cancelFn) {
      $$rAF(function() {
        if (!cancelFn) nextTick();
      });
    }
  }

  function runNextTask(tasks) {
    var nextTask = tasks.shift();
    nextTask();
  }
}];

var $$AnimateChildrenDirective = [function() {
  return function(scope, element, attrs) {
    var val = attrs.ngAnimateChildren;
    if (angular.isString(val) && val.length === 0) { //empty attribute
      element.data(NG_ANIMATE_CHILDREN_DATA, true);
    } else {
      attrs.$observe('ngAnimateChildren', function(value) {
        value = value === 'on' || value === 'true';
        element.data(NG_ANIMATE_CHILDREN_DATA, value);
      });
    }
  };
}];

/**
 * @ngdoc service
 * @name $animateCss
 * @kind object
 *
 * @description
 * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes
 * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT
 * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or
 * directives to create more complex animations that can be purely driven using CSS code.
 *
 * Note that only browsers that support CSS transitions and/or keyframe animations are capable of
 * rendering animations triggered via `$animateCss` (bad news for IE9 and lower).
 *
 * ## Usage
 * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that
 * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however,
 * any automatic control over cancelling animations and/or preventing animations from being run on
 * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to
 * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger
 * the CSS animation.
 *
 * The example below shows how we can create a folding animation on an element using `ng-if`:
 *
 * ```html
 * <!-- notice the `fold-animation` CSS class -->
 * <div ng-if="onOff" class="fold-animation">
 *   This element will go BOOM
 * </div>
 * <button ng-click="onOff=true">Fold In</button>
 * ```
 *
 * Now we create the **JavaScript animation** that will trigger the CSS transition:
 *
 * ```js
 * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
 *   return {
 *     enter: function(element, doneFn) {
 *       var height = element[0].offsetHeight;
 *       return $animateCss(element, {
 *         from: { height:'0px' },
 *         to: { height:height + 'px' },
 *         duration: 1 // one second
 *       });
 *     }
 *   }
 * }]);
 * ```
 *
 * ## More Advanced Uses
 *
 * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks
 * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code.
 *
 * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation,
 * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with
 * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order
 * to provide a working animation that will run in CSS.
 *
 * The example below showcases a more advanced version of the `.fold-animation` from the example above:
 *
 * ```js
 * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
 *   return {
 *     enter: function(element, doneFn) {
 *       var height = element[0].offsetHeight;
 *       return $animateCss(element, {
 *         addClass: 'red large-text pulse-twice',
 *         easing: 'ease-out',
 *         from: { height:'0px' },
 *         to: { height:height + 'px' },
 *         duration: 1 // one second
 *       });
 *     }
 *   }
 * }]);
 * ```
 *
 * Since we're adding/removing CSS classes then the CSS transition will also pick those up:
 *
 * ```css
 * /&#42; since a hardcoded duration value of 1 was provided in the JavaScript animation code,
 * the CSS classes below will be transitioned despite them being defined as regular CSS classes &#42;/
 * .red { background:red; }
 * .large-text { font-size:20px; }
 *
 * /&#42; we can also use a keyframe animation and $animateCss will make it work alongside the transition &#42;/
 * .pulse-twice {
 *   animation: 0.5s pulse linear 2;
 *   -webkit-animation: 0.5s pulse linear 2;
 * }
 *
 * @keyframes pulse {
 *   from { transform: scale(0.5); }
 *   to { transform: scale(1.5); }
 * }
 *
 * @-webkit-keyframes pulse {
 *   from { -webkit-transform: scale(0.5); }
 *   to { -webkit-transform: scale(1.5); }
 * }
 * ```
 *
 * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen.
 *
 * ## How the Options are handled
 *
 * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation
 * works with the options provided. Say for example we were adding a class that contained a keyframe value and we wanted to also animate some inline
 * styles using the `from` and `to` properties.
 *
 * ```js
 * var animator = $animateCss(element, {
 *   from: { background:'red' },
 *   to: { background:'blue' }
 * });
 * animator.start();
 * ```
 *
 * ```css
 * .rotating-animation {
 *   animation:0.5s rotate linear;
 *   -webkit-animation:0.5s rotate linear;
 * }
 *
 * @keyframes rotate {
 *   from { transform: rotate(0deg); }
 *   to { transform: rotate(360deg); }
 * }
 *
 * @-webkit-keyframes rotate {
 *   from { -webkit-transform: rotate(0deg); }
 *   to { -webkit-transform: rotate(360deg); }
 * }
 * ```
 *
 * The missing pieces here are that we do not have a transition set (within the CSS code nor within the `$animateCss` options) and the duration of the animation is
 * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition
 * style matching the duration detected from the keyframe style (which is present in the CSS class that is being added) and then prepare both the transition
 * and keyframe animations to run in parallel on the element. Then when the animation is underway the provided `from` and `to` CSS styles will be applied
 * and spread across the transition and keyframe animation.
 *
 * ## What is returned
 *
 * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually
 * start the animation. All that is going on here is that the element is being prepared for the animation (which means that the generated CSS classes are
 * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties:
 *
 * ```js
 * var animator = $animateCss(element, { ... });
 * ```
 *
 * Now what do the contents of our `animator` variable look like:
 *
 * ```js
 * {
 *   // starts the animation
 *   start: Function,
 *
 *   // ends (aborts) the animation
 *   end: Function
 * }
 * ```
 *
 * To actually start the animation we need to run `animation.start()` which will then return a promise that we can hook into to detect when the animation ends.
 * If we choose not to run the animation then we MUST run `animation.end()` to perform a cleanup on the element (since some CSS classes and stlyes may have been
 * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties
 * and that changing them will not reconfigure the parameters of the animation.
 *
 * ### runner.done() vs runner.then()
 * It is documented that `animation.start()` will return a promise object and this is true, however, there is also an additional method available on the
 * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**.
 * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()`
 * unless you really need a digest to kick off afterwards.
 *
 * Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss
 * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code).
 * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works.
 *
 * @param {DOMElement} element the element that will be animated
 * @param {object} options the animation-related options that will be applied during the animation
 *
 * * `event` - The DOM event (e.g. enter, leave, move). When used, a generated CSS class of `ng-EVENT` and `ng-EVENT-active` will be applied
 * to the element during the animation. Multiple events can be provided when spaces are used as a separator. (Note that this will not perform any DOM operation.)
 * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both).
 * * `transition` - The raw CSS transition style that will be used (e.g. `1s linear all`).
 * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`).
 * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation.
 * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
 * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation.
 * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation.
 * * `duration` - A number value representing the total duration of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `0`
 * is provided then the animation will be skipped entirely.
 * * `delay` - A number value representing the total delay of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `true` is
 * used then whatever delay value is detected from the CSS classes will be mirrored on the elements styles (e.g. by setting delay true then the style value
 * of the element will be `transition-delay: DETECTED_VALUE`). Using `true` is useful when you want the CSS classes and inline styles to all share the same
 * CSS delay value.
 * * `stagger` - A numeric time value representing the delay between successively animated elements
 * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.})
 * * `staggerIndex` - The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item in the stagger; therefore when a
 * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`)
 * `applyClassesEarly` - Whether or not the classes being added or removed will be used when detecting the animation. This is set by `$animate` when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. (Note that this will prevent any transitions from occuring on the classes being added and removed.)
 *
 * @return {object} an object with start and end methods and details about the animation.
 *
 * * `start` - The method to start the animation. This will return a `Promise` when called.
 * * `end` - This method will cancel the animation and remove all applied CSS classes and styles.
 */

// Detect proper transitionend/animationend event names.
var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;

// If unprefixed events are not supported but webkit-prefixed are, use the latter.
// Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
// Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`
// but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
// Register both events in case `window.onanimationend` is not supported because of that,
// do the same for `transitionend` as Safari is likely to exhibit similar behavior.
// Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
// therefore there is no reason to test anymore for other vendor prefixes:
// http://caniuse.com/#search=transition
if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) {
  CSS_PREFIX = '-webkit-';
  TRANSITION_PROP = 'WebkitTransition';
  TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
} else {
  TRANSITION_PROP = 'transition';
  TRANSITIONEND_EVENT = 'transitionend';
}

if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) {
  CSS_PREFIX = '-webkit-';
  ANIMATION_PROP = 'WebkitAnimation';
  ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
} else {
  ANIMATION_PROP = 'animation';
  ANIMATIONEND_EVENT = 'animationend';
}

var DURATION_KEY = 'Duration';
var PROPERTY_KEY = 'Property';
var DELAY_KEY = 'Delay';
var TIMING_KEY = 'TimingFunction';
var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';
var ANIMATION_PLAYSTATE_KEY = 'PlayState';
var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
var CLOSING_TIME_BUFFER = 1.5;
var ONE_SECOND = 1000;
var BASE_TEN = 10;

var SAFE_FAST_FORWARD_DURATION_VALUE = 9999;

var ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY;
var ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY;

var TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY;
var TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY;

var DETECT_CSS_PROPERTIES = {
  transitionDuration:      TRANSITION_DURATION_PROP,
  transitionDelay:         TRANSITION_DELAY_PROP,
  transitionProperty:      TRANSITION_PROP + PROPERTY_KEY,
  animationDuration:       ANIMATION_DURATION_PROP,
  animationDelay:          ANIMATION_DELAY_PROP,
  animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY
};

var DETECT_STAGGER_CSS_PROPERTIES = {
  transitionDuration:      TRANSITION_DURATION_PROP,
  transitionDelay:         TRANSITION_DELAY_PROP,
  animationDuration:       ANIMATION_DURATION_PROP,
  animationDelay:          ANIMATION_DELAY_PROP
};

function computeCssStyles($window, element, properties) {
  var styles = Object.create(null);
  var detectedStyles = $window.getComputedStyle(element) || {};
  forEach(properties, function(formalStyleName, actualStyleName) {
    var val = detectedStyles[formalStyleName];
    if (val) {
      var c = val.charAt(0);

      // only numerical-based values have a negative sign or digit as the first value
      if (c === '-' || c === '+' || c >= 0) {
        val = parseMaxTime(val);
      }

      // by setting this to null in the event that the delay is not set or is set directly as 0
      // then we can still allow for zegative values to be used later on and not mistake this
      // value for being greater than any other negative value.
      if (val === 0) {
        val = null;
      }
      styles[actualStyleName] = val;
    }
  });

  return styles;
}

function parseMaxTime(str) {
  var maxValue = 0;
  var values = str.split(/\s*,\s*/);
  forEach(values, function(value) {
    // it's always safe to consider only second values and omit `ms` values since
    // getComputedStyle will always handle the conversion for us
    if (value.charAt(value.length - 1) == 's') {
      value = value.substring(0, value.length - 1);
    }
    value = parseFloat(value) || 0;
    maxValue = maxValue ? Math.max(value, maxValue) : value;
  });
  return maxValue;
}

function truthyTimingValue(val) {
  return val === 0 || val != null;
}

function getCssTransitionDurationStyle(duration, applyOnlyDuration) {
  var style = TRANSITION_PROP;
  var value = duration + 's';
  if (applyOnlyDuration) {
    style += DURATION_KEY;
  } else {
    value += ' linear all';
  }
  return [style, value];
}

function getCssKeyframeDurationStyle(duration) {
  return [ANIMATION_DURATION_PROP, duration + 's'];
}

function getCssDelayStyle(delay, isKeyframeAnimation) {
  var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP;
  return [prop, delay + 's'];
}

function blockTransitions(node, duration) {
  // we use a negative delay value since it performs blocking
  // yet it doesn't kill any existing transitions running on the
  // same element which makes this safe for class-based animations
  var value = duration ? '-' + duration + 's' : '';
  applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]);
  return [TRANSITION_DELAY_PROP, value];
}

function blockKeyframeAnimations(node, applyBlock) {
  var value = applyBlock ? 'paused' : '';
  var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY;
  applyInlineStyle(node, [key, value]);
  return [key, value];
}

function applyInlineStyle(node, styleTuple) {
  var prop = styleTuple[0];
  var value = styleTuple[1];
  node.style[prop] = value;
}

function createLocalCacheLookup() {
  var cache = Object.create(null);
  return {
    flush: function() {
      cache = Object.create(null);
    },

    count: function(key) {
      var entry = cache[key];
      return entry ? entry.total : 0;
    },

    get: function(key) {
      var entry = cache[key];
      return entry && entry.value;
    },

    put: function(key, value) {
      if (!cache[key]) {
        cache[key] = { total: 1, value: value };
      } else {
        cache[key].total++;
      }
    }
  };
}

var $AnimateCssProvider = ['$animateProvider', function($animateProvider) {
  var gcsLookup = createLocalCacheLookup();
  var gcsStaggerLookup = createLocalCacheLookup();

  this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout',
               '$document', '$sniffer', '$$rAFScheduler',
       function($window,   $$jqLite,   $$AnimateRunner,   $timeout,
                $document,   $sniffer,   $$rAFScheduler) {

    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);

    var parentCounter = 0;
    function gcsHashFn(node, extraClasses) {
      var KEY = "$$ngAnimateParentKey";
      var parentNode = node.parentNode;
      var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter);
      return parentID + '-' + node.getAttribute('class') + '-' + extraClasses;
    }

    function computeCachedCssStyles(node, className, cacheKey, properties) {
      var timings = gcsLookup.get(cacheKey);

      if (!timings) {
        timings = computeCssStyles($window, node, properties);
        if (timings.animationIterationCount === 'infinite') {
          timings.animationIterationCount = 1;
        }
      }

      // we keep putting this in multiple times even though the value and the cacheKey are the same
      // because we're keeping an interal tally of how many duplicate animations are detected.
      gcsLookup.put(cacheKey, timings);
      return timings;
    }

    function computeCachedCssStaggerStyles(node, className, cacheKey, properties) {
      var stagger;

      // if we have one or more existing matches of matching elements
      // containing the same parent + CSS styles (which is how cacheKey works)
      // then staggering is possible
      if (gcsLookup.count(cacheKey) > 0) {
        stagger = gcsStaggerLookup.get(cacheKey);

        if (!stagger) {
          var staggerClassName = pendClasses(className, '-stagger');

          $$jqLite.addClass(node, staggerClassName);

          stagger = computeCssStyles($window, node, properties);

          // force the conversion of a null value to zero incase not set
          stagger.animationDuration = Math.max(stagger.animationDuration, 0);
          stagger.transitionDuration = Math.max(stagger.transitionDuration, 0);

          $$jqLite.removeClass(node, staggerClassName);

          gcsStaggerLookup.put(cacheKey, stagger);
        }
      }

      return stagger || {};
    }

    var bod = getDomNode($document).body;
    var rafWaitQueue = [];
    function waitUntilQuiet(callback) {
      rafWaitQueue.push(callback);
      $$rAFScheduler.waitUntilQuiet(function() {
        gcsLookup.flush();
        gcsStaggerLookup.flush();

        //the line below will force the browser to perform a repaint so
        //that all the animated elements within the animation frame will
        //be properly updated and drawn on screen. This is required to
        //ensure that the preparation animation is properly flushed so that
        //the active state picks up from there. DO NOT REMOVE THIS LINE.
        //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
        //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
        //WILL TAKE YEARS AWAY FROM YOUR LIFE.
        var width = bod.offsetWidth + 1;

        // we use a for loop to ensure that if the queue is changed
        // during this looping then it will consider new requests
        for (var i = 0; i < rafWaitQueue.length; i++) {
          rafWaitQueue[i](width);
        }
        rafWaitQueue.length = 0;
      });
    }

    return init;

    function computeTimings(node, className, cacheKey) {
      var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES);
      var aD = timings.animationDelay;
      var tD = timings.transitionDelay;
      timings.maxDelay = aD && tD
          ? Math.max(aD, tD)
          : (aD || tD);
      timings.maxDuration = Math.max(
          timings.animationDuration * timings.animationIterationCount,
          timings.transitionDuration);

      return timings;
    }

    function init(element, options) {
      var node = getDomNode(element);
      if (!node || !node.parentNode) {
        return closeAndReturnNoopAnimator();
      }

      options = prepareAnimationOptions(options);

      var temporaryStyles = [];
      var classes = element.attr('class');
      var styles = packageStyles(options);
      var animationClosed;
      var animationPaused;
      var animationCompleted;
      var runner;
      var runnerHost;
      var maxDelay;
      var maxDelayTime;
      var maxDuration;
      var maxDurationTime;

      if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) {
        return closeAndReturnNoopAnimator();
      }

      var method = options.event && isArray(options.event)
            ? options.event.join(' ')
            : options.event;

      var isStructural = method && options.structural;
      var structuralClassName = '';
      var addRemoveClassName = '';

      if (isStructural) {
        structuralClassName = pendClasses(method, 'ng-', true);
      } else if (method) {
        structuralClassName = method;
      }

      if (options.addClass) {
        addRemoveClassName += pendClasses(options.addClass, '-add');
      }

      if (options.removeClass) {
        if (addRemoveClassName.length) {
          addRemoveClassName += ' ';
        }
        addRemoveClassName += pendClasses(options.removeClass, '-remove');
      }

      // there may be a situation where a structural animation is combined together
      // with CSS classes that need to resolve before the animation is computed.
      // However this means that there is no explicit CSS code to block the animation
      // from happening (by setting 0s none in the class name). If this is the case
      // we need to apply the classes before the first rAF so we know to continue if
      // there actually is a detected transition or keyframe animation
      if (options.applyClassesEarly && addRemoveClassName.length) {
        applyAnimationClasses(element, options);
        addRemoveClassName = '';
      }

      var setupClasses = [structuralClassName, addRemoveClassName].join(' ').trim();
      var fullClassName = classes + ' ' + setupClasses;
      var activeClasses = pendClasses(setupClasses, '-active');
      var hasToStyles = styles.to && Object.keys(styles.to).length > 0;
      var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0;

      // there is no way we can trigger an animation if no styles and
      // no classes are being applied which would then trigger a transition,
      // unless there a is raw keyframe value that is applied to the element.
      if (!containsKeyframeAnimation
           && !hasToStyles
           && !setupClasses) {
        return closeAndReturnNoopAnimator();
      }

      var cacheKey, stagger;
      if (options.stagger > 0) {
        var staggerVal = parseFloat(options.stagger);
        stagger = {
          transitionDelay: staggerVal,
          animationDelay: staggerVal,
          transitionDuration: 0,
          animationDuration: 0
        };
      } else {
        cacheKey = gcsHashFn(node, fullClassName);
        stagger = computeCachedCssStaggerStyles(node, setupClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES);
      }

      $$jqLite.addClass(element, setupClasses);

      var applyOnlyDuration;

      if (options.transitionStyle) {
        var transitionStyle = [TRANSITION_PROP, options.transitionStyle];
        applyInlineStyle(node, transitionStyle);
        temporaryStyles.push(transitionStyle);
      }

      if (options.duration >= 0) {
        applyOnlyDuration = node.style[TRANSITION_PROP].length > 0;
        var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration);

        // we set the duration so that it will be picked up by getComputedStyle later
        applyInlineStyle(node, durationStyle);
        temporaryStyles.push(durationStyle);
      }

      if (options.keyframeStyle) {
        var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle];
        applyInlineStyle(node, keyframeStyle);
        temporaryStyles.push(keyframeStyle);
      }

      var itemIndex = stagger
          ? options.staggerIndex >= 0
              ? options.staggerIndex
              : gcsLookup.count(cacheKey)
          : 0;

      var isFirst = itemIndex === 0;

      // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY
      // without causing any combination of transitions to kick in. By adding a negative delay value
      // it forces the setup class' transition to end immediately. We later then remove the negative
      // transition delay to allow for the transition to naturally do it's thing. The beauty here is
      // that if there is no transition defined then nothing will happen and this will also allow
      // other transitions to be stacked on top of each other without any chopping them out.
      if (isFirst) {
        blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE);
      }

      var timings = computeTimings(node, fullClassName, cacheKey);
      var relativeDelay = timings.maxDelay;
      maxDelay = Math.max(relativeDelay, 0);
      maxDuration = timings.maxDuration;

      var flags = {};
      flags.hasTransitions          = timings.transitionDuration > 0;
      flags.hasAnimations           = timings.animationDuration > 0;
      flags.hasTransitionAll        = flags.hasTransitions && timings.transitionProperty == 'all';
      flags.applyTransitionDuration = hasToStyles && (
                                        (flags.hasTransitions && !flags.hasTransitionAll)
                                         || (flags.hasAnimations && !flags.hasTransitions));
      flags.applyAnimationDuration  = options.duration && flags.hasAnimations;
      flags.applyTransitionDelay    = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions);
      flags.applyAnimationDelay     = truthyTimingValue(options.delay) && flags.hasAnimations;
      flags.recalculateTimingStyles = addRemoveClassName.length > 0;

      if (flags.applyTransitionDuration || flags.applyAnimationDuration) {
        maxDuration = options.duration ? parseFloat(options.duration) : maxDuration;

        if (flags.applyTransitionDuration) {
          flags.hasTransitions = true;
          timings.transitionDuration = maxDuration;
          applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0;
          temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration));
        }

        if (flags.applyAnimationDuration) {
          flags.hasAnimations = true;
          timings.animationDuration = maxDuration;
          temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration));
        }
      }

      if (maxDuration === 0 && !flags.recalculateTimingStyles) {
        return closeAndReturnNoopAnimator();
      }

      // we need to recalculate the delay value since we used a pre-emptive negative
      // delay value and the delay value is required for the final event checking. This
      // property will ensure that this will happen after the RAF phase has passed.
      if (options.duration == null && timings.transitionDuration > 0) {
        flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst;
      }

      maxDelayTime = maxDelay * ONE_SECOND;
      maxDurationTime = maxDuration * ONE_SECOND;
      if (!options.skipBlocking) {
        flags.blockTransition = timings.transitionDuration > 0;
        flags.blockKeyframeAnimation = timings.animationDuration > 0 &&
                                       stagger.animationDelay > 0 &&
                                       stagger.animationDuration === 0;
      }

      applyAnimationFromStyles(element, options);
      if (!flags.blockTransition) {
        blockTransitions(node, false);
      }

      applyBlocking(maxDuration);

      // TODO(matsko): for 1.5 change this code to have an animator object for better debugging
      return {
        $$willAnimate: true,
        end: endFn,
        start: function() {
          if (animationClosed) return;

          runnerHost = {
            end: endFn,
            cancel: cancelFn,
            resume: null, //this will be set during the start() phase
            pause: null
          };

          runner = new $$AnimateRunner(runnerHost);

          waitUntilQuiet(start);

          // we don't have access to pause/resume the animation
          // since it hasn't run yet. AnimateRunner will therefore
          // set noop functions for resume and pause and they will
          // later be overridden once the animation is triggered
          return runner;
        }
      };

      function endFn() {
        close();
      }

      function cancelFn() {
        close(true);
      }

      function close(rejected) { // jshint ignore:line
        // if the promise has been called already then we shouldn't close
        // the animation again
        if (animationClosed || (animationCompleted && animationPaused)) return;
        animationClosed = true;
        animationPaused = false;

        $$jqLite.removeClass(element, setupClasses);
        $$jqLite.removeClass(element, activeClasses);

        blockKeyframeAnimations(node, false);
        blockTransitions(node, false);

        forEach(temporaryStyles, function(entry) {
          // There is only one way to remove inline style properties entirely from elements.
          // By using `removeProperty` this works, but we need to convert camel-cased CSS
          // styles down to hyphenated values.
          node.style[entry[0]] = '';
        });

        applyAnimationClasses(element, options);
        applyAnimationStyles(element, options);

        // the reason why we have this option is to allow a synchronous closing callback
        // that is fired as SOON as the animation ends (when the CSS is removed) or if
        // the animation never takes off at all. A good example is a leave animation since
        // the element must be removed just after the animation is over or else the element
        // will appear on screen for one animation frame causing an overbearing flicker.
        if (options.onDone) {
          options.onDone();
        }

        // if the preparation function fails then the promise is not setup
        if (runner) {
          runner.complete(!rejected);
        }
      }

      function applyBlocking(duration) {
        if (flags.blockTransition) {
          blockTransitions(node, duration);
        }

        if (flags.blockKeyframeAnimation) {
          blockKeyframeAnimations(node, !!duration);
        }
      }

      function closeAndReturnNoopAnimator() {
        runner = new $$AnimateRunner({
          end: endFn,
          cancel: cancelFn
        });

        close();

        return {
          $$willAnimate: false,
          start: function() {
            return runner;
          },
          end: endFn
        };
      }

      function start() {
        if (animationClosed) return;
        if (!node.parentNode) {
          close();
          return;
        }

        var startTime, events = [];

        // even though we only pause keyframe animations here the pause flag
        // will still happen when transitions are used. Only the transition will
        // not be paused since that is not possible. If the animation ends when
        // paused then it will not complete until unpaused or cancelled.
        var playPause = function(playAnimation) {
          if (!animationCompleted) {
            animationPaused = !playAnimation;
            if (timings.animationDuration) {
              var value = blockKeyframeAnimations(node, animationPaused);
              animationPaused
                  ? temporaryStyles.push(value)
                  : removeFromArray(temporaryStyles, value);
            }
          } else if (animationPaused && playAnimation) {
            animationPaused = false;
            close();
          }
        };

        // checking the stagger duration prevents an accidently cascade of the CSS delay style
        // being inherited from the parent. If the transition duration is zero then we can safely
        // rely that the delay value is an intential stagger delay style.
        var maxStagger = itemIndex > 0
                         && ((timings.transitionDuration && stagger.transitionDuration === 0) ||
                            (timings.animationDuration && stagger.animationDuration === 0))
                         && Math.max(stagger.animationDelay, stagger.transitionDelay);
        if (maxStagger) {
          $timeout(triggerAnimationStart,
                   Math.floor(maxStagger * itemIndex * ONE_SECOND),
                   false);
        } else {
          triggerAnimationStart();
        }

        // this will decorate the existing promise runner with pause/resume methods
        runnerHost.resume = function() {
          playPause(true);
        };

        runnerHost.pause = function() {
          playPause(false);
        };

        function triggerAnimationStart() {
          // just incase a stagger animation kicks in when the animation
          // itself was cancelled entirely
          if (animationClosed) return;

          applyBlocking(false);

          forEach(temporaryStyles, function(entry) {
            var key = entry[0];
            var value = entry[1];
            node.style[key] = value;
          });

          applyAnimationClasses(element, options);
          $$jqLite.addClass(element, activeClasses);

          if (flags.recalculateTimingStyles) {
            fullClassName = node.className + ' ' + setupClasses;
            cacheKey = gcsHashFn(node, fullClassName);

            timings = computeTimings(node, fullClassName, cacheKey);
            relativeDelay = timings.maxDelay;
            maxDelay = Math.max(relativeDelay, 0);
            maxDuration = timings.maxDuration;

            if (maxDuration === 0) {
              close();
              return;
            }

            flags.hasTransitions = timings.transitionDuration > 0;
            flags.hasAnimations = timings.animationDuration > 0;
          }

          if (flags.applyTransitionDelay || flags.applyAnimationDelay) {
            relativeDelay = typeof options.delay !== "boolean" && truthyTimingValue(options.delay)
                  ? parseFloat(options.delay)
                  : relativeDelay;

            maxDelay = Math.max(relativeDelay, 0);

            var delayStyle;
            if (flags.applyTransitionDelay) {
              timings.transitionDelay = relativeDelay;
              delayStyle = getCssDelayStyle(relativeDelay);
              temporaryStyles.push(delayStyle);
              node.style[delayStyle[0]] = delayStyle[1];
            }

            if (flags.applyAnimationDelay) {
              timings.animationDelay = relativeDelay;
              delayStyle = getCssDelayStyle(relativeDelay, true);
              temporaryStyles.push(delayStyle);
              node.style[delayStyle[0]] = delayStyle[1];
            }
          }

          maxDelayTime = maxDelay * ONE_SECOND;
          maxDurationTime = maxDuration * ONE_SECOND;

          if (options.easing) {
            var easeProp, easeVal = options.easing;
            if (flags.hasTransitions) {
              easeProp = TRANSITION_PROP + TIMING_KEY;
              temporaryStyles.push([easeProp, easeVal]);
              node.style[easeProp] = easeVal;
            }
            if (flags.hasAnimations) {
              easeProp = ANIMATION_PROP + TIMING_KEY;
              temporaryStyles.push([easeProp, easeVal]);
              node.style[easeProp] = easeVal;
            }
          }

          if (timings.transitionDuration) {
            events.push(TRANSITIONEND_EVENT);
          }

          if (timings.animationDuration) {
            events.push(ANIMATIONEND_EVENT);
          }

          startTime = Date.now();
          element.on(events.join(' '), onAnimationProgress);
          $timeout(onAnimationExpired, maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime);

          applyAnimationToStyles(element, options);
        }

        function onAnimationExpired() {
          // although an expired animation is a failed animation, getting to
          // this outcome is very easy if the CSS code screws up. Therefore we
          // should still continue normally as if the animation completed correctly.
          close();
        }

        function onAnimationProgress(event) {
          event.stopPropagation();
          var ev = event.originalEvent || event;
          var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now();

          /* Firefox (or possibly just Gecko) likes to not round values up
           * when a ms measurement is used for the animation */
          var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));

          /* $manualTimeStamp is a mocked timeStamp value which is set
           * within browserTrigger(). This is only here so that tests can
           * mock animations properly. Real events fallback to event.timeStamp,
           * or, if they don't, then a timeStamp is automatically created for them.
           * We're checking to see if the timeStamp surpasses the expected delay,
           * but we're using elapsedTime instead of the timeStamp on the 2nd
           * pre-condition since animations sometimes close off early */
          if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
            // we set this flag to ensure that if the transition is paused then, when resumed,
            // the animation will automatically close itself since transitions cannot be paused.
            animationCompleted = true;
            close();
          }
        }
      }
    }
  }];
}];

var $$AnimateCssDriverProvider = ['$$animationProvider', function($$animationProvider) {
  $$animationProvider.drivers.push('$$animateCssDriver');

  var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim';
  var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor';

  var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out';
  var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in';

  this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$document', '$sniffer',
       function($animateCss,   $rootScope,   $$AnimateRunner,   $rootElement,   $document,   $sniffer) {

    // only browsers that support these properties can render animations
    if (!$sniffer.animations && !$sniffer.transitions) return noop;

    var bodyNode = getDomNode($document).body;
    var rootNode = getDomNode($rootElement);

    var rootBodyElement = jqLite(bodyNode.parentNode === rootNode ? bodyNode : rootNode);

    return function initDriverFn(animationDetails) {
      return animationDetails.from && animationDetails.to
          ? prepareFromToAnchorAnimation(animationDetails.from,
                                         animationDetails.to,
                                         animationDetails.classes,
                                         animationDetails.anchors)
          : prepareRegularAnimation(animationDetails);
    };

    function filterCssClasses(classes) {
      //remove all the `ng-` stuff
      return classes.replace(/\bng-\S+\b/g, '');
    }

    function getUniqueValues(a, b) {
      if (isString(a)) a = a.split(' ');
      if (isString(b)) b = b.split(' ');
      return a.filter(function(val) {
        return b.indexOf(val) === -1;
      }).join(' ');
    }

    function prepareAnchoredAnimation(classes, outAnchor, inAnchor) {
      var clone = jqLite(getDomNode(outAnchor).cloneNode(true));
      var startingClasses = filterCssClasses(getClassVal(clone));

      outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
      inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);

      clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME);

      rootBodyElement.append(clone);

      var animatorIn, animatorOut = prepareOutAnimation();

      // the user may not end up using the `out` animation and
      // only making use of the `in` animation or vice-versa.
      // In either case we should allow this and not assume the
      // animation is over unless both animations are not used.
      if (!animatorOut) {
        animatorIn = prepareInAnimation();
        if (!animatorIn) {
          return end();
        }
      }

      var startingAnimator = animatorOut || animatorIn;

      return {
        start: function() {
          var runner;

          var currentAnimation = startingAnimator.start();
          currentAnimation.done(function() {
            currentAnimation = null;
            if (!animatorIn) {
              animatorIn = prepareInAnimation();
              if (animatorIn) {
                currentAnimation = animatorIn.start();
                currentAnimation.done(function() {
                  currentAnimation = null;
                  end();
                  runner.complete();
                });
                return currentAnimation;
              }
            }
            // in the event that there is no `in` animation
            end();
            runner.complete();
          });

          runner = new $$AnimateRunner({
            end: endFn,
            cancel: endFn
          });

          return runner;

          function endFn() {
            if (currentAnimation) {
              currentAnimation.end();
            }
          }
        }
      };

      function calculateAnchorStyles(anchor) {
        var styles = {};

        var coords = getDomNode(anchor).getBoundingClientRect();

        // we iterate directly since safari messes up and doesn't return
        // all the keys for the coods object when iterated
        forEach(['width','height','top','left'], function(key) {
          var value = coords[key];
          switch (key) {
            case 'top':
              value += bodyNode.scrollTop;
              break;
            case 'left':
              value += bodyNode.scrollLeft;
              break;
          }
          styles[key] = Math.floor(value) + 'px';
        });
        return styles;
      }

      function prepareOutAnimation() {
        var animator = $animateCss(clone, {
          addClass: NG_OUT_ANCHOR_CLASS_NAME,
          delay: true,
          from: calculateAnchorStyles(outAnchor)
        });

        // read the comment within `prepareRegularAnimation` to understand
        // why this check is necessary
        return animator.$$willAnimate ? animator : null;
      }

      function getClassVal(element) {
        return element.attr('class') || '';
      }

      function prepareInAnimation() {
        var endingClasses = filterCssClasses(getClassVal(inAnchor));
        var toAdd = getUniqueValues(endingClasses, startingClasses);
        var toRemove = getUniqueValues(startingClasses, endingClasses);

        var animator = $animateCss(clone, {
          to: calculateAnchorStyles(inAnchor),
          addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd,
          removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove,
          delay: true
        });

        // read the comment within `prepareRegularAnimation` to understand
        // why this check is necessary
        return animator.$$willAnimate ? animator : null;
      }

      function end() {
        clone.remove();
        outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
        inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
      }
    }

    function prepareFromToAnchorAnimation(from, to, classes, anchors) {
      var fromAnimation = prepareRegularAnimation(from);
      var toAnimation = prepareRegularAnimation(to);

      var anchorAnimations = [];
      forEach(anchors, function(anchor) {
        var outElement = anchor['out'];
        var inElement = anchor['in'];
        var animator = prepareAnchoredAnimation(classes, outElement, inElement);
        if (animator) {
          anchorAnimations.push(animator);
        }
      });

      // no point in doing anything when there are no elements to animate
      if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return;

      return {
        start: function() {
          var animationRunners = [];

          if (fromAnimation) {
            animationRunners.push(fromAnimation.start());
          }

          if (toAnimation) {
            animationRunners.push(toAnimation.start());
          }

          forEach(anchorAnimations, function(animation) {
            animationRunners.push(animation.start());
          });

          var runner = new $$AnimateRunner({
            end: endFn,
            cancel: endFn // CSS-driven animations cannot be cancelled, only ended
          });

          $$AnimateRunner.all(animationRunners, function(status) {
            runner.complete(status);
          });

          return runner;

          function endFn() {
            forEach(animationRunners, function(runner) {
              runner.end();
            });
          }
        }
      };
    }

    function prepareRegularAnimation(animationDetails) {
      var element = animationDetails.element;
      var options = animationDetails.options || {};

      if (animationDetails.structural) {
        // structural animations ensure that the CSS classes are always applied
        // before the detection starts.
        options.structural = options.applyClassesEarly = true;

        // we special case the leave animation since we want to ensure that
        // the element is removed as soon as the animation is over. Otherwise
        // a flicker might appear or the element may not be removed at all
        options.event = animationDetails.event;
        if (options.event === 'leave') {
          options.onDone = options.domOperation;
        }
      } else {
        options.event = null;
      }

      var animator = $animateCss(element, options);

      // the driver lookup code inside of $$animation attempts to spawn a
      // driver one by one until a driver returns a.$$willAnimate animator object.
      // $animateCss will always return an object, however, it will pass in
      // a flag as a hint as to whether an animation was detected or not
      return animator.$$willAnimate ? animator : null;
    }
  }];
}];

// TODO(matsko): use caching here to speed things up for detection
// TODO(matsko): add documentation
//  by the time...

var $$AnimateJsProvider = ['$animateProvider', function($animateProvider) {
  this.$get = ['$injector', '$$AnimateRunner', '$$rAFMutex', '$$jqLite',
       function($injector,   $$AnimateRunner,   $$rAFMutex,   $$jqLite) {

    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
         // $animateJs(element, 'enter');
    return function(element, event, classes, options) {
      // the `classes` argument is optional and if it is not used
      // then the classes will be resolved from the element's className
      // property as well as options.addClass/options.removeClass.
      if (arguments.length === 3 && isObject(classes)) {
        options = classes;
        classes = null;
      }

      options = prepareAnimationOptions(options);
      if (!classes) {
        classes = element.attr('class') || '';
        if (options.addClass) {
          classes += ' ' + options.addClass;
        }
        if (options.removeClass) {
          classes += ' ' + options.removeClass;
        }
      }

      var classesToAdd = options.addClass;
      var classesToRemove = options.removeClass;

      // the lookupAnimations function returns a series of animation objects that are
      // matched up with one or more of the CSS classes. These animation objects are
      // defined via the module.animation factory function. If nothing is detected then
      // we don't return anything which then makes $animation query the next driver.
      var animations = lookupAnimations(classes);
      var before, after;
      if (animations.length) {
        var afterFn, beforeFn;
        if (event == 'leave') {
          beforeFn = 'leave';
          afterFn = 'afterLeave'; // TODO(matsko): get rid of this
        } else {
          beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1);
          afterFn = event;
        }

        if (event !== 'enter' && event !== 'move') {
          before = packageAnimations(element, event, options, animations, beforeFn);
        }
        after  = packageAnimations(element, event, options, animations, afterFn);
      }

      // no matching animations
      if (!before && !after) return;

      function applyOptions() {
        options.domOperation();
        applyAnimationClasses(element, options);
      }

      return {
        start: function() {
          var closeActiveAnimations;
          var chain = [];

          if (before) {
            chain.push(function(fn) {
              closeActiveAnimations = before(fn);
            });
          }

          if (chain.length) {
            chain.push(function(fn) {
              applyOptions();
              fn(true);
            });
          } else {
            applyOptions();
          }

          if (after) {
            chain.push(function(fn) {
              closeActiveAnimations = after(fn);
            });
          }

          var animationClosed = false;
          var runner = new $$AnimateRunner({
            end: function() {
              endAnimations();
            },
            cancel: function() {
              endAnimations(true);
            }
          });

          $$AnimateRunner.chain(chain, onComplete);
          return runner;

          function onComplete(success) {
            animationClosed = true;
            applyOptions();
            applyAnimationStyles(element, options);
            runner.complete(success);
          }

          function endAnimations(cancelled) {
            if (!animationClosed) {
              (closeActiveAnimations || noop)(cancelled);
              onComplete(cancelled);
            }
          }
        }
      };

      function executeAnimationFn(fn, element, event, options, onDone) {
        var args;
        switch (event) {
          case 'animate':
            args = [element, options.from, options.to, onDone];
            break;

          case 'setClass':
            args = [element, classesToAdd, classesToRemove, onDone];
            break;

          case 'addClass':
            args = [element, classesToAdd, onDone];
            break;

          case 'removeClass':
            args = [element, classesToRemove, onDone];
            break;

          default:
            args = [element, onDone];
            break;
        }

        args.push(options);

        var value = fn.apply(fn, args);
        if (value) {
          if (isFunction(value.start)) {
            value = value.start();
          }

          if (value instanceof $$AnimateRunner) {
            value.done(onDone);
          } else if (isFunction(value)) {
            // optional onEnd / onCancel callback
            return value;
          }
        }

        return noop;
      }

      function groupEventedAnimations(element, event, options, animations, fnName) {
        var operations = [];
        forEach(animations, function(ani) {
          var animation = ani[fnName];
          if (!animation) return;

          // note that all of these animations will run in parallel
          operations.push(function() {
            var runner;
            var endProgressCb;

            var resolved = false;
            var onAnimationComplete = function(rejected) {
              if (!resolved) {
                resolved = true;
                (endProgressCb || noop)(rejected);
                runner.complete(!rejected);
              }
            };

            runner = new $$AnimateRunner({
              end: function() {
                onAnimationComplete();
              },
              cancel: function() {
                onAnimationComplete(true);
              }
            });

            endProgressCb = executeAnimationFn(animation, element, event, options, function(result) {
              var cancelled = result === false;
              onAnimationComplete(cancelled);
            });

            return runner;
          });
        });

        return operations;
      }

      function packageAnimations(element, event, options, animations, fnName) {
        var operations = groupEventedAnimations(element, event, options, animations, fnName);
        if (operations.length === 0) {
          var a,b;
          if (fnName === 'beforeSetClass') {
            a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass');
            b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass');
          } else if (fnName === 'setClass') {
            a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass');
            b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass');
          }

          if (a) {
            operations = operations.concat(a);
          }
          if (b) {
            operations = operations.concat(b);
          }
        }

        if (operations.length === 0) return;

        // TODO(matsko): add documentation
        return function startAnimation(callback) {
          var runners = [];
          if (operations.length) {
            forEach(operations, function(animateFn) {
              runners.push(animateFn());
            });
          }

          runners.length ? $$AnimateRunner.all(runners, callback) : callback();

          return function endFn(reject) {
            forEach(runners, function(runner) {
              reject ? runner.cancel() : runner.end();
            });
          };
        };
      }
    };

    function lookupAnimations(classes) {
      classes = isArray(classes) ? classes : classes.split(' ');
      var matches = [], flagMap = {};
      for (var i=0; i < classes.length; i++) {
        var klass = classes[i],
            animationFactory = $animateProvider.$$registeredAnimations[klass];
        if (animationFactory && !flagMap[klass]) {
          matches.push($injector.get(animationFactory));
          flagMap[klass] = true;
        }
      }
      return matches;
    }
  }];
}];

var $$AnimateJsDriverProvider = ['$$animationProvider', function($$animationProvider) {
  $$animationProvider.drivers.push('$$animateJsDriver');
  this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) {
    return function initDriverFn(animationDetails) {
      if (animationDetails.from && animationDetails.to) {
        var fromAnimation = prepareAnimation(animationDetails.from);
        var toAnimation = prepareAnimation(animationDetails.to);
        if (!fromAnimation && !toAnimation) return;

        return {
          start: function() {
            var animationRunners = [];

            if (fromAnimation) {
              animationRunners.push(fromAnimation.start());
            }

            if (toAnimation) {
              animationRunners.push(toAnimation.start());
            }

            $$AnimateRunner.all(animationRunners, done);

            var runner = new $$AnimateRunner({
              end: endFnFactory(),
              cancel: endFnFactory()
            });

            return runner;

            function endFnFactory() {
              return function() {
                forEach(animationRunners, function(runner) {
                  // at this point we cannot cancel animations for groups just yet. 1.5+
                  runner.end();
                });
              };
            }

            function done(status) {
              runner.complete(status);
            }
          }
        };
      } else {
        return prepareAnimation(animationDetails);
      }
    };

    function prepareAnimation(animationDetails) {
      // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations
      var element = animationDetails.element;
      var event = animationDetails.event;
      var options = animationDetails.options;
      var classes = animationDetails.classes;
      return $$animateJs(element, event, classes, options);
    }
  }];
}];

var NG_ANIMATE_ATTR_NAME = 'data-ng-animate';
var NG_ANIMATE_PIN_DATA = '$ngAnimatePin';
var $$AnimateQueueProvider = ['$animateProvider', function($animateProvider) {
  var PRE_DIGEST_STATE = 1;
  var RUNNING_STATE = 2;

  var rules = this.rules = {
    skip: [],
    cancel: [],
    join: []
  };

  function isAllowed(ruleType, element, currentAnimation, previousAnimation) {
    return rules[ruleType].some(function(fn) {
      return fn(element, currentAnimation, previousAnimation);
    });
  }

  function hasAnimationClasses(options, and) {
    options = options || {};
    var a = (options.addClass || '').length > 0;
    var b = (options.removeClass || '').length > 0;
    return and ? a && b : a || b;
  }

  rules.join.push(function(element, newAnimation, currentAnimation) {
    // if the new animation is class-based then we can just tack that on
    return !newAnimation.structural && hasAnimationClasses(newAnimation.options);
  });

  rules.skip.push(function(element, newAnimation, currentAnimation) {
    // there is no need to animate anything if no classes are being added and
    // there is no structural animation that will be triggered
    return !newAnimation.structural && !hasAnimationClasses(newAnimation.options);
  });

  rules.skip.push(function(element, newAnimation, currentAnimation) {
    // why should we trigger a new structural animation if the element will
    // be removed from the DOM anyway?
    return currentAnimation.event == 'leave' && newAnimation.structural;
  });

  rules.skip.push(function(element, newAnimation, currentAnimation) {
    // if there is a current animation then skip the class-based animation
    return currentAnimation.structural && !newAnimation.structural;
  });

  rules.cancel.push(function(element, newAnimation, currentAnimation) {
    // there can never be two structural animations running at the same time
    return currentAnimation.structural && newAnimation.structural;
  });

  rules.cancel.push(function(element, newAnimation, currentAnimation) {
    // if the previous animation is already running, but the new animation will
    // be triggered, but the new animation is structural
    return currentAnimation.state === RUNNING_STATE && newAnimation.structural;
  });

  rules.cancel.push(function(element, newAnimation, currentAnimation) {
    var nO = newAnimation.options;
    var cO = currentAnimation.options;

    // if the exact same CSS class is added/removed then it's safe to cancel it
    return (nO.addClass && nO.addClass === cO.removeClass) || (nO.removeClass && nO.removeClass === cO.addClass);
  });

  this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap',
               '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite',
       function($$rAF,   $rootScope,   $rootElement,   $document,   $$HashMap,
                $$animation,   $$AnimateRunner,   $templateRequest,   $$jqLite) {

    var activeAnimationsLookup = new $$HashMap();
    var disabledElementsLookup = new $$HashMap();

    var animationsEnabled = null;

    // Wait until all directive and route-related templates are downloaded and
    // compiled. The $templateRequest.totalPendingRequests variable keeps track of
    // all of the remote templates being currently downloaded. If there are no
    // templates currently downloading then the watcher will still fire anyway.
    var deregisterWatch = $rootScope.$watch(
      function() { return $templateRequest.totalPendingRequests === 0; },
      function(isEmpty) {
        if (!isEmpty) return;
        deregisterWatch();

        // Now that all templates have been downloaded, $animate will wait until
        // the post digest queue is empty before enabling animations. By having two
        // calls to $postDigest calls we can ensure that the flag is enabled at the
        // very end of the post digest queue. Since all of the animations in $animate
        // use $postDigest, it's important that the code below executes at the end.
        // This basically means that the page is fully downloaded and compiled before
        // any animations are triggered.
        $rootScope.$$postDigest(function() {
          $rootScope.$$postDigest(function() {
            // we check for null directly in the event that the application already called
            // .enabled() with whatever arguments that it provided it with
            if (animationsEnabled === null) {
              animationsEnabled = true;
            }
          });
        });
      }
    );

    var bodyElement = jqLite($document[0].body);

    var callbackRegistry = {};

    // remember that the classNameFilter is set during the provider/config
    // stage therefore we can optimize here and setup a helper function
    var classNameFilter = $animateProvider.classNameFilter();
    var isAnimatableClassName = !classNameFilter
              ? function() { return true; }
              : function(className) {
                return classNameFilter.test(className);
              };

    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);

    function normalizeAnimationOptions(element, options) {
      return mergeAnimationOptions(element, options, {});
    }

    function findCallbacks(element, event) {
      var targetNode = getDomNode(element);

      var matches = [];
      var entries = callbackRegistry[event];
      if (entries) {
        forEach(entries, function(entry) {
          if (entry.node.contains(targetNode)) {
            matches.push(entry.callback);
          }
        });
      }

      return matches;
    }

    function triggerCallback(event, element, phase, data) {
      $$rAF(function() {
        forEach(findCallbacks(element, event), function(callback) {
          callback(element, phase, data);
        });
      });
    }

    return {
      on: function(event, container, callback) {
        var node = extractElementNode(container);
        callbackRegistry[event] = callbackRegistry[event] || [];
        callbackRegistry[event].push({
          node: node,
          callback: callback
        });
      },

      off: function(event, container, callback) {
        var entries = callbackRegistry[event];
        if (!entries) return;

        callbackRegistry[event] = arguments.length === 1
            ? null
            : filterFromRegistry(entries, container, callback);

        function filterFromRegistry(list, matchContainer, matchCallback) {
          var containerNode = extractElementNode(matchContainer);
          return list.filter(function(entry) {
            var isMatch = entry.node === containerNode &&
                            (!matchCallback || entry.callback === matchCallback);
            return !isMatch;
          });
        }
      },

      pin: function(element, parentElement) {
        assertArg(isElement(element), 'element', 'not an element');
        assertArg(isElement(parentElement), 'parentElement', 'not an element');
        element.data(NG_ANIMATE_PIN_DATA, parentElement);
      },

      push: function(element, event, options, domOperation) {
        options = options || {};
        options.domOperation = domOperation;
        return queueAnimation(element, event, options);
      },

      // this method has four signatures:
      //  () - global getter
      //  (bool) - global setter
      //  (element) - element getter
      //  (element, bool) - element setter<F37>
      enabled: function(element, bool) {
        var argCount = arguments.length;

        if (argCount === 0) {
          // () - Global getter
          bool = !!animationsEnabled;
        } else {
          var hasElement = isElement(element);

          if (!hasElement) {
            // (bool) - Global setter
            bool = animationsEnabled = !!element;
          } else {
            var node = getDomNode(element);
            var recordExists = disabledElementsLookup.get(node);

            if (argCount === 1) {
              // (element) - Element getter
              bool = !recordExists;
            } else {
              // (element, bool) - Element setter
              bool = !!bool;
              if (!bool) {
                disabledElementsLookup.put(node, true);
              } else if (recordExists) {
                disabledElementsLookup.remove(node);
              }
            }
          }
        }

        return bool;
      }
    };

    function queueAnimation(element, event, options) {
      var node, parent;
      element = stripCommentsFromElement(element);
      if (element) {
        node = getDomNode(element);
        parent = element.parent();
      }

      options = prepareAnimationOptions(options);

      // we create a fake runner with a working promise.
      // These methods will become available after the digest has passed
      var runner = new $$AnimateRunner();

      // there are situations where a directive issues an animation for
      // a jqLite wrapper that contains only comment nodes... If this
      // happens then there is no way we can perform an animation
      if (!node) {
        close();
        return runner;
      }

      if (isArray(options.addClass)) {
        options.addClass = options.addClass.join(' ');
      }

      if (isArray(options.removeClass)) {
        options.removeClass = options.removeClass.join(' ');
      }

      if (options.from && !isObject(options.from)) {
        options.from = null;
      }

      if (options.to && !isObject(options.to)) {
        options.to = null;
      }

      var className = [node.className, options.addClass, options.removeClass].join(' ');
      if (!isAnimatableClassName(className)) {
        close();
        return runner;
      }

      var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;

      // this is a hard disable of all animations for the application or on
      // the element itself, therefore  there is no need to continue further
      // past this point if not enabled
      var skipAnimations = !animationsEnabled || disabledElementsLookup.get(node);
      var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {};
      var hasExistingAnimation = !!existingAnimation.state;

      // there is no point in traversing the same collection of parent ancestors if a followup
      // animation will be run on the same element that already did all that checking work
      if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state != PRE_DIGEST_STATE)) {
        skipAnimations = !areAnimationsAllowed(element, parent, event);
      }

      if (skipAnimations) {
        close();
        return runner;
      }

      if (isStructural) {
        closeChildAnimations(element);
      }

      var newAnimation = {
        structural: isStructural,
        element: element,
        event: event,
        close: close,
        options: options,
        runner: runner
      };

      if (hasExistingAnimation) {
        var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation);
        if (skipAnimationFlag) {
          if (existingAnimation.state === RUNNING_STATE) {
            close();
            return runner;
          } else {
            mergeAnimationOptions(element, existingAnimation.options, options);
            return existingAnimation.runner;
          }
        }

        var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation);
        if (cancelAnimationFlag) {
          if (existingAnimation.state === RUNNING_STATE) {
            // this will end the animation right away and it is safe
            // to do so since the animation is already running and the
            // runner callback code will run in async
            existingAnimation.runner.end();
          } else if (existingAnimation.structural) {
            // this means that the animation is queued into a digest, but
            // hasn't started yet. Therefore it is safe to run the close
            // method which will call the runner methods in async.
            existingAnimation.close();
          } else {
            // this will merge the existing animation options into this new follow-up animation
            mergeAnimationOptions(element, newAnimation.options, existingAnimation.options);
          }
        } else {
          // a joined animation means that this animation will take over the existing one
          // so an example would involve a leave animation taking over an enter. Then when
          // the postDigest kicks in the enter will be ignored.
          var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation);
          if (joinAnimationFlag) {
            if (existingAnimation.state === RUNNING_STATE) {
              normalizeAnimationOptions(element, options);
            } else {
              event = newAnimation.event = existingAnimation.event;
              options = mergeAnimationOptions(element, existingAnimation.options, newAnimation.options);
              return runner;
            }
          }
        }
      } else {
        // normalization in this case means that it removes redundant CSS classes that
        // already exist (addClass) or do not exist (removeClass) on the element
        normalizeAnimationOptions(element, options);
      }

      // when the options are merged and cleaned up we may end up not having to do
      // an animation at all, therefore we should check this before issuing a post
      // digest callback. Structural animations will always run no matter what.
      var isValidAnimation = newAnimation.structural;
      if (!isValidAnimation) {
        // animate (from/to) can be quickly checked first, otherwise we check if any classes are present
        isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0)
                            || hasAnimationClasses(newAnimation.options);
      }

      if (!isValidAnimation) {
        close();
        clearElementAnimationState(element);
        return runner;
      }

      if (isStructural) {
        closeParentClassBasedAnimations(parent);
      }

      // the counter keeps track of cancelled animations
      var counter = (existingAnimation.counter || 0) + 1;
      newAnimation.counter = counter;

      markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation);

      $rootScope.$$postDigest(function() {
        var animationDetails = activeAnimationsLookup.get(node);
        var animationCancelled = !animationDetails;
        animationDetails = animationDetails || {};

        // if addClass/removeClass is called before something like enter then the
        // registered parent element may not be present. The code below will ensure
        // that a final value for parent element is obtained
        var parentElement = element.parent() || [];

        // animate/structural/class-based animations all have requirements. Otherwise there
        // is no point in performing an animation. The parent node must also be set.
        var isValidAnimation = parentElement.length > 0
                                && (animationDetails.event === 'animate'
                                    || animationDetails.structural
                                    || hasAnimationClasses(animationDetails.options));

        // this means that the previous animation was cancelled
        // even if the follow-up animation is the same event
        if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) {
          // if another animation did not take over then we need
          // to make sure that the domOperation and options are
          // handled accordingly
          if (animationCancelled) {
            applyAnimationClasses(element, options);
            applyAnimationStyles(element, options);
          }

          // if the event changed from something like enter to leave then we do
          // it, otherwise if it's the same then the end result will be the same too
          if (animationCancelled || (isStructural && animationDetails.event !== event)) {
            options.domOperation();
            runner.end();
          }

          // in the event that the element animation was not cancelled or a follow-up animation
          // isn't allowed to animate from here then we need to clear the state of the element
          // so that any future animations won't read the expired animation data.
          if (!isValidAnimation) {
            clearElementAnimationState(element);
          }

          return;
        }

        // this combined multiple class to addClass / removeClass into a setClass event
        // so long as a structural event did not take over the animation
        event = !animationDetails.structural && hasAnimationClasses(animationDetails.options, true)
            ? 'setClass'
            : animationDetails.event;

        if (animationDetails.structural) {
          closeParentClassBasedAnimations(parentElement);
        }

        markElementAnimationState(element, RUNNING_STATE);
        var realRunner = $$animation(element, event, animationDetails.options);
        realRunner.done(function(status) {
          close(!status);
          var animationDetails = activeAnimationsLookup.get(node);
          if (animationDetails && animationDetails.counter === counter) {
            clearElementAnimationState(getDomNode(element));
          }
          notifyProgress(runner, event, 'close', {});
        });

        // this will update the runner's flow-control events based on
        // the `realRunner` object.
        runner.setHost(realRunner);
        notifyProgress(runner, event, 'start', {});
      });

      return runner;

      function notifyProgress(runner, event, phase, data) {
        triggerCallback(event, element, phase, data);
        runner.progress(event, phase, data);
      }

      function close(reject) { // jshint ignore:line
        applyAnimationClasses(element, options);
        applyAnimationStyles(element, options);
        options.domOperation();
        runner.complete(!reject);
      }
    }

    function closeChildAnimations(element) {
      var node = getDomNode(element);
      var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']');
      forEach(children, function(child) {
        var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME));
        var animationDetails = activeAnimationsLookup.get(child);
        switch (state) {
          case RUNNING_STATE:
            animationDetails.runner.end();
            /* falls through */
          case PRE_DIGEST_STATE:
            if (animationDetails) {
              activeAnimationsLookup.remove(child);
            }
            break;
        }
      });
    }

    function clearElementAnimationState(element) {
      var node = getDomNode(element);
      node.removeAttribute(NG_ANIMATE_ATTR_NAME);
      activeAnimationsLookup.remove(node);
    }

    function isMatchingElement(nodeOrElmA, nodeOrElmB) {
      return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB);
    }

    function closeParentClassBasedAnimations(startingElement) {
      var parentNode = getDomNode(startingElement);
      do {
        if (!parentNode || parentNode.nodeType !== ELEMENT_NODE) break;

        var animationDetails = activeAnimationsLookup.get(parentNode);
        if (animationDetails) {
          examineParentAnimation(parentNode, animationDetails);
        }

        parentNode = parentNode.parentNode;
      } while (true);

      // since animations are detected from CSS classes, we need to flush all parent
      // class-based animations so that the parent classes are all present for child
      // animations to properly function (otherwise any CSS selectors may not work)
      function examineParentAnimation(node, animationDetails) {
        // enter/leave/move always have priority
        if (animationDetails.structural || !hasAnimationClasses(animationDetails.options)) return;

        if (animationDetails.state === RUNNING_STATE) {
          animationDetails.runner.end();
        }
        clearElementAnimationState(node);
      }
    }

    function areAnimationsAllowed(element, parentElement, event) {
      var bodyElementDetected = false;
      var rootElementDetected = false;
      var parentAnimationDetected = false;
      var animateChildren;

      var parentHost = element.data(NG_ANIMATE_PIN_DATA);
      if (parentHost) {
        parentElement = parentHost;
      }

      while (parentElement && parentElement.length) {
        if (!rootElementDetected) {
          // angular doesn't want to attempt to animate elements outside of the application
          // therefore we need to ensure that the rootElement is an ancestor of the current element
          rootElementDetected = isMatchingElement(parentElement, $rootElement);
        }

        var parentNode = parentElement[0];
        if (parentNode.nodeType !== ELEMENT_NODE) {
          // no point in inspecting the #document element
          break;
        }

        var details = activeAnimationsLookup.get(parentNode) || {};
        // either an enter, leave or move animation will commence
        // therefore we can't allow any animations to take place
        // but if a parent animation is class-based then that's ok
        if (!parentAnimationDetected) {
          parentAnimationDetected = details.structural || disabledElementsLookup.get(parentNode);
        }

        if (isUndefined(animateChildren) || animateChildren === true) {
          var value = parentElement.data(NG_ANIMATE_CHILDREN_DATA);
          if (isDefined(value)) {
            animateChildren = value;
          }
        }

        // there is no need to continue traversing at this point
        if (parentAnimationDetected && animateChildren === false) break;

        if (!rootElementDetected) {
          // angular doesn't want to attempt to animate elements outside of the application
          // therefore we need to ensure that the rootElement is an ancestor of the current element
          rootElementDetected = isMatchingElement(parentElement, $rootElement);
          if (!rootElementDetected) {
            parentHost = parentElement.data(NG_ANIMATE_PIN_DATA);
            if (parentHost) {
              parentElement = parentHost;
            }
          }
        }

        if (!bodyElementDetected) {
          // we also need to ensure that the element is or will be apart of the body element
          // otherwise it is pointless to even issue an animation to be rendered
          bodyElementDetected = isMatchingElement(parentElement, bodyElement);
        }

        parentElement = parentElement.parent();
      }

      var allowAnimation = !parentAnimationDetected || animateChildren;
      return allowAnimation && rootElementDetected && bodyElementDetected;
    }

    function markElementAnimationState(element, state, details) {
      details = details || {};
      details.state = state;

      var node = getDomNode(element);
      node.setAttribute(NG_ANIMATE_ATTR_NAME, state);

      var oldValue = activeAnimationsLookup.get(node);
      var newValue = oldValue
          ? extend(oldValue, details)
          : details;
      activeAnimationsLookup.put(node, newValue);
    }
  }];
}];

var $$rAFMutexFactory = ['$$rAF', function($$rAF) {
  return function() {
    var passed = false;
    $$rAF(function() {
      passed = true;
    });
    return function(fn) {
      passed ? fn() : $$rAF(fn);
    };
  };
}];

var $$AnimateRunnerFactory = ['$q', '$$rAFMutex', function($q, $$rAFMutex) {
  var INITIAL_STATE = 0;
  var DONE_PENDING_STATE = 1;
  var DONE_COMPLETE_STATE = 2;

  AnimateRunner.chain = function(chain, callback) {
    var index = 0;

    next();
    function next() {
      if (index === chain.length) {
        callback(true);
        return;
      }

      chain[index](function(response) {
        if (response === false) {
          callback(false);
          return;
        }
        index++;
        next();
      });
    }
  };

  AnimateRunner.all = function(runners, callback) {
    var count = 0;
    var status = true;
    forEach(runners, function(runner) {
      runner.done(onProgress);
    });

    function onProgress(response) {
      status = status && response;
      if (++count === runners.length) {
        callback(status);
      }
    }
  };

  function AnimateRunner(host) {
    this.setHost(host);

    this._doneCallbacks = [];
    this._runInAnimationFrame = $$rAFMutex();
    this._state = 0;
  }

  AnimateRunner.prototype = {
    setHost: function(host) {
      this.host = host || {};
    },

    done: function(fn) {
      if (this._state === DONE_COMPLETE_STATE) {
        fn();
      } else {
        this._doneCallbacks.push(fn);
      }
    },

    progress: noop,

    getPromise: function() {
      if (!this.promise) {
        var self = this;
        this.promise = $q(function(resolve, reject) {
          self.done(function(status) {
            status === false ? reject() : resolve();
          });
        });
      }
      return this.promise;
    },

    then: function(resolveHandler, rejectHandler) {
      return this.getPromise().then(resolveHandler, rejectHandler);
    },

    'catch': function(handler) {
      return this.getPromise()['catch'](handler);
    },

    'finally': function(handler) {
      return this.getPromise()['finally'](handler);
    },

    pause: function() {
      if (this.host.pause) {
        this.host.pause();
      }
    },

    resume: function() {
      if (this.host.resume) {
        this.host.resume();
      }
    },

    end: function() {
      if (this.host.end) {
        this.host.end();
      }
      this._resolve(true);
    },

    cancel: function() {
      if (this.host.cancel) {
        this.host.cancel();
      }
      this._resolve(false);
    },

    complete: function(response) {
      var self = this;
      if (self._state === INITIAL_STATE) {
        self._state = DONE_PENDING_STATE;
        self._runInAnimationFrame(function() {
          self._resolve(response);
        });
      }
    },

    _resolve: function(response) {
      if (this._state !== DONE_COMPLETE_STATE) {
        forEach(this._doneCallbacks, function(fn) {
          fn(response);
        });
        this._doneCallbacks.length = 0;
        this._state = DONE_COMPLETE_STATE;
      }
    }
  };

  return AnimateRunner;
}];

var $$AnimationProvider = ['$animateProvider', function($animateProvider) {
  var NG_ANIMATE_REF_ATTR = 'ng-animate-ref';

  var drivers = this.drivers = [];

  var RUNNER_STORAGE_KEY = '$$animationRunner';

  function setRunner(element, runner) {
    element.data(RUNNER_STORAGE_KEY, runner);
  }

  function removeRunner(element) {
    element.removeData(RUNNER_STORAGE_KEY);
  }

  function getRunner(element) {
    return element.data(RUNNER_STORAGE_KEY);
  }

  this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$rAFScheduler',
       function($$jqLite,   $rootScope,   $injector,   $$AnimateRunner,   $$rAFScheduler) {

    var animationQueue = [];
    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);

    var totalPendingClassBasedAnimations = 0;
    var totalActiveClassBasedAnimations = 0;
    var classBasedAnimationsQueue = [];

    // TODO(matsko): document the signature in a better way
    return function(element, event, options) {
      options = prepareAnimationOptions(options);
      var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;

      // there is no animation at the current moment, however
      // these runner methods will get later updated with the
      // methods leading into the driver's end/cancel methods
      // for now they just stop the animation from starting
      var runner = new $$AnimateRunner({
        end: function() { close(); },
        cancel: function() { close(true); }
      });

      if (!drivers.length) {
        close();
        return runner;
      }

      setRunner(element, runner);

      var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass));
      var tempClasses = options.tempClasses;
      if (tempClasses) {
        classes += ' ' + tempClasses;
        options.tempClasses = null;
      }

      var classBasedIndex;
      if (!isStructural) {
        classBasedIndex = totalPendingClassBasedAnimations;
        totalPendingClassBasedAnimations += 1;
      }

      animationQueue.push({
        // this data is used by the postDigest code and passed into
        // the driver step function
        element: element,
        classes: classes,
        event: event,
        classBasedIndex: classBasedIndex,
        structural: isStructural,
        options: options,
        beforeStart: beforeStart,
        close: close
      });

      element.on('$destroy', handleDestroyedElement);

      // we only want there to be one function called within the post digest
      // block. This way we can group animations for all the animations that
      // were apart of the same postDigest flush call.
      if (animationQueue.length > 1) return runner;

      $rootScope.$$postDigest(function() {
        totalActiveClassBasedAnimations = totalPendingClassBasedAnimations;
        totalPendingClassBasedAnimations = 0;
        classBasedAnimationsQueue.length = 0;

        var animations = [];
        forEach(animationQueue, function(entry) {
          // the element was destroyed early on which removed the runner
          // form its storage. This means we can't animate this element
          // at all and it already has been closed due to destruction.
          if (getRunner(entry.element)) {
            animations.push(entry);
          }
        });

        // now any future animations will be in another postDigest
        animationQueue.length = 0;

        forEach(groupAnimations(animations), function(animationEntry) {
          if (animationEntry.structural) {
            triggerAnimationStart();
          } else {
            classBasedAnimationsQueue.push({
              node: getDomNode(animationEntry.element),
              fn: triggerAnimationStart
            });

            if (animationEntry.classBasedIndex === totalActiveClassBasedAnimations - 1) {
              // we need to sort each of the animations in order of parent to child
              // relationships. This ensures that the child classes are applied at the
              // right time.
              classBasedAnimationsQueue = classBasedAnimationsQueue.sort(function(a,b) {
                return b.node.contains(a.node);
              }).map(function(entry) {
                return entry.fn;
              });

              $$rAFScheduler(classBasedAnimationsQueue);
            }
          }

          function triggerAnimationStart() {
            // it's important that we apply the `ng-animate` CSS class and the
            // temporary classes before we do any driver invoking since these
            // CSS classes may be required for proper CSS detection.
            animationEntry.beforeStart();

            var startAnimationFn, closeFn = animationEntry.close;

            // in the event that the element was removed before the digest runs or
            // during the RAF sequencing then we should not trigger the animation.
            var targetElement = animationEntry.anchors
                ? (animationEntry.from.element || animationEntry.to.element)
                : animationEntry.element;

            if (getRunner(targetElement) && getDomNode(targetElement).parentNode) {
              var operation = invokeFirstDriver(animationEntry);
              if (operation) {
                startAnimationFn = operation.start;
              }
            }

            if (!startAnimationFn) {
              closeFn();
            } else {
              var animationRunner = startAnimationFn();
              animationRunner.done(function(status) {
                closeFn(!status);
              });
              updateAnimationRunners(animationEntry, animationRunner);
            }
          }
        });
      });

      return runner;

      // TODO(matsko): change to reference nodes
      function getAnchorNodes(node) {
        var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']';
        var items = node.hasAttribute(NG_ANIMATE_REF_ATTR)
              ? [node]
              : node.querySelectorAll(SELECTOR);
        var anchors = [];
        forEach(items, function(node) {
          var attr = node.getAttribute(NG_ANIMATE_REF_ATTR);
          if (attr && attr.length) {
            anchors.push(node);
          }
        });
        return anchors;
      }

      function groupAnimations(animations) {
        var preparedAnimations = [];
        var refLookup = {};
        forEach(animations, function(animation, index) {
          var element = animation.element;
          var node = getDomNode(element);
          var event = animation.event;
          var enterOrMove = ['enter', 'move'].indexOf(event) >= 0;
          var anchorNodes = animation.structural ? getAnchorNodes(node) : [];

          if (anchorNodes.length) {
            var direction = enterOrMove ? 'to' : 'from';

            forEach(anchorNodes, function(anchor) {
              var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR);
              refLookup[key] = refLookup[key] || {};
              refLookup[key][direction] = {
                animationID: index,
                element: jqLite(anchor)
              };
            });
          } else {
            preparedAnimations.push(animation);
          }
        });

        var usedIndicesLookup = {};
        var anchorGroups = {};
        forEach(refLookup, function(operations, key) {
          var from = operations.from;
          var to = operations.to;

          if (!from || !to) {
            // only one of these is set therefore we can't have an
            // anchor animation since all three pieces are required
            var index = from ? from.animationID : to.animationID;
            var indexKey = index.toString();
            if (!usedIndicesLookup[indexKey]) {
              usedIndicesLookup[indexKey] = true;
              preparedAnimations.push(animations[index]);
            }
            return;
          }

          var fromAnimation = animations[from.animationID];
          var toAnimation = animations[to.animationID];
          var lookupKey = from.animationID.toString();
          if (!anchorGroups[lookupKey]) {
            var group = anchorGroups[lookupKey] = {
              structural: true,
              beforeStart: function() {
                fromAnimation.beforeStart();
                toAnimation.beforeStart();
              },
              close: function() {
                fromAnimation.close();
                toAnimation.close();
              },
              classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes),
              from: fromAnimation,
              to: toAnimation,
              anchors: [] // TODO(matsko): change to reference nodes
            };

            // the anchor animations require that the from and to elements both have at least
            // one shared CSS class which effictively marries the two elements together to use
            // the same animation driver and to properly sequence the anchor animation.
            if (group.classes.length) {
              preparedAnimations.push(group);
            } else {
              preparedAnimations.push(fromAnimation);
              preparedAnimations.push(toAnimation);
            }
          }

          anchorGroups[lookupKey].anchors.push({
            'out': from.element, 'in': to.element
          });
        });

        return preparedAnimations;
      }

      function cssClassesIntersection(a,b) {
        a = a.split(' ');
        b = b.split(' ');
        var matches = [];

        for (var i = 0; i < a.length; i++) {
          var aa = a[i];
          if (aa.substring(0,3) === 'ng-') continue;

          for (var j = 0; j < b.length; j++) {
            if (aa === b[j]) {
              matches.push(aa);
              break;
            }
          }
        }

        return matches.join(' ');
      }

      function invokeFirstDriver(animationDetails) {
        // we loop in reverse order since the more general drivers (like CSS and JS)
        // may attempt more elements, but custom drivers are more particular
        for (var i = drivers.length - 1; i >= 0; i--) {
          var driverName = drivers[i];
          if (!$injector.has(driverName)) continue; // TODO(matsko): remove this check

          var factory = $injector.get(driverName);
          var driver = factory(animationDetails);
          if (driver) {
            return driver;
          }
        }
      }

      function beforeStart() {
        element.addClass(NG_ANIMATE_CLASSNAME);
        if (tempClasses) {
          $$jqLite.addClass(element, tempClasses);
        }
      }

      function updateAnimationRunners(animation, newRunner) {
        if (animation.from && animation.to) {
          update(animation.from.element);
          update(animation.to.element);
        } else {
          update(animation.element);
        }

        function update(element) {
          getRunner(element).setHost(newRunner);
        }
      }

      function handleDestroyedElement() {
        var runner = getRunner(element);
        if (runner && (event !== 'leave' || !options.$$domOperationFired)) {
          runner.end();
        }
      }

      function close(rejected) { // jshint ignore:line
        element.off('$destroy', handleDestroyedElement);
        removeRunner(element);

        applyAnimationClasses(element, options);
        applyAnimationStyles(element, options);
        options.domOperation();

        if (tempClasses) {
          $$jqLite.removeClass(element, tempClasses);
        }

        element.removeClass(NG_ANIMATE_CLASSNAME);
        runner.complete(!rejected);
      }
    };
  }];
}];

/* global angularAnimateModule: true,

   $$rAFMutexFactory,
   $$rAFSchedulerFactory,
   $$AnimateChildrenDirective,
   $$AnimateRunnerFactory,
   $$AnimateQueueProvider,
   $$AnimationProvider,
   $AnimateCssProvider,
   $$AnimateCssDriverProvider,
   $$AnimateJsProvider,
   $$AnimateJsDriverProvider,
*/

/**
 * @ngdoc module
 * @name ngAnimate
 * @description
 *
 * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via
 * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` then the animation hooks are enabled for an Angular app.
 *
 * <div doc-module-components="ngAnimate"></div>
 *
 * # Usage
 * Simply put, there are two ways to make use of animations when ngAnimate is used: by using **CSS** and **JavaScript**. The former works purely based
 * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For
 * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within
 * the HTML element that the animation will be triggered on.
 *
 * ## Directive Support
 * The following directives are "animation aware":
 *
 * | Directive                                                                                                | Supported Animations                                                     |
 * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|
 * | {@link ng.directive:ngRepeat#animations ngRepeat}                                                        | enter, leave and move                                                    |
 * | {@link ngRoute.directive:ngView#animations ngView}                                                       | enter and leave                                                          |
 * | {@link ng.directive:ngInclude#animations ngInclude}                                                      | enter and leave                                                          |
 * | {@link ng.directive:ngSwitch#animations ngSwitch}                                                        | enter and leave                                                          |
 * | {@link ng.directive:ngIf#animations ngIf}                                                                | enter and leave                                                          |
 * | {@link ng.directive:ngClass#animations ngClass}                                                          | add and remove (the CSS class(es) present)                               |
 * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide}            | add and remove (the ng-hide class value)                                 |
 * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel}    | add and remove (dirty, pristine, valid, invalid & all other validations) |
 * | {@link module:ngMessages#animations ngMessages}                                                          | add and remove (ng-active & ng-inactive)                                 |
 * | {@link module:ngMessages#animations ngMessage}                                                           | enter and leave                                                          |
 *
 * (More information can be found by visiting each the documentation associated with each directive.)
 *
 * ## CSS-based Animations
 *
 * CSS-based animations with ngAnimate are unique since they require no JavaScript code at all. By using a CSS class that we reference between our HTML
 * and CSS code we can create an animation that will be picked up by Angular when an the underlying directive performs an operation.
 *
 * The example below shows how an `enter` animation can be made possible on a element using `ng-if`:
 *
 * ```html
 * <div ng-if="bool" class="fade">
 *    Fade me in out
 * </div>
 * <button ng-click="bool=true">Fade In!</button>
 * <button ng-click="bool=false">Fade Out!</button>
 * ```
 *
 * Notice the CSS class **fade**? We can now create the CSS transition code that references this class:
 *
 * ```css
 * /&#42; The starting CSS styles for the enter animation &#42;/
 * .fade.ng-enter {
 *   transition:0.5s linear all;
 *   opacity:0;
 * }
 *
 * /&#42; The finishing CSS styles for the enter animation &#42;/
 * .fade.ng-enter.ng-enter-active {
 *   opacity:1;
 * }
 * ```
 *
 * The key thing to remember here is that, depending on the animation event (which each of the directives above trigger depending on what's going on) two
 * generated CSS classes will be applied to the element; in the example above we have `.ng-enter` and `.ng-enter-active`. For CSS transitions, the transition
 * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards.
 *
 * If for example we wanted to create animations for `leave` and `move` (ngRepeat triggers move) then we can do so using the same CSS naming conventions:
 *
 * ```css
 * /&#42; now the element will fade out before it is removed from the DOM &#42;/
 * .fade.ng-leave {
 *   transition:0.5s linear all;
 *   opacity:1;
 * }
 * .fade.ng-leave.ng-leave-active {
 *   opacity:0;
 * }
 * ```
 *
 * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class:
 *
 * ```css
 * /&#42; there is no need to define anything inside of the destination
 * CSS class since the keyframe will take charge of the animation &#42;/
 * .fade.ng-leave {
 *   animation: my_fade_animation 0.5s linear;
 *   -webkit-animation: my_fade_animation 0.5s linear;
 * }
 *
 * @keyframes my_fade_animation {
 *   from { opacity:1; }
 *   to { opacity:0; }
 * }
 *
 * @-webkit-keyframes my_fade_animation {
 *   from { opacity:1; }
 *   to { opacity:0; }
 * }
 * ```
 *
 * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element.
 *
 * ### CSS Class-based Animations
 *
 * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different
 * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added
 * and removed.
 *
 * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class:
 *
 * ```html
 * <div ng-show="bool" class="fade">
 *   Show and hide me
 * </div>
 * <button ng-click="bool=true">Toggle</button>
 *
 * <style>
 * .fade.ng-hide {
 *   transition:0.5s linear all;
 *   opacity:0;
 * }
 * </style>
 * ```
 *
 * All that is going on here with ngShow/ngHide behind the scenes is the `.ng-hide` class is added/removed (when the hidden state is valid). Since
 * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest.
 *
 * In addition the addition and removal of the CSS class, ngAnimate also provides two helper methods that we can use to further decorate the animation
 * with CSS styles.
 *
 * ```html
 * <div ng-class="{on:onOff}" class="highlight">
 *   Highlight this box
 * </div>
 * <button ng-click="onOff=!onOff">Toggle</button>
 *
 * <style>
 * .highlight {
 *   transition:0.5s linear all;
 * }
 * .highlight.on-add {
 *   background:white;
 * }
 * .highlight.on {
 *   background:yellow;
 * }
 * .highlight.on-remove {
 *   background:black;
 * }
 * </style>
 * ```
 *
 * We can also make use of CSS keyframes by placing them within the CSS classes.
 *
 *
 * ### CSS Staggering Animations
 * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a
 * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be
 * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for
 * the animation. The style property expected within the stagger class can either be a **transition-delay** or an
 * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).
 *
 * ```css
 * .my-animation.ng-enter {
 *   /&#42; standard transition code &#42;/
 *   transition: 1s linear all;
 *   opacity:0;
 * }
 * .my-animation.ng-enter-stagger {
 *   /&#42; this will have a 100ms delay between each successive leave animation &#42;/
 *   transition-delay: 0.1s;
 *
 *   /&#42; in case the stagger doesn't work then the duration value
 *    must be set to 0 to avoid an accidental CSS inheritance &#42;/
 *   transition-duration: 0s;
 * }
 * .my-animation.ng-enter.ng-enter-active {
 *   /&#42; standard transition styles &#42;/
 *   opacity:1;
 * }
 * ```
 *
 * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations
 * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this
 * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation
 * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired.
 *
 * The following code will issue the **ng-leave-stagger** event on the element provided:
 *
 * ```js
 * var kids = parent.children();
 *
 * $animate.leave(kids[0]); //stagger index=0
 * $animate.leave(kids[1]); //stagger index=1
 * $animate.leave(kids[2]); //stagger index=2
 * $animate.leave(kids[3]); //stagger index=3
 * $animate.leave(kids[4]); //stagger index=4
 *
 * window.requestAnimationFrame(function() {
 *   //stagger has reset itself
 *   $animate.leave(kids[5]); //stagger index=0
 *   $animate.leave(kids[6]); //stagger index=1
 *
 *   $scope.$digest();
 * });
 * ```
 *
 * Stagger animations are currently only supported within CSS-defined animations.
 *
 * ### The `ng-animate` CSS class
 *
 * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation.
 * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations).
 *
 * Therefore, animations can be applied to an element using this temporary class directly via CSS.
 *
 * ```css
 * .zipper.ng-animate {
 *   transition:0.5s linear all;
 * }
 * .zipper.ng-enter {
 *   opacity:0;
 * }
 * .zipper.ng-enter.ng-enter-active {
 *   opacity:1;
 * }
 * .zipper.ng-leave {
 *   opacity:1;
 * }
 * .zipper.ng-leave.ng-leave-active {
 *   opacity:0;
 * }
 * ```
 *
 * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove
 * the CSS class once an animation has completed.)
 *
 *
 * ## JavaScript-based Animations
 *
 * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared
 * CSS class that is referenced in our HTML code) but in addition we need to register the JavaScript animation on the module. By making use of the
 * `module.animation()` module function we can register the ainmation.
 *
 * Let's see an example of a enter/leave animation using `ngRepeat`:
 *
 * ```html
 * <div ng-repeat="item in items" class="slide">
 *   {{ item }}
 * </div>
 * ```
 *
 * See the **slide** CSS class? Let's use that class to define an animation that we'll structure in our module code by using `module.animation`:
 *
 * ```js
 * myModule.animation('.slide', [function() {
 *   return {
 *     // make note that other events (like addClass/removeClass)
 *     // have different function input parameters
 *     enter: function(element, doneFn) {
 *       jQuery(element).fadeIn(1000, doneFn);
 *
 *       // remember to call doneFn so that angular
 *       // knows that the animation has concluded
 *     },
 *
 *     move: function(element, doneFn) {
 *       jQuery(element).fadeIn(1000, doneFn);
 *     },
 *
 *     leave: function(element, doneFn) {
 *       jQuery(element).fadeOut(1000, doneFn);
 *     }
 *   }
 * }]
 * ```
 *
 * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as
 * greensock.js and velocity.js.
 *
 * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define
 * our animations inside of the same registered animation, however, the function input arguments are a bit different:
 *
 * ```html
 * <div ng-class="color" class="colorful">
 *   this box is moody
 * </div>
 * <button ng-click="color='red'">Change to red</button>
 * <button ng-click="color='blue'">Change to blue</button>
 * <button ng-click="color='green'">Change to green</button>
 * ```
 *
 * ```js
 * myModule.animation('.colorful', [function() {
 *   return {
 *     addClass: function(element, className, doneFn) {
 *       // do some cool animation and call the doneFn
 *     },
 *     removeClass: function(element, className, doneFn) {
 *       // do some cool animation and call the doneFn
 *     },
 *     setClass: function(element, addedClass, removedClass, doneFn) {
 *       // do some cool animation and call the doneFn
 *     }
 *   }
 * }]
 * ```
 *
 * ## CSS + JS Animations Together
 *
 * AngularJS 1.4 and higher has taken steps to make the amalgamation of CSS and JS animations more flexible. However, unlike earlier versions of Angular,
 * defining CSS and JS animations to work off of the same CSS class will not work anymore. Therefore the example below will only result in **JS animations taking
 * charge of the animation**:
 *
 * ```html
 * <div ng-if="bool" class="slide">
 *   Slide in and out
 * </div>
 * ```
 *
 * ```js
 * myModule.animation('.slide', [function() {
 *   return {
 *     enter: function(element, doneFn) {
 *       jQuery(element).slideIn(1000, doneFn);
 *     }
 *   }
 * }]
 * ```
 *
 * ```css
 * .slide.ng-enter {
 *   transition:0.5s linear all;
 *   transform:translateY(-100px);
 * }
 * .slide.ng-enter.ng-enter-active {
 *   transform:translateY(0);
 * }
 * ```
 *
 * Does this mean that CSS and JS animations cannot be used together? Do JS-based animations always have higher priority? We can make up for the
 * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from
 * our own JS-based animation code:
 *
 * ```js
 * myModule.animation('.slide', ['$animateCss', function($animateCss) {
 *   return {
 *     enter: function(element, doneFn) {
*        // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`.
 *       var runner = $animateCss(element, {
 *         event: 'enter',
 *         structural: true
 *       }).start();
*        runner.done(doneFn);
 *     }
 *   }
 * }]
 * ```
 *
 * The nice thing here is that we can save bandwidth by sticking to our CSS-based animation code and we don't need to rely on a 3rd-party animation framework.
 *
 * The `$animateCss` service is very powerful since we can feed in all kinds of extra properties that will be evaluated and fed into a CSS transition or
 * keyframe animation. For example if we wanted to animate the height of an element while adding and removing classes then we can do so by providing that
 * data into `$animateCss` directly:
 *
 * ```js
 * myModule.animation('.slide', ['$animateCss', function($animateCss) {
 *   return {
 *     enter: function(element, doneFn) {
 *       var runner = $animateCss(element, {
 *         event: 'enter',
 *         addClass: 'maroon-setting',
 *         from: { height:0 },
 *         to: { height: 200 }
 *       }).start();
 *
 *       runner.done(doneFn);
 *     }
 *   }
 * }]
 * ```
 *
 * Now we can fill in the rest via our transition CSS code:
 *
 * ```css
 * /&#42; the transition tells ngAnimate to make the animation happen &#42;/
 * .slide.ng-enter { transition:0.5s linear all; }
 *
 * /&#42; this extra CSS class will be absorbed into the transition
 * since the $animateCss code is adding the class &#42;/
 * .maroon-setting { background:red; }
 * ```
 *
 * And `$animateCss` will figure out the rest. Just make sure to have the `done()` callback fire the `doneFn` function to signal when the animation is over.
 *
 * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}.
 *
 * ## Animation Anchoring (via `ng-animate-ref`)
 *
 * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between
 * structural areas of an application (like views) by pairing up elements using an attribute
 * called `ng-animate-ref`.
 *
 * Let's say for example we have two views that are managed by `ng-view` and we want to show
 * that there is a relationship between two components situated in within these views. By using the
 * `ng-animate-ref` attribute we can identify that the two components are paired together and we
 * can then attach an animation, which is triggered when the view changes.
 *
 * Say for example we have the following template code:
 *
 * ```html
 * <!-- index.html -->
 * <div ng-view class="view-animation">
 * </div>
 *
 * <!-- home.html -->
 * <a href="#/banner-page">
 *   <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
 * </a>
 *
 * <!-- banner-page.html -->
 * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
 * ```
 *
 * Now, when the view changes (once the link is clicked), ngAnimate will examine the
 * HTML contents to see if there is a match reference between any components in the view
 * that is leaving and the view that is entering. It will scan both the view which is being
 * removed (leave) and inserted (enter) to see if there are any paired DOM elements that
 * contain a matching ref value.
 *
 * The two images match since they share the same ref value. ngAnimate will now create a
 * transport element (which is a clone of the first image element) and it will then attempt
 * to animate to the position of the second image element in the next view. For the animation to
 * work a special CSS class called `ng-anchor` will be added to the transported element.
 *
 * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then
 * ngAnimate will handle the entire transition for us as well as the addition and removal of
 * any changes of CSS classes between the elements:
 *
 * ```css
 * .banner.ng-anchor {
 *   /&#42; this animation will last for 1 second since there are
 *          two phases to the animation (an `in` and an `out` phase) &#42;/
 *   transition:0.5s linear all;
 * }
 * ```
 *
 * We also **must** include animations for the views that are being entered and removed
 * (otherwise anchoring wouldn't be possible since the new view would be inserted right away).
 *
 * ```css
 * .view-animation.ng-enter, .view-animation.ng-leave {
 *   transition:0.5s linear all;
 *   position:fixed;
 *   left:0;
 *   top:0;
 *   width:100%;
 * }
 * .view-animation.ng-enter {
 *   transform:translateX(100%);
 * }
 * .view-animation.ng-leave,
 * .view-animation.ng-enter.ng-enter-active {
 *   transform:translateX(0%);
 * }
 * .view-animation.ng-leave.ng-leave-active {
 *   transform:translateX(-100%);
 * }
 * ```
 *
 * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur:
 * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away
 * from its origin. Once that animation is over then the `in` stage occurs which animates the
 * element to its destination. The reason why there are two animations is to give enough time
 * for the enter animation on the new element to be ready.
 *
 * The example above sets up a transition for both the in and out phases, but we can also target the out or
 * in phases directly via `ng-anchor-out` and `ng-anchor-in`.
 *
 * ```css
 * .banner.ng-anchor-out {
 *   transition: 0.5s linear all;
 *
 *   /&#42; the scale will be applied during the out animation,
 *          but will be animated away when the in animation runs &#42;/
 *   transform: scale(1.2);
 * }
 *
 * .banner.ng-anchor-in {
 *   transition: 1s linear all;
 * }
 * ```
 *
 *
 *
 *
 * ### Anchoring Demo
 *
  <example module="anchoringExample"
           name="anchoringExample"
           id="anchoringExample"
           deps="angular-animate.js;angular-route.js"
           animations="true">
    <file name="index.html">
      <a href="#/">Home</a>
      <hr />
      <div class="view-container">
        <div ng-view class="view"></div>
      </div>
    </file>
    <file name="script.js">
      angular.module('anchoringExample', ['ngAnimate', 'ngRoute'])
        .config(['$routeProvider', function($routeProvider) {
          $routeProvider.when('/', {
            templateUrl: 'home.html',
            controller: 'HomeController as home'
          });
          $routeProvider.when('/profile/:id', {
            templateUrl: 'profile.html',
            controller: 'ProfileController as profile'
          });
        }])
        .run(['$rootScope', function($rootScope) {
          $rootScope.records = [
            { id:1, title: "Miss Beulah Roob" },
            { id:2, title: "Trent Morissette" },
            { id:3, title: "Miss Ava Pouros" },
            { id:4, title: "Rod Pouros" },
            { id:5, title: "Abdul Rice" },
            { id:6, title: "Laurie Rutherford Sr." },
            { id:7, title: "Nakia McLaughlin" },
            { id:8, title: "Jordon Blanda DVM" },
            { id:9, title: "Rhoda Hand" },
            { id:10, title: "Alexandrea Sauer" }
          ];
        }])
        .controller('HomeController', [function() {
          //empty
        }])
        .controller('ProfileController', ['$rootScope', '$routeParams', function($rootScope, $routeParams) {
          var index = parseInt($routeParams.id, 10);
          var record = $rootScope.records[index - 1];

          this.title = record.title;
          this.id = record.id;
        }]);
    </file>
    <file name="home.html">
      <h2>Welcome to the home page</h1>
      <p>Please click on an element</p>
      <a class="record"
         ng-href="#/profile/{{ record.id }}"
         ng-animate-ref="{{ record.id }}"
         ng-repeat="record in records">
        {{ record.title }}
      </a>
    </file>
    <file name="profile.html">
      <div class="profile record" ng-animate-ref="{{ profile.id }}">
        {{ profile.title }}
      </div>
    </file>
    <file name="animations.css">
      .record {
        display:block;
        font-size:20px;
      }
      .profile {
        background:black;
        color:white;
        font-size:100px;
      }
      .view-container {
        position:relative;
      }
      .view-container > .view.ng-animate {
        position:absolute;
        top:0;
        left:0;
        width:100%;
        min-height:500px;
      }
      .view.ng-enter, .view.ng-leave,
      .record.ng-anchor {
        transition:0.5s linear all;
      }
      .view.ng-enter {
        transform:translateX(100%);
      }
      .view.ng-enter.ng-enter-active, .view.ng-leave {
        transform:translateX(0%);
      }
      .view.ng-leave.ng-leave-active {
        transform:translateX(-100%);
      }
      .record.ng-anchor-out {
        background:red;
      }
    </file>
  </example>
 *
 * ### How is the element transported?
 *
 * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting
 * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element
 * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The
 * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match
 * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied
 * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class
 * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element
 * will become visible since the shim class will be removed.
 *
 * ### How is the morphing handled?
 *
 * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out
 * what CSS classes differ between the starting element and the destination element. These different CSS classes
 * will be added/removed on the anchor element and a transition will be applied (the transition that is provided
 * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will
 * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that
 * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since
 * the cloned element is placed inside of root element which is likely close to the body element).
 *
 * Note that if the root element is on the `<html>` element then the cloned node will be placed inside of body.
 *
 *
 * ## Using $animate in your directive code
 *
 * So far we've explored how to feed in animations into an Angular application, but how do we trigger animations within our own directives in our application?
 * By injecting the `$animate` service into our directive code, we can trigger structural and class-based hooks which can then be consumed by animations. Let's
 * imagine we have a greeting box that shows and hides itself when the data changes
 *
 * ```html
 * <greeting-box active="onOrOff">Hi there</greeting-box>
 * ```
 *
 * ```js
 * ngModule.directive('greetingBox', ['$animate', function($animate) {
 *   return function(scope, element, attrs) {
 *     attrs.$observe('active', function(value) {
 *       value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on');
 *     });
 *   });
 * }]);
 * ```
 *
 * Now the `on` CSS class is added and removed on the greeting box component. Now if we add a CSS class on top of the greeting box element
 * in our HTML code then we can trigger a CSS or JS animation to happen.
 *
 * ```css
 * /&#42; normally we would create a CSS class to reference on the element &#42;/
 * greeting-box.on { transition:0.5s linear all; background:green; color:white; }
 * ```
 *
 * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's
 * possible be sure to visit the {@link ng.$animate $animate service API page}.
 *
 *
 * ### Preventing Collisions With Third Party Libraries
 *
 * Some third-party frameworks place animation duration defaults across many element or className
 * selectors in order to make their code small and reuseable. This can lead to issues with ngAnimate, which
 * is expecting actual animations on these elements and has to wait for their completion.
 *
 * You can prevent this unwanted behavior by using a prefix on all your animation classes:
 *
 * ```css
 * /&#42; prefixed with animate- &#42;/
 * .animate-fade-add.animate-fade-add-active {
 *   transition:1s linear all;
 *   opacity:0;
 * }
 * ```
 *
 * You then configure `$animate` to enforce this prefix:
 *
 * ```js
 * $animateProvider.classNameFilter(/animate-/);
 * ```
 *
 * This also may provide your application with a speed boost since only specific elements containing CSS class prefix
 * will be evaluated for animation when any DOM changes occur in the application.
 *
 * ## Callbacks and Promises
 *
 * When `$animate` is called it returns a promise that can be used to capture when the animation has ended. Therefore if we were to trigger
 * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has
 * ended by chaining onto the returned promise that animation method returns.
 *
 * ```js
 * // somewhere within the depths of the directive
 * $animate.enter(element, parent).then(function() {
 *   //the animation has completed
 * });
 * ```
 *
 * (Note that earlier versions of Angular prior to v1.4 required the promise code to be wrapped using `$scope.$apply(...)`. This is not the case
 * anymore.)
 *
 * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering
 * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view
 * routing controller to hook into that:
 *
 * ```js
 * ngModule.controller('HomePageController', ['$animate', function($animate) {
 *   $animate.on('enter', ngViewElement, function(element) {
 *     // the animation for this route has completed
 *   }]);
 * }])
 * ```
 *
 * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.)
 */

/**
 * @ngdoc service
 * @name $animate
 * @kind object
 *
 * @description
 * The ngAnimate `$animate` service documentation is the same for the core `$animate` service.
 *
 * Click here {@link ng.$animate $animate to learn more about animations with `$animate`}.
 */
angular.module('ngAnimate', [])
  .directive('ngAnimateChildren', $$AnimateChildrenDirective)

  .factory('$$rAFMutex', $$rAFMutexFactory)
  .factory('$$rAFScheduler', $$rAFSchedulerFactory)

  .factory('$$AnimateRunner', $$AnimateRunnerFactory)

  .provider('$$animateQueue', $$AnimateQueueProvider)
  .provider('$$animation', $$AnimationProvider)

  .provider('$animateCss', $AnimateCssProvider)
  .provider('$$animateCssDriver', $$AnimateCssDriverProvider)

  .provider('$$animateJs', $$AnimateJsProvider)
  .provider('$$animateJsDriver', $$AnimateJsDriverProvider);


})(window, window.angular);
/*! Hammer.JS - v1.0.5 - 2013-04-07
 * http://eightmedia.github.com/hammer.js
 *
 * Copyright (c) 2013 Jorik Tangelder <j.tangelder@gmail.com>;
 * Licensed under the MIT license */

(function(window, undefined) {
    'use strict';

/**
 * Hammer
 * use this to create instances
 * @param   {HTMLElement}   element
 * @param   {Object}        options
 * @returns {Hammer.Instance}
 * @constructor
 */
var Hammer = function(element, options) {
    return new Hammer.Instance(element, options || {});
};

// default settings
Hammer.defaults = {
    // add styles and attributes to the element to prevent the browser from doing
    // its native behavior. this doesnt prevent the scrolling, but cancels
    // the contextmenu, tap highlighting etc
    // set to false to disable this
    stop_browser_behavior: {
		// this also triggers onselectstart=false for IE
        userSelect: 'none',
		// this makes the element blocking in IE10 >, you could experiment with the value
		// see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
        touchAction: 'none',
		touchCallout: 'none',
        contentZooming: 'none',
        userDrag: 'none',
        tapHighlightColor: 'rgba(0,0,0,0)'
    }

    // more settings are defined per gesture at gestures.js
};

// detect touchevents
Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);

// dont use mouseevents on mobile devices
Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX);

// eventtypes per touchevent (start, move, end)
// are filled by Hammer.event.determineEventTypes on setup
Hammer.EVENT_TYPES = {};

// direction defines
Hammer.DIRECTION_DOWN = 'down';
Hammer.DIRECTION_LEFT = 'left';
Hammer.DIRECTION_UP = 'up';
Hammer.DIRECTION_RIGHT = 'right';

// pointer type
Hammer.POINTER_MOUSE = 'mouse';
Hammer.POINTER_TOUCH = 'touch';
Hammer.POINTER_PEN = 'pen';

// touch event defines
Hammer.EVENT_START = 'start';
Hammer.EVENT_MOVE = 'move';
Hammer.EVENT_END = 'end';

// hammer document where the base events are added at
Hammer.DOCUMENT = document;

// plugins namespace
Hammer.plugins = {};

// if the window events are set...
Hammer.READY = false;

/**
 * setup events to detect gestures on the document
 */
function setup() {
    if(Hammer.READY) {
        return;
    }

    // find what eventtypes we add listeners to
    Hammer.event.determineEventTypes();

    // Register all gestures inside Hammer.gestures
    for(var name in Hammer.gestures) {
        if(Hammer.gestures.hasOwnProperty(name)) {
            Hammer.detection.register(Hammer.gestures[name]);
        }
    }

    // Add touch events on the document
    Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect);
    Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect);

    // Hammer is ready...!
    Hammer.READY = true;
}

/**
 * create new hammer instance
 * all methods should return the instance itself, so it is chainable.
 * @param   {HTMLElement}       element
 * @param   {Object}            [options={}]
 * @returns {Hammer.Instance}
 * @constructor
 */
Hammer.Instance = function(element, options) {
    var self = this;

    // setup HammerJS window events and register all gestures
    // this also sets up the default options
    setup();

    this.element = element;

    // start/stop detection option
    this.enabled = true;

    // merge options
    this.options = Hammer.utils.extend(
        Hammer.utils.extend({}, Hammer.defaults),
        options || {});

    // add some css to the element to prevent the browser from doing its native behavoir
    if(this.options.stop_browser_behavior) {
        Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
    }

    // start detection on touchstart
    Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) {
        if(self.enabled) {
            Hammer.detection.startDetect(self, ev);
        }
    });

    // return instance
    return this;
};


Hammer.Instance.prototype = {
    /**
     * bind events to the instance
     * @param   {String}      gesture
     * @param   {Function}    handler
     * @returns {Hammer.Instance}
     */
    on: function onEvent(gesture, handler){
        var gestures = gesture.split(' ');
        for(var t=0; t<gestures.length; t++) {
            this.element.addEventListener(gestures[t], handler, false);
        }
        return this;
    },


    /**
     * unbind events to the instance
     * @param   {String}      gesture
     * @param   {Function}    handler
     * @returns {Hammer.Instance}
     */
    off: function offEvent(gesture, handler){
        var gestures = gesture.split(' ');
        for(var t=0; t<gestures.length; t++) {
            this.element.removeEventListener(gestures[t], handler, false);
        }
        return this;
    },


    /**
     * trigger gesture event
     * @param   {String}      gesture
     * @param   {Object}      eventData
     * @returns {Hammer.Instance}
     */
    trigger: function triggerEvent(gesture, eventData){
        // create DOM event
        var event = Hammer.DOCUMENT.createEvent('Event');
		event.initEvent(gesture, true, true);
		event.gesture = eventData;

        // trigger on the target if it is in the instance element,
        // this is for event delegation tricks
        var element = this.element;
        if(Hammer.utils.hasParent(eventData.target, element)) {
            element = eventData.target;
        }

        element.dispatchEvent(event);
        return this;
    },


    /**
     * enable of disable hammer.js detection
     * @param   {Boolean}   state
     * @returns {Hammer.Instance}
     */
    enable: function enable(state) {
        this.enabled = state;
        return this;
    }
};

/**
 * this holds the last move event,
 * used to fix empty touchend issue
 * see the onTouch event for an explanation
 * @type {Object}
 */
var last_move_event = null;


/**
 * when the mouse is hold down, this is true
 * @type {Boolean}
 */
var enable_detect = false;


/**
 * when touch events have been fired, this is true
 * @type {Boolean}
 */
var touch_triggered = false;


Hammer.event = {
    /**
     * simple addEventListener
     * @param   {HTMLElement}   element
     * @param   {String}        type
     * @param   {Function}      handler
     */
    bindDom: function(element, type, handler) {
        var types = type.split(' ');
        for(var t=0; t<types.length; t++) {
            element.addEventListener(types[t], handler, false);
        }
    },


    /**
     * touch events with mouse fallback
     * @param   {HTMLElement}   element
     * @param   {String}        eventType        like Hammer.EVENT_MOVE
     * @param   {Function}      handler
     */
    onTouch: function onTouch(element, eventType, handler) {
		var self = this;

        this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
            var sourceEventType = ev.type.toLowerCase();

            // onmouseup, but when touchend has been fired we do nothing.
            // this is for touchdevices which also fire a mouseup on touchend
            if(sourceEventType.match(/mouse/) && touch_triggered) {
                return;
            }

            // mousebutton must be down or a touch event
            else if( sourceEventType.match(/touch/) ||   // touch events are always on screen
                sourceEventType.match(/pointerdown/) || // pointerevents touch
                (sourceEventType.match(/mouse/) && ev.which === 1)   // mouse is pressed
            ){
                enable_detect = true;
            }

            // we are in a touch event, set the touch triggered bool to true,
            // this for the conflicts that may occur on ios and android
            if(sourceEventType.match(/touch|pointer/)) {
                touch_triggered = true;
            }

            // count the total touches on the screen
            var count_touches = 0;

            // when touch has been triggered in this detection session
            // and we are now handling a mouse event, we stop that to prevent conflicts
            if(enable_detect) {
                // update pointerevent
                if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) {
                    count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
                }
                // touch
                else if(sourceEventType.match(/touch/)) {
                    count_touches = ev.touches.length;
                }
                // mouse
                else if(!touch_triggered) {
                    count_touches = sourceEventType.match(/up/) ? 0 : 1;
                }

                // if we are in a end event, but when we remove one touch and
                // we still have enough, set eventType to move
                if(count_touches > 0 && eventType == Hammer.EVENT_END) {
                    eventType = Hammer.EVENT_MOVE;
                }
                // no touches, force the end event
                else if(!count_touches) {
                    eventType = Hammer.EVENT_END;
                }

                // because touchend has no touches, and we often want to use these in our gestures,
                // we send the last move event as our eventData in touchend
                if(!count_touches && last_move_event !== null) {
                    ev = last_move_event;
                }
                // store the last move event
                else {
                    last_move_event = ev;
                }

                // trigger the handler
                handler.call(Hammer.detection, self.collectEventData(element, eventType, ev));

                // remove pointerevent from list
                if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) {
                    count_touches = Hammer.PointerEvent.updatePointer(eventType, ev);
                }
            }

            //debug(sourceEventType +" "+ eventType);

            // on the end we reset everything
            if(!count_touches) {
                last_move_event = null;
                enable_detect = false;
                touch_triggered = false;
                Hammer.PointerEvent.reset();
            }
        });
    },


    /**
     * we have different events for each device/browser
     * determine what we need and set them in the Hammer.EVENT_TYPES constant
     */
    determineEventTypes: function determineEventTypes() {
        // determine the eventtype we want to set
        var types;

        // pointerEvents magic
        if(Hammer.HAS_POINTEREVENTS) {
            types = Hammer.PointerEvent.getEvents();
        }
        // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
        else if(Hammer.NO_MOUSEEVENTS) {
            types = [
                'touchstart',
                'touchmove',
                'touchend touchcancel'];
        }
        // for non pointer events browsers and mixed browsers,
        // like chrome on windows8 touch laptop
        else {
            types = [
                'touchstart mousedown',
                'touchmove mousemove',
                'touchend touchcancel mouseup'];
        }

        Hammer.EVENT_TYPES[Hammer.EVENT_START]  = types[0];
        Hammer.EVENT_TYPES[Hammer.EVENT_MOVE]   = types[1];
        Hammer.EVENT_TYPES[Hammer.EVENT_END]    = types[2];
    },


    /**
     * create touchlist depending on the event
     * @param   {Object}    ev
     * @param   {String}    eventType   used by the fakemultitouch plugin
     */
    getTouchList: function getTouchList(ev/*, eventType*/) {
        // get the fake pointerEvent touchlist
        if(Hammer.HAS_POINTEREVENTS) {
            return Hammer.PointerEvent.getTouchList();
        }
        // get the touchlist
        else if(ev.touches) {
            return ev.touches;
        }
        // make fake touchlist from mouse position
        else {
            return [{
                identifier: 1,
                pageX: ev.pageX,
                pageY: ev.pageY,
                target: ev.target
            }];
        }
    },


    /**
     * collect event data for Hammer js
     * @param   {HTMLElement}   element
     * @param   {String}        eventType        like Hammer.EVENT_MOVE
     * @param   {Object}        eventData
     */
    collectEventData: function collectEventData(element, eventType, ev) {
        var touches = this.getTouchList(ev, eventType);

        // find out pointerType
        var pointerType = Hammer.POINTER_TOUCH;
        if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) {
            pointerType = Hammer.POINTER_MOUSE;
        }

        return {
            center      : Hammer.utils.getCenter(touches),
            timeStamp   : new Date().getTime(),
            target      : ev.target,
            touches     : touches,
            eventType   : eventType,
            pointerType : pointerType,
            srcEvent    : ev,

            /**
             * prevent the browser default actions
             * mostly used to disable scrolling of the browser
             */
            preventDefault: function() {
                if(this.srcEvent.preventManipulation) {
                    this.srcEvent.preventManipulation();
                }

                if(this.srcEvent.preventDefault) {
                    this.srcEvent.preventDefault();
                }
            },

            /**
             * stop bubbling the event up to its parents
             */
            stopPropagation: function() {
                this.srcEvent.stopPropagation();
            },

            /**
             * immediately stop gesture detection
             * might be useful after a swipe was detected
             * @return {*}
             */
            stopDetect: function() {
                return Hammer.detection.stopDetect();
            }
        };
    }
};

Hammer.PointerEvent = {
    /**
     * holds all pointers
     * @type {Object}
     */
    pointers: {},

    /**
     * get a list of pointers
     * @returns {Array}     touchlist
     */
    getTouchList: function() {
        var self = this;
        var touchlist = [];

        // we can use forEach since pointerEvents only is in IE10
        Object.keys(self.pointers).sort().forEach(function(id) {
            touchlist.push(self.pointers[id]);
        });
        return touchlist;
    },

    /**
     * update the position of a pointer
     * @param   {String}   type             Hammer.EVENT_END
     * @param   {Object}   pointerEvent
     */
    updatePointer: function(type, pointerEvent) {
        if(type == Hammer.EVENT_END) {
            this.pointers = {};
        }
        else {
            pointerEvent.identifier = pointerEvent.pointerId;
            this.pointers[pointerEvent.pointerId] = pointerEvent;
        }

        return Object.keys(this.pointers).length;
    },

    /**
     * check if ev matches pointertype
     * @param   {String}        pointerType     Hammer.POINTER_MOUSE
     * @param   {PointerEvent}  ev
     */
    matchType: function(pointerType, ev) {
        if(!ev.pointerType) {
            return false;
        }

        var types = {};
        types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE);
        types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH);
        types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN);
        return types[pointerType];
    },


    /**
     * get events
     */
    getEvents: function() {
        return [
            'pointerdown MSPointerDown',
            'pointermove MSPointerMove',
            'pointerup pointercancel MSPointerUp MSPointerCancel'
        ];
    },

    /**
     * reset the list
     */
    reset: function() {
        this.pointers = {};
    }
};


Hammer.utils = {
    /**
     * extend method,
     * also used for cloning when dest is an empty object
     * @param   {Object}    dest
     * @param   {Object}    src
	 * @parm	{Boolean}	merge		do a merge
     * @returns {Object}    dest
     */
    extend: function extend(dest, src, merge) {
        for (var key in src) {
			if(dest[key] !== undefined && merge) {
				continue;
			}
            dest[key] = src[key];
        }
        return dest;
    },


    /**
     * find if a node is in the given parent
     * used for event delegation tricks
     * @param   {HTMLElement}   node
     * @param   {HTMLElement}   parent
     * @returns {boolean}       has_parent
     */
    hasParent: function(node, parent) {
        while(node){
            if(node == parent) {
                return true;
            }
            node = node.parentNode;
        }
        return false;
    },


    /**
     * get the center of all the touches
     * @param   {Array}     touches
     * @returns {Object}    center
     */
    getCenter: function getCenter(touches) {
        var valuesX = [], valuesY = [];

        for(var t= 0,len=touches.length; t<len; t++) {
            valuesX.push(touches[t].pageX);
            valuesY.push(touches[t].pageY);
        }

        return {
            pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
            pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
        };
    },


    /**
     * calculate the velocity between two points
     * @param   {Number}    delta_time
     * @param   {Number}    delta_x
     * @param   {Number}    delta_y
     * @returns {Object}    velocity
     */
    getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
        return {
            x: Math.abs(delta_x / delta_time) || 0,
            y: Math.abs(delta_y / delta_time) || 0
        };
    },


    /**
     * calculate the angle between two coordinates
     * @param   {Touch}     touch1
     * @param   {Touch}     touch2
     * @returns {Number}    angle
     */
    getAngle: function getAngle(touch1, touch2) {
        var y = touch2.pageY - touch1.pageY,
            x = touch2.pageX - touch1.pageX;
        return Math.atan2(y, x) * 180 / Math.PI;
    },


    /**
     * angle to direction define
     * @param   {Touch}     touch1
     * @param   {Touch}     touch2
     * @returns {String}    direction constant, like Hammer.DIRECTION_LEFT
     */
    getDirection: function getDirection(touch1, touch2) {
        var x = Math.abs(touch1.pageX - touch2.pageX),
            y = Math.abs(touch1.pageY - touch2.pageY);

        if(x >= y) {
            return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
        }
        else {
            return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
        }
    },


    /**
     * calculate the distance between two touches
     * @param   {Touch}     touch1
     * @param   {Touch}     touch2
     * @returns {Number}    distance
     */
    getDistance: function getDistance(touch1, touch2) {
        var x = touch2.pageX - touch1.pageX,
            y = touch2.pageY - touch1.pageY;
        return Math.sqrt((x*x) + (y*y));
    },


    /**
     * calculate the scale factor between two touchLists (fingers)
     * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
     * @param   {Array}     start
     * @param   {Array}     end
     * @returns {Number}    scale
     */
    getScale: function getScale(start, end) {
        // need two fingers...
        if(start.length >= 2 && end.length >= 2) {
            return this.getDistance(end[0], end[1]) /
                this.getDistance(start[0], start[1]);
        }
        return 1;
    },


    /**
     * calculate the rotation degrees between two touchLists (fingers)
     * @param   {Array}     start
     * @param   {Array}     end
     * @returns {Number}    rotation
     */
    getRotation: function getRotation(start, end) {
        // need two fingers
        if(start.length >= 2 && end.length >= 2) {
            return this.getAngle(end[1], end[0]) -
                this.getAngle(start[1], start[0]);
        }
        return 0;
    },


    /**
     * boolean if the direction is vertical
     * @param    {String}    direction
     * @returns  {Boolean}   is_vertical
     */
    isVertical: function isVertical(direction) {
        return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN);
    },


    /**
     * stop browser default behavior with css props
     * @param   {HtmlElement}   element
     * @param   {Object}        css_props
     */
    stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
        var prop,
            vendors = ['webkit','khtml','moz','ms','o',''];

        if(!css_props || !element.style) {
            return;
        }

        // with css properties for modern browsers
        for(var i = 0; i < vendors.length; i++) {
            for(var p in css_props) {
                if(css_props.hasOwnProperty(p)) {
                    prop = p;

                    // vender prefix at the property
                    if(vendors[i]) {
                        prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
                    }

                    // set the style
                    element.style[prop] = css_props[p];
                }
            }
        }

        // also the disable onselectstart
        if(css_props.userSelect == 'none') {
            element.onselectstart = function() {
                return false;
            };
        }
    }
};

Hammer.detection = {
    // contains all registred Hammer.gestures in the correct order
    gestures: [],

    // data of the current Hammer.gesture detection session
    current: null,

    // the previous Hammer.gesture session data
    // is a full clone of the previous gesture.current object
    previous: null,

    // when this becomes true, no gestures are fired
    stopped: false,


    /**
     * start Hammer.gesture detection
     * @param   {Hammer.Instance}   inst
     * @param   {Object}            eventData
     */
    startDetect: function startDetect(inst, eventData) {
        // already busy with a Hammer.gesture detection on an element
        if(this.current) {
            return;
        }

        this.stopped = false;

        this.current = {
            inst        : inst, // reference to HammerInstance we're working for
            startEvent  : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc
            lastEvent   : false, // last eventData
            name        : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
        };

        this.detect(eventData);
    },


    /**
     * Hammer.gesture detection
     * @param   {Object}    eventData
     * @param   {Object}    eventData
     */
    detect: function detect(eventData) {
        if(!this.current || this.stopped) {
            return;
        }

        // extend event data with calculations about scale, distance etc
        eventData = this.extendEventData(eventData);

        // instance options
        var inst_options = this.current.inst.options;

        // call Hammer.gesture handlers
        for(var g=0,len=this.gestures.length; g<len; g++) {
            var gesture = this.gestures[g];

            // only when the instance options have enabled this gesture
            if(!this.stopped && inst_options[gesture.name] !== false) {
                // if a handler returns false, we stop with the detection
                if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
                    this.stopDetect();
                    break;
                }
            }
        }

        // store as previous event event
        if(this.current) {
            this.current.lastEvent = eventData;
        }

        // endevent, but not the last touch, so dont stop
        if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) {
            this.stopDetect();
        }

        return eventData;
    },


    /**
     * clear the Hammer.gesture vars
     * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
     * to stop other Hammer.gestures from being fired
     */
    stopDetect: function stopDetect() {
        // clone current data to the store as the previous gesture
        // used for the double tap gesture, since this is an other gesture detect session
        this.previous = Hammer.utils.extend({}, this.current);

        // reset the current
        this.current = null;

        // stopped!
        this.stopped = true;
    },


    /**
     * extend eventData for Hammer.gestures
     * @param   {Object}   ev
     * @returns {Object}   ev
     */
    extendEventData: function extendEventData(ev) {
        var startEv = this.current.startEvent;

        // if the touches change, set the new touches over the startEvent touches
        // this because touchevents don't have all the touches on touchstart, or the
        // user must place his fingers at the EXACT same time on the screen, which is not realistic
        // but, sometimes it happens that both fingers are touching at the EXACT same time
        if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
            // extend 1 level deep to get the touchlist with the touch objects
            startEv.touches = [];
            for(var i=0,len=ev.touches.length; i<len; i++) {
                startEv.touches.push(Hammer.utils.extend({}, ev.touches[i]));
            }
        }

        var delta_time = ev.timeStamp - startEv.timeStamp,
            delta_x = ev.center.pageX - startEv.center.pageX,
            delta_y = ev.center.pageY - startEv.center.pageY,
            velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y);

        Hammer.utils.extend(ev, {
            deltaTime   : delta_time,

            deltaX      : delta_x,
            deltaY      : delta_y,

            velocityX   : velocity.x,
            velocityY   : velocity.y,

            distance    : Hammer.utils.getDistance(startEv.center, ev.center),
            angle       : Hammer.utils.getAngle(startEv.center, ev.center),
            direction   : Hammer.utils.getDirection(startEv.center, ev.center),

            scale       : Hammer.utils.getScale(startEv.touches, ev.touches),
            rotation    : Hammer.utils.getRotation(startEv.touches, ev.touches),

            startEvent  : startEv
        });

        return ev;
    },


    /**
     * register new gesture
     * @param   {Object}    gesture object, see gestures.js for documentation
     * @returns {Array}     gestures
     */
    register: function register(gesture) {
        // add an enable gesture options if there is no given
        var options = gesture.defaults || {};
        if(options[gesture.name] === undefined) {
            options[gesture.name] = true;
        }

        // extend Hammer default options with the Hammer.gesture options
        Hammer.utils.extend(Hammer.defaults, options, true);

        // set its index
        gesture.index = gesture.index || 1000;

        // add Hammer.gesture to the list
        this.gestures.push(gesture);

        // sort the list by index
        this.gestures.sort(function(a, b) {
            if (a.index < b.index) {
                return -1;
            }
            if (a.index > b.index) {
                return 1;
            }
            return 0;
        });

        return this.gestures;
    }
};


Hammer.gestures = Hammer.gestures || {};

/**
 * Custom gestures
 * ==============================
 *
 * Gesture object
 * --------------------
 * The object structure of a gesture:
 *
 * { name: 'mygesture',
 *   index: 1337,
 *   defaults: {
 *     mygesture_option: true
 *   }
 *   handler: function(type, ev, inst) {
 *     // trigger gesture event
 *     inst.trigger(this.name, ev);
 *   }
 * }

 * @param   {String}    name
 * this should be the name of the gesture, lowercase
 * it is also being used to disable/enable the gesture per instance config.
 *
 * @param   {Number}    [index=1000]
 * the index of the gesture, where it is going to be in the stack of gestures detection
 * like when you build an gesture that depends on the drag gesture, it is a good
 * idea to place it after the index of the drag gesture.
 *
 * @param   {Object}    [defaults={}]
 * the default settings of the gesture. these are added to the instance settings,
 * and can be overruled per instance. you can also add the name of the gesture,
 * but this is also added by default (and set to true).
 *
 * @param   {Function}  handler
 * this handles the gesture detection of your custom gesture and receives the
 * following arguments:
 *
 *      @param  {Object}    eventData
 *      event data containing the following properties:
 *          timeStamp   {Number}        time the event occurred
 *          target      {HTMLElement}   target element
 *          touches     {Array}         touches (fingers, pointers, mouse) on the screen
 *          pointerType {String}        kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH
 *          center      {Object}        center position of the touches. contains pageX and pageY
 *          deltaTime   {Number}        the total time of the touches in the screen
 *          deltaX      {Number}        the delta on x axis we haved moved
 *          deltaY      {Number}        the delta on y axis we haved moved
 *          velocityX   {Number}        the velocity on the x
 *          velocityY   {Number}        the velocity on y
 *          angle       {Number}        the angle we are moving
 *          direction   {String}        the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT
 *          distance    {Number}        the distance we haved moved
 *          scale       {Number}        scaling of the touches, needs 2 touches
 *          rotation    {Number}        rotation of the touches, needs 2 touches *
 *          eventType   {String}        matches Hammer.EVENT_START|MOVE|END
 *          srcEvent    {Object}        the source event, like TouchStart or MouseDown *
 *          startEvent  {Object}        contains the same properties as above,
 *                                      but from the first touch. this is used to calculate
 *                                      distances, deltaTime, scaling etc
 *
 *      @param  {Hammer.Instance}    inst
 *      the instance we are doing the detection for. you can get the options from
 *      the inst.options object and trigger the gesture event by calling inst.trigger
 *
 *
 * Handle gestures
 * --------------------
 * inside the handler you can get/set Hammer.detection.current. This is the current
 * detection session. It has the following properties
 *      @param  {String}    name
 *      contains the name of the gesture we have detected. it has not a real function,
 *      only to check in other gestures if something is detected.
 *      like in the drag gesture we set it to 'drag' and in the swipe gesture we can
 *      check if the current gesture is 'drag' by accessing Hammer.detection.current.name
 *
 *      @readonly
 *      @param  {Hammer.Instance}    inst
 *      the instance we do the detection for
 *
 *      @readonly
 *      @param  {Object}    startEvent
 *      contains the properties of the first gesture detection in this session.
 *      Used for calculations about timing, distance, etc.
 *
 *      @readonly
 *      @param  {Object}    lastEvent
 *      contains all the properties of the last gesture detect in this session.
 *
 * after the gesture detection session has been completed (user has released the screen)
 * the Hammer.detection.current object is copied into Hammer.detection.previous,
 * this is usefull for gestures like doubletap, where you need to know if the
 * previous gesture was a tap
 *
 * options that have been set by the instance can be received by calling inst.options
 *
 * You can trigger a gesture event by calling inst.trigger("mygesture", event).
 * The first param is the name of your gesture, the second the event argument
 *
 *
 * Register gestures
 * --------------------
 * When an gesture is added to the Hammer.gestures object, it is auto registered
 * at the setup of the first Hammer instance. You can also call Hammer.detection.register
 * manually and pass your gesture object as a param
 *
 */

/**
 * Hold
 * Touch stays at the same place for x time
 * @events  hold
 */
Hammer.gestures.Hold = {
    name: 'hold',
    index: 10,
    defaults: {
        hold_timeout	: 500,
        hold_threshold	: 1
    },
    timer: null,
    handler: function holdGesture(ev, inst) {
        switch(ev.eventType) {
            case Hammer.EVENT_START:
                // clear any running timers
                clearTimeout(this.timer);

                // set the gesture so we can check in the timeout if it still is
                Hammer.detection.current.name = this.name;

                // set timer and if after the timeout it still is hold,
                // we trigger the hold event
                this.timer = setTimeout(function() {
                    if(Hammer.detection.current.name == 'hold') {
                        inst.trigger('hold', ev);
                    }
                }, inst.options.hold_timeout);
                break;

            // when you move or end we clear the timer
            case Hammer.EVENT_MOVE:
                if(ev.distance > inst.options.hold_threshold) {
                    clearTimeout(this.timer);
                }
                break;

            case Hammer.EVENT_END:
                clearTimeout(this.timer);
                break;
        }
    }
};


/**
 * Tap/DoubleTap
 * Quick touch at a place or double at the same place
 * @events  tap, doubletap
 */
Hammer.gestures.Tap = {
    name: 'tap',
    index: 100,
    defaults: {
        tap_max_touchtime	: 250,
        tap_max_distance	: 10,
		tap_always			: true,
        doubletap_distance	: 20,
        doubletap_interval	: 300
    },
    handler: function tapGesture(ev, inst) {
        if(ev.eventType == Hammer.EVENT_END) {
            // previous gesture, for the double tap since these are two different gesture detections
            var prev = Hammer.detection.previous,
				did_doubletap = false;

            // when the touchtime is higher then the max touch time
            // or when the moving distance is too much
            if(ev.deltaTime > inst.options.tap_max_touchtime ||
                ev.distance > inst.options.tap_max_distance) {
                return;
            }

            // check if double tap
            if(prev && prev.name == 'tap' &&
                (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
                ev.distance < inst.options.doubletap_distance) {
				inst.trigger('doubletap', ev);
				did_doubletap = true;
            }

			// do a single tap
			if(!did_doubletap || inst.options.tap_always) {
				Hammer.detection.current.name = 'tap';
				inst.trigger(Hammer.detection.current.name, ev);
			}
        }
    }
};


/**
 * Swipe
 * triggers swipe events when the end velocity is above the threshold
 * @events  swipe, swipeleft, swiperight, swipeup, swipedown
 */
Hammer.gestures.Swipe = {
    name: 'swipe',
    index: 40,
    defaults: {
        // set 0 for unlimited, but this can conflict with transform
        swipe_max_touches  : 1,
        swipe_velocity     : 0.7
    },
    handler: function swipeGesture(ev, inst) {
        if(ev.eventType == Hammer.EVENT_END) {
            // max touches
            if(inst.options.swipe_max_touches > 0 &&
                ev.touches.length > inst.options.swipe_max_touches) {
                return;
            }

            // when the distance we moved is too small we skip this gesture
            // or we can be already in dragging
            if(ev.velocityX > inst.options.swipe_velocity ||
                ev.velocityY > inst.options.swipe_velocity) {
                // trigger swipe events
                inst.trigger(this.name, ev);
                inst.trigger(this.name + ev.direction, ev);
            }
        }
    }
};


/**
 * Drag
 * Move with x fingers (default 1) around on the page. Blocking the scrolling when
 * moving left and right is a good practice. When all the drag events are blocking
 * you disable scrolling on that area.
 * @events  drag, drapleft, dragright, dragup, dragdown
 */
Hammer.gestures.Drag = {
    name: 'drag',
    index: 50,
    defaults: {
        drag_min_distance : 10,
        // set 0 for unlimited, but this can conflict with transform
        drag_max_touches  : 1,
        // prevent default browser behavior when dragging occurs
        // be careful with it, it makes the element a blocking element
        // when you are using the drag gesture, it is a good practice to set this true
        drag_block_horizontal   : false,
        drag_block_vertical     : false,
        // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
        // It disallows vertical directions if the initial direction was horizontal, and vice versa.
        drag_lock_to_axis       : false,
        // drag lock only kicks in when distance > drag_lock_min_distance
        // This way, locking occurs only when the distance has become large enough to reliably determine the direction
        drag_lock_min_distance : 25
    },
    triggered: false,
    handler: function dragGesture(ev, inst) {
        // current gesture isnt drag, but dragged is true
        // this means an other gesture is busy. now call dragend
        if(Hammer.detection.current.name != this.name && this.triggered) {
            inst.trigger(this.name +'end', ev);
            this.triggered = false;
            return;
        }

        // max touches
        if(inst.options.drag_max_touches > 0 &&
            ev.touches.length > inst.options.drag_max_touches) {
            return;
        }

        switch(ev.eventType) {
            case Hammer.EVENT_START:
                this.triggered = false;
                break;

            case Hammer.EVENT_MOVE:
                // when the distance we moved is too small we skip this gesture
                // or we can be already in dragging
                if(ev.distance < inst.options.drag_min_distance &&
                    Hammer.detection.current.name != this.name) {
                    return;
                }

                // we are dragging!
                Hammer.detection.current.name = this.name;

                // lock drag to axis?
                if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
                    ev.drag_locked_to_axis = true;
                }
                var last_direction = Hammer.detection.current.lastEvent.direction;
                if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
                    // keep direction on the axis that the drag gesture started on
                    if(Hammer.utils.isVertical(last_direction)) {
                        ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN;
                    }
                    else {
                        ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT;
                    }
                }

                // first time, trigger dragstart event
                if(!this.triggered) {
                    inst.trigger(this.name +'start', ev);
                    this.triggered = true;
                }

                // trigger normal event
                inst.trigger(this.name, ev);

                // direction event, like dragdown
                inst.trigger(this.name + ev.direction, ev);

                // block the browser events
                if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) ||
                    (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) {
                    ev.preventDefault();
                }
                break;

            case Hammer.EVENT_END:
                // trigger dragend
                if(this.triggered) {
                    inst.trigger(this.name +'end', ev);
                }

                this.triggered = false;
                break;
        }
    }
};


/**
 * Transform
 * User want to scale or rotate with 2 fingers
 * @events  transform, pinch, pinchin, pinchout, rotate
 */
Hammer.gestures.Transform = {
    name: 'transform',
    index: 45,
    defaults: {
        // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
        transform_min_scale     : 0.01,
        // rotation in degrees
        transform_min_rotation  : 1,
        // prevent default browser behavior when two touches are on the screen
        // but it makes the element a blocking element
        // when you are using the transform gesture, it is a good practice to set this true
        transform_always_block  : false
    },
    triggered: false,
    handler: function transformGesture(ev, inst) {
        // current gesture isnt drag, but dragged is true
        // this means an other gesture is busy. now call dragend
        if(Hammer.detection.current.name != this.name && this.triggered) {
            inst.trigger(this.name +'end', ev);
            this.triggered = false;
            return;
        }

        // atleast multitouch
        if(ev.touches.length < 2) {
            return;
        }

        // prevent default when two fingers are on the screen
        if(inst.options.transform_always_block) {
            ev.preventDefault();
        }

        switch(ev.eventType) {
            case Hammer.EVENT_START:
                this.triggered = false;
                break;

            case Hammer.EVENT_MOVE:
                var scale_threshold = Math.abs(1-ev.scale);
                var rotation_threshold = Math.abs(ev.rotation);

                // when the distance we moved is too small we skip this gesture
                // or we can be already in dragging
                if(scale_threshold < inst.options.transform_min_scale &&
                    rotation_threshold < inst.options.transform_min_rotation) {
                    return;
                }

                // we are transforming!
                Hammer.detection.current.name = this.name;

                // first time, trigger dragstart event
                if(!this.triggered) {
                    inst.trigger(this.name +'start', ev);
                    this.triggered = true;
                }

                inst.trigger(this.name, ev); // basic transform event

                // trigger rotate event
                if(rotation_threshold > inst.options.transform_min_rotation) {
                    inst.trigger('rotate', ev);
                }

                // trigger pinch event
                if(scale_threshold > inst.options.transform_min_scale) {
                    inst.trigger('pinch', ev);
                    inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
                }
                break;

            case Hammer.EVENT_END:
                // trigger dragend
                if(this.triggered) {
                    inst.trigger(this.name +'end', ev);
                }

                this.triggered = false;
                break;
        }
    }
};


/**
 * Touch
 * Called as first, tells the user has touched the screen
 * @events  touch
 */
Hammer.gestures.Touch = {
    name: 'touch',
    index: -Infinity,
    defaults: {
        // call preventDefault at touchstart, and makes the element blocking by
        // disabling the scrolling of the page, but it improves gestures like
        // transforming and dragging.
        // be careful with using this, it can be very annoying for users to be stuck
        // on the page
        prevent_default: false,

        // disable mouse events, so only touch (or pen!) input triggers events
        prevent_mouseevents: false
    },
    handler: function touchGesture(ev, inst) {
        if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) {
            ev.stopDetect();
            return;
        }

        if(inst.options.prevent_default) {
            ev.preventDefault();
        }

        if(ev.eventType ==  Hammer.EVENT_START) {
            inst.trigger(this.name, ev);
        }
    }
};


/**
 * Release
 * Called as last, tells the user has released the screen
 * @events  release
 */
Hammer.gestures.Release = {
    name: 'release',
    index: Infinity,
    handler: function releaseGesture(ev, inst) {
        if(ev.eventType ==  Hammer.EVENT_END) {
            inst.trigger(this.name, ev);
        }
    }
};

// node export
if(typeof module === 'object' && typeof module.exports === 'object'){
    module.exports = Hammer;
}
// just window export
else {
    window.Hammer = Hammer;

    // requireJS module definition
    if(typeof window.define === 'function' && window.define.amd) {
        window.define('hammer', [], function() {
            return Hammer;
        });
    }
}
})(this);
'use strict';

angular.module('angular-gestures', []);

/**
 * Inspired by AngularJS' implementation of "click dblclick mousedown..."
 *
 * This ties in the Hammer 1.0.0 events to attributes like:
 *
 * hm-tap="add_something()" hm-swipe="remove_something()"
 *
 * and also has support for Hammer options with:
 *
 * hm-tap-opts="{hold: false}"
 *
 * or any other of the "hm-event" listed underneath.
 */
var HGESTURES = {
    hmDoubleTap : 'doubletap',
    hmDragstart : 'dragstart',
    hmDrag : 'drag',
    hmDragUp : 'dragup',
    hmDragDown : 'dragdown',
    hmDragLeft : 'dragleft',
    hmDragRight : 'dragright',
    hmDragend : 'dragend',
    hmHold : 'hold',
    hmPinch : 'pinch',
    hmPinchIn : 'pinchin',
    hmPinchOut : 'pinchout',
    hmRelease : 'release',
    hmRotate : 'rotate',
    hmSwipe : 'swipe',
    hmSwipeUp : 'swipeup',
    hmSwipeDown : 'swipedown',
    hmSwipeLeft : 'swipeleft',
    hmSwipeRight : 'swiperight',
    hmTap : 'tap',
    hmTouch : 'touch',
    hmTransformstart : 'transformstart',
    hmTransform : 'transform',
    hmTransformend : 'transformend'
};

var VERBOSE = false;

angular.forEach(HGESTURES, function(eventName, directiveName) {
    angular.module('angular-gestures').directive(
            directiveName,
            ['$parse', '$log', '$timeout', function($parse, $log, $timeout) {
                return function(scope, element, attr) {
                    var hammertime, handler;
                    attr.$observe(directiveName, function(value) {
                        var fn = $parse(value);
                        var opts = $parse(attr[directiveName + 'Opts'])
                        (scope, {});
                        hammertime = new Hammer(element[0], opts);
                        handler = function(event) {
                            if (VERBOSE) {
                                $log.debug('angular-gestures: %s',
                                        eventName);
                            }
                            $timeout(function() {
                                fn(scope, { $event : event });
                            }, 0);
                        };
                        hammertime.on(eventName, handler);
                    });
                    scope.$on('$destroy', function() {
                        hammertime.off(eventName, handler);
                    });
                };
            }]);
});
(function() {
/* Start angularLocalStorage */
'use strict';
var angularLocalStorage = angular.module('LocalStorageModule', []);

angularLocalStorage.provider('localStorageService', function() {

  // You should set a prefix to avoid overwriting any local storage variables from the rest of your app
  // e.g. localStorageServiceProvider.setPrefix('youAppName');
  // With provider you can use config as this:
  // myApp.config(function (localStorageServiceProvider) {
  //    localStorageServiceProvider.prefix = 'yourAppName';
  // });
  this.prefix = 'ls';

  // You could change web storage type localstorage or sessionStorage
  this.storageType = 'localStorage';

  // Cookie options (usually in case of fallback)
  // expiry = Number of days before cookies expire // 0 = Does not expire
  // path = The web path the cookie represents
  this.cookie = {
    expiry: 30,
    path: '/'
  };

  // Send signals for each of the following actions?
  this.notify = {
    setItem: true,
    removeItem: false
  };

  // Setter for the prefix
  this.setPrefix = function(prefix) {
    this.prefix = prefix;
  };

   // Setter for the storageType
   this.setStorageType = function(storageType) {
       this.storageType = storageType;
   };

  // Setter for cookie config
  this.setStorageCookie = function(exp, path) {
    this.cookie = {
      expiry: exp,
      path: path
    };
  };

  // Setter for cookie domain
  this.setStorageCookieDomain = function(domain) {
    this.cookie.domain = domain;
  };

  // Setter for notification config
  // itemSet & itemRemove should be booleans
  this.setNotify = function(itemSet, itemRemove) {
    this.notify = {
      setItem: itemSet,
      removeItem: itemRemove
    };
  };



  this.$get = ['$rootScope', '$window', '$document', function($rootScope, $window, $document) {
    var self = this;
    var prefix = self.prefix;
    var cookie = self.cookie;
    var notify = self.notify;
    var storageType = self.storageType;
    var webStorage;

    // When Angular's $document is not available
    if (!$document) {
      $document = document;
    } else if ($document[0]) {
      $document = $document[0];
    }

    // If there is a prefix set in the config lets use that with an appended period for readability
    if (prefix.substr(-1) !== '.') {
      prefix = !!prefix ? prefix + '.' : '';
    }
    var deriveQualifiedKey = function(key) {
      return prefix + key;
    }
    // Checks the browser to see if local storage is supported
    var browserSupportsLocalStorage = (function () {
      try {
        var supported = (storageType in $window && $window[storageType] !== null);

        // When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage
        // is available, but trying to call .setItem throws an exception.
        //
        // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage
        // that exceeded the quota."
        var key = deriveQualifiedKey('__' + Math.round(Math.random() * 1e7));
        if (supported) {
          webStorage = $window[storageType];
          webStorage.setItem(key, '');
          webStorage.removeItem(key);
        }

        return supported;
      } catch (e) {
        storageType = 'cookie';
        $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
        return false;
      }
    }());



    // Directly adds a value to local storage
    // If local storage is not available in the browser use cookies
    // Example use: localStorageService.add('library','angular');
    var addToLocalStorage = function (key, value) {

      // If this browser does not support local storage use cookies
      if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        if (notify.setItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'});
        }
        return addToCookies(key, value);
      }

      // Let's convert undefined values to null to get the value consistent
      if (typeof value === "undefined") {
        value = null;
      }

      try {
        if (angular.isObject(value) || angular.isArray(value)) {
          value = angular.toJson(value);
        }
        if (webStorage) {webStorage.setItem(deriveQualifiedKey(key), value)};
        if (notify.setItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: self.storageType});
        }
      } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
        return addToCookies(key, value);
      }
      return true;
    };

    // Directly get a value from local storage
    // Example use: localStorageService.get('library'); // returns 'angular'
    var getFromLocalStorage = function (key) {

      if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
        $rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
        return getFromCookies(key);
      }

      var item = webStorage ? webStorage.getItem(deriveQualifiedKey(key)) : null;
      // angular.toJson will convert null to 'null', so a proper conversion is needed
      // FIXME not a perfect solution, since a valid 'null' string can't be stored
      if (!item || item === 'null') {
        return null;
      }

      if (item.charAt(0) === "{" || item.charAt(0) === "[") {
        return angular.fromJson(item);
      }

      return item;
    };

    // Remove an item from local storage
    // Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular'
    var removeFromLocalStorage = function (key) {
      if (!browserSupportsLocalStorage) {
        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        if (notify.removeItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'});
        }
        return removeFromCookies(key);
      }

      try {
        webStorage.removeItem(deriveQualifiedKey(key));
        if (notify.removeItem) {
          $rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: self.storageType});
        }
      } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
        return removeFromCookies(key);
      }
      return true;
    };

    // Return array of keys for local storage
    // Example use: var keys = localStorageService.keys()
    var getKeysForLocalStorage = function () {

      if (!browserSupportsLocalStorage) {
        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        return false;
      }

      var prefixLength = prefix.length;
      var keys = [];
      for (var key in webStorage) {
        // Only return keys that are for this app
        if (key.substr(0,prefixLength) === prefix) {
          try {
            keys.push(key.substr(prefixLength));
          } catch (e) {
            $rootScope.$broadcast('LocalStorageModule.notification.error', e.Description);
            return [];
          }
        }
      }
      return keys;
    };

    // Remove all data for this app from local storage
    // Also optionally takes a regular expression string and removes the matching key-value pairs
    // Example use: localStorageService.clearAll();
    // Should be used mostly for development purposes
    var clearAllFromLocalStorage = function (regularExpression) {

      regularExpression = regularExpression || "";
      //accounting for the '.' in the prefix when creating a regex
      var tempPrefix = prefix.slice(0, -1);
      var testRegex = new RegExp(tempPrefix + '.' + regularExpression);

      if (!browserSupportsLocalStorage) {
        $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
        return clearAllFromCookies();
      }

      var prefixLength = prefix.length;

      for (var key in webStorage) {
        // Only remove items that are for this app and match the regular expression
        if (testRegex.test(key)) {
          try {
            removeFromLocalStorage(key.substr(prefixLength));
          } catch (e) {
            $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
            return clearAllFromCookies();
          }
        }
      }
      return true;
    };

    // Checks the browser to see if cookies are supported
    var browserSupportsCookies = function() {
      try {
        return navigator.cookieEnabled ||
          ("cookie" in $document && ($document.cookie.length > 0 ||
          ($document.cookie = "test").indexOf.call($document.cookie, "test") > -1));
      } catch (e) {
          $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
          return false;
      }
    };

    // Directly adds a value to cookies
    // Typically used as a fallback is local storage is not available in the browser
    // Example use: localStorageService.cookie.add('library','angular');
    var addToCookies = function (key, value) {

      if (typeof value === "undefined") {
        return false;
      }

      if (!browserSupportsCookies()) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
        return false;
      }

      try {
        var expiry = '',
            expiryDate = new Date(),
            cookieDomain = '';

        if (value === null) {
          // Mark that the cookie has expired one day ago
          expiryDate.setTime(expiryDate.getTime() + (-1 * 24 * 60 * 60 * 1000));
          expiry = "; expires=" + expiryDate.toGMTString();
          value = '';
        } else if (cookie.expiry !== 0) {
          expiryDate.setTime(expiryDate.getTime() + (cookie.expiry * 24 * 60 * 60 * 1000));
          expiry = "; expires=" + expiryDate.toGMTString();
        }
        if (!!key) {
          var cookiePath = "; path=" + cookie.path;
          if(cookie.domain){
            cookieDomain = "; domain=" + cookie.domain;
          }
          $document.cookie = deriveQualifiedKey(key) + "=" + encodeURIComponent(value) + expiry + cookiePath + cookieDomain;
        }
      } catch (e) {
        $rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
        return false;
      }
      return true;
    };

    // Directly get a value from a cookie
    // Example use: localStorageService.cookie.get('library'); // returns 'angular'
    var getFromCookies = function (key) {
      if (!browserSupportsCookies()) {
        $rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
        return false;
      }

      var cookies = $document.cookie && $document.cookie.split(';') || [];
      for(var i=0; i < cookies.length; i++) {
        var thisCookie = cookies[i];
        while (thisCookie.charAt(0) === ' ') {
          thisCookie = thisCookie.substring(1,thisCookie.length);
        }
        if (thisCookie.indexOf(deriveQualifiedKey(key) + '=') === 0) {
          return decodeURIComponent(thisCookie.substring(prefix.length + key.length + 1, thisCookie.length));
        }
      }
      return null;
    };

    var removeFromCookies = function (key) {
      addToCookies(key,null);
    };

    var clearAllFromCookies = function () {
      var thisCookie = null, thisKey = null;
      var prefixLength = prefix.length;
      var cookies = $document.cookie.split(';');
      for(var i = 0; i < cookies.length; i++) {
        thisCookie = cookies[i];

        while (thisCookie.charAt(0) === ' ') {
          thisCookie = thisCookie.substring(1, thisCookie.length);
        }

        var key = thisCookie.substring(prefixLength, thisCookie.indexOf('='));
        removeFromCookies(key);
      }
    };

    var getStorageType = function() {
      return storageType;
    };

    var bindToScope = function(scope, key, def) {
      var value = getFromLocalStorage(key);

      if (value === null && angular.isDefined(def)) {
        value = def;
      } else if (angular.isObject(value) && angular.isObject(def)) {
        value = angular.extend(def, value);
      }

      scope[key] = value;

      scope.$watchCollection(key, function(newVal) {
        addToLocalStorage(key, newVal);
      });
    };

    return {
      isSupported: browserSupportsLocalStorage,
      getStorageType: getStorageType,
      set: addToLocalStorage,
      add: addToLocalStorage, //DEPRECATED
      get: getFromLocalStorage,
      keys: getKeysForLocalStorage,
      remove: removeFromLocalStorage,
      clearAll: clearAllFromLocalStorage,
      bind: bindToScope,
      deriveKey: deriveQualifiedKey,
      cookie: {
        set: addToCookies,
        add: addToCookies, //DEPRECATED
        get: getFromCookies,
        remove: removeFromCookies,
        clearAll: clearAllFromCookies
      }
    };
  }];
});
}).call(this);

/**
 * Intro.js v2.0
 * https://github.com/usablica/intro.js
 * MIT licensed
 *
 * Copyright (C) 2013 usabli.ca - A weekend project by Afshin Mehrabani (@afshinmeh)
 */

(function (root, factory) {
  if (typeof exports === 'object') {
    // CommonJS
    factory(exports);
  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['exports'], factory);
  } else {
    // Browser globals
    factory(root);
  }
} (this, function (exports) {
  //Default config/variables
  var VERSION = '2.0';

  /**
   * IntroJs main class
   *
   * @class IntroJs
   */
  function IntroJs(obj) {
    this._targetElement = obj;
    this._introItems = [];

    this._options = {
      /* Next button label in tooltip box */
      nextLabel: 'Next &rarr;',
      /* Previous button label in tooltip box */
      prevLabel: '&larr; Back',
      /* Skip button label in tooltip box */
      skipLabel: 'Skip',
      /* Done button label in tooltip box */
      doneLabel: 'Done',
      /* Default tooltip box position */
      tooltipPosition: 'bottom',
      /* Next CSS class for tooltip boxes */
      tooltipClass: '',
      /* CSS class that is added to the helperLayer */
      highlightClass: '',
      /* Close introduction when pressing Escape button? */
      exitOnEsc: true,
      /* Close introduction when clicking on overlay layer? */
      exitOnOverlayClick: true,
      /* Show step numbers in introduction? */
      showStepNumbers: true,
      /* Let user use keyboard to navigate the tour? */
      keyboardNavigation: true,
      /* Show tour control buttons? */
      showButtons: true,
      /* Show tour bullets? */
      showBullets: true,
      /* Show tour progress? */
      showProgress: false,
      /* Scroll to highlighted element? */
      scrollToElement: true,
      /* Set the overlay opacity */
      overlayOpacity: 0.8,
      /* Precedence of positions, when auto is enabled */
      positionPrecedence: ["bottom", "top", "right", "left"],
      /* Disable an interaction with element? */
      disableInteraction: false,
      /* Default hint position */
      hintPosition: 'top-middle',
      /* Hint button label */
      hintButtonLabel: 'Got it'
    };
  }

  /**
   * Initiate a new introduction/guide from an element in the page
   *
   * @api private
   * @method _introForElement
   * @param {Object} targetElm
   * @returns {Boolean} Success or not?
   */
  function _introForElement(targetElm) {
    var introItems = [],
        self = this;

    if (this._options.steps) {
      //use steps passed programmatically
      for (var i = 0, stepsLength = this._options.steps.length; i < stepsLength; i++) {
        var currentItem = _cloneObject(this._options.steps[i]);
        //set the step
        currentItem.step = introItems.length + 1;
        //use querySelector function only when developer used CSS selector
        if (typeof(currentItem.element) === 'string') {
          //grab the element with given selector from the page
          currentItem.element = document.querySelector(currentItem.element);
        }

        //intro without element
        if (typeof(currentItem.element) === 'undefined' || currentItem.element == null) {
          var floatingElementQuery = document.querySelector(".introjsFloatingElement");

          if (floatingElementQuery == null) {
            floatingElementQuery = document.createElement('div');
            floatingElementQuery.className = 'introjsFloatingElement';

            document.body.appendChild(floatingElementQuery);
          }

          currentItem.element  = floatingElementQuery;
          currentItem.position = 'floating';
        }

        if (currentItem.element != null) {
          introItems.push(currentItem);
        }
      }

    } else {
      //use steps from data-* annotations
      var allIntroSteps = targetElm.querySelectorAll('*[data-intro]');
      //if there's no element to intro
      if (allIntroSteps.length < 1) {
        return false;
      }

      //first add intro items with data-step
      for (var i = 0, elmsLength = allIntroSteps.length; i < elmsLength; i++) {
        var currentElement = allIntroSteps[i];
        var step = parseInt(currentElement.getAttribute('data-step'), 10);

        if (step > 0) {
          introItems[step - 1] = {
            element: currentElement,
            intro: currentElement.getAttribute('data-intro'),
            step: parseInt(currentElement.getAttribute('data-step'), 10),
            tooltipClass: currentElement.getAttribute('data-tooltipClass'),
            highlightClass: currentElement.getAttribute('data-highlightClass'),
            position: currentElement.getAttribute('data-position') || this._options.tooltipPosition
          };
        }
      }

      //next add intro items without data-step
      //todo: we need a cleanup here, two loops are redundant
      var nextStep = 0;
      for (var i = 0, elmsLength = allIntroSteps.length; i < elmsLength; i++) {
        var currentElement = allIntroSteps[i];

        if (currentElement.getAttribute('data-step') == null) {

          while (true) {
            if (typeof introItems[nextStep] == 'undefined') {
              break;
            } else {
              nextStep++;
            }
          }

          introItems[nextStep] = {
            element: currentElement,
            intro: currentElement.getAttribute('data-intro'),
            step: nextStep + 1,
            tooltipClass: currentElement.getAttribute('data-tooltipClass'),
            highlightClass: currentElement.getAttribute('data-highlightClass'),
            position: currentElement.getAttribute('data-position') || this._options.tooltipPosition
          };
        }
      }
    }

    //removing undefined/null elements
    var tempIntroItems = [];
    for (var z = 0; z < introItems.length; z++) {
      introItems[z] && tempIntroItems.push(introItems[z]);  // copy non-empty values to the end of the array
    }

    introItems = tempIntroItems;

    //Ok, sort all items with given steps
    introItems.sort(function (a, b) {
      return a.step - b.step;
    });

    //set it to the introJs object
    self._introItems = introItems;

    //add overlay layer to the page
    if(_addOverlayLayer.call(self, targetElm)) {
      //then, start the show
      _nextStep.call(self);

      var skipButton     = targetElm.querySelector('.introjs-skipbutton'),
          nextStepButton = targetElm.querySelector('.introjs-nextbutton');

      self._onKeyDown = function(e) {
        if (e.keyCode === 27 && self._options.exitOnEsc == true) {
          //escape key pressed, exit the intro
          //check if exit callback is defined
          if (self._introExitCallback != undefined) {
            self._introExitCallback.call(self);
          }
          _exitIntro.call(self, targetElm);
        } else if(e.keyCode === 37) {
          //left arrow
          _previousStep.call(self);
        } else if (e.keyCode === 39) {
          //right arrow
          _nextStep.call(self);
        } else if (e.keyCode === 13) {
          //srcElement === ie
          var target = e.target || e.srcElement;
          if (target && target.className.indexOf('introjs-prevbutton') > 0) {
            //user hit enter while focusing on previous button
            _previousStep.call(self);
          } else if (target && target.className.indexOf('introjs-skipbutton') > 0) {
            //user hit enter while focusing on skip button
            if (self._introItems.length - 1 == self._currentStep && typeof (self._introCompleteCallback) === 'function') {
                self._introCompleteCallback.call(self);
            }
            //check if any callback is defined
            if (self._introExitCallback != undefined) {
              self._introExitCallback.call(self);
            }
            _exitIntro.call(self, targetElm);
          } else {
            //default behavior for responding to enter
            _nextStep.call(self);
          }

          //prevent default behaviour on hitting Enter, to prevent steps being skipped in some browsers
          if(e.preventDefault) {
            e.preventDefault();
          } else {
            e.returnValue = false;
          }
        }
      };

      self._onResize = function(e) {
        _setHelperLayerPosition.call(self, document.querySelector('.introjs-helperLayer'));
        _setHelperLayerPosition.call(self, document.querySelector('.introjs-tooltipReferenceLayer'));
      };

      if (window.addEventListener) {
        if (this._options.keyboardNavigation) {
          window.addEventListener('keydown', self._onKeyDown, true);
        }
        //for window resize
        window.addEventListener('resize', self._onResize, true);
      } else if (document.attachEvent) { //IE
        if (this._options.keyboardNavigation) {
          document.attachEvent('onkeydown', self._onKeyDown);
        }
        //for window resize
        document.attachEvent('onresize', self._onResize);
      }
    }
    return false;
  }

 /*
   * makes a copy of the object
   * @api private
   * @method _cloneObject
  */
  function _cloneObject(object) {
      if (object == null || typeof (object) != 'object' || typeof (object.nodeType) != 'undefined') {
        return object;
      }
      var temp = {};
      for (var key in object) {
        if (typeof (jQuery) != 'undefined' && object[key] instanceof jQuery) {
          temp[key] = object[key];
        } else {
          temp[key] = _cloneObject(object[key]);
        }
      }
      return temp;
  }
  /**
   * Go to specific step of introduction
   *
   * @api private
   * @method _goToStep
   */
  function _goToStep(step) {
    //because steps starts with zero
    this._currentStep = step - 2;
    if (typeof (this._introItems) !== 'undefined') {
      _nextStep.call(this);
    }
  }

  /**
   * Go to next step on intro
   *
   * @api private
   * @method _nextStep
   */
  function _nextStep() {
    this._direction = 'forward';

    if (typeof (this._currentStep) === 'undefined') {
      this._currentStep = 0;
    } else {
      ++this._currentStep;
    }

    if ((this._introItems.length) <= this._currentStep) {
      //end of the intro
      //check if any callback is defined
      if (typeof (this._introCompleteCallback) === 'function') {
        this._introCompleteCallback.call(this);
      }
      _exitIntro.call(this, this._targetElement);
      return;
    }

    var nextStep = this._introItems[this._currentStep];
    if (typeof (this._introBeforeChangeCallback) !== 'undefined') {
      this._introBeforeChangeCallback.call(this, nextStep.element);
    }

    _showElement.call(this, nextStep);
  }

  /**
   * Go to previous step on intro
   *
   * @api private
   * @method _nextStep
   */
  function _previousStep() {
    this._direction = 'backward';

    if (this._currentStep === 0) {
      return false;
    }

    var nextStep = this._introItems[--this._currentStep];
    if (typeof (this._introBeforeChangeCallback) !== 'undefined') {
      this._introBeforeChangeCallback.call(this, nextStep.element);
    }

    _showElement.call(this, nextStep);
  }

  /**
   * Exit from intro
   *
   * @api private
   * @method _exitIntro
   * @param {Object} targetElement
   */
  function _exitIntro(targetElement) {
    //remove overlay layer from the page
    var overlayLayer = targetElement.querySelector('.introjs-overlay');

    //return if intro already completed or skipped
    if (overlayLayer == null) {
      return;
    }

    //for fade-out animation
    overlayLayer.style.opacity = 0;
    setTimeout(function () {
      if (overlayLayer.parentNode) {
        overlayLayer.parentNode.removeChild(overlayLayer);
      }
    }, 500);

    //remove all helper layers
    var helperLayer = targetElement.querySelector('.introjs-helperLayer');
    if (helperLayer) {
      helperLayer.parentNode.removeChild(helperLayer);
    }

    var referenceLayer = targetElement.querySelector('.introjs-tooltipReferenceLayer');
    if (referenceLayer) {
      referenceLayer.parentNode.removeChild(referenceLayer);
    }
    //remove disableInteractionLayer
    var disableInteractionLayer = targetElement.querySelector('.introjs-disableInteraction');
    if (disableInteractionLayer) {
      disableInteractionLayer.parentNode.removeChild(disableInteractionLayer);
    }

    //remove intro floating element
    var floatingElement = document.querySelector('.introjsFloatingElement');
    if (floatingElement) {
      floatingElement.parentNode.removeChild(floatingElement);
    }

    //remove `introjs-showElement` class from the element
    var showElement = document.querySelector('.introjs-showElement');
    if (showElement) {
      showElement.className = showElement.className.replace(/introjs-[a-zA-Z]+/g, '').replace(/^\s+|\s+$/g, ''); // This is a manual trim.
    }

    //remove `introjs-fixParent` class from the elements
    var fixParents = document.querySelectorAll('.introjs-fixParent');
    if (fixParents && fixParents.length > 0) {
      for (var i = fixParents.length - 1; i >= 0; i--) {
        fixParents[i].className = fixParents[i].className.replace(/introjs-fixParent/g, '').replace(/^\s+|\s+$/g, '');
      }
    }

    //clean listeners
    if (window.removeEventListener) {
      window.removeEventListener('keydown', this._onKeyDown, true);
    } else if (document.detachEvent) { //IE
      document.detachEvent('onkeydown', this._onKeyDown);
    }

    //set the step to zero
    this._currentStep = undefined;
  }

  /**
   * Render tooltip box in the page
   *
   * @api private
   * @method _placeTooltip
   * @param {HTMLElement} targetElement
   * @param {HTMLElement} tooltipLayer
   * @param {HTMLElement} arrowLayer
   * @param {HTMLElement} helperNumberLayer
   * @param {Boolean} hintMode
   */
  function _placeTooltip(targetElement, tooltipLayer, arrowLayer, helperNumberLayer, hintMode) {
    var tooltipCssClass = '',
        currentStepObj,
        tooltipOffset,
        targetOffset,
        windowSize,
        currentTooltipPosition;

    hintMode = hintMode || false;

    //reset the old style
    tooltipLayer.style.top        = null;
    tooltipLayer.style.right      = null;
    tooltipLayer.style.bottom     = null;
    tooltipLayer.style.left       = null;
    tooltipLayer.style.marginLeft = null;
    tooltipLayer.style.marginTop  = null;

    arrowLayer.style.display = 'inherit';

    if (typeof(helperNumberLayer) != 'undefined' && helperNumberLayer != null) {
      helperNumberLayer.style.top  = null;
      helperNumberLayer.style.left = null;
    }

    //prevent error when `this._currentStep` is undefined
    if (!this._introItems[this._currentStep]) return;

    //if we have a custom css class for each step
    currentStepObj = this._introItems[this._currentStep];
    if (typeof (currentStepObj.tooltipClass) === 'string') {
      tooltipCssClass = currentStepObj.tooltipClass;
    } else {
      tooltipCssClass = this._options.tooltipClass;
    }

    tooltipLayer.className = ('introjs-tooltip ' + tooltipCssClass).replace(/^\s+|\s+$/g, '');

    currentTooltipPosition = this._introItems[this._currentStep].position;
    if ((currentTooltipPosition == "auto" || this._options.tooltipPosition == "auto")) {
      if (currentTooltipPosition != "floating") { // Floating is always valid, no point in calculating
        currentTooltipPosition = _determineAutoPosition.call(this, targetElement, tooltipLayer, currentTooltipPosition);
      }
    }
    targetOffset  = _getOffset(targetElement);
    tooltipOffset = _getOffset(tooltipLayer);
    windowSize    = _getWinSize();

    switch (currentTooltipPosition) {
      case 'top':
        arrowLayer.className = 'introjs-arrow bottom';

        if (hintMode) {
          var tooltipLayerStyleLeft = 0;
        } else {
          var tooltipLayerStyleLeft = 15;
        }

        _checkRight(targetOffset, tooltipLayerStyleLeft, tooltipOffset, windowSize, tooltipLayer);
        tooltipLayer.style.bottom = (targetOffset.height +  20) + 'px';
        break;
      case 'right':
        tooltipLayer.style.left = (targetOffset.width + 20) + 'px';
        if (targetOffset.top + tooltipOffset.height > windowSize.height) {
          // In this case, right would have fallen below the bottom of the screen.
          // Modify so that the bottom of the tooltip connects with the target
          arrowLayer.className = "introjs-arrow left-bottom";
          tooltipLayer.style.top = "-" + (tooltipOffset.height - targetOffset.height - 20) + "px";
        } else {
          arrowLayer.className = 'introjs-arrow left';
        }
        break;
      case 'left':
        if (!hintMode && this._options.showStepNumbers == true) {
          tooltipLayer.style.top = '15px';
        }

        if (targetOffset.top + tooltipOffset.height > windowSize.height) {
          // In this case, left would have fallen below the bottom of the screen.
          // Modify so that the bottom of the tooltip connects with the target
          tooltipLayer.style.top = "-" + (tooltipOffset.height - targetOffset.height - 20) + "px";
          arrowLayer.className = 'introjs-arrow right-bottom';
        } else {
          arrowLayer.className = 'introjs-arrow right';
        }
        tooltipLayer.style.right = (targetOffset.width + 20) + 'px';

        break;
      case 'floating':
        arrowLayer.style.display = 'none';

        //we have to adjust the top and left of layer manually for intro items without element
        tooltipLayer.style.left   = '50%';
        tooltipLayer.style.top    = '50%';
        tooltipLayer.style.marginLeft = '-' + (tooltipOffset.width / 2)  + 'px';
        tooltipLayer.style.marginTop  = '-' + (tooltipOffset.height / 2) + 'px';

        if (typeof(helperNumberLayer) != 'undefined' && helperNumberLayer != null) {
          helperNumberLayer.style.left = '-' + ((tooltipOffset.width / 2) + 18) + 'px';
          helperNumberLayer.style.top  = '-' + ((tooltipOffset.height / 2) + 18) + 'px';
        }

        break;
      case 'bottom-right-aligned':
        arrowLayer.className      = 'introjs-arrow top-right';

        var tooltipLayerStyleRight = 0;
        _checkLeft(targetOffset, tooltipLayerStyleRight, tooltipOffset, tooltipLayer);
        tooltipLayer.style.top    = (targetOffset.height +  20) + 'px';
        break;

      case 'bottom-middle-aligned':
        arrowLayer.className      = 'introjs-arrow top-middle';

        var tooltipLayerStyleLeftRight = targetOffset.width / 2 - tooltipOffset.width / 2;

        // a fix for middle aligned hints
        if (hintMode) {
          tooltipLayerStyleLeftRight += 5;
        }

        if (_checkLeft(targetOffset, tooltipLayerStyleLeftRight, tooltipOffset, tooltipLayer)) {
          tooltipLayer.style.right = null;
          _checkRight(targetOffset, tooltipLayerStyleLeftRight, tooltipOffset, windowSize, tooltipLayer);
        }
        tooltipLayer.style.top = (targetOffset.height + 20) + 'px';
        break;

      case 'bottom-left-aligned':
      // Bottom-left-aligned is the same as the default bottom
      case 'bottom':
      // Bottom going to follow the default behavior
      default:
        arrowLayer.className = 'introjs-arrow top';

        var tooltipLayerStyleLeft = 0;
        _checkRight(targetOffset, tooltipLayerStyleLeft, tooltipOffset, windowSize, tooltipLayer);
        tooltipLayer.style.top    = (targetOffset.height +  20) + 'px';
        break;
    }
  }

  /**
   * Set tooltip left so it doesn't go off the right side of the window
   *
   * @return boolean true, if tooltipLayerStyleLeft is ok.  false, otherwise.
   */
  function _checkRight(targetOffset, tooltipLayerStyleLeft, tooltipOffset, windowSize, tooltipLayer) {
    if (targetOffset.left + tooltipLayerStyleLeft + tooltipOffset.width > windowSize.width) {
      // off the right side of the window
      tooltipLayer.style.left = (windowSize.width - tooltipOffset.width - targetOffset.left) + 'px';
      return false;
    }
    tooltipLayer.style.left = tooltipLayerStyleLeft + 'px';
    return true;
  }

  /**
   * Set tooltip right so it doesn't go off the left side of the window
   *
   * @return boolean true, if tooltipLayerStyleRight is ok.  false, otherwise.
   */
  function _checkLeft(targetOffset, tooltipLayerStyleRight, tooltipOffset, tooltipLayer) {
    if (targetOffset.left + targetOffset.width - tooltipLayerStyleRight - tooltipOffset.width < 0) {
      // off the left side of the window
      tooltipLayer.style.left = (-targetOffset.left) + 'px';
      return false;
    }
    tooltipLayer.style.right = tooltipLayerStyleRight + 'px';
    return true;
  }

  /**
   * Determines the position of the tooltip based on the position precedence and availability
   * of screen space.
   *
   * @param {Object} targetElement
   * @param {Object} tooltipLayer
   * @param {Object} desiredTooltipPosition
   *
   */
  function _determineAutoPosition(targetElement, tooltipLayer, desiredTooltipPosition) {

    // Take a clone of position precedence. These will be the available
    var possiblePositions = this._options.positionPrecedence.slice();

    var windowSize = _getWinSize();
    var tooltipHeight = _getOffset(tooltipLayer).height + 10;
    var tooltipWidth = _getOffset(tooltipLayer).width + 20;
    var targetOffset = _getOffset(targetElement);

    // If we check all the possible areas, and there are no valid places for the tooltip, the element
    // must take up most of the screen real estate. Show the tooltip floating in the middle of the screen.
    var calculatedPosition = "floating";

    // Check if the width of the tooltip + the starting point would spill off the right side of the screen
    // If no, neither bottom or top are valid
    if (targetOffset.left + tooltipWidth > windowSize.width || ((targetOffset.left + (targetOffset.width / 2)) - tooltipWidth) < 0) {
      _removeEntry(possiblePositions, "bottom");
      _removeEntry(possiblePositions, "top");
    } else {
      // Check for space below
      if ((targetOffset.height + targetOffset.top + tooltipHeight) > windowSize.height) {
        _removeEntry(possiblePositions, "bottom");
      }

      // Check for space above
      if (targetOffset.top - tooltipHeight < 0) {
        _removeEntry(possiblePositions, "top");
      }
    }

    // Check for space to the right
    if (targetOffset.width + targetOffset.left + tooltipWidth > windowSize.width) {
      _removeEntry(possiblePositions, "right");
    }

    // Check for space to the left
    if (targetOffset.left - tooltipWidth < 0) {
      _removeEntry(possiblePositions, "left");
    }

    // At this point, our array only has positions that are valid. Pick the first one, as it remains in order
    if (possiblePositions.length > 0) {
      calculatedPosition = possiblePositions[0];
    }

    // If the requested position is in the list, replace our calculated choice with that
    if (desiredTooltipPosition && desiredTooltipPosition != "auto") {
      if (possiblePositions.indexOf(desiredTooltipPosition) > -1) {
        calculatedPosition = desiredTooltipPosition;
      }
    }

    return calculatedPosition;
  }

  /**
   * Remove an entry from a string array if it's there, does nothing if it isn't there.
   *
   * @param {Array} stringArray
   * @param {String} stringToRemove
   */
  function _removeEntry(stringArray, stringToRemove) {
    if (stringArray.indexOf(stringToRemove) > -1) {
      stringArray.splice(stringArray.indexOf(stringToRemove), 1);
    }
  }

  /**
   * Update the position of the helper layer on the screen
   *
   * @api private
   * @method _setHelperLayerPosition
   * @param {Object} helperLayer
   */
  function _setHelperLayerPosition(helperLayer) {
    if (helperLayer) {
      //prevent error when `this._currentStep` in undefined
      if (!this._introItems[this._currentStep]) return;

      var currentElement  = this._introItems[this._currentStep],
          elementPosition = _getOffset(currentElement.element),
          widthHeightPadding = 10;

      // if the target element is fixed, the tooltip should be fixed as well.
      if (_isFixed(currentElement.element)) {
        helperLayer.className += ' introjs-fixedTooltip';
      }

      if (currentElement.position == 'floating') {
        widthHeightPadding = 0;
      }

      //set new position to helper layer
      helperLayer.setAttribute('style', 'width: ' + (elementPosition.width  + widthHeightPadding)  + 'px; ' +
                                        'height:' + (elementPosition.height + widthHeightPadding)  + 'px; ' +
                                        'top:'    + (elementPosition.top    - 5)   + 'px;' +
                                        'left: '  + (elementPosition.left   - 5)   + 'px;');

    }
  }

  /**
   * Add disableinteraction layer and adjust the size and position of the layer
   *
   * @api private
   * @method _disableInteraction
   */
  function _disableInteraction() {
    var disableInteractionLayer = document.querySelector('.introjs-disableInteraction');
    if (disableInteractionLayer === null) {
      disableInteractionLayer = document.createElement('div');
      disableInteractionLayer.className = 'introjs-disableInteraction';
      this._targetElement.appendChild(disableInteractionLayer);
    }

    _setHelperLayerPosition.call(this, disableInteractionLayer);
  }

  /**
   * Show an element on the page
   *
   * @api private
   * @method _showElement
   * @param {Object} targetElement
   */
  function _showElement(targetElement) {

    if (typeof (this._introChangeCallback) !== 'undefined') {
      this._introChangeCallback.call(this, targetElement.element);
    }

    var self = this,
        oldHelperLayer = document.querySelector('.introjs-helperLayer'),
        oldReferenceLayer = document.querySelector('.introjs-tooltipReferenceLayer'),
        highlightClass = 'introjs-helperLayer',
        elementPosition = _getOffset(targetElement.element);

    //check for a current step highlight class
    if (typeof (targetElement.highlightClass) === 'string') {
      highlightClass += (' ' + targetElement.highlightClass);
    }
    //check for options highlight class
    if (typeof (this._options.highlightClass) === 'string') {
      highlightClass += (' ' + this._options.highlightClass);
    }

    if (oldHelperLayer != null) {
      var oldHelperNumberLayer = oldReferenceLayer.querySelector('.introjs-helperNumberLayer'),
          oldtooltipLayer      = oldReferenceLayer.querySelector('.introjs-tooltiptext'),
          oldArrowLayer        = oldReferenceLayer.querySelector('.introjs-arrow'),
          oldtooltipContainer  = oldReferenceLayer.querySelector('.introjs-tooltip'),
          skipTooltipButton    = oldReferenceLayer.querySelector('.introjs-skipbutton'),
          prevTooltipButton    = oldReferenceLayer.querySelector('.introjs-prevbutton'),
          nextTooltipButton    = oldReferenceLayer.querySelector('.introjs-nextbutton');

      //update or reset the helper highlight class
      oldHelperLayer.className = highlightClass;
      //hide the tooltip
      oldtooltipContainer.style.opacity = 0;
      oldtooltipContainer.style.display = "none";

      if (oldHelperNumberLayer != null) {
        var lastIntroItem = this._introItems[(targetElement.step - 2 >= 0 ? targetElement.step - 2 : 0)];

        if (lastIntroItem != null && (this._direction == 'forward' && lastIntroItem.position == 'floating') || (this._direction == 'backward' && targetElement.position == 'floating')) {
          oldHelperNumberLayer.style.opacity = 0;
        }
      }

      //set new position to helper layer
      _setHelperLayerPosition.call(self, oldHelperLayer);
      _setHelperLayerPosition.call(self, oldReferenceLayer);

      //remove `introjs-fixParent` class from the elements
      var fixParents = document.querySelectorAll('.introjs-fixParent');
      if (fixParents && fixParents.length > 0) {
        for (var i = fixParents.length - 1; i >= 0; i--) {
          fixParents[i].className = fixParents[i].className.replace(/introjs-fixParent/g, '').replace(/^\s+|\s+$/g, '');
        };
      }

      //remove old classes
      var oldShowElement = document.querySelector('.introjs-showElement');
      oldShowElement.className = oldShowElement.className.replace(/introjs-[a-zA-Z]+/g, '').replace(/^\s+|\s+$/g, '');

      //we should wait until the CSS3 transition is competed (it's 0.3 sec) to prevent incorrect `height` and `width` calculation
      if (self._lastShowElementTimer) {
        clearTimeout(self._lastShowElementTimer);
      }
      self._lastShowElementTimer = setTimeout(function() {
        //set current step to the label
        if (oldHelperNumberLayer != null) {
          oldHelperNumberLayer.innerHTML = targetElement.step;
        }
        //set current tooltip text
        oldtooltipLayer.innerHTML = targetElement.intro;
        //set the tooltip position
        oldtooltipContainer.style.display = "block";
        _placeTooltip.call(self, targetElement.element, oldtooltipContainer, oldArrowLayer, oldHelperNumberLayer);

        //change active bullet
        oldReferenceLayer.querySelector('.introjs-bullets li > a.active').className = '';
        oldReferenceLayer.querySelector('.introjs-bullets li > a[data-stepnumber="' + targetElement.step + '"]').className = 'active';

        oldReferenceLayer.querySelector('.introjs-progress .introjs-progressbar').setAttribute('style', 'width:' + _getProgress.call(self) + '%;');

        //show the tooltip
        oldtooltipContainer.style.opacity = 1;
        if (oldHelperNumberLayer) oldHelperNumberLayer.style.opacity = 1;

        //reset button focus
        if (nextTooltipButton.tabIndex === -1) {
          //tabindex of -1 means we are at the end of the tour - focus on skip / done
          skipTooltipButton.focus();
        } else {
          //still in the tour, focus on next
          nextTooltipButton.focus();
        }
      }, 350);

    } else {
      var helperLayer       = document.createElement('div'),
          referenceLayer    = document.createElement('div'),
          arrowLayer        = document.createElement('div'),
          tooltipLayer      = document.createElement('div'),
          tooltipTextLayer  = document.createElement('div'),
          bulletsLayer      = document.createElement('div'),
          progressLayer     = document.createElement('div'),
          buttonsLayer      = document.createElement('div');

      helperLayer.className = highlightClass;
      referenceLayer.className = 'introjs-tooltipReferenceLayer';

      //set new position to helper layer
      _setHelperLayerPosition.call(self, helperLayer);
      _setHelperLayerPosition.call(self, referenceLayer);

      //add helper layer to target element
      this._targetElement.appendChild(helperLayer);
      this._targetElement.appendChild(referenceLayer);

      arrowLayer.className = 'introjs-arrow';

      tooltipTextLayer.className = 'introjs-tooltiptext';
      tooltipTextLayer.innerHTML = targetElement.intro;

      bulletsLayer.className = 'introjs-bullets';

      if (this._options.showBullets === false) {
        bulletsLayer.style.display = 'none';
      }

      var ulContainer = document.createElement('ul');

      for (var i = 0, stepsLength = this._introItems.length; i < stepsLength; i++) {
        var innerLi    = document.createElement('li');
        var anchorLink = document.createElement('a');

        anchorLink.onclick = function() {
          self.goToStep(this.getAttribute('data-stepnumber'));
        };

        if (i === (targetElement.step-1)) anchorLink.className = 'active';

        anchorLink.href = 'javascript:void(0);';
        anchorLink.innerHTML = "&nbsp;";
        anchorLink.setAttribute('data-stepnumber', this._introItems[i].step);

        innerLi.appendChild(anchorLink);
        ulContainer.appendChild(innerLi);
      }

      bulletsLayer.appendChild(ulContainer);

      progressLayer.className = 'introjs-progress';

      if (this._options.showProgress === false) {
        progressLayer.style.display = 'none';
      }
      var progressBar = document.createElement('div');
      progressBar.className = 'introjs-progressbar';
      progressBar.setAttribute('style', 'width:' + _getProgress.call(this) + '%;');

      progressLayer.appendChild(progressBar);

      buttonsLayer.className = 'introjs-tooltipbuttons';
      if (this._options.showButtons === false) {
        buttonsLayer.style.display = 'none';
      }

      tooltipLayer.className = 'introjs-tooltip';
      tooltipLayer.appendChild(tooltipTextLayer);
      tooltipLayer.appendChild(bulletsLayer);
      tooltipLayer.appendChild(progressLayer);

      //add helper layer number
      if (this._options.showStepNumbers == true) {
        var helperNumberLayer = document.createElement('span');
        helperNumberLayer.className = 'introjs-helperNumberLayer';
        helperNumberLayer.innerHTML = targetElement.step;
        referenceLayer.appendChild(helperNumberLayer);
      }

      tooltipLayer.appendChild(arrowLayer);
      referenceLayer.appendChild(tooltipLayer);

      //next button
      var nextTooltipButton = document.createElement('a');

      nextTooltipButton.onclick = function() {
        if (self._introItems.length - 1 != self._currentStep) {
          _nextStep.call(self);
        }
      };

      nextTooltipButton.href = 'javascript:void(0);';
      nextTooltipButton.innerHTML = this._options.nextLabel;

      //previous button
      var prevTooltipButton = document.createElement('a');

      prevTooltipButton.onclick = function() {
        if (self._currentStep != 0) {
          _previousStep.call(self);
        }
      };

      prevTooltipButton.href = 'javascript:void(0);';
      prevTooltipButton.innerHTML = this._options.prevLabel;

      //skip button
      var skipTooltipButton = document.createElement('a');
      skipTooltipButton.className = 'introjs-button introjs-skipbutton';
      skipTooltipButton.href = 'javascript:void(0);';
      skipTooltipButton.innerHTML = this._options.skipLabel;

      skipTooltipButton.onclick = function() {
        if (self._introItems.length - 1 == self._currentStep && typeof (self._introCompleteCallback) === 'function') {
          self._introCompleteCallback.call(self);
        }

        if (self._introItems.length - 1 != self._currentStep && typeof (self._introExitCallback) === 'function') {
          self._introExitCallback.call(self);
        }

        _exitIntro.call(self, self._targetElement);
      };

      buttonsLayer.appendChild(skipTooltipButton);

      //in order to prevent displaying next/previous button always
      if (this._introItems.length > 1) {
        buttonsLayer.appendChild(prevTooltipButton);
        buttonsLayer.appendChild(nextTooltipButton);
      }

      tooltipLayer.appendChild(buttonsLayer);

      //set proper position
      _placeTooltip.call(self, targetElement.element, tooltipLayer, arrowLayer, helperNumberLayer);
    }

    //disable interaction
    if (this._options.disableInteraction === true) {
      _disableInteraction.call(self);
    }

    prevTooltipButton.removeAttribute('tabIndex');
    nextTooltipButton.removeAttribute('tabIndex');

    if (this._currentStep == 0 && this._introItems.length > 1) {
      prevTooltipButton.className = 'introjs-button introjs-prevbutton introjs-disabled';
      prevTooltipButton.tabIndex = '-1';
      nextTooltipButton.className = 'introjs-button introjs-nextbutton';
      skipTooltipButton.innerHTML = this._options.skipLabel;
    } else if (this._introItems.length - 1 == this._currentStep || this._introItems.length == 1) {
      skipTooltipButton.innerHTML = this._options.doneLabel;
      prevTooltipButton.className = 'introjs-button introjs-prevbutton';
      nextTooltipButton.className = 'introjs-button introjs-nextbutton introjs-disabled';
      nextTooltipButton.tabIndex = '-1';
    } else {
      prevTooltipButton.className = 'introjs-button introjs-prevbutton';
      nextTooltipButton.className = 'introjs-button introjs-nextbutton';
      skipTooltipButton.innerHTML = this._options.skipLabel;
    }

    //Set focus on "next" button, so that hitting Enter always moves you onto the next step
    nextTooltipButton.focus();

    //add target element position style
    targetElement.element.className += ' introjs-showElement';

    var currentElementPosition = _getPropValue(targetElement.element, 'position');
    if (currentElementPosition !== 'absolute' &&
        currentElementPosition !== 'relative') {
      //change to new intro item
      targetElement.element.className += ' introjs-relativePosition';
    }

    var parentElm = targetElement.element.parentNode;
    while (parentElm != null) {
      if (parentElm.tagName.toLowerCase() === 'body') break;

      //fix The Stacking Contenxt problem.
      //More detail: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context
      var zIndex = _getPropValue(parentElm, 'z-index');
      var opacity = parseFloat(_getPropValue(parentElm, 'opacity'));
      var transform = _getPropValue(parentElm, 'transform') || _getPropValue(parentElm, '-webkit-transform') || _getPropValue(parentElm, '-moz-transform') || _getPropValue(parentElm, '-ms-transform') || _getPropValue(parentElm, '-o-transform');
      if (/[0-9]+/.test(zIndex) || opacity < 1 || (transform !== 'none' && transform !== undefined)) {
        parentElm.className += ' introjs-fixParent';
      }

      parentElm = parentElm.parentNode;
    }

    if (!_elementInViewport(targetElement.element) && this._options.scrollToElement === true) {
      var rect = targetElement.element.getBoundingClientRect(),
        winHeight = _getWinSize().height,
        top = rect.bottom - (rect.bottom - rect.top),
        bottom = rect.bottom - winHeight;

      //Scroll up
      if (top < 0 || targetElement.element.clientHeight > winHeight) {
        window.scrollBy(0, top - 30); // 30px padding from edge to look nice

      //Scroll down
      } else {
        window.scrollBy(0, bottom + 100); // 70px + 30px padding from edge to look nice
      }
    }

    if (typeof (this._introAfterChangeCallback) !== 'undefined') {
      this._introAfterChangeCallback.call(this, targetElement.element);
    }
  }

  /**
   * Get an element CSS property on the page
   * Thanks to JavaScript Kit: http://www.javascriptkit.com/dhtmltutors/dhtmlcascade4.shtml
   *
   * @api private
   * @method _getPropValue
   * @param {Object} element
   * @param {String} propName
   * @returns Element's property value
   */
  function _getPropValue (element, propName) {
    var propValue = '';
    if (element.currentStyle) { //IE
      propValue = element.currentStyle[propName];
    } else if (document.defaultView && document.defaultView.getComputedStyle) { //Others
      propValue = document.defaultView.getComputedStyle(element, null).getPropertyValue(propName);
    }

    //Prevent exception in IE
    if (propValue && propValue.toLowerCase) {
      return propValue.toLowerCase();
    } else {
      return propValue;
    }
  };

  /**
   * Checks to see if target element (or parents) position is fixed or not
   *
   * @api private
   * @method _isFixed
   * @param {Object} element
   * @returns Boolean
   */
  function _isFixed (element) {
    var p = element.parentNode;

    if (p.nodeName === 'HTML') {
      return false;
    }

    if (_getPropValue(element, 'position') == 'fixed') {
      return true;
    }

    return _isFixed(p);
  };

  /**
   * Provides a cross-browser way to get the screen dimensions
   * via: http://stackoverflow.com/questions/5864467/internet-explorer-innerheight
   *
   * @api private
   * @method _getWinSize
   * @returns {Object} width and height attributes
   */
  function _getWinSize() {
    if (window.innerWidth != undefined) {
      return { width: window.innerWidth, height: window.innerHeight };
    } else {
      var D = document.documentElement;
      return { width: D.clientWidth, height: D.clientHeight };
    }
  }

  /**
   * Add overlay layer to the page
   * http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
   *
   * @api private
   * @method _elementInViewport
   * @param {Object} el
   */
  function _elementInViewport(el) {
    var rect = el.getBoundingClientRect();

    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      (rect.bottom+80) <= window.innerHeight && // add 80 to get the text right
      rect.right <= window.innerWidth
    );
  }

  /**
   * Add overlay layer to the page
   *
   * @api private
   * @method _addOverlayLayer
   * @param {Object} targetElm
   */
  function _addOverlayLayer(targetElm) {
    var overlayLayer = document.createElement('div'),
        styleText = '',
        self = this;

    //set css class name
    overlayLayer.className = 'introjs-overlay';

    //check if the target element is body, we should calculate the size of overlay layer in a better way
    if (targetElm.tagName.toLowerCase() === 'body') {
      styleText += 'top: 0;bottom: 0; left: 0;right: 0;position: fixed;';
      overlayLayer.setAttribute('style', styleText);
    } else {
      //set overlay layer position
      var elementPosition = _getOffset(targetElm);
      if (elementPosition) {
        styleText += 'width: ' + elementPosition.width + 'px; height:' + elementPosition.height + 'px; top:' + elementPosition.top + 'px;left: ' + elementPosition.left + 'px;';
        overlayLayer.setAttribute('style', styleText);
      }
    }

    targetElm.appendChild(overlayLayer);

    overlayLayer.onclick = function() {
      if (self._options.exitOnOverlayClick == true) {

        //check if any callback is defined
        if (self._introExitCallback != undefined) {
          self._introExitCallback.call(self);
        }
        _exitIntro.call(self, targetElm);
      }
    };

    setTimeout(function() {
      styleText += 'opacity: ' + self._options.overlayOpacity.toString() + ';';
      overlayLayer.setAttribute('style', styleText);
    }, 10);

    return true;
  };

  /**
   * Removes open hint (tooltip hint)
   *
   * @api private
   * @method _removeHintTooltip
   */
  function _removeHintTooltip() {
    var tooltip = this._targetElement.querySelector('.introjs-hintReference');


    if (tooltip) {
      var step = tooltip.getAttribute('data-step');
      tooltip.parentNode.removeChild(tooltip);
      return step;
    }
  };

  /**
   * Start parsing hint items
   *
   * @api private
   * @param {Object} targetElm
   * @method _startHint
   */
  function _populateHints(targetElm) {
    var self = this;
    this._introItems = []

    if (this._options.hints) {
      for (var i = 0, l = this._options.hints.length; i < l; i++) {
        var currentItem = _cloneObject(this._options.hints[i]);

        if (typeof(currentItem.element) === 'string') {
          //grab the element with given selector from the page
          currentItem.element = document.querySelector(currentItem.element);
        }

        currentItem.hintPosition = currentItem.hintPosition || 'top-middle';

        if (currentItem.element != null) {
          this._introItems.push(currentItem);
        }
      }
    } else {
      var hints = targetElm.querySelectorAll('*[data-hint]');

      if (hints.length < 1) {
        return false;
      }

      //first add intro items with data-step
      for (var i = 0, l = hints.length; i < l; i++) {
        var currentElement = hints[i];

        this._introItems.push({
          element: currentElement,
          hint: currentElement.getAttribute('data-hint'),
          hintPosition: currentElement.getAttribute('data-hintPosition') || this._options.hintPosition,
          tooltipClass: currentElement.getAttribute('data-tooltipClass'),
          position: currentElement.getAttribute('data-position') || this._options.tooltipPosition
        });
      }
    }

    _addHints.call(this);

    if (document.addEventListener) {
      document.addEventListener('click', _removeHintTooltip.bind(this), false);
      //for window resize
      window.addEventListener('resize', _reAlignHints.bind(this), true);
    } else if (document.attachEvent) { //IE
      //for window resize
      document.attachEvent('onclick', _removeHintTooltip.bind(this));
      document.attachEvent('onresize', _reAlignHints.bind(this));
    }
  };

  /**
   * Re-aligns all hint elements
   *
   * @api private
   * @method _reAlignHints
   */
  function _reAlignHints() {
    for (var i = 0, l = this._introItems.length; i < l; i++) {
      var item = this._introItems[i];
      _alignHintPosition.call(this, item.hintPosition, item.element, item.targetElement)
    }
  }

  /**
   * Hide a hint
   *
   * @api private
   * @method _hideHint
   */
  function _hideHint(stepId) {
    _removeHintTooltip.call(this);
    var hint = this._targetElement.querySelector('.introjs-hint[data-step="' + stepId + '"]');

    if (hint) {
      hint.className += ' introjs-hidehint';
    }

    // call the callback function (if any)
    if (typeof (this._hintCloseCallback) !== 'undefined') {
      this._hintCloseCallback.call(this, stepId);
    }
  };

  /**
   * Add all available hints to the page
   *
   * @api private
   * @method _addHints
   */
  function _addHints() {
    var self = this;

    var oldHintsWrapper = document.querySelector('.introjs-hints');

    if (oldHintsWrapper != null) {
      hintsWrapper = oldHintsWrapper;
    } else {
      var hintsWrapper = document.createElement('div');
      hintsWrapper.className = 'introjs-hints';
    }

    for (var i = 0, l = this._introItems.length; i < l; i++) {
      var item = this._introItems[i];

      // avoid append a hint twice
      if (document.querySelector('.introjs-hint[data-step="' + i + '"]'))
        continue;

      var hint = document.createElement('a');
      hint.href = "javascript:void(0);";

      (function (hint, item, i) {
        // when user clicks on the hint element
        hint.onclick = function(e) {
          var evt = e ? e : window.event;
          if (evt.stopPropagation)    evt.stopPropagation();
          if (evt.cancelBubble != null) evt.cancelBubble = true;

          _hintClick.call(self, hint, item, i);
        };
      }(hint, item, i));

      hint.className = 'introjs-hint';

      // hint's position should be fixed if the target element's position is fixed
      if (_isFixed(item.element)) {
        hint.className += ' introjs-fixedhint';
      }

      var hintDot = document.createElement('div');
      hintDot.className = 'introjs-hint-dot';
      var hintPulse = document.createElement('div');
      hintPulse.className = 'introjs-hint-pulse';

      hint.appendChild(hintDot);
      hint.appendChild(hintPulse);
      hint.setAttribute('data-step', i);

      // we swap the hint element with target element
      // because _setHelperLayerPosition uses `element` property
      item.targetElement = item.element;
      item.element = hint;

      // align the hint position
      _alignHintPosition.call(this, item.hintPosition, hint, item.targetElement);

      hintsWrapper.appendChild(hint);
    }

    // adding the hints wrapper
    document.body.appendChild(hintsWrapper);

    // call the callback function (if any)
    if (typeof (this._hintsAddedCallback) !== 'undefined') {
      this._hintsAddedCallback.call(this);
    }
  };

  /**
   * Aligns hint position
   *
   * @api private
   * @method _alignHintPosition
   * @param {String} position
   * @param {Object} hint
   * @param {Object} element
   */
  function _alignHintPosition(position, hint, element) {
    // get/calculate offset of target element
    var offset = _getOffset.call(this, element);

    // align the hint element
    switch (position) {
      default:
      case 'top-left':
        hint.style.left = offset.left + 'px';
        hint.style.top = offset.top + 'px';
        break;
      case 'top-right':
        hint.style.left = (offset.left + offset.width) + 'px';
        hint.style.top = offset.top + 'px';
        break;
      case 'bottom-left':
        hint.style.left = offset.left + 'px';
        hint.style.top = (offset.top + offset.height) + 'px';
        break;
      case 'bottom-right':
        hint.style.left = (offset.left + offset.width) + 'px';
        hint.style.top = (offset.top + offset.height) + 'px';
        break;
      case 'bottom-middle':
        hint.style.left = (offset.left + (offset.width / 2)) + 'px';
        hint.style.top = (offset.top + offset.height) + 'px';
        break;
      case 'top-middle':
        hint.style.left = (offset.left + (offset.width / 2)) + 'px';
        hint.style.top = offset.top + 'px';
        break;
    }
  };

  /**
   * Triggers when user clicks on the hint element
   *
   * @api private
   * @method _hintClick
   * @param {Object} hintElement
   * @param {Object} item
   * @param {Number} stepId
   */
  function _hintClick(hintElement, item, stepId) {
    // call the callback function (if any)
    if (typeof (this._hintClickCallback) !== 'undefined') {
      this._hintClickCallback.call(this, hintElement, item, stepId);
    }

    // remove all open tooltips
    var removedStep = _removeHintTooltip.call(this);

    // to toggle the tooltip
    if (parseInt(removedStep, 10) == stepId) {
      return;
    }

    var tooltipLayer = document.createElement('div');
    var tooltipTextLayer = document.createElement('div');
    var arrowLayer = document.createElement('div');
    var referenceLayer = document.createElement('div');

    tooltipLayer.className = 'introjs-tooltip';

    tooltipLayer.onclick = function (e) {
      //IE9 & Other Browsers
      if (e.stopPropagation) {
        e.stopPropagation();
      }
      //IE8 and Lower
      else {
        e.cancelBubble = true;
      }
    };

    tooltipTextLayer.className = 'introjs-tooltiptext';

    var tooltipWrapper = document.createElement('p');
    tooltipWrapper.innerHTML = item.hint;

    var closeButton = document.createElement('a');
    closeButton.className = 'introjs-button';
    closeButton.innerHTML = this._options.hintButtonLabel;
    closeButton.onclick = _hideHint.bind(this, stepId);

    tooltipTextLayer.appendChild(tooltipWrapper);
    tooltipTextLayer.appendChild(closeButton);

    arrowLayer.className = 'introjs-arrow';
    tooltipLayer.appendChild(arrowLayer);

    tooltipLayer.appendChild(tooltipTextLayer);

    // set current step for _placeTooltip function
    this._currentStep = hintElement.getAttribute('data-step');

    // align reference layer position
    referenceLayer.className = 'introjs-tooltipReferenceLayer introjs-hintReference';
    referenceLayer.setAttribute('data-step', hintElement.getAttribute('data-step'));
    _setHelperLayerPosition.call(this, referenceLayer);

    referenceLayer.appendChild(tooltipLayer);
    document.body.appendChild(referenceLayer);

    //set proper position
    _placeTooltip.call(this, hintElement, tooltipLayer, arrowLayer, null, true);
  };

  /**
   * Get an element position on the page
   * Thanks to `meouw`: http://stackoverflow.com/a/442474/375966
   *
   * @api private
   * @method _getOffset
   * @param {Object} element
   * @returns Element's position info
   */
  function _getOffset(element) {
    var elementPosition = {};

    //set width
    elementPosition.width = element.offsetWidth;

    //set height
    elementPosition.height = element.offsetHeight;

    //calculate element top and left
    var _x = 0;
    var _y = 0;
    while (element && !isNaN(element.offsetLeft) && !isNaN(element.offsetTop)) {
      _x += element.offsetLeft;
      _y += element.offsetTop;
      element = element.offsetParent;
    }
    //set top
    elementPosition.top = _y;
    //set left
    elementPosition.left = _x;

    return elementPosition;
  };

  /**
   * Gets the current progress percentage
   *
   * @api private
   * @method _getProgress
   * @returns current progress percentage
   */
  function _getProgress() {
    // Steps are 0 indexed
    var currentStep = parseInt((this._currentStep + 1), 10);
    return ((currentStep / this._introItems.length) * 100);
  };

  /**
   * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
   * via: http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically
   *
   * @param obj1
   * @param obj2
   * @returns obj3 a new object based on obj1 and obj2
   */
  function _mergeOptions(obj1,obj2) {
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
  };

  var introJs = function (targetElm) {
    if (typeof (targetElm) === 'object') {
      //Ok, create a new instance
      return new IntroJs(targetElm);

    } else if (typeof (targetElm) === 'string') {
      //select the target element with query selector
      var targetElement = document.querySelector(targetElm);

      if (targetElement) {
        return new IntroJs(targetElement);
      } else {
        throw new Error('There is no element with given selector.');
      }
    } else {
      return new IntroJs(document.body);
    }
  };

  /**
   * Current IntroJs version
   *
   * @property version
   * @type String
   */
  introJs.version = VERSION;

  //Prototype
  introJs.fn = IntroJs.prototype = {
    clone: function () {
      return new IntroJs(this);
    },
    setOption: function(option, value) {
      this._options[option] = value;
      return this;
    },
    setOptions: function(options) {
      this._options = _mergeOptions(this._options, options);
      return this;
    },
    start: function () {
      _introForElement.call(this, this._targetElement);
      return this;
    },
    goToStep: function(step) {
      _goToStep.call(this, step);
      return this;
    },
    nextStep: function() {
      _nextStep.call(this);
      return this;
    },
    previousStep: function() {
      _previousStep.call(this);
      return this;
    },
    exit: function() {
      _exitIntro.call(this, this._targetElement);
      return this;
    },
    refresh: function() {
      _setHelperLayerPosition.call(this, document.querySelector('.introjs-helperLayer'));
      _setHelperLayerPosition.call(this, document.querySelector('.introjs-tooltipReferenceLayer'));
      return this;
    },
    onbeforechange: function(providedCallback) {
      if (typeof (providedCallback) === 'function') {
        this._introBeforeChangeCallback = providedCallback;
      } else {
        throw new Error('Provided callback for onbeforechange was not a function');
      }
      return this;
    },
    onchange: function(providedCallback) {
      if (typeof (providedCallback) === 'function') {
        this._introChangeCallback = providedCallback;
      } else {
        throw new Error('Provided callback for onchange was not a function.');
      }
      return this;
    },
    onafterchange: function(providedCallback) {
      if (typeof (providedCallback) === 'function') {
        this._introAfterChangeCallback = providedCallback;
      } else {
        throw new Error('Provided callback for onafterchange was not a function');
      }
      return this;
    },
    oncomplete: function(providedCallback) {
      if (typeof (providedCallback) === 'function') {
        this._introCompleteCallback = providedCallback;
      } else {
        throw new Error('Provided callback for oncomplete was not a function.');
      }
      return this;
    },
    onhintsadded: function(providedCallback) {
      if (typeof (providedCallback) === 'function') {
        this._hintsAddedCallback = providedCallback;
      } else {
        throw new Error('Provided callback for onhintsadded was not a function.');
      }
      return this;
    },
    onhintclick: function(providedCallback) {
      if (typeof (providedCallback) === 'function') {
        this._hintClickCallback = providedCallback;
      } else {
        throw new Error('Provided callback for onhintclick was not a function.');
      }
      return this;
    },
    onhintclose: function(providedCallback) {
      if (typeof (providedCallback) === 'function') {
        this._hintCloseCallback = providedCallback;
      } else {
        throw new Error('Provided callback for onhintclose was not a function.');
      }
      return this;
    },
    onexit: function(providedCallback) {
      if (typeof (providedCallback) === 'function') {
        this._introExitCallback = providedCallback;
      } else {
        throw new Error('Provided callback for onexit was not a function.');
      }
      return this;
    },
    addHints: function() {
      _populateHints.call(this, this._targetElement);
      return this;
    }
  };

  exports.introJs = introJs;
  return introJs;
}));
/*! angular-intro.js - v2.0.2 - 2016-05-31 */
!function(a,b){"function"==typeof define&&define.amd?define(["angular","intro.js"],b):"object"==typeof exports?module.exports=b(require("angular"),require("intro.js")):a.angularIntroJs=b(a.angular,a.introJs)}(this,function(a,b){"object"==typeof b&&(b=b.introJs);var c=a.module("angular-intro",[]);return c.directive("ngIntroOptions",["$timeout",function(a){return{restrict:"A",scope:{ngIntroMethod:"=",ngIntroExitMethod:"=?",ngIntroNextMethod:"=?",ngIntroPreviousMethod:"=?",ngIntroRefreshMethod:"=?",ngIntroOptions:"=",ngIntroOncomplete:"=",ngIntroOnexit:"=",ngIntroOnchange:"=",ngIntroOnbeforechange:"=",ngIntroOnafterchange:"=",ngIntroAutostart:"=",ngIntroAutorefresh:"="},link:function(c,d,e){var f,g,h;c.ngIntroMethod=function(d){h=c.$on("$locationChangeStart",function(){f.exit()}),f="string"==typeof d?b(d):b(),f.setOptions(c.ngIntroOptions),c.ngIntroAutorefresh&&(g=c.$watch(function(){f.refresh()})),c.ngIntroOncomplete&&f.oncomplete(function(){c.ngIntroOncomplete.call(this,c),a(function(){c.$digest()}),j()}),c.ngIntroOnexit&&f.onexit(function(){c.ngIntroOnexit.call(this,c),a(function(){c.$digest()}),j()}),c.ngIntroOnchange&&f.onchange(function(b){c.ngIntroOnchange.call(this,b,c),a(function(){c.$digest()})}),c.ngIntroOnbeforechange&&f.onbeforechange(function(b){c.ngIntroOnbeforechange.call(this,b,c),a(function(){c.$digest()})}),c.ngIntroOnafterchange&&f.onafterchange(function(b){c.ngIntroOnafterchange.call(this,b,c),a(function(){c.$digest()})}),"number"==typeof d?f.goToStep(d).start():f.start()},c.ngIntroNextMethod=function(){f.nextStep()},c.ngIntroPreviousMethod=function(){f.previousStep()},c.ngIntroExitMethod=function(a){f.exit(),"function"==typeof a&&a()},c.ngIntroRefreshMethod=function(){f.refresh()};var i=c.$watch("ngIntroAutostart",function(){c.ngIntroAutostart&&a(function(){c.ngIntroMethod()}),i()});c.$on("$locationChangeSuccess",function(){"undefined"!=typeof f&&f.exit()});var j=function(){h&&h(),g&&g()};c.$on("$destroy",function(){j()})}}}]),c});(function (angular) {
    "use strict";
    angular.module("ng.deviceDetector", ["reTree"])
        .constant("BROWSERS", {
            CHROME: "chrome",
            FIREFOX: "firefox",
            SAFARI: "safari",
            OPERA: "opera",
            IE: "ie",
            MS_EDGE: "ms-edge",
            FB_MESSANGER: "fb-messanger",
            UNKNOWN: "unknown"
        })
        .constant("DEVICES", {
            ANDROID: "android",
            I_PAD: "ipad",
            IPHONE: "iphone",
            I_POD: "ipod",
            BLACKBERRY: "blackberry",
            FIREFOX_OS: "firefox-os",
            CHROME_BOOK: "chrome-book",
            WINDOWS_PHONE: "windows-phone",
            PS4: "ps4",
            VITA: "vita",
            CHROMECAST: "chromecast",
            APPLE_TV:"apple-tv",
            GOOGLE_TV:"google-tv",
            UNKNOWN: "unknown"
        })
        .constant("OS", {
            WINDOWS: "windows",
            MAC: "mac",
            IOS: "ios",
            ANDROID: "android",
            LINUX: "linux",
            UNIX: "unix",
            FIREFOX_OS: "firefox-os",
            CHROME_OS: "chrome-os",
            WINDOWS_PHONE: "windows-phone",
            UNKNOWN: "unknown"
        })
        .constant("OS_VERSIONS", {
            WINDOWS_3_11: "windows-3-11",
            WINDOWS_95: "windows-95",
            WINDOWS_ME: "windows-me",
            WINDOWS_98: "windows-98",
            WINDOWS_CE: "windows-ce",
            WINDOWS_2000: "windows-2000",
            WINDOWS_XP: "windows-xp",
            WINDOWS_SERVER_2003: "windows-server-2003",
            WINDOWS_VISTA: "windows-vista",
            WINDOWS_7: "windows-7",
            WINDOWS_8_1: "windows-8-1",
            WINDOWS_8: "windows-8",
            WINDOWS_10: "windows-10",
            WINDOWS_PHONE_7_5: "windows-phone-7-5",
            WINDOWS_PHONE_8_1: "windows-phone-8-1",
            WINDOWS_PHONE_10: "windows-phone-10",
            WINDOWS_NT_4_0: "windows-nt-4-0",
            MACOSX_15: "mac-os-x-15",
            MACOSX_14: "mac-os-x-14",
            MACOSX_13: "mac-os-x-13",
            MACOSX_12: "mac-os-x-12",
            MACOSX_11: "mac-os-x-11",
            MACOSX_10: "mac-os-x-10",
            MACOSX_9: "mac-os-x-9",
            MACOSX_8: "mac-os-x-8",
            MACOSX_7: "mac-os-x-7",
            MACOSX_6: "mac-os-x-6",
            MACOSX_5: "mac-os-x-5",
            MACOSX_4: "mac-os-x-4",
            MACOSX_3: "mac-os-x-3",
            MACOSX_2: "mac-os-x-2",
            MACOSX: "mac-os-x",
            UNKNOWN: "unknown"
        })
        .service("detectUtils", ["deviceDetector", "DEVICES", "BROWSERS", "OS",
            function (deviceDetector, DEVICES, BROWSERS, OS) {
                var deviceInfo = deviceDetector;

                this.isMobile = function () {
                    return deviceInfo.device !== 'unknown';
                };

                this.isAndroid = function () {
                    return (deviceInfo.device === DEVICES.ANDROID || deviceInfo.OS === OS.ANDROID);
                };

                this.isIOS = function () {
                    return (deviceInfo.os === OS.IOS || deviceInfo.device === DEVICES.I_POD || deviceInfo.device === DEVICES.IPHONE);
                };
            }
        ])
        .factory("deviceDetector", ["$window", "DEVICES", "BROWSERS", "OS", "OS_VERSIONS", "reTree",
            function ($window, DEVICES, BROWSERS, OS, OS_VERSIONS, reTree) {
                /* ES5 polyfills Start*/

                // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
                if (!Object.keys) {
                    Object.keys = (function () {
                        'use strict';
                        var hasOwnProperty = Object.prototype.hasOwnProperty,
                            hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
                            dontEnums = [
                                'toString',
                                'toLocaleString',
                                'valueOf',
                                'hasOwnProperty',
                                'isPrototypeOf',
                                'propertyIsEnumerable',
                                'constructor'
                            ],
                            dontEnumsLength = dontEnums.length;

                        return function (obj) {
                            if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
                                throw new TypeError('Object.keys called on non-object');
                            }

                            var result = [], prop, i;

                            for (prop in obj) {
                                if (hasOwnProperty.call(obj, prop)) {
                                    result.push(prop);
                                }
                            }

                            if (hasDontEnumBug) {
                                for (i = 0; i < dontEnumsLength; i++) {
                                    if (hasOwnProperty.call(obj, dontEnums[i])) {
                                        result.push(dontEnums[i]);
                                    }
                                }
                            }
                            return result;
                        };
                    }());
                }

                // Production steps of ECMA-262, Edition 5, 15.4.4.21
                // Reference: http://es5.github.io/#x15.4.4.21
                if (!Array.prototype.reduce) {
                    Array.prototype.reduce = function (callback /*, initialValue*/) {
                        'use strict';
                        if (this == null) {
                            throw new TypeError('Array.prototype.reduce called on null or undefined');
                        }
                        if (typeof callback !== 'function') {
                            throw new TypeError(callback + ' is not a function');
                        }
                        var t = Object(this), len = t.length >>> 0, k = 0, value;
                        if (arguments.length == 2) {
                            value = arguments[1];
                        } else {
                            while (k < len && !(k in t)) {
                                k++;
                            }
                            if (k >= len) {
                                throw new TypeError('Reduce of empty array with no initial value');
                            }
                            value = t[k++];
                        }
                        for (; k < len; k++) {
                            if (k in t) {
                                value = callback(value, t[k], k, t);
                            }
                        }
                        return value;
                    };
                }
                /* ES5 polyfills End*/

                var OS_RE = {
                    WINDOWS: {and: [{or: [/\bWindows|(Win\d\d)\b/, /\bWin 9x\b/]}, {not: /\bWindows Phone\b/}]},
                    MAC: {and: [/\bMac OS\b/, {not: /Windows Phone/}]},
                    IOS: {and: [{or: [/\biPad\b/, /\biPhone\b/, /\biPod\b/]}, {not: /Windows Phone/}]},
                    ANDROID: {and: [/\bAndroid\b/, {not: /Windows Phone/}]},
                    LINUX: /\bLinux\b/,
                    UNIX: /\bUNIX\b/,
                    FIREFOX_OS: {and: [/\bFirefox\b/, /Mobile\b/]},
                    CHROME_OS: /\bCrOS\b/,
                    WINDOWS_PHONE: {or: [/\bIEMobile\b/, /\bWindows Phone\b/]},
                    PS4: /\bMozilla\/5.0 \(PlayStation 4\b/,
                    VITA: /\bMozilla\/5.0 \(Play(S|s)tation Vita\b/
                };

                var BROWSERS_RE = {
                    CHROME: {and: [{or: [/\bChrome\b/, /\bCriOS\b/]}, {not: {or: [/\bOPR\b/, /\bEdge\b/]}}]},
                    FIREFOX: /\bFirefox\b/,
                    SAFARI: {and: [/^((?!CriOS).)*\Safari\b.*$/, {not: {or: [/\bOPR\b/, /\bEdge\b/, /Windows Phone/]}}]},
                    OPERA: {or: [/Opera\b/, /\bOPR\b/]},
                    IE: {or: [/\bMSIE\b/, /\bTrident\b/,/^Mozilla\/5\.0 \(Windows NT 10\.0; Win64; x64\)$/]},
                    MS_EDGE: {or: [/\bEdge\b/]},
                    PS4: /\bMozilla\/5.0 \(PlayStation 4\b/,
                    VITA: /\bMozilla\/5.0 \(Play(S|s)tation Vita\b/,
                    FB_MESSANGER: /\bFBAN\/MessengerForiOS\b/
                };

                var DEVICES_RE = {
                    ANDROID: {and: [/\bAndroid\b/, {not: /Windows Phone/}]},
                    I_PAD: /\biPad\b/,
                    IPHONE: {and: [/\biPhone\b/, {not: /Windows Phone/}]},
                    I_POD: /\biPod\b/,
                    BLACKBERRY: /\bblackberry\b/,
                    FIREFOX_OS: {and: [/\bFirefox\b/, /\bMobile\b/]},
                    CHROME_BOOK: /\bCrOS\b/,
                    WINDOWS_PHONE: {or: [/\bIEMobile\b/, /\bWindows Phone\b/]},
                    PS4: /\bMozilla\/5.0 \(PlayStation 4\b/,
                    CHROMECAST: /\bCrKey\b/,
                    APPLE_TV:/^iTunes-AppleTV\/4.1$/,
                    GOOGLE_TV:/\bGoogleTV\b/,
                    VITA: /\bMozilla\/5.0 \(Play(S|s)tation Vita\b/
                };

                var OS_VERSIONS_RE = {
                    WINDOWS_3_11: /Win16/,
                    WINDOWS_95: /(Windows 95|Win95|Windows_95)/,
                    WINDOWS_ME: /(Win 9x 4.90|Windows ME)/,
                    WINDOWS_98: /(Windows 98|Win98)/,
                    WINDOWS_CE: /Windows CE/,
                    WINDOWS_2000: /(Windows NT 5.0|Windows 2000)/,
                    WINDOWS_XP: /(Windows NT 5.1|Windows XP)/,
                    WINDOWS_SERVER_2003: /Windows NT 5.2/,
                    WINDOWS_VISTA: /Windows NT 6.0/,
                    WINDOWS_7: /(Windows 7|Windows NT 6.1)/,
                    WINDOWS_8_1: /(Windows 8.1|Windows NT 6.3)/,
                    WINDOWS_8: /(Windows 8|Windows NT 6.2)/,
                    WINDOWS_10: /(Windows NT 10.0)/,
                    WINDOWS_PHONE_7_5: /(Windows Phone OS 7.5)/,
                    WINDOWS_PHONE_8_1: /(Windows Phone 8.1)/,
                    WINDOWS_PHONE_10: /(Windows Phone 10)/,
                    WINDOWS_NT_4_0: {and: [/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/, {not: /Windows NT 10.0/}]},
                    MACOSX: /(MAC OS X\s*[^ 0-9])/,
                    MACOSX_3: /(Darwin 10.3|Mac OS X 10.3)/,
                    MACOSX_4: /(Darwin 10.4|Mac OS X 10.4)/,
                    MACOSX_5: /(Mac OS X 10.5)/,
                    MACOSX_6: /(Mac OS X 10.6)/,
                    MACOSX_7: /(Mac OS X 10.7)/,
                    MACOSX_8: /(Mac OS X 10.8)/,
                    MACOSX_9: /(Mac OS X 10.9)/,
                    MACOSX_10: /(Mac OS X 10.10)/,
                    MACOSX_11: /(Mac OS X 10.11)/,
                    MACOSX_12: /(Mac OS X 10.12)/,
                    MACOSX_13: /(Mac OS X 10.13)/,
                    MACOSX_14: /(Mac OS X 10.14)/,
                    MACOSX_15: /(Mac OS X 10.15)/
                };

                var BROWSER_VERSIONS_RE_MAP = {
                    CHROME: [/\bChrome\/([\d\.]+)\b/, /\bCriOS\/([\d\.]+)\b/],
                    FIREFOX: /\bFirefox\/([\d\.]+)\b/,
                    SAFARI: /\bVersion\/([\d\.]+)\b/,
                    OPERA: [/\bVersion\/([\d\.]+)\b/, /\bOPR\/([\d\.]+)\b/],
                    IE: [/\bMSIE ([\d\.]+\w?)\b/, /\brv:([\d\.]+\w?)\b/],
                    MS_EDGE: /\bEdge\/([\d\.]+)\b/
                };

                var BROWSER_VERSIONS_RE = Object.keys(BROWSER_VERSIONS_RE_MAP).reduce(function (obj, key) {
                    obj[BROWSERS[key]] = BROWSER_VERSIONS_RE_MAP[key];
                    return obj;
                }, {});

                var ua = $window.navigator.userAgent;

                var deviceInfo = {
                    raw: {
                        userAgent: ua,
                        os: {},
                        browser: {},
                        device: {}
                    }
                };

                deviceInfo.raw.os = Object.keys(OS).reduce(function (obj, item) {
                    obj[OS[item]] = reTree.test(ua, OS_RE[item]);
                    return obj;
                }, {});

                deviceInfo.raw.browser = Object.keys(BROWSERS).reduce(function (obj, item) {
                    obj[BROWSERS[item]] = reTree.test(ua, BROWSERS_RE[item]);
                    return obj;
                }, {});

                deviceInfo.raw.device = Object.keys(DEVICES).reduce(function (obj, item) {
                    obj[DEVICES[item]] = reTree.test(ua, DEVICES_RE[item]);
                    return obj;
                }, {});

                deviceInfo.raw.os_version = Object.keys(OS_VERSIONS).reduce(function (obj, item) {
                    obj[OS_VERSIONS[item]] = reTree.test(ua, OS_VERSIONS_RE[item]);
                    return obj;
                }, {});

                deviceInfo.os = [
                    OS.WINDOWS,
                    OS.IOS,
                    OS.MAC,
                    OS.ANDROID,
                    OS.LINUX,
                    OS.UNIX,
                    OS.FIREFOX_OS,
                    OS.CHROME_OS,
                    OS.WINDOWS_PHONE
                ].reduce(function (previousValue, currentValue) {
                    return (previousValue === OS.UNKNOWN && deviceInfo.raw.os[currentValue]) ? currentValue : previousValue;
                }, OS.UNKNOWN);

                deviceInfo.browser = [
                    BROWSERS.CHROME,
                    BROWSERS.FIREFOX,
                    BROWSERS.SAFARI,
                    BROWSERS.OPERA,
                    BROWSERS.IE,
                    BROWSERS.MS_EDGE,
                    BROWSERS.FB_MESSANGER
                ].reduce(function (previousValue, currentValue) {
                    return (previousValue === BROWSERS.UNKNOWN && deviceInfo.raw.browser[currentValue]) ? currentValue : previousValue;
                }, BROWSERS.UNKNOWN);

                deviceInfo.device = [
                    DEVICES.ANDROID,
                    DEVICES.I_PAD,
                    DEVICES.IPHONE,
                    DEVICES.I_POD,
                    DEVICES.BLACKBERRY,
                    DEVICES.FIREFOX_OS,
                    DEVICES.CHROME_BOOK,
                    DEVICES.WINDOWS_PHONE,
                    DEVICES.PS4,
                    DEVICES.CHROMECAST,
                    DEVICES.APPLE_TV,
                    DEVICES.GOOGLE_TV,
                    DEVICES.VITA
                ].reduce(function (previousValue, currentValue) {
                    return (previousValue === DEVICES.UNKNOWN && deviceInfo.raw.device[currentValue]) ? currentValue : previousValue;
                }, DEVICES.UNKNOWN);

                deviceInfo.os_version = [
                    OS_VERSIONS.WINDOWS_3_11,
                    OS_VERSIONS.WINDOWS_95,
                    OS_VERSIONS.WINDOWS_ME,
                    OS_VERSIONS.WINDOWS_98,
                    OS_VERSIONS.WINDOWS_CE,
                    OS_VERSIONS.WINDOWS_2000,
                    OS_VERSIONS.WINDOWS_XP,
                    OS_VERSIONS.WINDOWS_SERVER_2003,
                    OS_VERSIONS.WINDOWS_VISTA,
                    OS_VERSIONS.WINDOWS_7,
                    OS_VERSIONS.WINDOWS_8_1,
                    OS_VERSIONS.WINDOWS_8,
                    OS_VERSIONS.WINDOWS_10,
                    OS_VERSIONS.WINDOWS_PHONE_7_5,
                    OS_VERSIONS.WINDOWS_PHONE_8_1,
                    OS_VERSIONS.WINDOWS_PHONE_10,
                    OS_VERSIONS.WINDOWS_NT_4_0,
                    OS_VERSIONS.MACOSX,
                    OS_VERSIONS.MACOSX_3,
                    OS_VERSIONS.MACOSX_4,
                    OS_VERSIONS.MACOSX_5,
                    OS_VERSIONS.MACOSX_6,
                    OS_VERSIONS.MACOSX_7,
                    OS_VERSIONS.MACOSX_8,
                    OS_VERSIONS.MACOSX_9,
                    OS_VERSIONS.MACOSX_10,
                    OS_VERSIONS.MACOSX_11,
                    OS_VERSIONS.MACOSX_12,
                    OS_VERSIONS.MACOSX_13,
                    OS_VERSIONS.MACOSX_14,
                    OS_VERSIONS.MACOSX_15
                ].reduce(function (previousValue, currentValue) {
                    return (previousValue === OS_VERSIONS.UNKNOWN && deviceInfo.raw.os_version[currentValue]) ? currentValue : previousValue;
                }, OS_VERSIONS.UNKNOWN);

                deviceInfo.browser_version = "0";
                if (deviceInfo.browser !== BROWSERS.UNKNOWN) {
                    var re = BROWSER_VERSIONS_RE[deviceInfo.browser];
                    var res = reTree.exec(ua, re);
                    if (!!res) {
                        deviceInfo.browser_version = res[1];
                    }
                }

                deviceInfo.isMobile = function () {
                    return [
                        DEVICES.ANDROID,
                        DEVICES.I_PAD,
                        DEVICES.IPHONE,
                        DEVICES.I_POD,
                        DEVICES.BLACKBERRY,
                        DEVICES.FIREFOX_OS,
                        DEVICES.WINDOWS_PHONE,
                        DEVICES.VITA
                    ].some(function (item) {
                        return deviceInfo.device == item;
                    });
                };

                deviceInfo.isTablet = function () {
                    return [
                        DEVICES.I_PAD,
                        DEVICES.FIREFOX_OS
                    ].some(function (item) {
                        return deviceInfo.device == item;
                    });
                };

                deviceInfo.isDesktop = function () {
                    return [
                        DEVICES.PS4,
                        DEVICES.CHROME_BOOK,
                        DEVICES.UNKNOWN
                    ].some(function (item) {
                        return deviceInfo.device == item;
                    });
                };

                return deviceInfo;
            }
        ])
        .directive('deviceDetector', ["deviceDetector", function (deviceDetector) {
            return {
                restrict: "A",
                link: function (scope, elm/*, attrs*/) {
                    elm.addClass('os-' + deviceDetector.os);
                    elm.addClass('browser-' + deviceDetector.browser);
                    elm.addClass('device-' + deviceDetector.device);
                }
            };
        }]);
})(angular);
/**
 * URI.js
 * 
 * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.
 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
 * @version 1.3
 * @see http://github.com/garycourt/uri-js
 * @license URI.js v1.3 (c) 2010 Gary Court. License: http://github.com/garycourt/uri-js
 */

/**
 * Copyright 2010 Gary Court. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 * 
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 * 
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of Gary Court.
 */

/*jslint white: true, sub: true, onevar: true, undef: true, eqeqeq: true, newcap: true, immed: true, indent: 4 */
/*global exports:true, require:true */

if (typeof exports === "undefined") {
	exports = {}; 
}
if (typeof require !== "function") {
	require = function (id) {
		return exports;
	};
}
(function () {
	var	
		/**
		 * @param {...string} sets
		 * @return {string}
		 */
		mergeSet = function (sets) {
			var set = arguments[0],
				x = 1,
				nextSet = arguments[x];
			
			while (nextSet) {
				set = set.slice(0, -1) + nextSet.slice(1);
				nextSet = arguments[++x];
			}
			
			return set;
		},
		
		/**
		 * @param {string} str
		 * @return {string}
		 */
		subexp = function (str) {
			return "(?:" + str + ")";
		},
	
		ALPHA$$ = "[A-Za-z]",
		CR$ = "[\\x0D]",
		DIGIT$$ = "[0-9]",
		DQUOTE$$ = "[\\x22]",
		HEXDIG$$ = mergeSet(DIGIT$$, "[A-Fa-f]"),  //case-insensitive
		LF$$ = "[\\x0A]",
		SP$$ = "[\\x20]",
		PCT_ENCODED$ = subexp("%" + HEXDIG$$ + HEXDIG$$),
		GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]",
		SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",
		RESERVED$$ = mergeSet(GEN_DELIMS$$, SUB_DELIMS$$),
		UNRESERVED$$ = mergeSet(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]"),
		SCHEME$ = subexp(ALPHA$$ + mergeSet(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"),
		USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + mergeSet(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"),
		DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$),
		IPV4ADDRESS$ = subexp(DEC_OCTET$ + "\\." + DEC_OCTET$ + "\\." + DEC_OCTET$ + "\\." + DEC_OCTET$),
		H16$ = subexp(HEXDIG$$ + "{1,4}"),
		LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$),
		IPV6ADDRESS$ = subexp(mergeSet(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"),  //FIXME
		IPVFUTURE$ = subexp("v" + HEXDIG$$ + "+\\." + mergeSet(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"),
		IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"),
		REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + mergeSet(UNRESERVED$$, SUB_DELIMS$$)) + "*"),
		HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "|" + REG_NAME$),
		PORT$ = subexp(DIGIT$$ + "*"),
		AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"),
		PCHAR$ = subexp(PCT_ENCODED$ + "|" + mergeSet(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")),
		SEGMENT$ = subexp(PCHAR$ + "*"),
		SEGMENT_NZ$ = subexp(PCHAR$ + "+"),
		SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + mergeSet(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"),
		PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"),
		PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"),  //simplified
		PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$),  //simplified
		PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$),  //simplified
		PATH_EMPTY$ = subexp(""),  //simplified
		PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
		QUERY$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"),
		FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"),
		HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
		URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
		RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$),
		RELATIVE_REF$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
		URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE_REF$),
		ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"),
		
		URI_REF = new RegExp("^" + subexp("(" + URI$ + ")|(" + RELATIVE_REF$ + ")") + "$"),
		GENERIC_REF  = new RegExp("^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$"),
		RELATIVE_REF = new RegExp("^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$"),
		ABSOLUTE_REF = new RegExp("^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$"),
		SAMEDOC_REF = new RegExp("^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$"),
		AUTHORITY = new RegExp("^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"),
		
		NOT_SCHEME = new RegExp(mergeSet("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
		NOT_USERINFO = new RegExp(mergeSet("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
		NOT_HOST = new RegExp(mergeSet("[^\\%]", UNRESERVED$$, SUB_DELIMS$$), "g"),
		NOT_PATH = new RegExp(mergeSet("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
		NOT_PATH_NOSCHEME = new RegExp(mergeSet("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
		NOT_QUERY = new RegExp(mergeSet("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
		NOT_FRAGMENT = NOT_QUERY,
		ESCAPE = new RegExp(mergeSet("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"),
		UNRESERVED = new RegExp(UNRESERVED$$, "g"),
		OTHER_CHARS = new RegExp(mergeSet("[^\\%]", UNRESERVED$$, RESERVED$$), "g"),
		PCT_ENCODEDS = new RegExp(PCT_ENCODED$ + "+", "g"),
		URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?([^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/i,
		RDS1 = /^\.\.?\//,
		RDS2 = /^\/\.(\/|$)/,
		RDS3 = /^\/\.\.(\/|$)/,
		RDS4 = /^\.\.?$/,
		RDS5 = /^\/?.*?(?=\/|$)/,
		NO_MATCH_IS_UNDEFINED = ("").match(/(){0}/)[1] === undefined,
		
		/**
		 * @param {string} chr
		 * @return {string}
		 */
		pctEncChar = function (chr) {
			var c = chr.charCodeAt(0);
 
			if (c < 128) {
				return "%" + c.toString(16).toUpperCase();
			}
			else if ((c > 127) && (c < 2048)) {
				return "%" + ((c >> 6) | 192).toString(16).toUpperCase() + "%" + ((c & 63) | 128).toString(16).toUpperCase();
			}
			else {
				return "%" + ((c >> 12) | 224).toString(16).toUpperCase() + "%" + (((c >> 6) & 63) | 128).toString(16).toUpperCase() + "%" + ((c & 63) | 128).toString(16).toUpperCase();
			}
		},
		
		/**
		 * @param {string} str
		 * @return {string}
		 */
		pctDecUnreserved = function (str) {
			var newStr = "", 
				i = 0,
				c, s;
	 
			while (i < str.length) {
				c = parseInt(str.substr(i + 1, 2), 16);
	 
				if (c < 128) {
					s = String.fromCharCode(c);
					if (s.match(UNRESERVED)) {
						newStr += s;
					} else {
						newStr += str.substr(i, 3);
					}
					i += 3;
				}
				else if ((c > 191) && (c < 224)) {
					newStr += str.substr(i, 6);
					i += 6;
				}
				else {
					newStr += str.substr(i, 9);
					i += 9;
				}
			}
	 
			return newStr;
		},
		
		/**
		 * @param {string} str
		 * @return {string}
		 */
		pctDecChars = function (str) {
			var newStr = "", 
				i = 0,
				c, c2, c3;
	 
			while (i < str.length) {
				c = parseInt(str.substr(i + 1, 2), 16);
	 
				if (c < 128) {
					newStr += String.fromCharCode(c);
					i += 3;
				}
				else if ((c > 191) && (c < 224)) {
					c2 = parseInt(str.substr(i + 4, 2), 16);
					newStr += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 6;
				}
				else {
					c2 = parseInt(str.substr(i + 4, 2), 16);
					c3 = parseInt(str.substr(i + 7, 2), 16);
					newStr += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 9;
				}
			}
	 
			return newStr;
		},
		
		/**
		 * @return {string}
		 */
		typeOf = function (o) {
			return o === undefined ? "undefined" : (o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase());
		},
		
		/**
		 * @constructor
		 * @implements URIComponents
		 */
		Components = function () {
			this.errors = [];
		}, 
		
		/** @namespace */ 
		URI = exports;
	
	/**
	 * Components
	 */
	
	Components.prototype = {
		/**
		 * @type String
		 */
		
		scheme : undefined,
		
		/**
		 * @type String
		 */
		
		authority : undefined,
		
		/**
		 * @type String
		 */
		
		userinfo : undefined,
		
		/**
		 * @type String
		 */
		
		host : undefined,
		
		/**
		 * @type number
		 */
		
		port : undefined,
		
		/**
		 * @type string
		 */
		
		path : undefined,
		
		/**
		 * @type string
		 */
		
		query : undefined,
		
		/**
		 * @type string
		 */
		
		fragment : undefined,
		
		/**
		 * @type string
		 * @values "uri", "absolute", "relative", "same-document"
		 */
		
		reference : undefined,
		
		/**
		 * @type Array
		 */
		
		errors : undefined
	};
	
	/**
	 * URI
	 */
	
	/**
	 * @namespace
	 */
	
	URI.SCHEMES = {};
	
	/**
	 * @param {string} uriString
	 * @param {Options} [options]
	 * @returns {URIComponents}
	 */
	
	URI.parse = function (uriString, options) {
		var matches, 
			components = new Components(),
			schemeHandler;
		
		uriString = uriString ? uriString.toString() : "";
		options = options || {};
		
		if (options.reference === "suffix") {
			uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString;
		}
		
		matches = uriString.match(URI_REF);
		
		if (matches) {
			if (matches[1]) {
				//generic URI
				matches = uriString.match(GENERIC_REF);
			} else {
				//relative URI
				matches = uriString.match(RELATIVE_REF);
			}
		} 
		
		if (!matches) {
			if (!options.tolerant) {
				components.errors.push("URI is not strictly valid.");
			}
			matches = uriString.match(URI_PARSE);
		}
		
		if (matches) {
			if (NO_MATCH_IS_UNDEFINED) {
				//store each component
				components.scheme = matches[1];
				components.authority = matches[2];
				components.userinfo = matches[3];
				components.host = matches[4];
				components.port = parseInt(matches[5], 10);
				components.path = matches[6] || "";
				components.query = matches[7];
				components.fragment = matches[8];
				
				//fix port number
				if (isNaN(components.port)) {
					components.port = matches[5];
				}
			} else {  //IE FIX for improper RegExp matching
				//store each component
				components.scheme = matches[1] || undefined;
				components.authority = (uriString.indexOf("//") !== -1 ? matches[2] : undefined);
				components.userinfo = (uriString.indexOf("@") !== -1 ? matches[3] : undefined);
				components.host = (uriString.indexOf("//") !== -1 ? matches[4] : undefined);
				components.port = parseInt(matches[5], 10);
				components.path = matches[6] || "";
				components.query = (uriString.indexOf("?") !== -1 ? matches[7] : undefined);
				components.fragment = (uriString.indexOf("#") !== -1 ? matches[8] : undefined);
				
				//fix port number
				if (isNaN(components.port)) {
					components.port = (uriString.match(/\/\/.*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined);
				}
			}
			
			//determine reference type
			if (!components.scheme && !components.authority && !components.path && !components.query) {
				components.reference = "same-document";
			} else if (!components.scheme) {
				components.reference = "relative";
			} else if (!components.fragment) {
				components.reference = "absolute";
			} else {
				components.reference = "uri";
			}
			
			//check for reference errors
			if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) {
				components.errors.push("URI is not a " + options.reference + " reference.");
			}
			
			//check if a handler for the scheme exists
			schemeHandler = URI.SCHEMES[(components.scheme || options.scheme || "").toLowerCase()];
			if (schemeHandler && schemeHandler.parse) {
				//perform extra parsing
				schemeHandler.parse(components, options);
			}
		} else {
			components.errors.push("URI can not be parsed.");
		}
		
		return components;
	};
	
	/**
	 * @private
	 * @param {URIComponents} components
	 * @returns {string|undefined}
	 */
	
	URI._recomposeAuthority = function (components) {
		var uriTokens = [];
		
		if (components.userinfo !== undefined || components.host !== undefined || typeof components.port === "number") {
			if (components.userinfo !== undefined) {
				uriTokens.push(components.userinfo.toString().replace(NOT_USERINFO, pctEncChar));
				uriTokens.push("@");
			}
			if (components.host !== undefined) {
				uriTokens.push(components.host.toString().toLowerCase().replace(NOT_HOST, pctEncChar));
			}
			if (typeof components.port === "number") {
				uriTokens.push(":");
				uriTokens.push(components.port.toString(10));
			}
		}
		
		return uriTokens.length ? uriTokens.join("") : undefined;
	};
	
	/**
	 * @param {string} input
	 * @returns {string}
	 */
	
	URI.removeDotSegments = function (input) {
		var output = [], s;
		
		while (input.length) {
			if (input.match(RDS1)) {
				input = input.replace(RDS1, "");
			} else if (input.match(RDS2)) {
				input = input.replace(RDS2, "/");
			} else if (input.match(RDS3)) {
				input = input.replace(RDS3, "/");
				output.pop();
			} else if (input === "." || input === "..") {
				input = "";
			} else {
				s = input.match(RDS5)[0];
				input = input.slice(s.length);
				output.push(s);
			}
		}
		
		return output.join("");
	};
	
	/**
	 * @param {URIComponents} components
	 * @param {Options} [options]
	 * @returns {string}
	 */
	
	URI.serialize = function (components, options) {
		var uriTokens = [], 
			schemeHandler, 
			s;
		options = options || {};
		
		//check if a handler for the scheme exists
		schemeHandler = URI.SCHEMES[components.scheme || options.scheme];
		if (schemeHandler && schemeHandler.serialize) {
			//perform extra serialization
			schemeHandler.serialize(components, options);
		}
		
		if (options.reference !== "suffix" && components.scheme) {
			uriTokens.push(components.scheme.toString().toLowerCase().replace(NOT_SCHEME, ""));
			uriTokens.push(":");
		}
		
		components.authority = URI._recomposeAuthority(components);
		if (components.authority !== undefined) {
			if (options.reference !== "suffix") {
				uriTokens.push("//");
			}
			
			uriTokens.push(components.authority);
			
			if (components.path && components.path.charAt(0) !== "/") {
				uriTokens.push("/");
			}
		}
		
		if (components.path) {
			s = URI.removeDotSegments(components.path.toString().replace(/%2E/ig, "."));
			
			if (components.scheme) {
				s = s.replace(NOT_PATH, pctEncChar);
			} else {
				s = s.replace(NOT_PATH_NOSCHEME, pctEncChar);
			}
			
			if (components.authority === undefined) {
				s = s.replace(/^\/\//, "/%2F");  //don't allow the path to start with "//"
			}
			uriTokens.push(s);
		}
		
		if (components.query) {
			uriTokens.push("?");
			uriTokens.push(components.query.toString().replace(NOT_QUERY, pctEncChar));
		}
		
		if (components.fragment) {
			uriTokens.push("#");
			uriTokens.push(components.fragment.toString().replace(NOT_FRAGMENT, pctEncChar));
		}
		
		return uriTokens
			.join('')  //merge tokens into a string
			.replace(PCT_ENCODEDS, pctDecUnreserved)  //undecode unreserved characters
			//.replace(OTHER_CHARS, pctEncChar)  //replace non-URI characters
			.replace(/%[0-9A-Fa-f]{2}/g, function (str) {  //uppercase percent encoded characters
				return str.toUpperCase();
			})
		;
	};
	
	/**
	 * @param {URIComponents} base
	 * @param {URIComponents} relative
	 * @param {Options} [options]
	 * @param {boolean} [skipNormalization]
	 * @returns {URIComponents}
	 */
	
	URI.resolveComponents = function (base, relative, options, skipNormalization) {
		var target = new Components();
		
		if (!skipNormalization) {
			base = URI.parse(URI.serialize(base, options), options);  //normalize base components
			relative = URI.parse(URI.serialize(relative, options), options);  //normalize relative components
		}
		options = options || {};
		
		if (!options.tolerant && relative.scheme) {
			target.scheme = relative.scheme;
			target.authority = relative.authority;
			target.userinfo = relative.userinfo;
			target.host = relative.host;
			target.port = relative.port;
			target.path = URI.removeDotSegments(relative.path);
			target.query = relative.query;
		} else {
			if (relative.authority !== undefined) {
				target.authority = relative.authority;
				target.userinfo = relative.userinfo;
				target.host = relative.host;
				target.port = relative.port;
				target.path = URI.removeDotSegments(relative.path);
				target.query = relative.query;
			} else {
				if (!relative.path) {
					target.path = base.path;
					if (relative.query !== undefined) {
						target.query = relative.query;
					} else {
						target.query = base.query;
					}
				} else {
					if (relative.path.charAt(0) === "/") {
						target.path = URI.removeDotSegments(relative.path);
					} else {
						if (base.authority !== undefined && !base.path) {
							target.path = "/" + relative.path;
						} else if (!base.path) {
							target.path = relative.path;
						} else {
							target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
						}
						target.path = URI.removeDotSegments(target.path);
					}
					target.query = relative.query;
				}
				target.authority = base.authority;
				target.userinfo = base.userinfo;
				target.host = base.host;
				target.port = base.port;
			}
			target.scheme = base.scheme;
		}
		
		target.fragment = relative.fragment;
		
		return target;
	};
	
	/**
	 * @param {string} baseURI
	 * @param {string} relativeURI
	 * @param {Options} [options]
	 * @returns {string}
	 */
	
	URI.resolve = function (baseURI, relativeURI, options) {
		return URI.serialize(URI.resolveComponents(URI.parse(baseURI, options), URI.parse(relativeURI, options), options, true), options);
	};
	
	/**
	 * @param {string|URIComponents} uri
	 * @param {Options} options
	 * @returns {string|URIComponents}
	 */
	
	URI.normalize = function (uri, options) {
		if (typeof uri === "string") {
			return URI.serialize(URI.parse(uri, options), options);
		} else if (typeOf(uri) === "object") {
			return URI.parse(URI.serialize(uri, options), options);
		}
		
		return uri;
	};
	
	/**
	 * @param {string|URIComponents} uriA
	 * @param {string|URIComponents} uriB
	 * @param {Options} options
	 */
	
	URI.equal = function (uriA, uriB, options) {
		if (typeof uriA === "string") {
			uriA = URI.serialize(URI.parse(uriA, options), options);
		} else if (typeOf(uriA) === "object") {
			uriA = URI.serialize(uriA, options);
		}
		
		if (typeof uriB === "string") {
			uriB = URI.serialize(URI.parse(uriB, options), options);
		} else if (typeOf(uriB) === "object") {
			uriB = URI.serialize(uriB, options);
		}
		
		return uriA === uriB;
	};
	
	/**
	 * @param {string} str
	 * @returns {string}
	 */
	
	URI.escapeComponent = function (str) {
		return str && str.toString().replace(ESCAPE, pctEncChar);
	};
	
	/**
	 * @param {string} str
	 * @returns {string}
	 */
	
	URI.unescapeComponent = function (str) {
		return str && str.toString().replace(PCT_ENCODEDS, pctDecChars);
	};
	
	//export API
	exports.pctEncChar = pctEncChar;
	exports.pctDecChars = pctDecChars;
	exports.Components = Components;
	exports.URI = URI;
	
	//name-safe export API
	exports["pctEncChar"] = pctEncChar;
	exports["pctDecChars"] = pctDecChars;
	exports["Components"] = Components;
	exports["URI"] = {
		"SCHEMES" : URI.SCHEMES,
		"parse" : URI.parse,
		"removeDotSegments" : URI.removeDotSegments,
		"serialize" : URI.serialize,
		"resolveComponents" : URI.resolveComponents,
		"resolve" : URI.resolve,
		"normalize" : URI.normalize,
		"equal" : URI.equal,
		"escapeComponent" : URI.escapeComponent,
		"unescapeComponent" : URI.unescapeComponent
	};
	
}());require("./json-schema-draft-01");
require("./json-schema-draft-02");
require("./json-schema-draft-03");(function () {
	var URI_NS = require("../uri"),
		URI = URI_NS.URI,
		pctEncChar = URI_NS.pctEncChar,
		NID$ = "(?:[0-9A-Za-z][0-9A-Za-z\\-]{1,31})",
		PCT_ENCODED$ = "(?:\\%[0-9A-Fa-f]{2})",
		TRANS$$ = "[0-9A-Za-z\\(\\)\\+\\,\\-\\.\\:\\=\\@\\;\\$\\_\\!\\*\\'\\/\\?\\#]",
		NSS$ = "(?:(?:" + PCT_ENCODED$ + "|" + TRANS$$ + ")+)",
		URN_SCHEME = new RegExp("^urn\\:(" + NID$ + ")$"),
		URN_PATH = new RegExp("^(" + NID$ + ")\\:(" + NSS$ + ")$"),
		URN_PARSE = /^([^\:]+)\:(.*)/,
		URN_EXCLUDED = /[\x00-\x20\\\"\&\<\>\[\]\^\`\{\|\}\~\x7F-\xFF]/g,
		UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
	
	//RFC 2141
	URI.SCHEMES["urn"] = {
		parse : function (components, options) {
			var matches = components.path.match(URN_PATH),
				scheme, schemeHandler;
			
			if (!matches) {
				if (!options.tolerant) {
					components.errors.push("URN is not strictly valid.");
				}
				
				matches = components.path.match(URN_PARSE);
			}
			
			if (matches) {
				scheme = "urn:" + matches[1].toLowerCase();
				schemeHandler = URI.SCHEMES[scheme];
				
				//in order to serialize properly, 
				//every URN must have a serializer that calls the URN serializer 
				if (!schemeHandler) {
					schemeHandler = URI.SCHEMES[scheme] = {};
				}
				if (!schemeHandler.serialize) {
					schemeHandler.serialize = URI.SCHEMES["urn"].serialize;
				}
				
				components.scheme = scheme;
				components.path = matches[2];
				
				if (schemeHandler.parse) {
					schemeHandler.parse(components, options);
				}
			} else {
				components.errors.push("URN can not be parsed.");
			}
	
			return components;
		},
		
		serialize : function (components, options) {
			var scheme = components.scheme || options.scheme,
				matches;
			
			if (scheme && scheme !== "urn") {
				var matches = scheme.match(URN_SCHEME);
				
				if (!matches) {
					matches = ["urn:" + scheme, scheme];
				}
				
				components.scheme = "urn";
				components.path = matches[1] + ":" + (components.path ? components.path.replace(URN_EXCLUDED, pctEncChar) : "");
			}
			
			return components;
		}
	};
	
	//RFC 4122
	URI.SCHEMES["urn:uuid"] = {
		serialize : function (components, options) {
			//ensure UUID is valid
			if (!options.tolerant && (!components.path || !components.path.match(UUID))) {
				//invalid UUIDs can not have this scheme
				components.scheme = undefined;
			}
			
			return URI.SCHEMES["urn"].serialize(components, options);
		}
	};
}());/**
 * JSV: JSON Schema Validator
 * 
 * @fileOverview A JavaScript implementation of a extendable, fully compliant JSON Schema validator.
 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
 * @version 4.0.2
 * @see http://github.com/garycourt/JSV
 */

/*
 * Copyright 2010 Gary Court. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 * 
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 * 
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of Gary Court or the JSON Schema specification.
 */

/*jslint white: true, sub: true, onevar: true, undef: true, eqeqeq: true, newcap: true, immed: true, indent: 4 */

var exports = exports || this,
	require = require || function () {
		return exports;
	};

(function () {
	
	var URI = require("./uri/uri").URI,
		O = {},
		I2H = "0123456789abcdef".split(""),
		mapArray, filterArray, searchArray,
		
		JSV;
	
	//
	// Utility functions
	//
	
	function typeOf(o) {
		return o === undefined ? "undefined" : (o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase());
	}
	
	/** @inner */
	function F() {}
	
	function createObject(proto) {
		F.prototype = proto || {};
		return new F();
	}
	
	function mapObject(obj, func, scope) {
		var newObj = {}, key;
		for (key in obj) {
			if (obj[key] !== O[key]) {
				newObj[key] = func.call(scope, obj[key], key, obj);
			}
		}
		return newObj;
	}
	
	/** @ignore */
	mapArray = function (arr, func, scope) {
		var x = 0, xl = arr.length, newArr = new Array(xl);
		for (; x < xl; ++x) {
			newArr[x] = func.call(scope, arr[x], x, arr);
		}
		return newArr;
	};
		
	if (Array.prototype.map) {
		/** @ignore */
		mapArray = function (arr, func, scope) {
			return Array.prototype.map.call(arr, func, scope);
		};
	}
	
	/** @ignore */
	filterArray = function (arr, func, scope) {
		var x = 0, xl = arr.length, newArr = [];
		for (; x < xl; ++x) {
			if (func.call(scope, arr[x], x, arr)) {
				newArr[newArr.length] = arr[x];
			}
		}
		return newArr;
	};
	
	if (Array.prototype.filter) {
		/** @ignore */
		filterArray = function (arr, func, scope) {
			return Array.prototype.filter.call(arr, func, scope);
		};
	}
	
	/** @ignore */
	searchArray = function (arr, o) {
		var x = 0, xl = arr.length;
		for (; x < xl; ++x) {
			if (arr[x] === o) {
				return x;
			}
		}
		return -1;
	};
	
	if (Array.prototype.indexOf) {
		/** @ignore */
		searchArray = function (arr, o) {
			return Array.prototype.indexOf.call(arr, o);
		};
	}
	
	function toArray(o) {
		return o !== undefined && o !== null ? (o instanceof Array && !o.callee ? o : (typeof o.length !== "number" || o.split || o.setInterval || o.call ? [ o ] : Array.prototype.slice.call(o))) : [];
	}
	
	function keys(o) {
		var result = [], key;
		
		switch (typeOf(o)) {
		case "object":
			for (key in o) {
				if (o[key] !== O[key]) {
					result[result.length] = key;
				}
			}
			break;
		case "array":
			for (key = o.length - 1; key >= 0; --key) {
				result[key] = key;
			}
			break;
		}
		
		return result;
	}
	
	function pushUnique(arr, o) {
		if (searchArray(arr, o) === -1) {
			arr.push(o);
		}
		return arr;
	}
	
	function popFirst(arr, o) {
		var index = searchArray(arr, o);
		if (index > -1) {
			arr.splice(index, 1);
		}
		return arr;
	}
	
	function randomUUID() {
		return [
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			"-",
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			"-4",  //set 4 high bits of time_high field to version
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			"-",
			I2H[(Math.floor(Math.random() * 0x10) & 0x3) | 0x8],  //specify 2 high bits of clock sequence
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			"-",
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)],
			I2H[Math.floor(Math.random() * 0x10)]
		].join("");
	}
	
	function escapeURIComponent(str) {
		return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
	}
	
	function formatURI(uri) {
		if (typeof uri === "string" && uri.indexOf("#") === -1) {
			uri += "#";
		}
		return uri;
	}
	
	function stripInstances(o) {
		if (o instanceof JSONInstance) {
			return o.getURI();
		}
		
		switch (typeOf(o)) {
		case "undefined":
		case "null":
		case "boolean":
		case "number":
		case "string":
			return o;  //do nothing
		
		case "object":
			return mapObject(o, stripInstances);
		
		case "array":
			return mapArray(o, stripInstances);
		
		default:
			return o.toString();
		}
	}
	
	/**
	 * The exception that is thrown when a schema fails to be created.
	 * 
	 * @name InitializationError
	 * @class
	 * @param {JSONInstance|String} instance The instance (or instance URI) that is invalid
	 * @param {JSONSchema|String} schema The schema (or schema URI) that was validating the instance
	 * @param {String} attr The attribute that failed to validated
	 * @param {String} message A user-friendly message on why the schema attribute failed to validate the instance
	 * @param {Any} details The value of the schema attribute
	 */
	
	function InitializationError(instance, schema, attr, message, details) {
		Error.call(this, message);
		
		this.uri = instance instanceof JSONInstance ? instance.getURI() : instance;
		this.schemaUri = schema instanceof JSONInstance ? schema.getURI() : schema;
		this.attribute = attr;
		this.message = message;
		this.description = message;  //IE
		this.details = details;
	}
	
	InitializationError.prototype = new Error();
	InitializationError.prototype.constructor = InitializationError;
	InitializationError.prototype.name = "InitializationError";
	
	/**
	 * Defines an error, found by a schema, with an instance.
	 * This class can only be instantiated by {@link Report#addError}. 
	 * 
	 * @name ValidationError
	 * @class
	 * @see Report#addError
	 */
	
	/**
	 * The URI of the instance that has the error.
	 * 
	 * @name ValidationError.prototype.uri
	 * @type String
	 */
	
	/**
	 * The URI of the schema that generated the error.
	 * 
	 * @name ValidationError.prototype.schemaUri
	 * @type String
	 */
	
	/**
	 * The name of the schema attribute that generated the error.
	 * 
	 * @name ValidationError.prototype.attribute
	 * @type String
	 */
	
	/**
	 * An user-friendly (English) message about what failed to validate.
	 * 
	 * @name ValidationError.prototype.message
	 * @type String
	 */
	
	/**
	 * The value of the schema attribute that generated the error.
	 * 
	 * @name ValidationError.prototype.details
	 * @type Any
	 */
	
	/**
	 * Reports are returned from validation methods to describe the result of a validation.
	 * 
	 * @name Report
	 * @class
	 * @see JSONSchema#validate
	 * @see Environment#validate
	 */
	
	function Report() {
		/**
		 * An array of {@link ValidationError} objects that define all the errors generated by the schema against the instance.
		 * 
		 * @name Report.prototype.errors
		 * @type Array
		 * @see Report#addError
		 */
		this.errors = [];
		
		/**
		 * A hash table of every instance and what schemas were validated against it.
		 * <p>
		 * The key of each item in the table is the URI of the instance that was validated.
		 * The value of this key is an array of strings of URIs of the schema that validated it.
		 * </p>
		 * 
		 * @name Report.prototype.validated
		 * @type Object
		 * @see Report#registerValidation
		 * @see Report#isValidatedBy
		 */
		this.validated = {};
		
		/**
		 * If the report is generated by {@link Environment#validate}, this field is the generated instance.
		 * 
		 * @name Report.prototype.instance
		 * @type JSONInstance
		 * @see Environment#validate
		 */
		
		/**
		 * If the report is generated by {@link Environment#validate}, this field is the generated schema.
		 * 
		 * @name Report.prototype.schema
		 * @type JSONSchema
		 * @see Environment#validate
		 */
		 
		/**
		 * If the report is generated by {@link Environment#validate}, this field is the schema's schema.
		 * This value is the same as calling <code>schema.getSchema()</code>.
		 * 
		 * @name Report.prototype.schemaSchema
		 * @type JSONSchema
		 * @see Environment#validate
		 * @see JSONSchema#getSchema
		 */
	}
	
	/**
	 * Adds a {@link ValidationError} object to the <a href="#errors"><code>errors</code></a> field.
	 * 
	 * @param {JSONInstance|String} instance The instance (or instance URI) that is invalid
	 * @param {JSONSchema|String} schema The schema (or schema URI) that was validating the instance
	 * @param {String} attr The attribute that failed to validated
	 * @param {String} message A user-friendly message on why the schema attribute failed to validate the instance
	 * @param {Any} details The value of the schema attribute
	 */
	
	Report.prototype.addError = function (instance, schema, attr, message, details) {
		this.errors.push({
			uri : instance instanceof JSONInstance ? instance.getURI() : instance,
			schemaUri : schema instanceof JSONInstance ? schema.getURI() : schema,
			attribute : attr,
			message : message,
			details : stripInstances(details)
		});
	};
	
	/**
	 * Registers that the provided instance URI has been validated by the provided schema URI. 
	 * This is recorded in the <a href="#validated"><code>validated</code></a> field.
	 * 
	 * @param {String} uri The URI of the instance that was validated
	 * @param {String} schemaUri The URI of the schema that validated the instance
	 */
	
	Report.prototype.registerValidation = function (uri, schemaUri) {
		if (!this.validated[uri]) {
			this.validated[uri] = [ schemaUri ];
		} else {
			this.validated[uri].push(schemaUri);
		}
	};
	
	/**
	 * Returns if an instance with the provided URI has been validated by the schema with the provided URI. 
	 * 
	 * @param {String} uri The URI of the instance
	 * @param {String} schemaUri The URI of a schema
	 * @returns {Boolean} If the instance has been validated by the schema.
	 */
	
	Report.prototype.isValidatedBy = function (uri, schemaUri) {
		return !!this.validated[uri] && searchArray(this.validated[uri], schemaUri) !== -1;
	};
	
	/**
	 * A wrapper class for binding an Environment, URI and helper methods to an instance. 
	 * This class is most commonly instantiated with {@link Environment#createInstance}.
	 * 
	 * @name JSONInstance
	 * @class
	 * @param {Environment} env The environment this instance belongs to
	 * @param {JSONInstance|Any} json The value of the instance
	 * @param {String} [uri] The URI of the instance. If undefined, the URI will be a randomly generated UUID. 
	 * @param {String} [fd] The fragment delimiter for properties. If undefined, uses the environment default.
	 */
	
	function JSONInstance(env, json, uri, fd) {
		if (json instanceof JSONInstance) {
			if (typeof fd !== "string") {
				fd = json._fd;
			}
			if (typeof uri !== "string") {
				uri = json._uri;
			}
			json = json._value;
		}
		
		if (typeof uri !== "string") {
			uri = "urn:uuid:" + randomUUID() + "#";
		} else if (uri.indexOf(":") === -1) {
			uri = formatURI(URI.resolve("urn:uuid:" + randomUUID() + "#", uri));
		}
		
		this._env = env;
		this._value = json;
		this._uri = uri;
		this._fd = fd || this._env._options["defaultFragmentDelimiter"];
	}
	
	/**
	 * Returns the environment the instance is bound to.
	 * 
	 * @returns {Environment} The environment of the instance
	 */
	
	JSONInstance.prototype.getEnvironment = function () {
		return this._env;
	};
	
	/**
	 * Returns the name of the type of the instance.
	 * 
	 * @returns {String} The name of the type of the instance
	 */
	
	JSONInstance.prototype.getType = function () {
		return typeOf(this._value);
	};
	
	/**
	 * Returns the JSON value of the instance.
	 * 
	 * @returns {Any} The actual JavaScript value of the instance
	 */
	
	JSONInstance.prototype.getValue = function () {
		return this._value;
	};
	
	/**
	 * Returns the URI of the instance.
	 * 
	 * @returns {String} The URI of the instance
	 */
	
	JSONInstance.prototype.getURI = function () {
		return this._uri;
	};
	
	/**
	 * Returns a resolved URI of a provided relative URI against the URI of the instance.
	 * 
	 * @param {String} uri The relative URI to resolve
	 * @returns {String} The resolved URI
	 */
	
	JSONInstance.prototype.resolveURI = function (uri) {
		return formatURI(URI.resolve(this._uri, uri));
	};
	
	/**
	 * Returns an array of the names of all the properties.
	 * 
	 * @returns {Array} An array of strings which are the names of all the properties
	 */
	
	JSONInstance.prototype.getPropertyNames = function () {
		return keys(this._value);
	};
	
	/**
	 * Returns a {@link JSONInstance} of the value of the provided property name. 
	 * 
	 * @param {String} key The name of the property to fetch
	 * @returns {JSONInstance} The instance of the property value
	 */
	
	JSONInstance.prototype.getProperty = function (key) {
		var value = this._value ? this._value[key] : undefined;
		if (value instanceof JSONInstance) {
			return value;
		}
		//else
		return new JSONInstance(this._env, value, this._uri + this._fd + escapeURIComponent(key), this._fd);
	};
	
	/**
	 * Returns all the property instances of the target instance.
	 * <p>
	 * If the target instance is an Object, then the method will return a hash table of {@link JSONInstance}s of all the properties. 
	 * If the target instance is an Array, then the method will return an array of {@link JSONInstance}s of all the items.
	 * </p> 
	 * 
	 * @returns {Object|Array|undefined} The list of instances for all the properties
	 */
	
	JSONInstance.prototype.getProperties = function () {
		var type = typeOf(this._value),
			self = this;
		
		if (type === "object") {
			return mapObject(this._value, function (value, key) {
				if (value instanceof JSONInstance) {
					return value;
				}
				return new JSONInstance(self._env, value, self._uri + self._fd + escapeURIComponent(key), self._fd);
			});
		} else if (type === "array") {
			return mapArray(this._value, function (value, key) {
				if (value instanceof JSONInstance) {
					return value;
				}
				return new JSONInstance(self._env, value, self._uri + self._fd + escapeURIComponent(key), self._fd);
			});
		}
	};
	
	/**
	 * Returns the JSON value of the provided property name. 
	 * This method is a faster version of calling <code>instance.getProperty(key).getValue()</code>.
	 * 
	 * @param {String} key The name of the property
	 * @returns {Any} The JavaScript value of the instance
	 * @see JSONInstance#getProperty
	 * @see JSONInstance#getValue
	 */
	
	JSONInstance.prototype.getValueOfProperty = function (key) {
		if (this._value) {
			if (this._value[key] instanceof JSONInstance) {
				return this._value[key]._value;
			}
			return this._value[key];
		}
	};
	
	/**
	 * Return if the provided value is the same as the value of the instance.
	 * 
	 * @param {JSONInstance|Any} instance The value to compare
	 * @returns {Boolean} If both the instance and the value match
	 */
	
	JSONInstance.prototype.equals = function (instance) {
		if (instance instanceof JSONInstance) {
			return this._value === instance._value;
		}
		//else
		return this._value === instance;
	};
	
	/**
	 * Warning: Not a generic clone function
	 * Produces a JSV acceptable clone
	 */
	
	function clone(obj, deep) {
		var newObj, x;
		
		if (obj instanceof JSONInstance) {
			obj = obj.getValue();
		}
		
		switch (typeOf(obj)) {
		case "object":
			if (deep) {
				newObj = {};
				for (x in obj) {
					if (obj[x] !== O[x]) {
						newObj[x] = clone(obj[x], deep);
					}
				}
				return newObj;
			} else {
				return createObject(obj);
			}
			break;
		case "array":
			if (deep) {
				newObj = new Array(obj.length);
				x = obj.length;
				while (--x >= 0) {
					newObj[x] = clone(obj[x], deep);
				}
				return newObj;
			} else {
				return Array.prototype.slice.call(obj);
			}
			break;
		default:
			return obj;
		}
	}
	
	/**
	 * This class binds a {@link JSONInstance} with a {@link JSONSchema} to provided context aware methods. 
	 * 
	 * @name JSONSchema
	 * @class
	 * @param {Environment} env The environment this schema belongs to
	 * @param {JSONInstance|Any} json The value of the schema
	 * @param {String} [uri] The URI of the schema. If undefined, the URI will be a randomly generated UUID. 
	 * @param {JSONSchema|Boolean} [schema] The schema to bind to the instance. If <code>undefined</code>, the environment's default schema will be used. If <code>true</code>, the instance's schema will be itself.
	 * @extends JSONInstance
	 */
	
	function JSONSchema(env, json, uri, schema) {
		var fr;
		JSONInstance.call(this, env, json, uri);
		
		if (schema === true) {
			this._schema = this;
		} else if (json instanceof JSONSchema && !(schema instanceof JSONSchema)) {
			this._schema = json._schema;  //TODO: Make sure cross environments don't mess everything up
		} else {
			this._schema = schema instanceof JSONSchema ? schema : this._env.getDefaultSchema() || this._env.createEmptySchema();
		}
		
		//determine fragment delimiter from schema
		fr = this._schema.getValueOfProperty("fragmentResolution");
		if (fr === "dot-delimited") {
			this._fd = ".";
		} else if (fr === "slash-delimited") {
			this._fd = "/";
		}
		
		return this.rebuild();  //this works even when called with "new"
	}
	
	JSONSchema.prototype = createObject(JSONInstance.prototype);
	
	/**
	 * Returns the schema of the schema.
	 * 
	 * @returns {JSONSchema} The schema of the schema
	 */
	
	JSONSchema.prototype.getSchema = function () {
		var uri = this._refs && this._refs["describedby"],
			newSchema;
		
		if (uri) {
			newSchema = uri && this._env.findSchema(uri);
			
			if (newSchema) {
				if (!newSchema.equals(this._schema)) {
					this._schema = newSchema;
					this.rebuild();  //if the schema has changed, the context has changed - so everything must be rebuilt
				}
			} else if (this._env._options["enforceReferences"]) {
				throw new InitializationError(this, this._schema, "{describedby}", "Unknown schema reference", uri);
			}
		}
		
		return this._schema;
	};
	
	/**
	 * Returns the value of the provided attribute name.
	 * <p>
	 * This method is different from {@link JSONInstance#getProperty} as the named property 
	 * is converted using a parser defined by the schema's schema before being returned. This
	 * makes the return value of this method attribute dependent.
	 * </p>
	 * 
	 * @param {String} key The name of the attribute
	 * @param {Any} [arg] Some attribute parsers accept special arguments for returning resolved values. This is attribute dependent.
	 * @returns {JSONSchema|Any} The value of the attribute
	 */
	
	JSONSchema.prototype.getAttribute = function (key, arg) {
		var schemaProperty, parser, property, result,
			schema = this.getSchema();  //we do this here to make sure the "describedby" reference has not changed, and that the attribute cache is up-to-date
		
		if (!arg && this._attributes && this._attributes.hasOwnProperty(key)) {
			return this._attributes[key];
		}
		
		schemaProperty = schema.getProperty("properties").getProperty(key);
		parser = schemaProperty.getValueOfProperty("parser");
		property = this.getProperty(key);
		if (typeof parser === "function") {
			result = parser(property, schemaProperty, arg);
			if (!arg && this._attributes) {
				this._attributes[key] = result;
			}
			return result;
		}
		//else
		return property.getValue();
	};
	
	/**
	 * Returns all the attributes of the schema.
	 * 
	 * @returns {Object} A map of all parsed attribute values
	 */
	
	JSONSchema.prototype.getAttributes = function () {
		var properties, schemaProperties, key, schemaProperty, parser,
			schema = this.getSchema();  //we do this here to make sure the "describedby" reference has not changed, and that the attribute cache is up-to-date
		
		if (!this._attributes && this.getType() === "object") {
			properties = this.getProperties();
			schemaProperties = schema.getProperty("properties");
			this._attributes = {};
			for (key in properties) {
				if (properties[key] !== O[key]) {
					schemaProperty = schemaProperties && schemaProperties.getProperty(key);
					parser = schemaProperty && schemaProperty.getValueOfProperty("parser");
					if (typeof parser === "function") {
						this._attributes[key] = parser(properties[key], schemaProperty);
					} else {
						this._attributes[key] = properties[key].getValue();
					}
				}
			}
		}
		
		return clone(this._attributes, false);
	};
	
	/**
	 * Convenience method for retrieving a link or link object from a schema. 
	 * This method is the same as calling <code>schema.getAttribute("links", [rel, instance])[0];</code>.
	 * 
	 * @param {String} rel The link relationship
	 * @param {JSONInstance} [instance] The instance to resolve any URIs from
	 * @returns {String|Object|undefined} If <code>instance</code> is provided, a string containing the resolve URI of the link is returned.
	 *   If <code>instance</code> is not provided, a link object is returned with details of the link.
	 *   If no link with the provided relationship exists, <code>undefined</code> is returned.
	 * @see JSONSchema#getAttribute
	 */
	
	JSONSchema.prototype.getLink = function (rel, instance) {
		var schemaLinks = this.getAttribute("links", [rel, instance]);
		if (schemaLinks && schemaLinks.length && schemaLinks[schemaLinks.length - 1]) {
			return schemaLinks[schemaLinks.length - 1];
		}
	};
	
	/**
	 * Validates the provided instance against the target schema and returns a {@link Report}.
	 * 
	 * @param {JSONInstance|Any} instance The instance to validate; may be a {@link JSONInstance} or any JavaScript value
	 * @param {Report} [report] A {@link Report} to concatenate the result of the validation to. If <code>undefined</code>, a new {@link Report} is created. 
	 * @param {JSONInstance} [parent] The parent/containing instance of the provided instance
	 * @param {JSONSchema} [parentSchema] The schema of the parent/containing instance
	 * @param {String} [name] The name of the parent object's property that references the instance
	 * @returns {Report} The result of the validation
	 */
	
	JSONSchema.prototype.validate = function (instance, report, parent, parentSchema, name) {
		var schemaSchema = this.getSchema(),
			validator = schemaSchema.getValueOfProperty("validator");
		
		if (!(instance instanceof JSONInstance)) {
			instance = this.getEnvironment().createInstance(instance);
		}
		
		if (!(report instanceof Report)) {
			report = new Report();
		}
		
		if (this._env._options["validateReferences"] && this._refs) {
			if (this._refs["describedby"] && !this._env.findSchema(this._refs["describedby"])) {
				report.addError(this, this._schema, "{describedby}", "Unknown schema reference", this._refs["describedby"]);
			}
			if (this._refs["full"] && !this._env.findSchema(this._refs["full"])) {
				report.addError(this, this._schema, "{full}", "Unknown schema reference", this._refs["full"]);
			}
		}
		
		if (typeof validator === "function" && !report.isValidatedBy(instance.getURI(), this.getURI())) {
			report.registerValidation(instance.getURI(), this.getURI());
			validator(instance, this, schemaSchema, report, parent, parentSchema, name);
		}
		
		return report;
	};
	
	/** @inner */
	function createFullLookupWrapper(func) {
		return /** @inner */ function fullLookupWrapper() {
			var scope = this,
				stack = [],
				uri = scope._refs && scope._refs["full"],
				schema;
			
			while (uri) {
				schema = scope._env.findSchema(uri);
				if (schema) {
					if (schema._value === scope._value) {
						break;
					}
					scope = schema;
					stack.push(uri);
					uri = scope._refs && scope._refs["full"];
					if (stack.indexOf(uri) > -1) {
						break;  //stop infinite loop
					}
				} else if (scope._env._options["enforceReferences"]) {
					throw new InitializationError(scope, scope._schema, "{full}", "Unknown schema reference", uri);
				} else {
					uri = null;
				}
			}
			return func.apply(scope, arguments);
		};
	}
	
	/**
	 * Wraps all JSONInstance methods with a function that resolves the "full" reference.
	 * 
	 * @inner
	 */
	
	(function () {
		var key;
		for (key in JSONSchema.prototype) {
			if (JSONSchema.prototype[key] !== O[key] && typeOf(JSONSchema.prototype[key]) === "function") {
				JSONSchema.prototype[key] = createFullLookupWrapper(JSONSchema.prototype[key]);
			}
		}
	}());
	
	/**
	 * Reinitializes/re-registers/rebuilds the schema.
	 * <br/>
	 * This is used internally, and should only be called when a schema's private variables are modified directly.
	 * 
	 * @private
	 * @return {JSONSchema} The newly rebuilt schema
	 */
	
	JSONSchema.prototype.rebuild = function () {
		var instance = this,
			initializer = instance.getSchema().getValueOfProperty("initializer");
		
		//clear previous built values
		instance._refs = null;
		instance._attributes = null;
		
		if (typeof initializer === "function") {
			instance = initializer(instance);
		}
		
		//register schema
		instance._env._schemas[instance._uri] = instance;
		
		//build & cache the rest of the schema
		instance.getAttributes();
		
		return instance;
	};
	
	/**
	 * Set the provided reference to the given value.
	 * <br/>
	 * References are used for establishing soft-links to other {@link JSONSchema}s.
	 * Currently, the following references are natively supported:
	 * <dl>
	 *   <dt><code>full</code></dt>
	 *   <dd>The value is the URI to the full instance of this instance.</dd>
	 *   <dt><code>describedby</code></dt>
	 *   <dd>The value is the URI to the schema of this instance.</dd>
	 * </dl>
	 * 
	 * @param {String} name The name of the reference
	 * @param {String} uri The URI of the schema to refer to
	 */
	
	JSONSchema.prototype.setReference = function (name, uri) {
		if (!this._refs) {
			this._refs = {};
		}
		this._refs[name] = this.resolveURI(uri);
	};
	
	/**
	 * Returns the value of the provided reference name.
	 * 
	 * @param {String} name The name of the reference
	 * @return {String} The value of the provided reference name
	 */
	
	JSONSchema.prototype.getReference = function (name) {
		return this._refs && this._refs[name];
	};
	
	/**
	 * Merges two schemas/instances together.
	 */
	
	function inherits(base, extra, extension) {
		var baseType = typeOf(base),
			extraType = typeOf(extra),
			child, x;
		
		if (extraType === "undefined") {
			return clone(base, true);
		} else if (baseType === "undefined" || extraType !== baseType) {
			return clone(extra, true);
		} else if (extraType === "object") {
			if (base instanceof JSONSchema) {
				base = base.getAttributes();
			}
			if (extra instanceof JSONSchema) {
				extra = extra.getAttributes();
				if (extra["extends"] && extension && extra["extends"] instanceof JSONSchema) {
					extra["extends"] = [ extra["extends"] ];
				}
			}
			child = clone(base, true);  //this could be optimized as some properties get overwritten
			for (x in extra) {
				if (extra[x] !== O[x]) {
					child[x] = inherits(base[x], extra[x], extension);
				}
			}
			return child;
		} else {
			return clone(extra, true);
		}
	}
	
	/**
	 * An Environment is a sandbox of schemas thats behavior is different from other environments.
	 * 
	 * @name Environment
	 * @class
	 */
	
	function Environment() {
		this._id = randomUUID();
		this._schemas = {};
		this._options = {};
		
		this.createSchema({}, true, "urn:jsv:empty-schema#");
	}
	
	/**
	 * Returns a clone of the target environment.
	 * 
	 * @returns {Environment} A new {@link Environment} that is a exact copy of the target environment 
	 */
	
	Environment.prototype.clone = function () {
		var env = new Environment();
		env._schemas = createObject(this._schemas);
		env._options = createObject(this._options);
		
		return env;
	};
	
	/**
	 * Returns a new {@link JSONInstance} of the provided data.
	 * 
	 * @param {JSONInstance|Any} data The value of the instance
	 * @param {String} [uri] The URI of the instance. If undefined, the URI will be a randomly generated UUID. 
	 * @returns {JSONInstance} A new {@link JSONInstance} from the provided data
	 */
	
	Environment.prototype.createInstance = function (data, uri) {
		uri = formatURI(uri);
		
		if (data instanceof JSONInstance && (!uri || data.getURI() === uri)) {
			return data;
		}

		return new JSONInstance(this, data, uri);
	};
	
	/**
	 * Creates a new {@link JSONSchema} from the provided data, and registers it with the environment. 
	 * 
	 * @param {JSONInstance|Any} data The value of the schema
	 * @param {JSONSchema|Boolean} [schema] The schema to bind to the instance. If <code>undefined</code>, the environment's default schema will be used. If <code>true</code>, the instance's schema will be itself.
	 * @param {String} [uri] The URI of the schema. If undefined, the URI will be a randomly generated UUID. 
	 * @returns {JSONSchema} A new {@link JSONSchema} from the provided data
	 * @throws {InitializationError} If a schema that is not registered with the environment is referenced 
	 */
	
	Environment.prototype.createSchema = function (data, schema, uri) {
		uri = formatURI(uri);
		
		if (data instanceof JSONSchema && (!uri || data._uri === uri) && (!schema || data.getSchema().equals(schema))) {
			return data;
		}
		
		return new JSONSchema(this, data, uri, schema);
	};
	
	/**
	 * Creates an empty schema.
	 * 
	 * @returns {JSONSchema} The empty schema, who's schema is itself.
	 */
	
	Environment.prototype.createEmptySchema = function () {
		return this._schemas["urn:jsv:empty-schema#"];
	};
	
	/**
	 * Returns the schema registered with the provided URI.
	 * 
	 * @param {String} uri The absolute URI of the required schema
	 * @returns {JSONSchema|undefined} The request schema, or <code>undefined</code> if not found
	 */
	
	Environment.prototype.findSchema = function (uri) {
		return this._schemas[formatURI(uri)];
	};
	
	/**
	 * Sets the specified environment option to the specified value.
	 * 
	 * @param {String} name The name of the environment option to set
	 * @param {Any} value The new value of the environment option
	 */
	
	Environment.prototype.setOption = function (name, value) {
		this._options[name] = value;
	};
	
	/**
	 * Returns the specified environment option.
	 * 
	 * @param {String} name The name of the environment option to set
	 * @returns {Any} The value of the environment option
	 */
	
	Environment.prototype.getOption = function (name) {
		return this._options[name];
	};
	
	/**
	 * Sets the default fragment delimiter of the environment.
	 * 
	 * @deprecated Use {@link Environment#setOption} with option "defaultFragmentDelimiter"
	 * @param {String} fd The fragment delimiter character
	 */
	
	Environment.prototype.setDefaultFragmentDelimiter = function (fd) {
		if (typeof fd === "string" && fd.length > 0) {
			this._options["defaultFragmentDelimiter"] = fd;
		}
	};
	
	/**
	 * Returns the default fragment delimiter of the environment.
	 * 
	 * @deprecated Use {@link Environment#getOption} with option "defaultFragmentDelimiter"
	 * @returns {String} The fragment delimiter character
	 */
	
	Environment.prototype.getDefaultFragmentDelimiter = function () {
		return this._options["defaultFragmentDelimiter"];
	};
	
	/**
	 * Sets the URI of the default schema for the environment.
	 * 
	 * @deprecated Use {@link Environment#setOption} with option "defaultSchemaURI"
	 * @param {String} uri The default schema URI
	 */
	
	Environment.prototype.setDefaultSchemaURI = function (uri) {
		if (typeof uri === "string") {
			this._options["defaultSchemaURI"] = formatURI(uri);
		}
	};
	
	/**
	 * Returns the default schema of the environment.
	 * 
	 * @returns {JSONSchema} The default schema
	 */
	
	Environment.prototype.getDefaultSchema = function () {
		return this.findSchema(this._options["defaultSchemaURI"]);
	};
	
	/**
	 * Validates both the provided schema and the provided instance, and returns a {@link Report}. 
	 * If the schema fails to validate, the instance will not be validated.
	 * 
	 * @param {JSONInstance|Any} instanceJSON The {@link JSONInstance} or JavaScript value to validate.
	 * @param {JSONSchema|Any} schemaJSON The {@link JSONSchema} or JavaScript value to use in the validation. This will also be validated againt the schema's schema.
	 * @returns {Report} The result of the validation
	 */
	
	Environment.prototype.validate = function (instanceJSON, schemaJSON) {
		var instance,
			schema,
			schemaSchema,
			report = new Report();
		
		try {
			instance = this.createInstance(instanceJSON);
			report.instance = instance;
		} catch (e) {
			report.addError(e.uri, e.schemaUri, e.attribute, e.message, e.details);
		}
		
		try {
			schema = this.createSchema(schemaJSON);
			report.schema = schema;
			
			schemaSchema = schema.getSchema();
			report.schemaSchema = schemaSchema;
		} catch (f) {
			report.addError(f.uri, f.schemaUri, f.attribute, f.message, f.details);
		}
		
		if (schemaSchema) {
			schemaSchema.validate(schema, report);
		}
			
		if (report.errors.length) {
			return report;
		}
		
		return schema.validate(instance, report);
	};
	
	/**
	 * @private
	 */
	
	Environment.prototype._checkForInvalidInstances = function (stackSize, schemaURI) {
		var result = [],
			stack = [
				[schemaURI, this._schemas[schemaURI]]
			], 
			counter = 0,
			item, uri, instance, properties, key;
		
		while (counter++ < stackSize && stack.length) {
			item = stack.shift();
			uri = item[0];
			instance = item[1];
			
			if (instance instanceof JSONSchema) {
				if (this._schemas[instance._uri] !== instance) {
					result.push("Instance " + uri + " does not match " + instance._uri);
				} else {
					//schema = instance.getSchema();
					//stack.push([uri + "/{schema}", schema]);
					
					properties = instance.getAttributes();
					for (key in properties) {
						if (properties[key] !== O[key]) {
							stack.push([uri + "/" + escapeURIComponent(key), properties[key]]);
						}
					}
				}
			} else if (typeOf(instance) === "object") {
				properties = instance;
				for (key in properties) {
					if (properties.hasOwnProperty(key)) {
						stack.push([uri + "/" + escapeURIComponent(key), properties[key]]);
					}
				}
			} else if (typeOf(instance) === "array") {
				properties = instance;
				for (key = 0; key < properties.length; ++key) {
					stack.push([uri + "/" + escapeURIComponent(key), properties[key]]);
				}
			}
		}
		
		return result.length ? result : counter;
	};
	
	/**
	 * A globaly accessible object that provides the ability to create and manage {@link Environments},
	 * as well as providing utility methods.
	 * 
	 * @namespace
	 */
	
	JSV = {
		_environments : {},
		_defaultEnvironmentID : "",
		
		/**
		 * Returns if the provide value is an instance of {@link JSONInstance}.
		 * 
		 * @param o The value to test
		 * @returns {Boolean} If the provide value is an instance of {@link JSONInstance}
		 */
		
		isJSONInstance : function (o) {
			return o instanceof JSONInstance;
		},
		
		/**
		 * Returns if the provide value is an instance of {@link JSONSchema}.
		 * 
		 * @param o The value to test
		 * @returns {Boolean} If the provide value is an instance of {@link JSONSchema}
		 */
		
		isJSONSchema : function (o) {
			return o instanceof JSONSchema;
		},
		
		/**
		 * Creates and returns a new {@link Environment} that is a clone of the environment registered with the provided ID.
		 * If no environment ID is provided, the default environment is cloned.
		 * 
		 * @param {String} [id] The ID of the environment to clone. If <code>undefined</code>, the default environment ID is used.
		 * @returns {Environment} A newly cloned {@link Environment}
		 * @throws {Error} If there is no environment registered with the provided ID
		 */
		
		createEnvironment : function (id) {
			id = id || this._defaultEnvironmentID;
			
			if (!this._environments[id]) {
				throw new Error("Unknown Environment ID");
			}
			//else
			return this._environments[id].clone();
		},
		
		Environment : Environment,
		
		/**
		 * Registers the provided {@link Environment} with the provided ID.
		 * 
		 * @param {String} id The ID of the environment
		 * @param {Environment} env The environment to register
		 */
		
		registerEnvironment : function (id, env) {
			id = id || (env || 0)._id;
			if (id && !this._environments[id] && env instanceof Environment) {
				env._id = id;
				this._environments[id] = env;
			}
		},
		
		/**
		 * Sets which registered ID is the default environment.
		 * 
		 * @param {String} id The ID of the registered environment that is default
		 * @throws {Error} If there is no registered environment with the provided ID
		 */
		
		setDefaultEnvironmentID : function (id) {
			if (typeof id === "string") {
				if (!this._environments[id]) {
					throw new Error("Unknown Environment ID");
				}
				
				this._defaultEnvironmentID = id;
			}
		},
		
		/**
		 * Returns the ID of the default environment.
		 * 
		 * @returns {String} The ID of the default environment
		 */
		
		getDefaultEnvironmentID : function () {
			return this._defaultEnvironmentID;
		},
		
		//
		// Utility Functions
		//
		
		/**
		 * Returns the name of the type of the provided value.
		 *
		 * @event //utility
		 * @param {Any} o The value to determine the type of
		 * @returns {String} The name of the type of the value
		 */
		typeOf : typeOf,
		
		/**
		 * Return a new object that inherits all of the properties of the provided object.
		 *
		 * @event //utility
		 * @param {Object} proto The prototype of the new object
		 * @returns {Object} A new object that inherits all of the properties of the provided object
		 */
		createObject : createObject,
		
		/**
		 * Returns a new object with each property transformed by the iterator.
		 *
		 * @event //utility
		 * @param {Object} obj The object to transform
		 * @param {Function} iterator A function that returns the new value of the provided property
		 * @param {Object} [scope] The value of <code>this</code> in the iterator
		 * @returns {Object} A new object with each property transformed
		 */
		mapObject : mapObject,
		
		/**
		 * Returns a new array with each item transformed by the iterator.
		 * 
		 * @event //utility
		 * @param {Array} arr The array to transform
		 * @param {Function} iterator A function that returns the new value of the provided item
		 * @param {Object} scope The value of <code>this</code> in the iterator
		 * @returns {Array} A new array with each item transformed
		 */
		mapArray : mapArray,
		
		/**
		 * Returns a new array that only contains the items allowed by the iterator.
		 *
		 * @event //utility
		 * @param {Array} arr The array to filter
		 * @param {Function} iterator The function that returns true if the provided property should be added to the array
		 * @param {Object} scope The value of <code>this</code> within the iterator
		 * @returns {Array} A new array that contains the items allowed by the iterator
		 */
		filterArray : filterArray,
		
		/**
		 * Returns the first index in the array that the provided item is located at.
		 *
		 * @event //utility
		 * @param {Array} arr The array to search
		 * @param {Any} o The item being searched for
		 * @returns {Number} The index of the item in the array, or <code>-1</code> if not found
		 */
		searchArray : searchArray,
			
		/**
		 * Returns an array representation of a value.
		 * <ul>
		 * <li>For array-like objects, the value will be casted as an Array type.</li>
		 * <li>If an array is provided, the function will simply return the same array.</li>
		 * <li>For a null or undefined value, the result will be an empty Array.</li>
		 * <li>For all other values, the value will be the first element in a new Array. </li>
		 * </ul>
		 *
		 * @event //utility
		 * @param {Any} o The value to convert into an array
		 * @returns {Array} The value as an array
		 */
		toArray : toArray,
		
		/**
		 * Returns an array of the names of all properties of an object.
		 * 
		 * @event //utility
		 * @param {Object|Array} o The object in question
		 * @returns {Array} The names of all properties
		 */
		keys : keys,
		
		/**
		 * Mutates the array by pushing the provided value onto the array only if it is not already there.
		 *
		 * @event //utility
		 * @param {Array} arr The array to modify
		 * @param {Any} o The object to add to the array if it is not already there
		 * @returns {Array} The provided array for chaining
		 */
		pushUnique : pushUnique,
		
		/**
		 * Mutates the array by removing the first item that matches the provided value in the array.
		 *
		 * @event //utility
		 * @param {Array} arr The array to modify
		 * @param {Any} o The object to remove from the array
		 * @returns {Array} The provided array for chaining
		 */
		popFirst : popFirst,
		
		/**
		 * Creates a copy of the target object.
		 * <p>
		 * This method will create a new instance of the target, and then mixin the properties of the target.
		 * If <code>deep</code> is <code>true</code>, then each property will be cloned before mixin.
		 * </p>
		 * <p><b>Warning</b>: This is not a generic clone function, as it will only properly clone objects and arrays.</p>
		 * 
		 * @event //utility
		 * @param {Any} o The value to clone 
		 * @param {Boolean} [deep=false] If each property should be recursively cloned
		 * @returns A cloned copy of the provided value
		 */
		clone : clone,
		
		/**
		 * Generates a pseudo-random UUID.
		 * 
		 * @event //utility
		 * @returns {String} A new universally unique ID
		 */
		randomUUID : randomUUID,
		
		/**
		 * Properly escapes a URI component for embedding into a URI string.
		 * 
		 * @event //utility
		 * @param {String} str The URI component to escape
		 * @returns {String} The escaped URI component
		 */
		escapeURIComponent : escapeURIComponent,
		
		/**
		 * Returns a URI that is formated for JSV. Currently, this only ensures that the URI ends with a hash tag (<code>#</code>).
		 * 
		 * @event //utility
		 * @param {String} uri The URI to format
		 * @returns {String} The URI formatted for JSV
		 */
		formatURI : formatURI,
		
		/**
		 * Merges two schemas/instance together.
		 * 
		 * @event //utility
		 * @param {JSONSchema|Any} base The old value to merge
		 * @param {JSONSchema|Any} extra The new value to merge
		 * @param {Boolean} extension If the merge is a JSON Schema extension
		 * @return {Any} The modified base value
		 */
		 
		inherits : inherits,
		
		/**
		 * @private
		 * @event //utility
		 */
		
		InitializationError : InitializationError
	};
	
	this.JSV = JSV;  //set global object
	exports.JSV = JSV;  //export to CommonJS
	
	require("./environments");  //load default environments
	
}());/**
 * json-schema-draft-03 Environment
 * 
 * @fileOverview Implementation of the third revision of the JSON Schema specification draft.
 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
 * @version 1.5.1
 * @see http://github.com/garycourt/JSV
 */

/*
 * Copyright 2010 Gary Court. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 * 
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 * 
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of Gary Court or the JSON Schema specification.
 */

/*jslint white: true, sub: true, onevar: true, undef: true, eqeqeq: true, newcap: true, immed: true, indent: 4 */
/*global require */

(function () {
	var O = {},
		JSV = require('./jsv').JSV,
		TYPE_VALIDATORS,
		ENVIRONMENT,
		SCHEMA_00_JSON,
		HYPERSCHEMA_00_JSON,
		LINKS_00_JSON, 
		SCHEMA_00,
		HYPERSCHEMA_00,
		LINKS_00, 
		SCHEMA_01_JSON,
		HYPERSCHEMA_01_JSON,
		LINKS_01_JSON, 
		SCHEMA_01,
		HYPERSCHEMA_01,
		LINKS_01, 
		SCHEMA_02_JSON,
		HYPERSCHEMA_02_JSON,
		LINKS_02_JSON,
		SCHEMA_02,
		HYPERSCHEMA_02,
		LINKS_02, 
		SCHEMA_03_JSON,
		HYPERSCHEMA_03_JSON,
		LINKS_03_JSON,
		SCHEMA_03,
		HYPERSCHEMA_03,
		LINKS_03;
	
	TYPE_VALIDATORS = {
		"string" : function (instance, report) {
			return instance.getType() === "string";
		},
		
		"number" : function (instance, report) {
			return instance.getType() === "number";
		},
		
		"integer" : function (instance, report) {
			return instance.getType() === "number" && instance.getValue() % 1 === 0;
		},
		
		"boolean" : function (instance, report) {
			return instance.getType() === "boolean";
		},
		
		"object" : function (instance, report) {
			return instance.getType() === "object";
		},
		
		"array" : function (instance, report) {
			return instance.getType() === "array";
		},
		
		"null" : function (instance, report) {
			return instance.getType() === "null";
		},
		
		"any" : function (instance, report) {
			return true;
		}
	};
	
	ENVIRONMENT = new JSV.Environment();
	ENVIRONMENT.setOption("validateReferences", true);
	ENVIRONMENT.setOption("enforceReferences", false);
	ENVIRONMENT.setOption("strict", false);
	
	//
	// draft-00
	//
	
	SCHEMA_00_JSON = {
		"$schema" : "http://json-schema.org/draft-00/hyper-schema#",
		"id" : "http://json-schema.org/draft-00/schema#",
		"type" : "object",
		
		"properties" : {
			"type" : {
				"type" : ["string", "array"],
				"items" : {
					"type" : ["string", {"$ref" : "#"}]
				},
				"optional" : true,
				"uniqueItems" : true,
				"default" : "any",
				
				"parser" : function (instance, self) {
					var parser;
					
					if (instance.getType() === "string") {
						return instance.getValue();
					} else if (instance.getType() === "object") {
						return instance.getEnvironment().createSchema(
							instance, 
							self.getEnvironment().findSchema(self.resolveURI("#"))
						);
					} else if (instance.getType() === "array") {
						parser = self.getValueOfProperty("parser");
						return JSV.mapArray(instance.getProperties(), function (prop) {
							return parser(prop, self);
						});
					}
					//else
					return "any";
				},
			
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var requiredTypes = JSV.toArray(schema.getAttribute("type")),
						x, xl, type, subreport, typeValidators;
					
					//for instances that are required to be a certain type
					if (instance.getType() !== "undefined" && requiredTypes && requiredTypes.length) {
						typeValidators = self.getValueOfProperty("typeValidators") || {};
						
						//ensure that type matches for at least one of the required types
						for (x = 0, xl = requiredTypes.length; x < xl; ++x) {
							type = requiredTypes[x];
							if (JSV.isJSONSchema(type)) {
								subreport = JSV.createObject(report);
								subreport.errors = [];
								subreport.validated = JSV.clone(report.validated);
								if (type.validate(instance, subreport, parent, parentSchema, name).errors.length === 0) {
									return true;  //instance matches this schema
								}
							} else {
								if (typeValidators[type] !== O[type] && typeof typeValidators[type] === "function") {
									if (typeValidators[type](instance, report)) {
										return true;  //type is valid
									}
								} else {
									return true;  //unknown types are assumed valid
								}
							}
						}
						
						//if we get to this point, type is invalid
						report.addError(instance, schema, "type", "Instance is not a required type", requiredTypes);
						return false;
					}
					//else, anything is allowed if no type is specified
					return true;
				},
				
				"typeValidators" : TYPE_VALIDATORS
			},
			
			"properties" : {
				"type" : "object",
				"additionalProperties" : {"$ref" : "#"},
				"optional" : true,
				"default" : {},
				
				"parser" : function (instance, self, arg) {
					var env = instance.getEnvironment(),
						selfEnv = self.getEnvironment();
					if (instance.getType() === "object") {
						if (arg) {
							return env.createSchema(instance.getProperty(arg), selfEnv.findSchema(self.resolveURI("#")));
						} else {
							return JSV.mapObject(instance.getProperties(), function (instance) {
								return env.createSchema(instance, selfEnv.findSchema(self.resolveURI("#")));
							});
						}
					}
					//else
					return {};
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var propertySchemas, key;
					//this attribute is for object type instances only
					if (instance.getType() === "object") {
						//for each property defined in the schema
						propertySchemas = schema.getAttribute("properties");
						for (key in propertySchemas) {
							if (propertySchemas[key] !== O[key] && propertySchemas[key]) {
								//ensure that instance property is valid
								propertySchemas[key].validate(instance.getProperty(key), report, instance, schema, key);
							}
						}
					}
				}
			},
			
			"items" : {
				"type" : [{"$ref" : "#"}, "array"],
				"items" : {"$ref" : "#"},
				"optional" : true,
				"default" : {},
				
				"parser" : function (instance, self) {
					if (instance.getType() === "object") {
						return instance.getEnvironment().createSchema(instance, self.getEnvironment().findSchema(self.resolveURI("#")));
					} else if (instance.getType() === "array") {
						return JSV.mapArray(instance.getProperties(), function (instance) {
							return instance.getEnvironment().createSchema(instance, self.getEnvironment().findSchema(self.resolveURI("#")));
						});
					}
					//else
					return instance.getEnvironment().createEmptySchema();
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var properties, items, x, xl, itemSchema, additionalProperties;
					
					if (instance.getType() === "array") {
						properties = instance.getProperties();
						items = schema.getAttribute("items");
						additionalProperties = schema.getAttribute("additionalProperties");
						
						if (JSV.typeOf(items) === "array") {
							for (x = 0, xl = properties.length; x < xl; ++x) {
								itemSchema = items[x] || additionalProperties;
								if (itemSchema !== false) {
									itemSchema.validate(properties[x], report, instance, schema, x);
								} else {
									report.addError(instance, schema, "additionalProperties", "Additional items are not allowed", itemSchema);
								}
							}
						} else {
							itemSchema = items || additionalProperties;
							for (x = 0, xl = properties.length; x < xl; ++x) {
								itemSchema.validate(properties[x], report, instance, schema, x);
							}
						}
					}
				}
			},
			
			"optional" : {
				"type" : "boolean",
				"optional" : true,
				"default" : false,
				
				"parser" : function (instance, self) {
					return !!instance.getValue();
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					if (instance.getType() === "undefined" && !schema.getAttribute("optional")) {
						report.addError(instance, schema, "optional", "Property is required", false);
					}
				},
				
				"validationRequired" : true
			},
			
			"additionalProperties" : {
				"type" : [{"$ref" : "#"}, "boolean"],
				"optional" : true,
				"default" : {},
				
				"parser" : function (instance, self) {
					if (instance.getType() === "object") {
						return instance.getEnvironment().createSchema(instance, self.getEnvironment().findSchema(self.resolveURI("#")));
					} else if (instance.getType() === "boolean" && instance.getValue() === false) {
						return false;
					}
					//else
					return instance.getEnvironment().createEmptySchema();
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var additionalProperties, propertySchemas, properties, key;
					//we only need to check against object types as arrays do their own checking on this property
					if (instance.getType() === "object") {
						additionalProperties = schema.getAttribute("additionalProperties");
						propertySchemas = schema.getAttribute("properties") || {};
						properties = instance.getProperties();
						for (key in properties) {
							if (properties[key] !== O[key] && properties[key] && propertySchemas[key] === O[key]) {
								if (JSV.isJSONSchema(additionalProperties)) {
									additionalProperties.validate(properties[key], report, instance, schema, key);
								} else if (additionalProperties === false) {
									report.addError(instance, schema, "additionalProperties", "Additional properties are not allowed", additionalProperties);
								}
							}
						}
					}
				}
			},
			
			"requires" : {
				"type" : ["string", {"$ref" : "#"}],
				"optional" : true,
				
				"parser" : function (instance, self) {
					if (instance.getType() === "string") {
						return instance.getValue();
					} else if (instance.getType() === "object") {
						return instance.getEnvironment().createSchema(instance, self.getEnvironment().findSchema(self.resolveURI("#")));
					}
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var requires;
					if (instance.getType() !== "undefined" && parent && parent.getType() !== "undefined") {
						requires = schema.getAttribute("requires");
						if (typeof requires === "string") {
							if (parent.getProperty(requires).getType() === "undefined") {
								report.addError(instance, schema, "requires", 'Property requires sibling property "' + requires + '"', requires);
							}
						} else if (JSV.isJSONSchema(requires)) {
							requires.validate(parent, report);  //WATCH: A "requires" schema does not support the "requires" attribute
						}
					}
				}
			},
			
			"minimum" : {
				"type" : "number",
				"optional" : true,
				
				"parser" : function (instance, self) {
					if (instance.getType() === "number") {
						return instance.getValue();
					}
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var minimum, minimumCanEqual;
					if (instance.getType() === "number") {
						minimum = schema.getAttribute("minimum");
						minimumCanEqual = schema.getAttribute("minimumCanEqual");
						if (typeof minimum === "number" && (instance.getValue() < minimum || (minimumCanEqual === false && instance.getValue() === minimum))) {
							report.addError(instance, schema, "minimum", "Number is less than the required minimum value", minimum);
						}
					}
				}
			},
			
			"maximum" : {
				"type" : "number",
				"optional" : true,
				
				"parser" : function (instance, self) {
					if (instance.getType() === "number") {
						return instance.getValue();
					}
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var maximum, maximumCanEqual;
					if (instance.getType() === "number") {
						maximum = schema.getAttribute("maximum");
						maximumCanEqual = schema.getAttribute("maximumCanEqual");
						if (typeof maximum === "number" && (instance.getValue() > maximum || (maximumCanEqual === false && instance.getValue() === maximum))) {
							report.addError(instance, schema, "maximum", "Number is greater than the required maximum value", maximum);
						}
					}
				}
			},
			
			"minimumCanEqual" : {
				"type" : "boolean",
				"optional" : true,
				"requires" : "minimum",
				"default" : true,
				
				"parser" : function (instance, self) {
					if (instance.getType() === "boolean") {
						return instance.getValue();
					}
					//else
					return true;
				}
			},
			
			"maximumCanEqual" : {
				"type" : "boolean",
				"optional" : true,
				"requires" : "maximum",
				"default" : true,
				
				"parser" : function (instance, self) {
					if (instance.getType() === "boolean") {
						return instance.getValue();
					}
					//else
					return true;
				}
			},
			
			"minItems" : {
				"type" : "integer",
				"optional" : true,
				"minimum" : 0,
				"default" : 0,
				
				"parser" : function (instance, self) {
					if (instance.getType() === "number") {
						return instance.getValue();
					}
					//else
					return 0;
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var minItems;
					if (instance.getType() === "array") {
						minItems = schema.getAttribute("minItems");
						if (typeof minItems === "number" && instance.getProperties().length < minItems) {
							report.addError(instance, schema, "minItems", "The number of items is less than the required minimum", minItems);
						}
					}
				}
			},
			
			"maxItems" : {
				"type" : "integer",
				"optional" : true,
				"minimum" : 0,
				
				"parser" : function (instance, self) {
					if (instance.getType() === "number") {
						return instance.getValue();
					}
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var maxItems;
					if (instance.getType() === "array") {
						maxItems = schema.getAttribute("maxItems");
						if (typeof maxItems === "number" && instance.getProperties().length > maxItems) {
							report.addError(instance, schema, "maxItems", "The number of items is greater than the required maximum", maxItems);
						}
					}
				}
			},
			
			"pattern" : {
				"type" : "string",
				"optional" : true,
				"format" : "regex",
				
				"parser" : function (instance, self) {
					if (instance.getType() === "string") {
						return instance.getValue();
					}
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var pattern;
					try {
						pattern = new RegExp(schema.getAttribute("pattern"));
						if (instance.getType() === "string" && pattern && !pattern.test(instance.getValue())) {
							report.addError(instance, schema, "pattern", "String does not match pattern", pattern.toString());
						}
					} catch (e) {
						report.addError(schema, self, "pattern", "Invalid pattern", schema.getValueOfProperty("pattern"));
					}
				}
			},
			
			"minLength" : {
				"type" : "integer",
				"optional" : true,
				"minimum" : 0,
				"default" : 0,
				
				"parser" : function (instance, self) {
					if (instance.getType() === "number") {
						return instance.getValue();
					}
					//else
					return 0;
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var minLength;
					if (instance.getType() === "string") {
						minLength = schema.getAttribute("minLength");
						if (typeof minLength === "number" && instance.getValue().length < minLength) {
							report.addError(instance, schema, "minLength", "String is less than the required minimum length", minLength);
						}
					}
				}
			},
			
			"maxLength" : {
				"type" : "integer",
				"optional" : true,
				
				"parser" : function (instance, self) {
					if (instance.getType() === "number") {
						return instance.getValue();
					}
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var maxLength;
					if (instance.getType() === "string") {
						maxLength = schema.getAttribute("maxLength");
						if (typeof maxLength === "number" && instance.getValue().length > maxLength) {
							report.addError(instance, schema, "maxLength", "String is greater than the required maximum length", maxLength);
						}
					}
				}
			},
			
			"enum" : {
				"type" : "array",
				"optional" : true,
				"minItems" : 1,
				"uniqueItems" : true,
				
				"parser" : function (instance, self) {
					if (instance.getType() === "array") {
						return instance.getValue();
					}
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var enums, x, xl;
					if (instance.getType() !== "undefined") {
						enums = schema.getAttribute("enum");
						if (enums) {
							for (x = 0, xl = enums.length; x < xl; ++x) {
								if (instance.equals(enums[x])) {
									return true;
								}
							}
							report.addError(instance, schema, "enum", "Instance is not one of the possible values", enums);
						}
					}
				}
			},
			
			"title" : {
				"type" : "string",
				"optional" : true
			},
			
			"description" : {
				"type" : "string",
				"optional" : true
			},
			
			"format" : {
				"type" : "string",
				"optional" : true,
				
				"parser" : function (instance, self) {
					if (instance.getType() === "string") {
						return instance.getValue();
					}
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var format, formatValidators;
					if (instance.getType() === "string") {
						format = schema.getAttribute("format");
						formatValidators = self.getValueOfProperty("formatValidators");
						if (typeof format === "string" && formatValidators[format] !== O[format] && typeof formatValidators[format] === "function" && !formatValidators[format].call(this, instance, report)) {
							report.addError(instance, schema, "format", "String is not in the required format", format);
						}
					}
				},
				
				"formatValidators" : {}
			},
			
			"contentEncoding" : {
				"type" : "string",
				"optional" : true
			},
			
			"default" : {
				"type" : "any",
				"optional" : true
			},
			
			"maxDecimal" : {
				"type" : "integer",
				"optional" : true,
				"minimum" : 0,
								
				"parser" : function (instance, self) {
					if (instance.getType() === "number") {
						return instance.getValue();
					}
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var maxDecimal, decimals;
					if (instance.getType() === "number") {
						maxDecimal = schema.getAttribute("maxDecimal");
						if (typeof maxDecimal === "number") {
							decimals = instance.getValue().toString(10).split('.')[1];
							if (decimals && decimals.length > maxDecimal) {
								report.addError(instance, schema, "maxDecimal", "The number of decimal places is greater than the allowed maximum", maxDecimal);
							}
						}
					}
				}
			},
			
			"disallow" : {
				"type" : ["string", "array"],
				"items" : {"type" : "string"},
				"optional" : true,
				"uniqueItems" : true,
				
				"parser" : function (instance, self) {
					if (instance.getType() === "string" || instance.getType() === "array") {
						return instance.getValue();
					}
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var disallowedTypes = JSV.toArray(schema.getAttribute("disallow")),
						x, xl, key, typeValidators, subreport;
					
					//for instances that are required to be a certain type
					if (instance.getType() !== "undefined" && disallowedTypes && disallowedTypes.length) {
						typeValidators = self.getValueOfProperty("typeValidators") || {};
						
						//ensure that type matches for at least one of the required types
						for (x = 0, xl = disallowedTypes.length; x < xl; ++x) {
							key = disallowedTypes[x];
							if (JSV.isJSONSchema(key)) {  //this is supported draft-03 and on
								subreport = JSV.createObject(report);
								subreport.errors = [];
								subreport.validated = JSV.clone(report.validated);
								if (key.validate(instance, subreport, parent, parentSchema, name).errors.length === 0) {
									//instance matches this schema
									report.addError(instance, schema, "disallow", "Instance is a disallowed type", disallowedTypes);
									return false;  
								}
							} else if (typeValidators[key] !== O[key] && typeof typeValidators[key] === "function") {
								if (typeValidators[key](instance, report)) {
									report.addError(instance, schema, "disallow", "Instance is a disallowed type", disallowedTypes);
									return false;
								}
							} 
							/*
							else {
								report.addError(instance, schema, "disallow", "Instance may be a disallowed type", disallowedTypes);
								return false;
							}
							*/
						}
						
						//if we get to this point, type is valid
						return true;
					}
					//else, everything is allowed if no disallowed types are specified
					return true;
				},
				
				"typeValidators" : TYPE_VALIDATORS
			},
		
			"extends" : {
				"type" : [{"$ref" : "#"}, "array"],
				"items" : {"$ref" : "#"},
				"optional" : true,
				"default" : {},
				
				"parser" : function (instance, self) {
					if (instance.getType() === "object") {
						return instance.getEnvironment().createSchema(instance, self.getEnvironment().findSchema(self.resolveURI("#")));
					} else if (instance.getType() === "array") {
						return JSV.mapArray(instance.getProperties(), function (instance) {
							return instance.getEnvironment().createSchema(instance, self.getEnvironment().findSchema(self.resolveURI("#")));
						});
					}
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var extensions = schema.getAttribute("extends"), x, xl;
					if (extensions) {
						if (JSV.isJSONSchema(extensions)) {
							extensions.validate(instance, report, parent, parentSchema, name);
						} else if (JSV.typeOf(extensions) === "array") {
							for (x = 0, xl = extensions.length; x < xl; ++x) {
								extensions[x].validate(instance, report, parent, parentSchema, name);
							}
						}
					}
				}
			}
		},
		
		"optional" : true,
		"default" : {},
		"fragmentResolution" : "dot-delimited",
		
		"parser" : function (instance, self) {
			if (instance.getType() === "object") {
				return instance.getEnvironment().createSchema(instance, self);
			}
		},
		
		"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
			var propNames = schema.getPropertyNames(), 
				x, xl,
				attributeSchemas = self.getAttribute("properties"),
				strict = instance.getEnvironment().getOption("strict"),
				validator;
			
			for (x in attributeSchemas) {
				if (attributeSchemas[x] !== O[x]) {
					if (attributeSchemas[x].getValueOfProperty("validationRequired")) {
						JSV.pushUnique(propNames, x);
					}
					if (strict && attributeSchemas[x].getValueOfProperty("deprecated")) {
						JSV.popFirst(propNames, x);
					}
				}
			}
			
			for (x = 0, xl = propNames.length; x < xl; ++x) {
				if (attributeSchemas[propNames[x]] !== O[propNames[x]]) {
					validator = attributeSchemas[propNames[x]].getValueOfProperty("validator");
					if (typeof validator === "function") {
						validator(instance, schema, attributeSchemas[propNames[x]], report, parent, parentSchema, name);
					}
				}
			}
		}
	};
	
	HYPERSCHEMA_00_JSON = {
		"$schema" : "http://json-schema.org/draft-00/hyper-schema#",
		"id" : "http://json-schema.org/draft-00/hyper-schema#",
	
		"properties" : {
			"links" : {
				"type" : "array",
				"items" : {"$ref" : "links#"},
				"optional" : true,
				
				"parser" : function (instance, self, arg) {
					var links,
						linkSchemaURI = self.getValueOfProperty("items")["$ref"],
						linkSchema = self.getEnvironment().findSchema(linkSchemaURI),
						linkParser = linkSchema && linkSchema.getValueOfProperty("parser"),
						selfReferenceVariable;
					arg = JSV.toArray(arg);
					
					if (typeof linkParser === "function") {
						links = JSV.mapArray(instance.getProperties(), function (link) {
							return linkParser(link, linkSchema);
						});
					} else {
						links = JSV.toArray(instance.getValue());
					}
					
					if (arg[0]) {
						links = JSV.filterArray(links, function (link) {
							return link["rel"] === arg[0];
						});
					}
					
					if (arg[1]) {
						selfReferenceVariable = self.getValueOfProperty("selfReferenceVariable");
						links = JSV.mapArray(links, function (link) {
							var instance = arg[1],
								href = link["href"];
							href = href.replace(/\{(.+)\}/g, function (str, p1, offset, s) {
								var value; 
								if (p1 === selfReferenceVariable) {
									value = instance.getValue();
								} else {
									value = instance.getValueOfProperty(p1);
								}
								return value !== undefined ? String(value) : "";
							});
							return href ? JSV.formatURI(instance.resolveURI(href)) : href;
						});
					}
					
					return links;
				},
				
				"selfReferenceVariable" : "-this"
			},
			
			"fragmentResolution" : {
				"type" : "string",
				"optional" : true,
				"default" : "dot-delimited"
			},
			
			"root" : {
				"type" : "boolean",
				"optional" : true,
				"default" : false
			},
			
			"readonly" : {
				"type" : "boolean",
				"optional" : true,
				"default" : false
			},
			
			"pathStart" : {
				"type" : "string",
				"optional" : true,
				"format" : "uri",
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var pathStart;
					if (instance.getType() !== "undefined") {
						pathStart = schema.getAttribute("pathStart");
						if (typeof pathStart === "string") {
							//TODO: Find out what pathStart is relative to
							if (instance.getURI().indexOf(pathStart) !== 0) {
								report.addError(instance, schema, "pathStart", "Instance's URI does not start with " + pathStart, pathStart);
							}
						}
					}
				}
			},
			
			"mediaType" : {
				"type" : "string",
				"optional" : true,
				"format" : "media-type"
			},
			
			"alternate" : {
				"type" : "array",
				"items" : {"$ref" : "#"},
				"optional" : true
			}
		},
		
		"links" : [
			{
				"href" : "{$ref}",
				"rel" : "full"
			},
			
			{
				"href" : "{$schema}",
				"rel" : "describedby"
			},
			
			{
				"href" : "{id}",
				"rel" : "self"
			}
		],
				
		"initializer" : function (instance) {
			var link, extension, extended;
			
			//if there is a link to a different schema, set reference
			link = instance._schema.getLink("describedby", instance);
			if (link && instance._schema._uri !== link) {
				instance.setReference("describedby", link);
			}
			
			//if instance has a URI link to itself, update it's own URI
			link = instance._schema.getLink("self", instance);
			if (JSV.typeOf(link) === "string") {
				instance._uri = JSV.formatURI(link);
			}
			
			//if there is a link to the full representation, set reference
			link = instance._schema.getLink("full", instance);
			if (link && instance._uri !== link) {
				instance.setReference("full", link);
			}
			
			//extend schema
			extension = instance.getAttribute("extends");
			if (JSV.isJSONSchema(extension)) {
				extended = JSV.inherits(extension, instance, true);
				instance = instance._env.createSchema(extended, instance._schema, instance._uri);
			}
			
			return instance;
		}
		
		//not needed as JSV.inherits does the job for us
		//"extends" : {"$ref" : "http://json-schema.org/schema#"}
	};
	
	LINKS_00_JSON = {
		"$schema" : "http://json-schema.org/draft-00/hyper-schema#",
		"id" : "http://json-schema.org/draft-00/links#",
		"type" : "object",
		
		"properties" : {
			"href" : {
				"type" : "string"
			},
			
			"rel" : {
				"type" : "string"
			},
			
			"method" : {
				"type" : "string",
				"default" : "GET",
				"optional" : true
			},
			
			"enctype" : {
				"type" : "string",
				"requires" : "method",
				"optional" : true
			},
			
			"properties" : {
				"type" : "object",
				"additionalProperties" : {"$ref" : "hyper-schema#"},
				"optional" : true,
				
				"parser" : function (instance, self, arg) {
					var env = instance.getEnvironment(),
						selfEnv = self.getEnvironment(),
						additionalPropertiesSchemaURI = self.getValueOfProperty("additionalProperties")["$ref"];
					if (instance.getType() === "object") {
						if (arg) {
							return env.createSchema(instance.getProperty(arg), selfEnv.findSchema(self.resolveURI(additionalPropertiesSchemaURI)));
						} else {
							return JSV.mapObject(instance.getProperties(), function (instance) {
								return env.createSchema(instance, selfEnv.findSchema(self.resolveURI(additionalPropertiesSchemaURI)));
							});
						}
					}
				}
			}
		},
		
		"parser" : function (instance, self) {
			var selfProperties = self.getProperty("properties");
			if (instance.getType() === "object") {
				return JSV.mapObject(instance.getProperties(), function (property, key) {
					var propertySchema = selfProperties.getProperty(key),
						parser = propertySchema && propertySchema.getValueOfProperty("parser");
					if (typeof parser === "function") {
						return parser(property, propertySchema);
					}
					//else
					return property.getValue();
				});
			}
			return instance.getValue();
		}
	};
	
	ENVIRONMENT.setOption("defaultFragmentDelimiter", ".");
	ENVIRONMENT.setOption("defaultSchemaURI", "http://json-schema.org/draft-00/schema#");  //updated later
	
	SCHEMA_00 = ENVIRONMENT.createSchema(SCHEMA_00_JSON, true, "http://json-schema.org/draft-00/schema#");
	HYPERSCHEMA_00 = ENVIRONMENT.createSchema(JSV.inherits(SCHEMA_00, ENVIRONMENT.createSchema(HYPERSCHEMA_00_JSON, true, "http://json-schema.org/draft-00/hyper-schema#"), true), true, "http://json-schema.org/draft-00/hyper-schema#");
	
	ENVIRONMENT.setOption("defaultSchemaURI", "http://json-schema.org/draft-00/hyper-schema#");
	
	LINKS_00 = ENVIRONMENT.createSchema(LINKS_00_JSON, HYPERSCHEMA_00, "http://json-schema.org/draft-00/links#");
	
	//
	// draft-01
	//
		
	SCHEMA_01_JSON = JSV.inherits(SCHEMA_00_JSON, {
		"$schema" : "http://json-schema.org/draft-01/hyper-schema#",
		"id" : "http://json-schema.org/draft-01/schema#"
	});
	
	HYPERSCHEMA_01_JSON = JSV.inherits(HYPERSCHEMA_00_JSON, {
		"$schema" : "http://json-schema.org/draft-01/hyper-schema#",
		"id" : "http://json-schema.org/draft-01/hyper-schema#"
	});
	
	LINKS_01_JSON = JSV.inherits(LINKS_00_JSON, {
		"$schema" : "http://json-schema.org/draft-01/hyper-schema#",
		"id" : "http://json-schema.org/draft-01/links#"
	});
	
	ENVIRONMENT.setOption("defaultSchemaURI", "http://json-schema.org/draft-01/schema#");  //update later
	
	SCHEMA_01 = ENVIRONMENT.createSchema(SCHEMA_01_JSON, true, "http://json-schema.org/draft-01/schema#");
	HYPERSCHEMA_01 = ENVIRONMENT.createSchema(JSV.inherits(SCHEMA_01, ENVIRONMENT.createSchema(HYPERSCHEMA_01_JSON, true, "http://json-schema.org/draft-01/hyper-schema#"), true), true, "http://json-schema.org/draft-01/hyper-schema#");
	
	ENVIRONMENT.setOption("defaultSchemaURI", "http://json-schema.org/draft-01/hyper-schema#");
	
	LINKS_01 = ENVIRONMENT.createSchema(LINKS_01_JSON, HYPERSCHEMA_01, "http://json-schema.org/draft-01/links#");
	
	//
	// draft-02
	//
	
	SCHEMA_02_JSON = JSV.inherits(SCHEMA_01_JSON, {
		"$schema" : "http://json-schema.org/draft-02/hyper-schema#",
		"id" : "http://json-schema.org/draft-02/schema#",
		
		"properties" : {
			"uniqueItems" : {
				"type" : "boolean",
				"optional" : true,
				"default" : false,
				
				"parser" : function (instance, self) {
					return !!instance.getValue();
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var value, x, xl, y, yl;
					if (instance.getType() === "array" && schema.getAttribute("uniqueItems")) {
						value = instance.getProperties();
						for (x = 0, xl = value.length - 1; x < xl; ++x) {
							for (y = x + 1, yl = value.length; y < yl; ++y) {
								if (value[x].equals(value[y])) {
									report.addError(instance, schema, "uniqueItems", "Array can only contain unique items", { x : x, y : y });
								}
							}
						}
					}
				}
			},
			
			"maxDecimal" : {
				"deprecated" : true
			},
			
			"divisibleBy" : {
				"type" : "number",
				"minimum" : 0,
				"minimumCanEqual" : false,
				"optional" : true,
				
				"parser" : function (instance, self) {
					if (instance.getType() === "number") {
						return instance.getValue();
					}
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var divisor, value, digits;
					if (instance.getType() === "number") {
						divisor = schema.getAttribute("divisibleBy");
						if (divisor === 0) {
							report.addError(instance, schema, "divisibleBy", "Nothing is divisible by 0", divisor);
						} else if (divisor !== 1) {
							value = instance.getValue();
							digits = Math.max((value.toString().split(".")[1] || " ").length, (divisor.toString().split(".")[1] || " ").length);
							digits = parseFloat(((value / divisor) % 1).toFixed(digits));  //cut out floating point errors
							if (0 < digits && digits < 1) {
								report.addError(instance, schema, "divisibleBy", "Number is not divisible by " + divisor, divisor);
							}
						}
					}
				}
			}
		},
		
		"fragmentResolution" : "slash-delimited"
	});
	
	HYPERSCHEMA_02_JSON = JSV.inherits(HYPERSCHEMA_01_JSON, {
		"id" : "http://json-schema.org/draft-02/hyper-schema#",
		
		"properties" : {
			"fragmentResolution" : {
				"default" : "slash-delimited"
			}
		}
	});
	
	LINKS_02_JSON = JSV.inherits(LINKS_01_JSON, {
		"$schema" : "http://json-schema.org/draft-02/hyper-schema#",
		"id" : "http://json-schema.org/draft-02/links#",
		
		"properties" : {
			"targetSchema" : {
				"$ref" : "hyper-schema#",
				
				//need this here because parsers are run before links are resolved
				"parser" : HYPERSCHEMA_01.getAttribute("parser")
			}
		}
	});
	
	ENVIRONMENT.setOption("defaultFragmentDelimiter", "/");
	ENVIRONMENT.setOption("defaultSchemaURI", "http://json-schema.org/draft-02/schema#");  //update later
	
	SCHEMA_02 = ENVIRONMENT.createSchema(SCHEMA_02_JSON, true, "http://json-schema.org/draft-02/schema#");
	HYPERSCHEMA_02 = ENVIRONMENT.createSchema(JSV.inherits(SCHEMA_02, ENVIRONMENT.createSchema(HYPERSCHEMA_02_JSON, true, "http://json-schema.org/draft-02/hyper-schema#"), true), true, "http://json-schema.org/draft-02/hyper-schema#");
	
	ENVIRONMENT.setOption("defaultSchemaURI", "http://json-schema.org/draft-02/hyper-schema#");
	
	LINKS_02 = ENVIRONMENT.createSchema(LINKS_02_JSON, HYPERSCHEMA_02, "http://json-schema.org/draft-02/links#");
	
	//
	// draft-03
	//
	
	function getMatchedPatternProperties(instance, schema, report, self) {
		var matchedProperties = {}, patternProperties, pattern, regexp, properties, key;
		
		if (instance.getType() === "object") {
			patternProperties = schema.getAttribute("patternProperties");
			properties = instance.getProperties();
			for (pattern in patternProperties) {
				if (patternProperties[pattern] !== O[pattern]) {
					regexp = null;
					try {
						regexp = new RegExp(pattern);
					} catch (e) {
						if (report) {
							report.addError(schema, self, "patternProperties", "Invalid pattern", pattern);
						}
					}
					
					if (regexp) {
						for (key in properties) {
							if (properties[key] !== O[key]  && regexp.test(key)) {
								matchedProperties[key] = matchedProperties[key] ? JSV.pushUnique(matchedProperties[key], patternProperties[pattern]) : [ patternProperties[pattern] ];
							}
						}
					}
				}
			}
		}
		
		return matchedProperties;
	}
	
	SCHEMA_03_JSON = JSV.inherits(SCHEMA_02_JSON, {
		"$schema" : "http://json-schema.org/draft-03/schema#",
		"id" : "http://json-schema.org/draft-03/schema#",
		
		"properties" : {
			"patternProperties" : {
				"type" : "object",
				"additionalProperties" : {"$ref" : "#"},
				"default" : {},
				
				"parser" : SCHEMA_02.getValueOfProperty("properties")["properties"]["parser"],
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var matchedProperties, key, x;
					if (instance.getType() === "object") {
						matchedProperties = getMatchedPatternProperties(instance, schema, report, self);
						for (key in matchedProperties) {
							if (matchedProperties[key] !== O[key]) {
								x = matchedProperties[key].length;
								while (x--) {
									matchedProperties[key][x].validate(instance.getProperty(key), report, instance, schema, key);
								}
							}
						}
					}
				}
			},
			
			"additionalProperties" : {
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var additionalProperties, propertySchemas, properties, matchedProperties, key;
					if (instance.getType() === "object") {
						additionalProperties = schema.getAttribute("additionalProperties");
						propertySchemas = schema.getAttribute("properties") || {};
						properties = instance.getProperties();
						matchedProperties = getMatchedPatternProperties(instance, schema);
						for (key in properties) {
							if (properties[key] !== O[key] && properties[key] && propertySchemas[key] === O[key] && matchedProperties[key] === O[key]) {
								if (JSV.isJSONSchema(additionalProperties)) {
									additionalProperties.validate(properties[key], report, instance, schema, key);
								} else if (additionalProperties === false) {
									report.addError(instance, schema, "additionalProperties", "Additional properties are not allowed", additionalProperties);
								}
							}
						}
					}
				}
			},
			
			"items" : {
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var properties, items, x, xl, itemSchema, additionalItems;
					
					if (instance.getType() === "array") {
						properties = instance.getProperties();
						items = schema.getAttribute("items");
						additionalItems = schema.getAttribute("additionalItems");
						
						if (JSV.typeOf(items) === "array") {
							for (x = 0, xl = properties.length; x < xl; ++x) {
								itemSchema = items[x] || additionalItems;
								if (itemSchema !== false) {
									itemSchema.validate(properties[x], report, instance, schema, x);
								} else {
									report.addError(instance, schema, "additionalItems", "Additional items are not allowed", itemSchema);
								}
							}
						} else {
							itemSchema = items || additionalItems;
							for (x = 0, xl = properties.length; x < xl; ++x) {
								itemSchema.validate(properties[x], report, instance, schema, x);
							}
						}
					}
				}
			},
			
			"additionalItems" : {
				"type" : [{"$ref" : "#"}, "boolean"],
				"default" : {},
				
				"parser" : SCHEMA_02.getValueOfProperty("properties")["additionalProperties"]["parser"],
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var additionalItems, properties, x, xl;
					//only validate if the "items" attribute is undefined
					if (instance.getType() === "array" && schema.getProperty("items").getType() === "undefined") {
						additionalItems = schema.getAttribute("additionalItems");
						properties = instance.getProperties();
						
						if (additionalItems !== false) {
							for (x = 0, xl = properties.length; x < xl; ++x) {
								additionalItems.validate(properties[x], report, instance, schema, x);
							}
						} else if (properties.length) {
							report.addError(instance, schema, "additionalItems", "Additional items are not allowed", additionalItems);
						}
					}
				}
			},
			
			"optional" : {
				"validationRequired" : false,
				"deprecated" : true
			},
			
			"required" : {
				"type" : "boolean",
				"default" : false,
				
				"parser" : function (instance, self) {
					return !!instance.getValue();
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					if (instance.getType() === "undefined" && schema.getAttribute("required")) {
						report.addError(instance, schema, "required", "Property is required", true);
					}
				}
			},
			
			"requires" : {
				"deprecated" : true
			},
			
			"dependencies" : {
				"type" : "object",
				"additionalProperties" : {
					"type" : ["string", "array", {"$ref" : "#"}],
					"items" : {
						"type" : "string"
					}
				},
				"default" : {},
				
				"parser" : function (instance, self, arg) {
					function parseProperty(property) {
						var type = property.getType();
						if (type === "string" || type === "array") {
							return property.getValue();
						} else if (type === "object") {
							return property.getEnvironment().createSchema(property, self.getEnvironment().findSchema(self.resolveURI("#")));
						}
					}
					
					if (instance.getType() === "object") {
						if (arg) {
							return parseProperty(instance.getProperty(arg));
						} else {
							return JSV.mapObject(instance.getProperties(), parseProperty);
						}
					}
					//else
					return {};
				},
				
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var dependencies, key, dependency, type, x, xl;
					if (instance.getType() === "object") {
						dependencies = schema.getAttribute("dependencies");
						for (key in dependencies) {
							if (dependencies[key] !== O[key] && instance.getProperty(key).getType() !== "undefined") {
								dependency = dependencies[key];
								type = JSV.typeOf(dependency);
								if (type === "string") {
									if (instance.getProperty(dependency).getType() === "undefined") {
										report.addError(instance, schema, "dependencies", 'Property "' + key + '" requires sibling property "' + dependency + '"', dependencies);
									}
								} else if (type === "array") {
									for (x = 0, xl = dependency.length; x < xl; ++x) {
										if (instance.getProperty(dependency[x]).getType() === "undefined") {
											report.addError(instance, schema, "dependencies", 'Property "' + key + '" requires sibling property "' + dependency[x] + '"', dependencies);
										}
									}
								} else if (JSV.isJSONSchema(dependency)) {
									dependency.validate(instance, report);
								}
							}
						}
					}
				}
			},
			
			"minimumCanEqual" : {
				"deprecated" : true
			},
			
			"maximumCanEqual" : {
				"deprecated" : true
			},
			
			"exclusiveMinimum" : {
				"type" : "boolean",
				"default" : false,
				
				"parser" : function (instance, self) {
					return !!instance.getValue();
				}
			},
			
			"exclusiveMaximum" : {
				"type" : "boolean",
				"default" : false,
				
				"parser" : function (instance, self) {
					return !!instance.getValue();
				}
			},
			
			"minimum" : {
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var minimum, exclusiveMinimum;
					if (instance.getType() === "number") {
						minimum = schema.getAttribute("minimum");
						exclusiveMinimum = schema.getAttribute("exclusiveMinimum") || (!instance.getEnvironment().getOption("strict") && !schema.getAttribute("minimumCanEqual"));
						if (typeof minimum === "number" && (instance.getValue() < minimum || (exclusiveMinimum === true && instance.getValue() === minimum))) {
							report.addError(instance, schema, "minimum", "Number is less than the required minimum value", minimum);
						}
					}
				}
			},
			
			"maximum" : {
				"validator" : function (instance, schema, self, report, parent, parentSchema, name) {
					var maximum, exclusiveMaximum;
					if (instance.getType() === "number") {
						maximum = schema.getAttribute("maximum");
						exclusiveMaximum = schema.getAttribute("exclusiveMaximum") || (!instance.getEnvironment().getOption("strict") && !schema.getAttribute("maximumCanEqual"));
						if (typeof maximum === "number" && (instance.getValue() > maximum || (exclusiveMaximum === true && instance.getValue() === maximum))) {
							report.addError(instance, schema, "maximum", "Number is greater than the required maximum value", maximum);
						}
					}
				}
			},
			
			"contentEncoding" : {
				"deprecated" : true
			},
			
			"divisibleBy" : {
				"exclusiveMinimum" : true
			},
			
			"disallow" : {
				"items" : {
					"type" : ["string", {"$ref" : "#"}]
				},
				
				"parser" : SCHEMA_02_JSON["properties"]["type"]["parser"]
			},
			
			"id" : {
				"type" : "string",
				"format" : "uri"
			},
			
			"$ref" : {
				"type" : "string",
				"format" : "uri"
			},
			
			"$schema" : {
				"type" : "string",
				"format" : "uri"
			}
		},
		
		"dependencies" : {
			"exclusiveMinimum" : "minimum",
			"exclusiveMaximum" : "maximum"
		},
		
		"initializer" : function (instance) {
			var link, extension, extended,
				schemaLink = instance.getValueOfProperty("$schema"),
				refLink = instance.getValueOfProperty("$ref"),
				idLink = instance.getValueOfProperty("id");
			
			//if there is a link to a different schema, set reference
			if (schemaLink) {
				link = instance.resolveURI(schemaLink);
				instance.setReference("describedby", link);
			}
			
			//if instance has a URI link to itself, update it's own URI
			if (idLink) {
				link = instance.resolveURI(idLink);
				if (JSV.typeOf(link) === "string") {
					instance._uri = JSV.formatURI(link);
				}
			}
			
			//if there is a link to the full representation, set reference
			if (refLink) {
				link = instance.resolveURI(refLink);
				instance.setReference("full", link);
			}
			
			//extend schema
			extension = instance.getAttribute("extends");
			if (JSV.isJSONSchema(extension)) {
				extended = JSV.inherits(extension, instance, true);
				instance = instance._env.createSchema(extended, instance._schema, instance._uri);
			}
			
			return instance;
		}
	});
	
	HYPERSCHEMA_03_JSON = JSV.inherits(HYPERSCHEMA_02_JSON, {
		"$schema" : "http://json-schema.org/draft-03/hyper-schema#",
		"id" : "http://json-schema.org/draft-03/hyper-schema#",
		
		"properties" : {
			"links" : {
				"selfReferenceVariable" : "@"
			},
			
			"root" : {
				"deprecated" : true
			},
			
			"contentEncoding" : {
				"deprecated" : false  //moved from core to hyper
			},
			
			"alternate" : {
				"deprecated" : true
			}
		}
	});
	
	LINKS_03_JSON = JSV.inherits(LINKS_02_JSON, {
		"$schema" : "http://json-schema.org/draft-03/hyper-schema#",
		"id" : "http://json-schema.org/draft-03/links#",
		
		"properties" : {
			"href" : {
				"required" : true,
				"format" : "link-description-object-template"
			},
			
			"rel" : {
				"required" : true
			},
			
			"properties" : {
				"deprecated" : true
			},
			
			"schema" : {"$ref" : "http://json-schema.org/draft-03/hyper-schema#"}
		}
	});
	
	ENVIRONMENT.setOption("defaultSchemaURI", "http://json-schema.org/draft-03/schema#");  //update later
	
	SCHEMA_03 = ENVIRONMENT.createSchema(SCHEMA_03_JSON, true, "http://json-schema.org/draft-03/schema#");
	HYPERSCHEMA_03 = ENVIRONMENT.createSchema(JSV.inherits(SCHEMA_03, ENVIRONMENT.createSchema(HYPERSCHEMA_03_JSON, true, "http://json-schema.org/draft-03/hyper-schema#"), true), true, "http://json-schema.org/draft-03/hyper-schema#");
	
	ENVIRONMENT.setOption("defaultSchemaURI", "http://json-schema.org/draft-03/hyper-schema#");
	
	LINKS_03 = ENVIRONMENT.createSchema(LINKS_03_JSON, true, "http://json-schema.org/draft-03/links#");
	
	ENVIRONMENT.setOption("latestJSONSchemaSchemaURI", "http://json-schema.org/draft-03/schema#");
	ENVIRONMENT.setOption("latestJSONSchemaHyperSchemaURI", "http://json-schema.org/draft-03/hyper-schema#");
	ENVIRONMENT.setOption("latestJSONSchemaLinksURI", "http://json-schema.org/draft-03/links#");
	
	//
	//Latest JSON Schema
	//
	
	//Hack, but WAY faster than instantiating a new schema
	ENVIRONMENT._schemas["http://json-schema.org/schema#"] = SCHEMA_03;
	ENVIRONMENT._schemas["http://json-schema.org/hyper-schema#"] = HYPERSCHEMA_03;
	ENVIRONMENT._schemas["http://json-schema.org/links#"] = LINKS_03;
	
	//
	//register environment
	//
	
	JSV.registerEnvironment("json-schema-draft-03", ENVIRONMENT);
	if (!JSV.getDefaultEnvironmentID() || JSV.getDefaultEnvironmentID() === "json-schema-draft-01" || JSV.getDefaultEnvironmentID() === "json-schema-draft-02") {
		JSV.setDefaultEnvironmentID("json-schema-draft-03");
	}
	
}());/*! 
 * angular-hotkeys v1.4.5
 * https://chieffancypants.github.io/angular-hotkeys
 * Copyright (c) 2014 Wes Cruver
 * License: MIT
 */
/*
 * angular-hotkeys
 *
 * Automatic keyboard shortcuts for your angular apps
 *
 * (c) 2014 Wes Cruver
 * License: MIT
 */

(function() {

  'use strict';

  angular.module('cfp.hotkeys', []).provider('hotkeys', function() {

    /**
     * Configurable setting to disable the cheatsheet entirely
     * @type {Boolean}
     */
    this.includeCheatSheet = true;

    /**
     * Configurable setting for the cheat sheet title
     * @type {String}
     */

    this.templateTitle = 'Keyboard Shortcuts:';

    /**
     * Cheat sheet template in the event you want to totally customize it.
     * @type {String}
     */
    this.template = '<div class="cfp-hotkeys-container fade" ng-class="{in: helpVisible}" style="display: none;"><div class="cfp-hotkeys">' +
                      '<h4 class="cfp-hotkeys-title">{{ title }}</h4>' +
                      '<table><tbody>' +
                        '<tr ng-repeat="hotkey in hotkeys | filter:{ description: \'!$$undefined$$\' }">' +
                          '<td class="cfp-hotkeys-keys">' +
                            '<span ng-repeat="key in hotkey.format() track by $index" class="cfp-hotkeys-key">{{ key }}</span>' +
                          '</td>' +
                          '<td class="cfp-hotkeys-text">{{ hotkey.description }}</td>' +
                        '</tr>' +
                      '</tbody></table>' +
                      '<div class="cfp-hotkeys-close" ng-click="toggleCheatSheet()">×</div>' +
                    '</div></div>';

    /**
     * Configurable setting for the cheat sheet hotkey
     * @type {String}
     */
    this.cheatSheetHotkey = '?';

    /**
     * Configurable setting for the cheat sheet description
     * @type {String}
     */
    this.cheatSheetDescription = 'Show / hide this help menu';

    this.$get = ['$rootElement', '$rootScope', '$compile', '$window', '$document', function ($rootElement, $rootScope, $compile, $window, $document) {

      // monkeypatch Mousetrap's stopCallback() function
      // this version doesn't return true when the element is an INPUT, SELECT, or TEXTAREA
      // (instead we will perform this check per-key in the _add() method)
      Mousetrap.stopCallback = function(event, element) {
        // if the element has the class "mousetrap" then no need to stop
        if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
          return false;
        }

        return (element.contentEditable && element.contentEditable == 'true');
      };

      /**
       * Convert strings like cmd into symbols like ⌘
       * @param  {String} combo Key combination, e.g. 'mod+f'
       * @return {String}       The key combination with symbols
       */
      function symbolize (combo) {
        var map = {
          command   : '⌘',
          shift     : '⇧',
          left      : '←',
          right     : '→',
          up        : '↑',
          down      : '↓',
          'return'  : '↩',
          backspace : '⌫'
        };
        combo = combo.split('+');

        for (var i = 0; i < combo.length; i++) {
          // try to resolve command / ctrl based on OS:
          if (combo[i] === 'mod') {
            if ($window.navigator && $window.navigator.platform.indexOf('Mac') >=0 ) {
              combo[i] = 'command';
            } else {
              combo[i] = 'ctrl';
            }
          }

          combo[i] = map[combo[i]] || combo[i];
        }

        return combo.join(' + ');
      }

      /**
       * Hotkey object used internally for consistency
       *
       * @param {array}    combo       The keycombo. it's an array to support multiple combos
       * @param {String}   description Description for the keycombo
       * @param {Function} callback    function to execute when keycombo pressed
       * @param {string}   action      the type of event to listen for (for mousetrap)
       * @param {array}    allowIn     an array of tag names to allow this combo in ('INPUT', 'SELECT', and/or 'TEXTAREA')
       * @param {Boolean}  persistent  Whether the hotkey persists navigation events
       */
      function Hotkey (combo, description, callback, action, allowIn, persistent) {
        // TODO: Check that the values are sane because we could
        // be trying to instantiate a new Hotkey with outside dev's
        // supplied values

        this.combo = combo instanceof Array ? combo : [combo];
        this.description = description;
        this.callback = callback;
        this.action = action;
        this.allowIn = allowIn;
        this.persistent = persistent;
      }

      /**
       * Helper method to format (symbolize) the key combo for display
       *
       * @return {[Array]} An array of the key combination sequence
       *   for example: "command+g c i" becomes ["⌘ + g", "c", "i"]
       *
       * TODO: this gets called a lot.  We should cache the result
       */
      Hotkey.prototype.format = function() {

        // Don't show all the possible key combos, just the first one.  Not sure
        // of usecase here, so open a ticket if my assumptions are wrong
        var combo = this.combo[0];

        var sequence = combo.split(/[\s]/);
        for (var i = 0; i < sequence.length; i++) {
          sequence[i] = symbolize(sequence[i]);
        }

        return sequence;
      };

      /**
       * A new scope used internally for the cheatsheet
       * @type {$rootScope.Scope}
       */
      var scope = $rootScope.$new();

      /**
       * Holds an array of Hotkey objects currently bound
       * @type {Array}
       */
      scope.hotkeys = [];

      /**
       * Contains the state of the help's visibility
       * @type {Boolean}
       */
      scope.helpVisible = false;

      /**
       * Holds the title string for the help menu
       * @type {String}
       */
      scope.title = this.templateTitle;

      /**
       * Expose toggleCheatSheet to hotkeys scope so we can call it using
       * ng-click from the template
       * @type {function}
       */
      scope.toggleCheatSheet = toggleCheatSheet;


      /**
       * Holds references to the different scopes that have bound hotkeys
       * attached.  This is useful to catch when the scopes are `$destroy`d and
       * then automatically unbind the hotkey.
       *
       * @type {Array}
       */
      var boundScopes = [];


      $rootScope.$on('$routeChangeSuccess', function (event, route) {
        purgeHotkeys();

        if (route && route.hotkeys) {
          angular.forEach(route.hotkeys, function (hotkey) {
            // a string was given, which implies this is a function that is to be
            // $eval()'d within that controller's scope
            // TODO: hotkey here is super confusing.  sometimes a function (that gets turned into an array), sometimes a string
            var callback = hotkey[2];
            if (typeof(callback) === 'string' || callback instanceof String) {
              hotkey[2] = [callback, route];
            }

            // todo: perform check to make sure not already defined:
            // this came from a route, so it's likely not meant to be persistent
            hotkey[5] = false;
            _add.apply(this, hotkey);
          });
        }
      });


      // Auto-create a help menu:
      if (this.includeCheatSheet) {
        var document = $document[0];
        var element = $rootElement[0];
        var helpMenu = angular.element(this.template);
        _add(this.cheatSheetHotkey, this.cheatSheetDescription, toggleCheatSheet);

        // If $rootElement is document or documentElement, then body must be used
        if (element === document || element === document.documentElement) {
          element = document.body;
        }

        angular.element(element).append($compile(helpMenu)(scope));
      }


      /**
       * Purges all non-persistent hotkeys (such as those defined in routes)
       *
       * Without this, the same hotkey would get recreated everytime
       * the route is accessed.
       */
      function purgeHotkeys() {
        var i = scope.hotkeys.length;
        while (i--) {
          var hotkey = scope.hotkeys[i];
          if (hotkey && !hotkey.persistent) {
            _del(hotkey);
          }
        }
      }

      /**
       * Toggles the help menu element's visiblity
       */
      var previousEsc = false;

      function toggleCheatSheet() {
        scope.helpVisible = !scope.helpVisible;

        // Bind to esc to remove the cheat sheet.  Ideally, this would be done
        // as a directive in the template, but that would create a nasty
        // circular dependency issue that I don't feel like sorting out.
        if (scope.helpVisible) {
          previousEsc = _get('esc');
          _del('esc');

          // Here's an odd way to do this: we're going to use the original
          // description of the hotkey on the cheat sheet so that it shows up.
          // without it, no entry for esc will ever show up (#22)
          _add('esc', previousEsc.description, toggleCheatSheet);
        } else {
          _del('esc');

          // restore the previously bound ESC key
          if (previousEsc !== false) {
            _add(previousEsc);
          }
        }
      }

      /**
       * Creates a new Hotkey and creates the Mousetrap binding
       *
       * @param {string}   combo       mousetrap key binding
       * @param {string}   description description for the help menu
       * @param {Function} callback    method to call when key is pressed
       * @param {string}   action      the type of event to listen for (for mousetrap)
       * @param {array}    allowIn     an array of tag names to allow this combo in ('INPUT', 'SELECT', and/or 'TEXTAREA')
       * @param {boolean}  persistent  if true, the binding is preserved upon route changes
       */
      function _add (combo, description, callback, action, allowIn, persistent) {

        // used to save original callback for "allowIn" wrapping:
        var _callback;

        // these elements are prevented by the default Mousetrap.stopCallback():
        var preventIn = ['INPUT', 'SELECT', 'TEXTAREA'];

        // Determine if object format was given:
        var objType = Object.prototype.toString.call(combo);

        if (objType === '[object Object]') {
          description = combo.description;
          callback    = combo.callback;
          action      = combo.action;
          persistent  = combo.persistent;
          allowIn     = combo.allowIn;
          combo       = combo.combo;
        }

        // description is optional:
        if (description instanceof Function) {
          action = callback;
          callback = description;
          description = '$$undefined$$';
        } else if (angular.isUndefined(description)) {
          description = '$$undefined$$';
        }

        // any items added through the public API are for controllers
        // that persist through navigation, and thus undefined should mean
        // true in this case.
        if (persistent === undefined) {
          persistent = true;
        }

        // if callback is defined, then wrap it in a function
        // that checks if the event originated from a form element.
        // the function blocks the callback from executing unless the element is specified
        // in allowIn (emulates Mousetrap.stopCallback() on a per-key level)
        if (typeof callback === 'function') {

          // save the original callback
          _callback = callback;

          // make sure allowIn is an array
          if (!(allowIn instanceof Array)) {
            allowIn = [];
          }

          // remove anything from preventIn that's present in allowIn
          var index;
          for (var i=0; i < allowIn.length; i++) {
            allowIn[i] = allowIn[i].toUpperCase();
            index = preventIn.indexOf(allowIn[i]);
            if (index !== -1) {
              preventIn.splice(index, 1);
            }
          }

          // create the new wrapper callback
          callback = function(event) {
            var shouldExecute = true;
            var target = event.target || event.srcElement; // srcElement is IE only
            var nodeName = target.nodeName.toUpperCase();

            // check if the input has a mousetrap class, and skip checking preventIn if so
            if ((' ' + target.className + ' ').indexOf(' mousetrap ') > -1) {
              shouldExecute = true;
            } else {
              // don't execute callback if the event was fired from inside an element listed in preventIn
              for (var i=0; i<preventIn.length; i++) {
                if (preventIn[i] === nodeName) {
                  shouldExecute = false;
                  break;
                }
              }
            }

            if (shouldExecute) {
              wrapApply(_callback.apply(this, arguments));
            }
          };
        }

        if (typeof(action) === 'string') {
          Mousetrap.bind(combo, wrapApply(callback), action);
        } else {
          Mousetrap.bind(combo, wrapApply(callback));
        }

        var hotkey = new Hotkey(combo, description, callback, action, allowIn, persistent);
        scope.hotkeys.push(hotkey);
        return hotkey;
      }

      /**
       * delete and unbind a Hotkey
       *
       * @param  {mixed} hotkey   Either the bound key or an instance of Hotkey
       * @return {boolean}        true if successful
       */
      function _del (hotkey) {
        var combo = (hotkey instanceof Hotkey) ? hotkey.combo : hotkey;

        Mousetrap.unbind(combo);

        if (angular.isArray(combo)) {
          var retStatus = true;
          var i = combo.length;
          while (i--) {
            retStatus = _del(combo[i]) && retStatus;
          }
          return retStatus;
        } else {
          var index = scope.hotkeys.indexOf(_get(combo));

          if (index > -1) {
            // if the combo has other combos bound, don't unbind the whole thing, just the one combo:
            if (scope.hotkeys[index].combo.length > 1) {
              scope.hotkeys[index].combo.splice(scope.hotkeys[index].combo.indexOf(combo), 1);
            } else {
              scope.hotkeys.splice(index, 1);
            }
            return true;
          }
        }

        return false;

      }

      /**
       * Get a Hotkey object by key binding
       *
       * @param  {[string]} combo  the key the Hotkey is bound to
       * @return {Hotkey}          The Hotkey object
       */
      function _get (combo) {

        var hotkey;

        for (var i = 0; i < scope.hotkeys.length; i++) {
          hotkey = scope.hotkeys[i];

          if (hotkey.combo.indexOf(combo) > -1) {
            return hotkey;
          }
        }

        return false;
      }

      /**
       * Binds the hotkey to a particular scope.  Useful if the scope is
       * destroyed, we can automatically destroy the hotkey binding.
       *
       * @param  {Object} scope The scope to bind to
       */
      function bindTo (scope) {
        // Only initialize once to allow multiple calls for same scope.
        if (!(scope.$id in boundScopes)) {

          // Add the scope to the list of bound scopes
          boundScopes[scope.$id] = [];

          scope.$on('$destroy', function () {
            var i = boundScopes[scope.$id].length;
            while (i--) {
              _del(boundScopes[scope.$id][i]);
              delete boundScopes[scope.$id][i];
            }
          });
        }
        // return an object with an add function so we can keep track of the
        // hotkeys and their scope that we added via this chaining method
        return {
          add: function (args) {
            var hotkey;

            if (arguments.length > 1) {
              hotkey = _add.apply(this, arguments);
            } else {
              hotkey = _add(args);
            }

            boundScopes[scope.$id].push(hotkey);
            return this;
          }
        };
      }

      /**
       * All callbacks sent to Mousetrap are wrapped using this function
       * so that we can force a $scope.$apply()
       *
       * @param  {Function} callback [description]
       * @return {[type]}            [description]
       */
      function wrapApply (callback) {
        // return mousetrap a function to call
        return function (event, combo) {

          // if this is an array, it means we provided a route object
          // because the scope wasn't available yet, so rewrap the callback
          // now that the scope is available:
          if (callback instanceof Array) {
            var funcString = callback[0];
            var route = callback[1];
            callback = function (event) {
              route.scope.$eval(funcString);
            };
          }

          // this takes place outside angular, so we'll have to call
          // $apply() to make sure angular's digest happens
          $rootScope.$apply(function() {
            // call the original hotkey callback with the keyboard event
            callback(event, _get(combo));
          });
        };
      }


      var publicApi = {
        add                   : _add,
        del                   : _del,
        get                   : _get,
        bindTo                : bindTo,
        template              : this.template,
        toggleCheatSheet      : toggleCheatSheet,
        includeCheatSheet     : this.includeCheatSheet,
        cheatSheetHotkey      : this.cheatSheetHotkey,
        cheatSheetDescription : this.cheatSheetDescription,
        purgeHotkeys          : purgeHotkeys,
        templateTitle         : this.templateTitle
      };

      return publicApi;

    }];
  })

  .directive('hotkey', ['hotkeys', function (hotkeys) {
    return {
      restrict: 'A',
      link: function (scope, el, attrs) {
        var key, allowIn;

        angular.forEach(scope.$eval(attrs.hotkey), function (func, hotkey) {
          // split and trim the hotkeys string into array
          allowIn = typeof attrs.hotkeyAllowIn === "string" ? attrs.hotkeyAllowIn.split(/[\s,]+/) : [];

          key = hotkey;

          hotkeys.add({
            combo: hotkey,
            description: attrs.hotkeyDescription,
            callback: func,
            action: attrs.hotkeyAction,
            allowIn: allowIn
          });
        });

        // remove the hotkey if the directive is destroyed:
        el.bind('$destroy', function() {
          hotkeys.del(key);
        });
      }
    };
  }])

  .run(['hotkeys', function(hotkeys) {
    // force hotkeys to run by injecting it. Without this, hotkeys only runs
    // when a controller or something else asks for it via DI.
  }]);

})();

/*global define:false */
/**
 * Copyright 2013 Craig Campbell
 *
 * 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.
 *
 * Mousetrap is a simple keyboard shortcut library for Javascript with
 * no external dependencies
 *
 * @version 1.4.6
 * @url craig.is/killing/mice
 */
(function(window, document, undefined) {

    /**
     * mapping of special keycodes to their corresponding keys
     *
     * everything in this dictionary cannot use keypress events
     * so it has to be here to map to the correct keycodes for
     * keyup/keydown events
     *
     * @type {Object}
     */
    var _MAP = {
            8: 'backspace',
            9: 'tab',
            13: 'enter',
            16: 'shift',
            17: 'ctrl',
            18: 'alt',
            20: 'capslock',
            27: 'esc',
            32: 'space',
            33: 'pageup',
            34: 'pagedown',
            35: 'end',
            36: 'home',
            37: 'left',
            38: 'up',
            39: 'right',
            40: 'down',
            45: 'ins',
            46: 'del',
            91: 'meta',
            93: 'meta',
            224: 'meta'
        },

        /**
         * mapping for special characters so they can support
         *
         * this dictionary is only used incase you want to bind a
         * keyup or keydown event to one of these keys
         *
         * @type {Object}
         */
        _KEYCODE_MAP = {
            106: '*',
            107: '+',
            109: '-',
            110: '.',
            111 : '/',
            186: ';',
            187: '=',
            188: ',',
            189: '-',
            190: '.',
            191: '/',
            192: '`',
            219: '[',
            220: '\\',
            221: ']',
            222: '\''
        },

        /**
         * this is a mapping of keys that require shift on a US keypad
         * back to the non shift equivelents
         *
         * this is so you can use keyup events with these keys
         *
         * note that this will only work reliably on US keyboards
         *
         * @type {Object}
         */
        _SHIFT_MAP = {
            '~': '`',
            '!': '1',
            '@': '2',
            '#': '3',
            '$': '4',
            '%': '5',
            '^': '6',
            '&': '7',
            '*': '8',
            '(': '9',
            ')': '0',
            '_': '-',
            '+': '=',
            ':': ';',
            '\"': '\'',
            '<': ',',
            '>': '.',
            '?': '/',
            '|': '\\'
        },

        /**
         * this is a list of special strings you can use to map
         * to modifier keys when you specify your keyboard shortcuts
         *
         * @type {Object}
         */
        _SPECIAL_ALIASES = {
            'option': 'alt',
            'command': 'meta',
            'return': 'enter',
            'escape': 'esc',
            'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl'
        },

        /**
         * variable to store the flipped version of _MAP from above
         * needed to check if we should use keypress or not when no action
         * is specified
         *
         * @type {Object|undefined}
         */
        _REVERSE_MAP,

        /**
         * a list of all the callbacks setup via Mousetrap.bind()
         *
         * @type {Object}
         */
        _callbacks = {},

        /**
         * direct map of string combinations to callbacks used for trigger()
         *
         * @type {Object}
         */
        _directMap = {},

        /**
         * keeps track of what level each sequence is at since multiple
         * sequences can start out with the same sequence
         *
         * @type {Object}
         */
        _sequenceLevels = {},

        /**
         * variable to store the setTimeout call
         *
         * @type {null|number}
         */
        _resetTimer,

        /**
         * temporary state where we will ignore the next keyup
         *
         * @type {boolean|string}
         */
        _ignoreNextKeyup = false,

        /**
         * temporary state where we will ignore the next keypress
         *
         * @type {boolean}
         */
        _ignoreNextKeypress = false,

        /**
         * are we currently inside of a sequence?
         * type of action ("keyup" or "keydown" or "keypress") or false
         *
         * @type {boolean|string}
         */
        _nextExpectedAction = false;

    /**
     * loop through the f keys, f1 to f19 and add them to the map
     * programatically
     */
    for (var i = 1; i < 20; ++i) {
        _MAP[111 + i] = 'f' + i;
    }

    /**
     * loop through to map numbers on the numeric keypad
     */
    for (i = 0; i <= 9; ++i) {
        _MAP[i + 96] = i;
    }

    /**
     * cross browser add event method
     *
     * @param {Element|HTMLDocument} object
     * @param {string} type
     * @param {Function} callback
     * @returns void
     */
    function _addEvent(object, type, callback) {
        if (object.addEventListener) {
            object.addEventListener(type, callback, false);
            return;
        }

        object.attachEvent('on' + type, callback);
    }

    /**
     * takes the event and returns the key character
     *
     * @param {Event} e
     * @return {string}
     */
    function _characterFromEvent(e) {

        // for keypress events we should return the character as is
        if (e.type == 'keypress') {
            var character = String.fromCharCode(e.which);

            // if the shift key is not pressed then it is safe to assume
            // that we want the character to be lowercase.  this means if
            // you accidentally have caps lock on then your key bindings
            // will continue to work
            //
            // the only side effect that might not be desired is if you
            // bind something like 'A' cause you want to trigger an
            // event when capital A is pressed caps lock will no longer
            // trigger the event.  shift+a will though.
            if (!e.shiftKey) {
                character = character.toLowerCase();
            }

            return character;
        }

        // for non keypress events the special maps are needed
        if (_MAP[e.which]) {
            return _MAP[e.which];
        }

        if (_KEYCODE_MAP[e.which]) {
            return _KEYCODE_MAP[e.which];
        }

        // if it is not in the special map

        // with keydown and keyup events the character seems to always
        // come in as an uppercase character whether you are pressing shift
        // or not.  we should make sure it is always lowercase for comparisons
        return String.fromCharCode(e.which).toLowerCase();
    }

    /**
     * checks if two arrays are equal
     *
     * @param {Array} modifiers1
     * @param {Array} modifiers2
     * @returns {boolean}
     */
    function _modifiersMatch(modifiers1, modifiers2) {
        return modifiers1.sort().join(',') === modifiers2.sort().join(',');
    }

    /**
     * resets all sequence counters except for the ones passed in
     *
     * @param {Object} doNotReset
     * @returns void
     */
    function _resetSequences(doNotReset) {
        doNotReset = doNotReset || {};

        var activeSequences = false,
            key;

        for (key in _sequenceLevels) {
            if (doNotReset[key]) {
                activeSequences = true;
                continue;
            }
            _sequenceLevels[key] = 0;
        }

        if (!activeSequences) {
            _nextExpectedAction = false;
        }
    }

    /**
     * finds all callbacks that match based on the keycode, modifiers,
     * and action
     *
     * @param {string} character
     * @param {Array} modifiers
     * @param {Event|Object} e
     * @param {string=} sequenceName - name of the sequence we are looking for
     * @param {string=} combination
     * @param {number=} level
     * @returns {Array}
     */
    function _getMatches(character, modifiers, e, sequenceName, combination, level) {
        var i,
            callback,
            matches = [],
            action = e.type;

        // if there are no events related to this keycode
        if (!_callbacks[character]) {
            return [];
        }

        // if a modifier key is coming up on its own we should allow it
        if (action == 'keyup' && _isModifier(character)) {
            modifiers = [character];
        }

        // loop through all callbacks for the key that was pressed
        // and see if any of them match
        for (i = 0; i < _callbacks[character].length; ++i) {
            callback = _callbacks[character][i];

            // if a sequence name is not specified, but this is a sequence at
            // the wrong level then move onto the next match
            if (!sequenceName && callback.seq && _sequenceLevels[callback.seq] != callback.level) {
                continue;
            }

            // if the action we are looking for doesn't match the action we got
            // then we should keep going
            if (action != callback.action) {
                continue;
            }

            // if this is a keypress event and the meta key and control key
            // are not pressed that means that we need to only look at the
            // character, otherwise check the modifiers as well
            //
            // chrome will not fire a keypress if meta or control is down
            // safari will fire a keypress if meta or meta+shift is down
            // firefox will fire a keypress if meta or control is down
            if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) {

                // when you bind a combination or sequence a second time it
                // should overwrite the first one.  if a sequenceName or
                // combination is specified in this call it does just that
                //
                // @todo make deleting its own method?
                var deleteCombo = !sequenceName && callback.combo == combination;
                var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level;
                if (deleteCombo || deleteSequence) {
                    _callbacks[character].splice(i, 1);
                }

                matches.push(callback);
            }
        }

        return matches;
    }

    /**
     * takes a key event and figures out what the modifiers are
     *
     * @param {Event} e
     * @returns {Array}
     */
    function _eventModifiers(e) {
        var modifiers = [];

        if (e.shiftKey) {
            modifiers.push('shift');
        }

        if (e.altKey) {
            modifiers.push('alt');
        }

        if (e.ctrlKey) {
            modifiers.push('ctrl');
        }

        if (e.metaKey) {
            modifiers.push('meta');
        }

        return modifiers;
    }

    /**
     * prevents default for this event
     *
     * @param {Event} e
     * @returns void
     */
    function _preventDefault(e) {
        if (e.preventDefault) {
            e.preventDefault();
            return;
        }

        e.returnValue = false;
    }

    /**
     * stops propogation for this event
     *
     * @param {Event} e
     * @returns void
     */
    function _stopPropagation(e) {
        if (e.stopPropagation) {
            e.stopPropagation();
            return;
        }

        e.cancelBubble = true;
    }

    /**
     * actually calls the callback function
     *
     * if your callback function returns false this will use the jquery
     * convention - prevent default and stop propogation on the event
     *
     * @param {Function} callback
     * @param {Event} e
     * @returns void
     */
    function _fireCallback(callback, e, combo, sequence) {

        // if this event should not happen stop here
        if (Mousetrap.stopCallback(e, e.target || e.srcElement, combo, sequence)) {
            return;
        }

        if (callback(e, combo) === false) {
            _preventDefault(e);
            _stopPropagation(e);
        }
    }

    /**
     * handles a character key event
     *
     * @param {string} character
     * @param {Array} modifiers
     * @param {Event} e
     * @returns void
     */
    function _handleKey(character, modifiers, e) {
        var callbacks = _getMatches(character, modifiers, e),
            i,
            doNotReset = {},
            maxLevel = 0,
            processedSequenceCallback = false;

        // Calculate the maxLevel for sequences so we can only execute the longest callback sequence
        for (i = 0; i < callbacks.length; ++i) {
            if (callbacks[i].seq) {
                maxLevel = Math.max(maxLevel, callbacks[i].level);
            }
        }

        // loop through matching callbacks for this key event
        for (i = 0; i < callbacks.length; ++i) {

            // fire for all sequence callbacks
            // this is because if for example you have multiple sequences
            // bound such as "g i" and "g t" they both need to fire the
            // callback for matching g cause otherwise you can only ever
            // match the first one
            if (callbacks[i].seq) {

                // only fire callbacks for the maxLevel to prevent
                // subsequences from also firing
                //
                // for example 'a option b' should not cause 'option b' to fire
                // even though 'option b' is part of the other sequence
                //
                // any sequences that do not match here will be discarded
                // below by the _resetSequences call
                if (callbacks[i].level != maxLevel) {
                    continue;
                }

                processedSequenceCallback = true;

                // keep a list of which sequences were matches for later
                doNotReset[callbacks[i].seq] = 1;
                _fireCallback(callbacks[i].callback, e, callbacks[i].combo, callbacks[i].seq);
                continue;
            }

            // if there were no sequence matches but we are still here
            // that means this is a regular match so we should fire that
            if (!processedSequenceCallback) {
                _fireCallback(callbacks[i].callback, e, callbacks[i].combo);
            }
        }

        // if the key you pressed matches the type of sequence without
        // being a modifier (ie "keyup" or "keypress") then we should
        // reset all sequences that were not matched by this event
        //
        // this is so, for example, if you have the sequence "h a t" and you
        // type "h e a r t" it does not match.  in this case the "e" will
        // cause the sequence to reset
        //
        // modifier keys are ignored because you can have a sequence
        // that contains modifiers such as "enter ctrl+space" and in most
        // cases the modifier key will be pressed before the next key
        //
        // also if you have a sequence such as "ctrl+b a" then pressing the
        // "b" key will trigger a "keypress" and a "keydown"
        //
        // the "keydown" is expected when there is a modifier, but the
        // "keypress" ends up matching the _nextExpectedAction since it occurs
        // after and that causes the sequence to reset
        //
        // we ignore keypresses in a sequence that directly follow a keydown
        // for the same character
        var ignoreThisKeypress = e.type == 'keypress' && _ignoreNextKeypress;
        if (e.type == _nextExpectedAction && !_isModifier(character) && !ignoreThisKeypress) {
            _resetSequences(doNotReset);
        }

        _ignoreNextKeypress = processedSequenceCallback && e.type == 'keydown';
    }

    /**
     * handles a keydown event
     *
     * @param {Event} e
     * @returns void
     */
    function _handleKeyEvent(e) {

        // normalize e.which for key events
        // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
        if (typeof e.which !== 'number') {
            e.which = e.keyCode;
        }

        var character = _characterFromEvent(e);

        // no character found then stop
        if (!character) {
            return;
        }

        // need to use === for the character check because the character can be 0
        if (e.type == 'keyup' && _ignoreNextKeyup === character) {
            _ignoreNextKeyup = false;
            return;
        }

        Mousetrap.handleKey(character, _eventModifiers(e), e);
    }

    /**
     * determines if the keycode specified is a modifier key or not
     *
     * @param {string} key
     * @returns {boolean}
     */
    function _isModifier(key) {
        return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
    }

    /**
     * called to set a 1 second timeout on the specified sequence
     *
     * this is so after each key press in the sequence you have 1 second
     * to press the next key before you have to start over
     *
     * @returns void
     */
    function _resetSequenceTimer() {
        clearTimeout(_resetTimer);
        _resetTimer = setTimeout(_resetSequences, 1000);
    }

    /**
     * reverses the map lookup so that we can look for specific keys
     * to see what can and can't use keypress
     *
     * @return {Object}
     */
    function _getReverseMap() {
        if (!_REVERSE_MAP) {
            _REVERSE_MAP = {};
            for (var key in _MAP) {

                // pull out the numeric keypad from here cause keypress should
                // be able to detect the keys from the character
                if (key > 95 && key < 112) {
                    continue;
                }

                if (_MAP.hasOwnProperty(key)) {
                    _REVERSE_MAP[_MAP[key]] = key;
                }
            }
        }
        return _REVERSE_MAP;
    }

    /**
     * picks the best action based on the key combination
     *
     * @param {string} key - character for key
     * @param {Array} modifiers
     * @param {string=} action passed in
     */
    function _pickBestAction(key, modifiers, action) {

        // if no action was picked in we should try to pick the one
        // that we think would work best for this key
        if (!action) {
            action = _getReverseMap()[key] ? 'keydown' : 'keypress';
        }

        // modifier keys don't work as expected with keypress,
        // switch to keydown
        if (action == 'keypress' && modifiers.length) {
            action = 'keydown';
        }

        return action;
    }

    /**
     * binds a key sequence to an event
     *
     * @param {string} combo - combo specified in bind call
     * @param {Array} keys
     * @param {Function} callback
     * @param {string=} action
     * @returns void
     */
    function _bindSequence(combo, keys, callback, action) {

        // start off by adding a sequence level record for this combination
        // and setting the level to 0
        _sequenceLevels[combo] = 0;

        /**
         * callback to increase the sequence level for this sequence and reset
         * all other sequences that were active
         *
         * @param {string} nextAction
         * @returns {Function}
         */
        function _increaseSequence(nextAction) {
            return function() {
                _nextExpectedAction = nextAction;
                ++_sequenceLevels[combo];
                _resetSequenceTimer();
            };
        }

        /**
         * wraps the specified callback inside of another function in order
         * to reset all sequence counters as soon as this sequence is done
         *
         * @param {Event} e
         * @returns void
         */
        function _callbackAndReset(e) {
            _fireCallback(callback, e, combo);

            // we should ignore the next key up if the action is key down
            // or keypress.  this is so if you finish a sequence and
            // release the key the final key will not trigger a keyup
            if (action !== 'keyup') {
                _ignoreNextKeyup = _characterFromEvent(e);
            }

            // weird race condition if a sequence ends with the key
            // another sequence begins with
            setTimeout(_resetSequences, 10);
        }

        // loop through keys one at a time and bind the appropriate callback
        // function.  for any key leading up to the final one it should
        // increase the sequence. after the final, it should reset all sequences
        //
        // if an action is specified in the original bind call then that will
        // be used throughout.  otherwise we will pass the action that the
        // next key in the sequence should match.  this allows a sequence
        // to mix and match keypress and keydown events depending on which
        // ones are better suited to the key provided
        for (var i = 0; i < keys.length; ++i) {
            var isFinal = i + 1 === keys.length;
            var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence(action || _getKeyInfo(keys[i + 1]).action);
            _bindSingle(keys[i], wrappedCallback, action, combo, i);
        }
    }

    /**
     * Converts from a string key combination to an array
     *
     * @param  {string} combination like "command+shift+l"
     * @return {Array}
     */
    function _keysFromString(combination) {
        if (combination === '+') {
            return ['+'];
        }

        return combination.split('+');
    }

    /**
     * Gets info for a specific key combination
     *
     * @param  {string} combination key combination ("command+s" or "a" or "*")
     * @param  {string=} action
     * @returns {Object}
     */
    function _getKeyInfo(combination, action) {
        var keys,
            key,
            i,
            modifiers = [];

        // take the keys from this pattern and figure out what the actual
        // pattern is all about
        keys = _keysFromString(combination);

        for (i = 0; i < keys.length; ++i) {
            key = keys[i];

            // normalize key names
            if (_SPECIAL_ALIASES[key]) {
                key = _SPECIAL_ALIASES[key];
            }

            // if this is not a keypress event then we should
            // be smart about using shift keys
            // this will only work for US keyboards however
            if (action && action != 'keypress' && _SHIFT_MAP[key]) {
                key = _SHIFT_MAP[key];
                modifiers.push('shift');
            }

            // if this key is a modifier then add it to the list of modifiers
            if (_isModifier(key)) {
                modifiers.push(key);
            }
        }

        // depending on what the key combination is
        // we will try to pick the best event for it
        action = _pickBestAction(key, modifiers, action);

        return {
            key: key,
            modifiers: modifiers,
            action: action
        };
    }

    /**
     * binds a single keyboard combination
     *
     * @param {string} combination
     * @param {Function} callback
     * @param {string=} action
     * @param {string=} sequenceName - name of sequence if part of sequence
     * @param {number=} level - what part of the sequence the command is
     * @returns void
     */
    function _bindSingle(combination, callback, action, sequenceName, level) {

        // store a direct mapped reference for use with Mousetrap.trigger
        _directMap[combination + ':' + action] = callback;

        // make sure multiple spaces in a row become a single space
        combination = combination.replace(/\s+/g, ' ');

        var sequence = combination.split(' '),
            info;

        // if this pattern is a sequence of keys then run through this method
        // to reprocess each pattern one key at a time
        if (sequence.length > 1) {
            _bindSequence(combination, sequence, callback, action);
            return;
        }

        info = _getKeyInfo(combination, action);

        // make sure to initialize array if this is the first time
        // a callback is added for this key
        _callbacks[info.key] = _callbacks[info.key] || [];

        // remove an existing match if there is one
        _getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level);

        // add this call back to the array
        // if it is a sequence put it at the beginning
        // if not put it at the end
        //
        // this is important because the way these are processed expects
        // the sequence ones to come first
        _callbacks[info.key][sequenceName ? 'unshift' : 'push']({
            callback: callback,
            modifiers: info.modifiers,
            action: info.action,
            seq: sequenceName,
            level: level,
            combo: combination
        });
    }

    /**
     * binds multiple combinations to the same callback
     *
     * @param {Array} combinations
     * @param {Function} callback
     * @param {string|undefined} action
     * @returns void
     */
    function _bindMultiple(combinations, callback, action) {
        for (var i = 0; i < combinations.length; ++i) {
            _bindSingle(combinations[i], callback, action);
        }
    }

    // start!
    _addEvent(document, 'keypress', _handleKeyEvent);
    _addEvent(document, 'keydown', _handleKeyEvent);
    _addEvent(document, 'keyup', _handleKeyEvent);

    var Mousetrap = {

        /**
         * binds an event to mousetrap
         *
         * can be a single key, a combination of keys separated with +,
         * an array of keys, or a sequence of keys separated by spaces
         *
         * be sure to list the modifier keys first to make sure that the
         * correct key ends up getting bound (the last key in the pattern)
         *
         * @param {string|Array} keys
         * @param {Function} callback
         * @param {string=} action - 'keypress', 'keydown', or 'keyup'
         * @returns void
         */
        bind: function(keys, callback, action) {
            keys = keys instanceof Array ? keys : [keys];
            _bindMultiple(keys, callback, action);
            return this;
        },

        /**
         * unbinds an event to mousetrap
         *
         * the unbinding sets the callback function of the specified key combo
         * to an empty function and deletes the corresponding key in the
         * _directMap dict.
         *
         * TODO: actually remove this from the _callbacks dictionary instead
         * of binding an empty function
         *
         * the keycombo+action has to be exactly the same as
         * it was defined in the bind method
         *
         * @param {string|Array} keys
         * @param {string} action
         * @returns void
         */
        unbind: function(keys, action) {
            return Mousetrap.bind(keys, function() {}, action);
        },

        /**
         * triggers an event that has already been bound
         *
         * @param {string} keys
         * @param {string=} action
         * @returns void
         */
        trigger: function(keys, action) {
            if (_directMap[keys + ':' + action]) {
                _directMap[keys + ':' + action]({}, keys);
            }
            return this;
        },

        /**
         * resets the library back to its initial state.  this is useful
         * if you want to clear out the current keyboard shortcuts and bind
         * new ones - for example if you switch to another page
         *
         * @returns void
         */
        reset: function() {
            _callbacks = {};
            _directMap = {};
            return this;
        },

       /**
        * should we stop this event before firing off callbacks
        *
        * @param {Event} e
        * @param {Element} element
        * @return {boolean}
        */
        stopCallback: function(e, element) {

            // if the element has the class "mousetrap" then no need to stop
            if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
                return false;
            }

            // stop for input, select, and textarea
            return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable;
        },

        /**
         * exposes _handleKey publicly so it can be overwritten by extensions
         */
        handleKey: _handleKey
    };

    // expose mousetrap to the global object
    window.Mousetrap = Mousetrap;

    // expose mousetrap as an AMD module
    if (typeof define === 'function' && define.amd) {
        define(Mousetrap);
    }
}) (window, document);
/*! 
 * angular-loading-bar v0.6.0
 * https://chieffancypants.github.io/angular-loading-bar
 * Copyright (c) 2014 Wes Cruver
 * License: MIT
 */
!function(){"use strict";angular.module("angular-loading-bar",["cfp.loadingBarInterceptor"]),angular.module("chieffancypants.loadingBar",["cfp.loadingBarInterceptor"]),angular.module("cfp.loadingBarInterceptor",["cfp.loadingBar"]).config(["$httpProvider",function(a){var b=["$q","$cacheFactory","$timeout","$rootScope","cfpLoadingBar",function(b,c,d,e,f){function g(){d.cancel(i),f.complete(),k=0,j=0}function h(b){var d,e=c.get("$http"),f=a.defaults;!b.cache&&!f.cache||b.cache===!1||"GET"!==b.method&&"JSONP"!==b.method||(d=angular.isObject(b.cache)?b.cache:angular.isObject(f.cache)?f.cache:e);var g=void 0!==d?void 0!==d.get(b.url):!1;return void 0!==b.cached&&g!==b.cached?b.cached:(b.cached=g,g)}var i,j=0,k=0,l=f.latencyThreshold;return{request:function(a){return a.ignoreLoadingBar||h(a)||(e.$broadcast("cfpLoadingBar:loading",{url:a.url}),0===j&&(i=d(function(){f.start()},l)),j++,f.set(k/j)),a},response:function(a){return a.config.ignoreLoadingBar||h(a.config)||(k++,e.$broadcast("cfpLoadingBar:loaded",{url:a.config.url}),k>=j?g():f.set(k/j)),a},responseError:function(a){return a.config.ignoreLoadingBar||h(a.config)||(k++,e.$broadcast("cfpLoadingBar:loaded",{url:a.config.url}),k>=j?g():f.set(k/j)),b.reject(a)}}}];a.interceptors.push(b)}]),angular.module("cfp.loadingBar",[]).provider("cfpLoadingBar",function(){this.includeSpinner=!0,this.includeBar=!0,this.latencyThreshold=100,this.startSize=.02,this.parentSelector="body",this.spinnerTemplate='<div id="loading-bar-spinner"><div class="spinner-icon"></div></div>',this.loadingBarTemplate='<div id="loading-bar"><div class="bar"><div class="peg"></div></div></div>',this.$get=["$injector","$document","$timeout","$rootScope",function(a,b,c,d){function e(){k||(k=a.get("$animate"));var e=b.find(n).eq(0);c.cancel(m),r||(d.$broadcast("cfpLoadingBar:started"),r=!0,u&&k.enter(o,e),t&&k.enter(q,e),f(v))}function f(a){if(r){var b=100*a+"%";p.css("width",b),s=a,c.cancel(l),l=c(function(){g()},250)}}function g(){if(!(h()>=1)){var a=0,b=h();a=b>=0&&.25>b?(3*Math.random()+3)/100:b>=.25&&.65>b?3*Math.random()/100:b>=.65&&.9>b?2*Math.random()/100:b>=.9&&.99>b?.005:0;var c=h()+a;f(c)}}function h(){return s}function i(){s=0,r=!1}function j(){k||(k=a.get("$animate")),d.$broadcast("cfpLoadingBar:completed"),f(1),c.cancel(m),m=c(function(){var a=k.leave(o,i);a&&a.then&&a.then(i),k.leave(q)},500)}var k,l,m,n=this.parentSelector,o=angular.element(this.loadingBarTemplate),p=o.find("div").eq(0),q=angular.element(this.spinnerTemplate),r=!1,s=0,t=this.includeSpinner,u=this.includeBar,v=this.startSize;return{start:e,set:f,status:h,inc:g,complete:j,includeSpinner:this.includeSpinner,latencyThreshold:this.latencyThreshold,parentSelector:this.parentSelector,startSize:this.startSize}}]})}();/**
 * Bunch of useful filters for angularJS(with no external dependencies!)
 * @version v0.4.9 - 2014-10-14 * @link https://github.com/a8m/angular-filter
 * @author Ariel Mashraki <ariel@mashraki.co.il>
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */!function(a,b,c){"use strict";function d(a){return D(a)?a:Object.keys(a).map(function(b){return a[b]})}function e(a){return null===a}function f(a,b){var c=Object.keys(a);return-1==c.map(function(c){return!(!b[c]||b[c]!=a[c])}).indexOf(!1)}function g(a,b){if(""===b)return a;var c=a.indexOf(b.charAt(0));return-1===c?!1:g(a.substr(c+1),b.substr(1))}function h(a,b,c){var d=0;return a.filter(function(a){var e=x(c)?b>d&&c(a):b>d;return d=e?d+1:d,e})}function i(a,b,c){return c.round(a*c.pow(10,b))/c.pow(10,b)}function j(a,b,c){b=b||[];var d=Object.keys(a);return d.forEach(function(d){if(C(a[d])&&!D(a[d])){var e=c?c+"."+d:c;j(a[d],b,e||d)}else{var f=c?c+"."+d:d;b.push(f)}}),b}function k(){return function(a,b){return a>b}}function l(){return function(a,b){return a>=b}}function m(){return function(a,b){return b>a}}function n(){return function(a,b){return b>=a}}function o(){return function(a,b){return a==b}}function p(){return function(a,b){return a!=b}}function q(){return function(a,b){return a===b}}function r(){return function(a,b){return a!==b}}function s(a){return function(b,c){return b=C(b)?d(b):b,!D(b)||y(c)?!0:b.some(function(b){return C(b)||z(c)?a(c)(b):b===c})}}function t(a,b){return b=b||0,b>=a.length?a:D(a[b])?t(a.slice(0,b).concat(a[b],a.slice(b+1)),b):t(a,b+1)}function u(a){var b=[];return a.forEach(function(c,d){b.push(a[a.length-d-1])}),b}function v(a){return function(b,c){function e(a,b){return y(b)?!1:a.some(function(a){return H(a,b)})}if(b=C(b)?d(b):b,!D(b))return b;var f=[],g=a(c);return b.filter(y(c)?function(a,b,c){return c.indexOf(a)===b}:function(a){var b=g(a);return e(f,b)?!1:(f.push(b),!0)})}}function w(a,b,c){return b?a+c+w(a,--b,c):a}var x=b.isDefined,y=b.isUndefined,z=b.isFunction,A=b.isString,B=b.isNumber,C=b.isObject,D=b.isArray,E=b.forEach,F=b.extend,G=b.copy,H=b.equals;String.prototype.contains||(String.prototype.contains=function(){return-1!==String.prototype.indexOf.apply(this,arguments)}),b.module("a8m.angular",[]).filter("isUndefined",function(){return function(a){return b.isUndefined(a)}}).filter("isDefined",function(){return function(a){return b.isDefined(a)}}).filter("isFunction",function(){return function(a){return b.isFunction(a)}}).filter("isString",function(){return function(a){return b.isString(a)}}).filter("isNumber",function(){return function(a){return b.isNumber(a)}}).filter("isArray",function(){return function(a){return b.isArray(a)}}).filter("isObject",function(){return function(a){return b.isObject(a)}}).filter("isEqual",function(){return function(a,c){return b.equals(a,c)}}),b.module("a8m.conditions",[]).filter({isGreaterThan:k,">":k,isGreaterThanOrEqualTo:l,">=":l,isLessThan:m,"<":m,isLessThanOrEqualTo:n,"<=":n,isEqualTo:o,"==":o,isNotEqualTo:p,"!=":p,isIdenticalTo:q,"===":q,isNotIdenticalTo:r,"!==":r}),b.module("a8m.is-null",[]).filter("isNull",function(){return function(a){return e(a)}}),b.module("a8m.after-where",[]).filter("afterWhere",function(){return function(a,b){if(a=C(a)?d(a):a,!D(a)||y(b))return a;var c=a.map(function(a){return f(b,a)}).indexOf(!0);return a.slice(-1===c?0:c)}}),b.module("a8m.after",[]).filter("after",function(){return function(a,b){return a=C(a)?d(a):a,D(a)?a.slice(b):a}}),b.module("a8m.before-where",[]).filter("beforeWhere",function(){return function(a,b){if(a=C(a)?d(a):a,!D(a)||y(b))return a;var c=a.map(function(a){return f(b,a)}).indexOf(!0);return a.slice(0,-1===c?a.length:++c)}}),b.module("a8m.before",[]).filter("before",function(){return function(a,b){return a=C(a)?d(a):a,D(a)?a.slice(0,b?--b:b):a}}),b.module("a8m.concat",[]).filter("concat",[function(){return function(a,b){if(y(b))return a;if(D(a))return a.concat(C(b)?d(b):b);if(C(a)){var c=d(a);return c.concat(C(b)?d(b):b)}return a}}]),b.module("a8m.contains",[]).filter({contains:["$parse",s],some:["$parse",s]}),b.module("a8m.count-by",[]).filter("countBy",["$parse",function(a){return function(b,c){var e,f={},g=a(c);return b=C(b)?d(b):b,!D(b)||y(c)?b:(b.forEach(function(a){e=g(a),f[e]||(f[e]=0),f[e]++}),f)}}]),b.module("a8m.defaults",[]).filter("defaults",["$parse",function(a){return function(b,c){if(b=C(b)?d(b):b,!D(b)||!C(c))return b;var e=j(c);return b.forEach(function(b){e.forEach(function(d){var e=a(d),f=e.assign;y(e(b))&&f(b,e(c))})}),b}}]),b.module("a8m.every",[]).filter("every",["$parse",function(a){return function(b,c){return b=C(b)?d(b):b,!D(b)||y(c)?!0:b.every(function(b){return C(b)||z(c)?a(c)(b):b===c})}}]),b.module("a8m.filter-by",[]).filter("filterBy",["$parse",function(a){return function(b,e,f){var g;return f=A(f)||B(f)?String(f).toLowerCase():c,b=C(b)?d(b):b,!D(b)||y(f)?b:b.filter(function(b){return e.some(function(c){if(~c.indexOf("+")){var d=c.replace(new RegExp("\\s","g"),"").split("+");g=d.reduce(function(c,d,e){return 1===e?a(c)(b)+" "+a(d)(b):c+" "+a(d)(b)})}else g=a(c)(b);return A(g)||B(g)?String(g).toLowerCase().contains(f):!1})})}}]),b.module("a8m.first",[]).filter("first",["$parse",function(a){return function(b){var e,f,g;return b=C(b)?d(b):b,D(b)?(g=Array.prototype.slice.call(arguments,1),e=B(g[0])?g[0]:1,f=B(g[0])?B(g[1])?c:g[1]:g[0],g.length?h(b,e,f?a(f):f):b[0]):b}}]),b.module("a8m.flatten",[]).filter("flatten",function(){return function(a,b){return b=b||!1,a=C(a)?d(a):a,D(a)?b?[].concat.apply([],a):t(a,0):a}}),b.module("a8m.fuzzy-by",[]).filter("fuzzyBy",["$parse",function(a){return function(b,c,e,f){var h,i,j=f||!1;return b=C(b)?d(b):b,!D(b)||y(c)||y(e)?b:(i=a(c),b.filter(function(a){return h=i(a),A(h)?(h=j?h:h.toLowerCase(),e=j?e:e.toLowerCase(),g(h,e)!==!1):!1}))}}]),b.module("a8m.fuzzy",[]).filter("fuzzy",function(){return function(a,b,c){function e(a,b){var c,d,e=Object.keys(a);return 0<e.filter(function(e){return c=a[e],d?!0:A(c)?(c=f?c:c.toLowerCase(),d=g(c,b)!==!1):!1}).length}var f=c||!1;return a=C(a)?d(a):a,!D(a)||y(b)?a:(b=f?b:b.toLowerCase(),a.filter(function(a){return A(a)?(a=f?a:a.toLowerCase(),g(a,b)!==!1):C(a)?e(a,b):!1}))}}),b.module("a8m.group-by",["a8m.filter-watcher"]).filter("groupBy",["$parse","filterWatcher",function(a,b){return function(c,d){var e,f,g=a(d);return!C(c)||y(d)?c:(e=b.$watch("groupBy",c),E(c,function(a){f=g(a),e[f]||(e[f]=[]),-1===e[f].indexOf(a)&&e[f].push(a)}),b.$destroy("groupBy",c),e)}}]),b.module("a8m.is-empty",[]).filter("isEmpty",function(){return function(a){return C(a)?!d(a).length:!a.length}}),b.module("a8m.last",[]).filter("last",["$parse",function(a){return function(b){var e,f,g,i=G(b);return i=C(i)?d(i):i,D(i)?(g=Array.prototype.slice.call(arguments,1),e=B(g[0])?g[0]:1,f=B(g[0])?B(g[1])?c:g[1]:g[0],g.length?h(i.reverse(),e,f?a(f):f).reverse():i[i.length-1]):i}}]),b.module("a8m.map",[]).filter("map",["$parse",function(a){return function(b,c){return b=C(b)?d(b):b,!D(b)||y(c)?b:b.map(function(b){return a(c)(b)})}}]),b.module("a8m.omit",[]).filter("omit",["$parse",function(a){return function(b,c){return b=C(b)?d(b):b,!D(b)||y(c)?b:b.filter(function(b){return!a(c)(b)})}}]),b.module("a8m.pick",[]).filter("pick",["$parse",function(a){return function(b,c){return b=C(b)?d(b):b,!D(b)||y(c)?b:b.filter(function(b){return a(c)(b)})}}]),b.module("a8m.remove-with",[]).filter("removeWith",function(){return function(a,b){return y(b)?a:(a=C(a)?d(a):a,a.filter(function(a){return!f(b,a)}))}}),b.module("a8m.remove",[]).filter("remove",function(){return function(a){a=C(a)?d(a):a;var b=Array.prototype.slice.call(arguments,1);return D(a)?a.filter(function(a){return!b.some(function(b){return H(b,a)})}):a}}),b.module("a8m.reverse",[]).filter("reverse",[function(){return function(a){return a=C(a)?d(a):a,A(a)?a.split("").reverse().join(""):D(a)?u(a):a}}]),b.module("a8m.search-field",[]).filter("searchField",["$parse",function(a){return function(b){var c,e;b=C(b)?d(b):b;var f=Array.prototype.slice.call(arguments,1);return D(b)&&f.length?b.map(function(b){return e=f.map(function(d){return(c=a(d))(b)}).join(" "),F(b,{searchField:e})}):b}}]),b.module("a8m.to-array",[]).filter("toArray",function(){return function(a,b){return C(a)?b?Object.keys(a).map(function(b){return F(a[b],{$key:b})}):d(a):a}}),b.module("a8m.unique",[]).filter({unique:["$parse",v],uniq:["$parse",v]}),b.module("a8m.where",[]).filter("where",function(){return function(a,b){return y(b)?a:(a=C(a)?d(a):a,a.filter(function(a){return f(b,a)}))}}),b.module("a8m.xor",[]).filter("xor",["$parse",function(a){return function(b,c,e){function f(b,c){var d=a(e);return c.some(function(a){return e?H(d(a),d(b)):H(a,b)})}return e=e||!1,b=C(b)?d(b):b,c=C(c)?d(c):c,D(b)&&D(c)?b.concat(c).filter(function(a){return!(f(a,b)&&f(a,c))}):b}}]),b.module("a8m.math.byteFmt",["a8m.math"]).filter("byteFmt",["$math",function(a){return function(b,c){return B(c)&&isFinite(c)&&c%1===0&&c>=0&&B(b)&&isFinite(b)?1024>b?i(b,c,a)+" B":1048576>b?i(b/1024,c,a)+" KB":1073741824>b?i(b/1048576,c,a)+" MB":i(b/1073741824,c,a)+" GB":"NaN"}}]),b.module("a8m.math.degrees",["a8m.math"]).filter("degrees",["$math",function(a){return function(b,c){if(B(c)&&isFinite(c)&&c%1===0&&c>=0&&B(b)&&isFinite(b)){var d=180*b/a.PI;return a.round(d*a.pow(10,c))/a.pow(10,c)}return"NaN"}}]),b.module("a8m.math.kbFmt",["a8m.math"]).filter("kbFmt",["$math",function(a){return function(b,c){return B(c)&&isFinite(c)&&c%1===0&&c>=0&&B(b)&&isFinite(b)?1024>b?i(b,c,a)+" KB":1048576>b?i(b/1024,c,a)+" MB":i(b/1048576,c,a)+" GB":"NaN"}}]),b.module("a8m.math",[]).factory("$math",["$window",function(a){return a.Math}]),b.module("a8m.math.max",["a8m.math"]).filter("max",["$math",function(a){return function(b){return D(b)?a.max.apply(a,b):b}}]),b.module("a8m.math.min",["a8m.math"]).filter("min",["$math",function(a){return function(b){return D(b)?a.min.apply(a,b):b}}]),b.module("a8m.math.percent",["a8m.math"]).filter("percent",["$math","$window",function(a,b){return function(c,d,e){var f=A(c)?b.Number(c):c;return d=d||100,e=e||!1,!B(f)||b.isNaN(f)?c:e?a.round(f/d*100):f/d*100}}]),b.module("a8m.math.radians",["a8m.math"]).filter("radians",["$math",function(a){return function(b,c){if(B(c)&&isFinite(c)&&c%1===0&&c>=0&&B(b)&&isFinite(b)){var d=3.14159265359*b/180;return a.round(d*a.pow(10,c))/a.pow(10,c)}return"NaN"}}]),b.module("a8m.math.radix",[]).filter("radix",function(){return function(a,b){var c=/^[2-9]$|^[1-2]\d$|^3[0-6]$/;return B(a)&&c.test(b)?a.toString(b).toUpperCase():a}}),b.module("a8m.math.shortFmt",["a8m.math"]).filter("shortFmt",["$math",function(a){return function(b,c){return B(c)&&isFinite(c)&&c%1===0&&c>=0&&B(b)&&isFinite(b)?1e3>b?b:1e6>b?i(b/1e3,c,a)+" K":1e9>b?i(b/1e6,c,a)+" M":i(b/1e9,c,a)+" B":"NaN"}}]),b.module("a8m.math.sum",[]).filter("sum",function(){return function(a,b){return D(a)?a.reduce(function(a,b){return a+b},b||0):a}}),b.module("a8m.ends-with",[]).filter("endsWith",function(){return function(a,b,c){var d,e=c||!1;return!A(a)||y(b)?a:(a=e?a:a.toLowerCase(),d=a.length-b.length,-1!==a.indexOf(e?b:b.toLowerCase(),d))}}),b.module("a8m.ltrim",[]).filter("ltrim",function(){return function(a,b){var c=b||"\\s";return A(a)?a.replace(new RegExp("^"+c+"+"),""):a}}),b.module("a8m.repeat",[]).filter("repeat",[function(){return function(a,b,c){var d=~~b;return A(a)&&d?w(a,--b,c||""):a}}]),b.module("a8m.rtrim",[]).filter("rtrim",function(){return function(a,b){var c=b||"\\s";return A(a)?a.replace(new RegExp(c+"+$"),""):a}}),b.module("a8m.slugify",[]).filter("slugify",[function(){return function(a,b){var c=b||"-";return A(a)?a.toLowerCase().replace(/\s+/g,c):a}}]),b.module("a8m.starts-with",[]).filter("startsWith",function(){return function(a,b,c){var d=c||!1;return!A(a)||y(b)?a:(a=d?a:a.toLowerCase(),!a.indexOf(d?b:b.toLowerCase()))}}),b.module("a8m.stringular",[]).filter("stringular",function(){return function(a){var b=Array.prototype.slice.call(arguments,1);return a.replace(/{(\d+)}/g,function(a,c){return y(b[c])?a:b[c]})}}),b.module("a8m.strip-tags",[]).filter("stripTags",function(){return function(a){return A(a)?a.replace(/<\S[^><]*>/g,""):a}}),b.module("a8m.trim",[]).filter("trim",function(){return function(a,b){var c=b||"\\s";return A(a)?a.replace(new RegExp("^"+c+"+|"+c+"+$","g"),""):a}}),b.module("a8m.truncate",[]).filter("truncate",function(){return function(a,b,c,d){return b=y(b)?a.length:b,d=d||!1,c=c||"",!A(a)||a.length<=b?a:a.substring(0,d?-1===a.indexOf(" ",b)?a.length:a.indexOf(" ",b):b)+c}}),b.module("a8m.ucfirst",[]).filter("ucfirst",[function(){return function(a){return b.isString(a)?a.split(" ").map(function(a){return a.charAt(0).toUpperCase()+a.substring(1)}).join(" "):a}}]),b.module("a8m.uri-encode",[]).filter("uriEncode",["$window",function(a){return function(b){return A(b)?a.encodeURI(b):b}}]),b.module("a8m.wrap",[]).filter("wrap",function(){return function(a,b,c){return!A(a)||y(b)?a:[b,a,c||b].join("")}}),b.module("a8m.filter-watcher",[]).provider("filterWatcher",function(){var a="_$$";this.setPrefix=function(b){return a=b,this},this.$get=["$window",function(b){function c(b){return a+b}function d(a,b){return x(b[a])}function e(a,b){var e=c(a);return d(e,b)||Object.defineProperty(b,e,{enumerable:!1,configurable:!0,value:{}}),b[e]}function f(a,b){return g(function(){delete b[c(a)]})}var g=b.setTimeout;return{$watch:e,$destroy:f}}]}),b.module("angular.filter",["a8m.ucfirst","a8m.uri-encode","a8m.slugify","a8m.strip-tags","a8m.stringular","a8m.truncate","a8m.starts-with","a8m.ends-with","a8m.wrap","a8m.trim","a8m.ltrim","a8m.rtrim","a8m.repeat","a8m.to-array","a8m.concat","a8m.contains","a8m.unique","a8m.is-empty","a8m.after","a8m.after-where","a8m.before","a8m.before-where","a8m.defaults","a8m.where","a8m.reverse","a8m.remove","a8m.remove-with","a8m.group-by","a8m.count-by","a8m.search-field","a8m.fuzzy-by","a8m.fuzzy","a8m.omit","a8m.pick","a8m.every","a8m.filter-by","a8m.xor","a8m.map","a8m.first","a8m.last","a8m.flatten","a8m.math","a8m.math.max","a8m.math.min","a8m.math.percent","a8m.math.radix","a8m.math.sum","a8m.math.degrees","a8m.math.radians","a8m.math.byteFmt","a8m.math.kbFmt","a8m.math.shortFmt","a8m.angular","a8m.conditions","a8m.is-null","a8m.filter-watcher"])}(window,window.angular);/*!
angular-xeditable - 0.5.0
Edit-in-place for angular.js
Build date: 2016-10-27 
*/
angular.module("xeditable",[]).value("editableOptions",{theme:"default",icon_set:"default",buttons:"right",blurElem:"cancel",blurForm:"ignore",activate:"focus",isDisabled:!1,activationEvent:"click",submitButtonTitle:"Submit",submitButtonAriaLabel:"Submit",cancelButtonTitle:"Cancel",cancelButtonAriaLabel:"Cancel",clearButtonTitle:"Clear",clearButtonAriaLabel:"Clear",displayClearButton:!1}),angular.module("xeditable").directive("editableBsdate",["editableDirectiveFactory",function(a){return a({directiveName:"editableBsdate",inputTpl:"<div></div>",render:function(){this.parent.render.call(this);var a=angular.element('<input type="text" class="form-control" data-ng-model="$parent.$data"/>');a.attr("uib-datepicker-popup",this.attrs.eDatepickerPopupXEditable||"yyyy/MM/dd"),a.attr("is-open",this.attrs.eIsOpen),a.attr("date-disabled",this.attrs.eDateDisabled),a.attr("uib-datepicker-popup",this.attrs.eDatepickerPopup),a.attr("year-range",this.attrs.eYearRange||20),a.attr("show-button-bar",this.attrs.eShowButtonBar||!0),a.attr("current-text",this.attrs.eCurrentText||"Today"),a.attr("clear-text",this.attrs.eClearText||"Clear"),a.attr("close-text",this.attrs.eCloseText||"Done"),a.attr("close-on-date-selection",this.attrs.eCloseOnDateSelection||!0),a.attr("datepicker-append-to-body",this.attrs.eDatePickerAppendToBody||!1),a.attr("date-disabled",this.attrs.eDateDisabled),a.attr("name",this.attrs.eName),a.attr("on-open-focus",this.attrs.eOnOpenFocus||!0),a.attr("ng-readonly",this.attrs.eReadonly||!1),this.attrs.eNgChange&&(a.attr("ng-change",this.attrs.eNgChange),this.inputEl.removeAttr("ng-change")),this.attrs.eStyle&&(a.attr("style",this.attrs.eStyle),this.inputEl.removeAttr("style")),this.scope.dateOptions={formatDay:this.attrs.eFormatDay||"dd",formatMonth:this.attrs.eFormatMonth||"MMMM",formatYear:this.attrs.eFormatYear||"yyyy",formatDayHeader:this.attrs.eFormatDayHeader||"EEE",formatDayTitle:this.attrs.eFormatDayTitle||"MMMM yyyy",formatMonthTitle:this.attrs.eFormatMonthTitle||"yyyy",showWeeks:this.attrs.eShowWeeks?"true"===this.attrs.eShowWeeks.toLowerCase():!0,startingDay:this.attrs.eStartingDay||0,minMode:this.attrs.eMinMode||"day",maxMode:this.attrs.eMaxMode||"year",initDate:this.scope.$eval(this.attrs.eInitDate)||new Date,datepickerMode:this.attrs.eDatepickerMode||"day",maxDate:this.scope.$eval(this.attrs.eMaxDate)||null,minDate:this.scope.$eval(this.attrs.eMinDate)||null};var b=angular.isDefined(this.attrs.eShowCalendarButton)?this.attrs.eShowCalendarButton:"true";if("true"===b){var c=angular.element('<button type="button" class="btn btn-default"><i class="glyphicon glyphicon-calendar"></i></button>'),d=angular.element('<span class="input-group-btn"></span>');c.attr("ng-click",this.attrs.eNgClick),d.append(c),this.inputEl.append(d)}else a.attr("ng-click",this.attrs.eNgClick);a.attr("datepicker-options","dateOptions"),this.inputEl.prepend(a),this.inputEl.removeAttr("class"),this.inputEl.removeAttr("ng-click"),this.inputEl.removeAttr("is-open"),this.inputEl.removeAttr("init-date"),this.inputEl.removeAttr("datepicker-popup"),this.inputEl.removeAttr("required"),this.inputEl.removeAttr("ng-model"),this.inputEl.removeAttr("date-picker-append-to-body"),this.inputEl.removeAttr("name"),this.inputEl.attr("class","input-group")}})}]),angular.module("xeditable").directive("editableBstime",["editableDirectiveFactory",function(a){return a({directiveName:"editableBstime",inputTpl:"<uib-timepicker></uib-timepicker>",render:function(){this.parent.render.call(this);var a=angular.element('<div class="well well-small" style="display:inline-block;"></div>');a.attr("ng-model",this.inputEl.attr("ng-model")),this.inputEl.removeAttr("ng-model"),this.attrs.eNgChange&&(a.attr("ng-change",this.inputEl.attr("ng-change")),this.inputEl.removeAttr("ng-change")),this.inputEl.wrap(a)}})}]),angular.module("xeditable").directive("editableCheckbox",["editableDirectiveFactory",function(a){return a({directiveName:"editableCheckbox",inputTpl:'<input type="checkbox">',render:function(){this.parent.render.call(this),this.attrs.eTitle&&(this.inputEl.wrap("<label></label>"),this.inputEl.parent().append("<span>"+this.attrs.eTitle+"</span>"))},autosubmit:function(){var a=this;a.inputEl.bind("change",function(){setTimeout(function(){a.scope.$apply(function(){a.scope.$form.$submit()})},500)})}})}]),angular.module("xeditable").directive("editableChecklist",["editableDirectiveFactory","editableNgOptionsParser",function(a,b){return a({directiveName:"editableChecklist",inputTpl:"<span></span>",useCopy:!0,render:function(){this.parent.render.call(this);var a=b(this.attrs.eNgOptions),c="",d="";this.attrs.eNgChange&&(c=' ng-change="'+this.attrs.eNgChange+'"'),this.attrs.eChecklistComparator&&(d=' checklist-comparator="'+this.attrs.eChecklistComparator+'"');var e='<label ng-repeat="'+a.ngRepeat+'"><input type="checkbox" checklist-model="$parent.$parent.$data" checklist-value="'+a.locals.valueFn+'"'+c+d+'><span ng-bind="'+a.locals.displayFn+'"></span></label>';this.inputEl.removeAttr("ng-model"),this.inputEl.removeAttr("ng-options"),this.inputEl.removeAttr("ng-change"),this.inputEl.removeAttr("checklist-comparator"),this.inputEl.html(e)}})}]),angular.module("xeditable").directive("editableCombodate",["editableDirectiveFactory","editableCombodate",function(a,b){return a({directiveName:"editableCombodate",inputTpl:'<input type="text">',render:function(){this.parent.render.call(this);var a={value:new Date(this.scope.$data)},c=this;angular.forEach(["format","template","minYear","maxYear","yearDescending","minuteStep","secondStep","firstItem","errorClass","customClass","roundTime","smartDays"],function(b){var d="e"+b.charAt(0).toUpperCase()+b.slice(1);d in c.attrs&&(a[b]=c.attrs[d])});var d=b.getInstance(this.inputEl,a);d.$widget.find("select").bind("change",function(a){c.scope.$data=new Date(d.getValue()).toISOString()})}})}]),function(){var a=function(a){return a.toLowerCase().replace(/-(.)/g,function(a,b){return b.toUpperCase()})},b="text|password|email|tel|number|url|search|color|date|datetime|datetime-local|time|month|week|file".split("|");angular.forEach(b,function(b){var c=a("editable-"+b);angular.module("xeditable").directive(c,["editableDirectiveFactory",function(a){return a({directiveName:c,inputTpl:'<input type="'+b+'">',render:function(){if(this.parent.render.call(this),this.attrs.eInputgroupleft||this.attrs.eInputgroupright){if(this.inputEl.wrap('<div class="input-group"></div>'),this.attrs.eInputgroupleft){var a=angular.element('<span class="input-group-addon">'+this.attrs.eInputgroupleft+"</span>");this.inputEl.parent().prepend(a)}if(this.attrs.eInputgroupright){var b=angular.element('<span class="input-group-addon">'+this.attrs.eInputgroupright+"</span>");this.inputEl.parent().append(b)}}if(this.attrs.eLabel){var c=angular.element("<label>"+this.attrs.eLabel+"</label>");this.attrs.eInputgroupleft||this.attrs.eInputgroupright?this.inputEl.parent().parent().prepend(c):this.inputEl.parent().prepend(c)}this.attrs.eFormclass&&this.editorEl.addClass(this.attrs.eFormclass)}})}])}),angular.module("xeditable").directive("editableRange",["editableDirectiveFactory","$interpolate",function(a,b){return a({directiveName:"editableRange",inputTpl:'<input type="range" id="range" name="range">',render:function(){this.parent.render.call(this),this.inputEl.after("<output>"+b.startSymbol()+"$data"+b.endSymbol()+"</output>")}})}])}(),angular.module("xeditable").directive("editableTagsInput",["editableDirectiveFactory","editableUtils",function(a,b){var c=a({directiveName:"editableTagsInput",inputTpl:"<tags-input></tags-input>",render:function(){this.parent.render.call(this),this.inputEl.append(b.rename("auto-complete",this.attrs.$autoCompleteElement)),this.inputEl.removeAttr("ng-model"),this.inputEl.attr("ng-model","$parent.$data")}}),d=c.link;return c.link=function(a,b,c,e){var f=b.find("editable-tags-input-auto-complete");return c.$autoCompleteElement=f.clone(),f.remove(),d(a,b,c,e)},c}]),angular.module("xeditable").directive("editableRadiolist",["editableDirectiveFactory","editableNgOptionsParser","$interpolate",function(a,b,c){return a({directiveName:"editableRadiolist",inputTpl:"<span></span>",render:function(){this.parent.render.call(this);var a=b(this.attrs.eNgOptions),d="";this.attrs.eNgChange&&(d='ng-change="'+this.attrs.eNgChange+'"');var e='<label data-ng-repeat="'+a.ngRepeat+'"><input type="radio" data-ng-disabled="::'+this.attrs.eNgDisabled+'" data-ng-model="$parent.$parent.$data" data-ng-value="'+c.startSymbol()+"::"+a.locals.valueFn+c.endSymbol()+'"'+d+'><span data-ng-bind="::'+a.locals.displayFn+'"></span></label>';this.inputEl.removeAttr("ng-model"),this.inputEl.removeAttr("ng-options"),this.inputEl.removeAttr("ng-change"),this.inputEl.html(e)},autosubmit:function(){var a=this;a.inputEl.bind("change",function(){setTimeout(function(){a.scope.$apply(function(){a.scope.$form.$submit()})},500)})}})}]),angular.module("xeditable").directive("editableSelect",["editableDirectiveFactory",function(a){return a({directiveName:"editableSelect",inputTpl:"<select></select>",render:function(){if(this.parent.render.call(this),this.attrs.ePlaceholder){var a=angular.element('<option value="">'+this.attrs.ePlaceholder+"</option>");this.inputEl.append(a)}},autosubmit:function(){var a=this;a.inputEl.bind("change",function(){a.scope.$apply(function(){a.scope.$form.$submit()})})}})}]),angular.module("xeditable").directive("editableTextarea",["editableDirectiveFactory",function(a){return a({directiveName:"editableTextarea",inputTpl:"<textarea></textarea>",addListeners:function(){var a=this;a.parent.addListeners.call(a),a.single&&"no"!==a.buttons&&a.autosubmit()},autosubmit:function(){var a=this;a.inputEl.bind("keydown",function(b){(b.ctrlKey||b.metaKey)&&13===b.keyCode&&a.scope.$apply(function(){a.scope.$form.$submit()})})}})}]),angular.module("xeditable").directive("editableUiSelect",["editableDirectiveFactory","editableUtils",function(a,b){var c=a({directiveName:"editableUiSelect",inputTpl:"<ui-select></ui-select>",render:function(){this.parent.render.call(this),this.inputEl.append(b.rename("ui-select-match",this.attrs.$matchElement)),this.inputEl.append(b.rename("ui-select-choices",this.attrs.$choicesElement)),this.inputEl.removeAttr("ng-model"),this.inputEl.attr("ng-model","$parent.$parent.$data")}}),d=c.link;return c.link=function(a,b,c,e){var f=b.find("editable-ui-select-match"),g=b.find("editable-ui-select-choices");return c.$matchElement=f.clone(),c.$choicesElement=g.clone(),f.remove(),g.remove(),d(a,b,c,e)},c}]),angular.module("xeditable").factory("editableController",["$q","editableUtils",function(a,b){function c(a,c,d,e,f,g,h,i,j,k){var l,m,n=this;n.scope=a,n.elem=d,n.attrs=c,n.inputEl=null,n.editorEl=null,n.single=!0,n.error="",n.theme=f[c.editableTheme]||f[h.theme]||f["default"],n.parent={},n.icon_set="default"===h.icon_set?g["default"][h.theme]:g.external[h.icon_set],n.inputTpl="",n.directiveName="",n.useCopy=!1,n.single=null,n.buttons="right",n.init=function(b){if(n.single=b,n.name=c.eName||c[n.directiveName],!c[n.directiveName])throw"You should provide value for `"+n.directiveName+"` in editable element!";l=e(c[n.directiveName]),n.single?n.buttons=n.attrs.buttons||h.buttons:n.buttons="no",c.eName&&n.scope.$watch("$data",function(a){n.scope.$form.$data[c.eName]=a}),c.onshow&&(n.onshow=function(){return n.catchError(e(c.onshow)(a))}),c.onhide&&(n.onhide=function(){return e(c.onhide)(a)}),c.oncancel&&(n.oncancel=function(){return e(c.oncancel)(a)}),c.onbeforesave&&(n.onbeforesave=function(){return n.catchError(e(c.onbeforesave)(a))}),c.onaftersave&&(n.onaftersave=function(){return n.catchError(e(c.onaftersave)(a))}),a.$parent.$watch(c[n.directiveName],function(a,b){n.setLocalValue(),n.handleEmpty()})},n.render=function(){var a=n.theme;n.inputEl=angular.element(n.inputTpl),n.controlsEl=angular.element(a.controlsTpl),n.controlsEl.append(n.inputEl),"no"!==n.buttons&&(n.buttonsEl=angular.element(a.buttonsTpl),n.submitEl=angular.element(a.submitTpl),n.resetEl=angular.element(a.resetTpl),n.cancelEl=angular.element(a.cancelTpl),n.submitEl.attr("title",h.submitButtonTitle),n.submitEl.attr("aria-label",h.submitButtonAriaLabel),n.cancelEl.attr("title",h.cancelButtonTitle),n.cancelEl.attr("aria-label",h.cancelButtonAriaLabel),n.resetEl.attr("title",h.clearButtonTitle),n.resetEl.attr("aria-label",h.clearButtonAriaLabel),n.icon_set&&(n.submitEl.find("span").addClass(n.icon_set.ok),n.cancelEl.find("span").addClass(n.icon_set.cancel),n.resetEl.find("span").addClass(n.icon_set.clear)),n.buttonsEl.append(n.submitEl).append(n.cancelEl),h.displayClearButton&&n.buttonsEl.append(n.resetEl),n.controlsEl.append(n.buttonsEl),n.inputEl.addClass("editable-has-buttons")),n.errorEl=angular.element(a.errorTpl),n.controlsEl.append(n.errorEl),n.editorEl=angular.element(n.single?a.formTpl:a.noformTpl),n.editorEl.append(n.controlsEl);for(var d in c.$attr)if(!(d.length<=1)){var e=!1,f=d.substring(1,2);if("e"===d.substring(0,1)&&f===f.toUpperCase()&&(e=d.substring(1),"Form"!==e&&"NgSubmit"!==e)){var g=e.substring(0,1),i=e.substring(1,2);e=i===i.toUpperCase()&&g===g.toUpperCase()?g.toLowerCase()+"-"+b.camelToDash(e.substring(1)):g.toLowerCase()+b.camelToDash(e.substring(1));var j="value"!==e&&""===c[d]?e:c[d];n.inputEl.attr(e,j)}}n.inputEl.addClass("editable-input"),n.inputEl.attr("ng-model","$parent.$data"),n.editorEl.addClass(b.camelToDash(n.directiveName)),n.single&&(n.editorEl.attr("editable-form","$form"),n.editorEl.attr("blur",n.attrs.blur||("no"===n.buttons?"cancel":h.blurElem))),angular.isFunction(a.postrender)&&a.postrender.call(n)},n.setLocalValue=function(){n.scope.$data=n.useCopy?angular.copy(l(a.$parent)):l(a.$parent)};var o=null;n.show=function(){return n.setLocalValue(),n.render(),d.after(n.editorEl),o=a.$new(),j(n.editorEl)(o),n.addListeners(),d.addClass("editable-hide"),n.onshow()},n.hide=function(){return o.$destroy(),n.controlsEl.remove(),n.editorEl.remove(),d.removeClass("editable-hide"),n.onhide()},n.cancel=function(){n.oncancel()},n.addListeners=function(){n.inputEl.bind("keyup",function(a){if(n.single)switch(a.keyCode){case 27:n.scope.$apply(function(){n.scope.$form.$cancel()})}}),n.single&&"no"===n.buttons&&n.autosubmit(),n.editorEl.bind("click",function(a){a.which&&1!==a.which||n.scope.$form.$visible&&(n.scope.$form._clicked=!0)})},n.setWaiting=function(a){a?(m=!n.inputEl.attr("disabled")&&!n.inputEl.attr("ng-disabled")&&!n.inputEl.attr("ng-enabled"),m&&(n.inputEl.attr("disabled","disabled"),n.buttonsEl&&n.buttonsEl.find("button").attr("disabled","disabled"))):m&&(n.inputEl.removeAttr("disabled"),n.buttonsEl&&n.buttonsEl.find("button").removeAttr("disabled"))},n.activate=function(a,b){setTimeout(function(){var c=n.inputEl[0];"focus"===h.activate&&c.focus?(a&&(b=b||a,c.onfocus=function(){var c=this;setTimeout(function(){c.setSelectionRange(a,b)})}),"editableRadiolist"==n.directiveName||"editableChecklist"==n.directiveName||"editableBsdate"==n.directiveName||"editableTagsInput"==n.directiveName?c.querySelector(".ng-pristine").focus():c.focus()):"select"===h.activate&&(c.select?c.select():c.focus&&c.focus())},0)},n.setError=function(b){angular.isObject(b)||(a.$error=b,n.error=b)},n.catchError=function(a,b){return angular.isObject(a)&&b!==!0?k.when(a).then(angular.bind(this,function(a){this.catchError(a,!0)}),angular.bind(this,function(a){this.catchError(a,!0)})):b&&angular.isObject(a)&&a.status&&200!==a.status&&a.data&&angular.isString(a.data)?(this.setError(a.data),a=a.data):angular.isString(a)&&this.setError(a),a},n.save=function(){l.assign(a.$parent,n.useCopy?angular.copy(n.scope.$data):n.scope.$data)},n.handleEmpty=function(){var b=l(a.$parent),c=null===b||void 0===b||""===b||angular.isArray(b)&&0===b.length;d.toggleClass("editable-empty",c)},n.autosubmit=angular.noop,n.onshow=angular.noop,n.onhide=angular.noop,n.oncancel=angular.noop,n.onbeforesave=angular.noop,n.onaftersave=angular.noop}return c.$inject=["$scope","$attrs","$element","$parse","editableThemes","editableIcons","editableOptions","$rootScope","$compile","$q"],c}]),angular.module("xeditable").factory("editableDirectiveFactory",["$parse","$compile","editableThemes","$rootScope","$document","editableController","editableFormController","editableOptions",function(a,b,c,d,e,f,g,h){return function(b){return{restrict:"A",scope:!0,require:[b.directiveName,"?^form"],controller:f,link:function(c,f,i,j){var k,l=j[0],m=!1;if(j[1])k=j[1],m=void 0===i.eSingle;else if(i.eForm){var n=a(i.eForm)(c);if(n)k=n,m=!0;else if(f&&"function"==typeof f.parents&&f.parents().last().find("form[name="+i.eForm+"]").length)k=null,m=!0;else for(var o=0;o<e[0].forms.length;o++)if(e[0].forms[o].name===i.eForm){k=null,m=!0;break}}angular.forEach(b,function(a,b){void 0!==l[b]&&(l.parent[b]=l[b])}),angular.extend(l,b);var p=function(){return angular.isDefined(i.editDisabled)?c.$eval(i.editDisabled):h.isDisabled};if(l.init(!m),c.$editable=l,f.addClass("editable"),m)if(k){if(c.$form=k,!c.$form.$addEditable)throw"Form with editable elements should have `editable-form` attribute.";c.$form.$addEditable(l)}else d.$$editableBuffer=d.$$editableBuffer||{},d.$$editableBuffer[i.eForm]=d.$$editableBuffer[i.eForm]||[],d.$$editableBuffer[i.eForm].push(l),c.$form=null;else c.$form=g(),c.$form.$addEditable(l),i.eForm&&(a(i.eForm).assign||angular.noop)(c.$parent,c.$form),(!i.eForm||i.eClickable)&&(f.addClass("editable-click"),f.bind(h.activationEvent,function(a){a.preventDefault(),a.editable=l,p()||c.$apply(function(){c.$form.$show()})}))}}}}]),angular.module("xeditable").factory("editableFormController",["$parse","$document","$rootScope","editablePromiseCollection","editableUtils",function(a,b,c,d,e){var f=[],g=function(a,b){if(b==a)return!0;for(var c=b.parentNode;null!==c;){if(c==a)return!0;c=c.parentNode}return!1},h=function(a,b){var c=!0,d=a.$editables;return angular.forEach(d,function(a){var d=a.editorEl[0];g(d,b.target)&&(c=!1)}),c};b.bind("click",function(a){if(!a.which||1===a.which){for(var b=[],d=[],e=0;e<f.length;e++)f[e]._clicked?f[e]._clicked=!1:f[e].$waiting||("cancel"===f[e]._blur&&h(f[e],a)&&b.push(f[e]),"submit"===f[e]._blur&&h(f[e],a)&&d.push(f[e]));(b.length||d.length)&&c.$apply(function(){angular.forEach(b,function(a){a.$cancel()}),angular.forEach(d,function(a){a.$submit()})})}}),c.$on("closeEdit",function(){for(var a=0;a<f.length;a++)f[a].$hide()});var i={$addEditable:function(a){this.$editables.push(a),a.elem.bind("$destroy",angular.bind(this,this.$removeEditable,a)),a.scope.$form||(a.scope.$form=this),this.$visible&&a.catchError(a.show()),a.catchError(a.setWaiting(this.$waiting))},$removeEditable:function(a){for(var b=0;b<this.$editables.length;b++)if(this.$editables[b]===a)return void this.$editables.splice(b,1)},$show:function(){if(!this.$visible){this.$visible=!0;var a=d();a.when(this.$onshow()),this.$setError(null,""),angular.forEach(this.$editables,function(b){a.when(b.show())}),a.then({onWait:angular.bind(this,this.$setWaiting),onTrue:angular.bind(this,this.$activate),onFalse:angular.bind(this,this.$activate),onString:angular.bind(this,this.$activate)}),setTimeout(angular.bind(this,function(){this._clicked=!1,-1===e.indexOf(f,this)&&f.push(this)}),0)}},$activate:function(a){var b;if(this.$editables.length){if(angular.isString(a))for(b=0;b<this.$editables.length;b++)if(this.$editables[b].name===a)return void this.$editables[b].activate();for(b=0;b<this.$editables.length;b++)if(this.$editables[b].error)return void this.$editables[b].activate();this.$editables[0].activate(this.$editables[0].elem[0].selectionStart,this.$editables[0].elem[0].selectionEnd)}},$hide:function(){this.$visible&&(this.$visible=!1,this.$onhide(),angular.forEach(this.$editables,function(a){a.hide()}),e.arrayRemove(f,this))},$cancel:function(){this.$visible&&(this.$oncancel(),angular.forEach(this.$editables,function(a){a.cancel()}),this.$hide())},$setWaiting:function(a){this.$waiting=!!a,angular.forEach(this.$editables,function(b){b.setWaiting(!!a)})},$setError:function(a,b){angular.forEach(this.$editables,function(c){a&&c.name!==a||c.setError(b)})},$submit:function(){function a(a){var b=d();b.when(this.$onbeforesave()),b.then({onWait:angular.bind(this,this.$setWaiting),onTrue:a?angular.bind(this,this.$save):angular.bind(this,this.$hide),onFalse:angular.bind(this,this.$hide),onString:angular.bind(this,this.$activate)})}if(!this.$waiting){this.$setError(null,"");var b=d();angular.forEach(this.$editables,function(a){b.when(a.onbeforesave())}),b.then({onWait:angular.bind(this,this.$setWaiting),onTrue:angular.bind(this,a,!0),onFalse:angular.bind(this,a,!1),onString:angular.bind(this,this.$activate)})}},$save:function(){angular.forEach(this.$editables,function(a){a.save()});var a=d();a.when(this.$onaftersave()),angular.forEach(this.$editables,function(b){a.when(b.onaftersave())}),a.then({onWait:angular.bind(this,this.$setWaiting),onTrue:angular.bind(this,this.$hide),onFalse:angular.bind(this,this.$hide),onString:angular.bind(this,this.$activate)})},$onshow:angular.noop,$oncancel:angular.noop,$onhide:angular.noop,$onbeforesave:angular.noop,$onaftersave:angular.noop};return function(){return angular.extend({$editables:[],$visible:!1,$waiting:!1,$data:{},_clicked:!1,_blur:null},i)}}]),angular.module("xeditable").directive("editableForm",["$rootScope","$parse","editableFormController","editableOptions",function(a,b,c,d){return{restrict:"A",require:["form"],compile:function(){return{pre:function(b,d,e,f){var g,h=f[0];e.editableForm?b[e.editableForm]&&b[e.editableForm].$show?(g=b[e.editableForm],angular.extend(h,g)):(g=c(),b[e.editableForm]=g,angular.extend(g,h)):(g=c(),angular.extend(h,g));var i=a.$$editableBuffer,j=h.$name;j&&i&&i[j]&&(angular.forEach(i[j],function(a){g.$addEditable(a)}),delete i[j])},post:function(a,c,e,f){var g;g=e.editableForm&&a[e.editableForm]&&a[e.editableForm].$show?a[e.editableForm]:f[0],e.onshow&&(g.$onshow=angular.bind(g,b(e.onshow),a)),e.onhide&&(g.$onhide=angular.bind(g,b(e.onhide),a)),e.oncancel&&(g.$oncancel=angular.bind(g,b(e.oncancel),a)),e.shown&&b(e.shown)(a)&&g.$show(),g._blur=e.blur||d.blurForm,e.ngSubmit||e.submit||(e.onbeforesave&&(g.$onbeforesave=function(){return b(e.onbeforesave)(a,{$data:g.$data})}),e.onaftersave&&(g.$onaftersave=function(){return b(e.onaftersave)(a,{$data:g.$data})}),c.bind("submit",function(b){b.preventDefault(),a.$apply(function(){g.$submit()})})),c.bind("click",function(a){a.which&&1!==a.which||g.$visible&&(g._clicked=!0)})}}}}}]),angular.module("xeditable").factory("editablePromiseCollection",["$q",function(a){function b(){return{promises:[],hasFalse:!1,hasString:!1,when:function(b,c){if(b===!1)this.hasFalse=!0;else if(!c&&angular.isObject(b))this.promises.push(a.when(b));else{if(!angular.isString(b))return;this.hasString=!0}},then:function(b){function c(){h.hasString||h.hasFalse?!h.hasString&&h.hasFalse?e():f():d()}b=b||{};var d=b.onTrue||angular.noop,e=b.onFalse||angular.noop,f=b.onString||angular.noop,g=b.onWait||angular.noop,h=this;this.promises.length?(g(!0),a.all(this.promises).then(function(a){g(!1),angular.forEach(a,function(a){h.when(a,!0)}),c()},function(a){g(!1),f()})):c()}}}return b}]),angular.module("xeditable").factory("editableUtils",[function(){return{indexOf:function(a,b){if(a.indexOf)return a.indexOf(b);for(var c=0;c<a.length;c++)if(b===a[c])return c;return-1},arrayRemove:function(a,b){var c=this.indexOf(a,b);return c>=0&&a.splice(c,1),b},camelToDash:function(a){var b=/[A-Z]/g;return a.replace(b,function(a,b){return(b?"-":"")+a.toLowerCase()})},dashToCamel:function(a){var b=/([\:\-\_]+(.))/g,c=/^moz([A-Z])/;return a.replace(b,function(a,b,c,d){return d?c.toUpperCase():c}).replace(c,"Moz$1")},rename:function(a,b){if(b[0]&&b[0].attributes){var c=angular.element("<"+a+"/>");c.html(b.html());for(var d=b[0].attributes,e=0;e<d.length;++e)c.attr(d.item(e).nodeName,d.item(e).value);return c}}}}]),angular.module("xeditable").factory("editableNgOptionsParser",[function(){function a(a){var c;if(!(c=a.match(b)))throw"ng-options parse error";var d,e=c[2]||c[1],f=c[4]||c[6],g=c[5],h=(c[3]||"",c[2]?c[1]:f),i=c[7],j=c[8],k=j?c[8]:null;return void 0===g?(d=f+" in "+i,void 0!==j&&(d+=" track by "+k)):d="("+g+", "+f+") in "+i,{ngRepeat:d,locals:{valueName:f,keyName:g,valueFn:h,displayFn:e}}}var b=/^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/;return a}]),angular.module("xeditable").factory("editableCombodate",[function(){function a(a,b){if(this.$element=angular.element(a),"INPUT"!=this.$element[0].nodeName)throw"Combodate should be applied to INPUT element";var c=(new Date).getFullYear();this.defaults={format:"YYYY-MM-DD HH:mm",template:"D / MMM / YYYY   H : mm",value:null,minYear:1970,maxYear:c,yearDescending:!0,minuteStep:5,secondStep:1,firstItem:"empty",errorClass:null,customClass:"",roundTime:!0,smartDays:!0},this.options=angular.extend({},this.defaults,b),this.init()}return a.prototype={constructor:a,init:function(){if(this.map={day:["D","date"],month:["M","month"],year:["Y","year"],hour:["[Hh]","hours"],minute:["m","minutes"],second:["s","seconds"],ampm:["[Aa]",""]},this.$widget=angular.element('<span class="combodate"></span>').html(this.getTemplate()),this.initCombos(),this.options.smartDays){var a=this;this.$widget.find("select").bind("change",function(b){(angular.element(b.target).hasClass("month")||angular.element(b.target).hasClass("year"))&&a.fillCombo("day")})}this.$widget.find("select").css("width","auto"),this.$element.css("display","none").after(this.$widget),this.setValue(this.$element.val()||this.options.value)},getTemplate:function(){var a=this.options.template,b=this.options.customClass;return angular.forEach(this.map,function(b,c){b=b[0];var d=new RegExp(b+"+"),e=b.length>1?b.substring(1,2):b;a=a.replace(d,"{"+e+"}")}),a=a.replace(/ /g,"&nbsp;"),angular.forEach(this.map,function(c,d){c=c[0];var e=c.length>1?c.substring(1,2):c;a=a.replace("{"+e+"}",'<select class="'+d+" "+b+'"></select>')}),a},initCombos:function(){for(var a in this.map){var b=this.$widget[0].querySelectorAll("."+a);this["$"+a]=b.length?angular.element(b):null,this.fillCombo(a)}},fillCombo:function(a){var b=this["$"+a];if(b){var c="fill"+a.charAt(0).toUpperCase()+a.slice(1),d=this[c](),e=b.val();b.html("");for(var f=0;f<d.length;f++)b.append('<option value="'+d[f][0]+'">'+d[f][1]+"</option>");b.val(e)}},fillCommon:function(a){var b,c=[];if("name"===this.options.firstItem){b=moment.relativeTime||moment.langData()._relativeTime;var d="function"==typeof b[a]?b[a](1,!0,a,!1):b[a];d=d.split(" ").reverse()[0],c.push(["",d])}else"empty"===this.options.firstItem&&c.push(["",""]);return c},fillDay:function(){var a,b,c=this.fillCommon("d"),d=-1!==this.options.template.indexOf("DD"),e=31;if(this.options.smartDays&&this.$month&&this.$year){var f=parseInt(this.$month.val(),10),g=parseInt(this.$year.val(),10);isNaN(f)||isNaN(g)||(e=moment([g,f]).daysInMonth())}for(b=1;e>=b;b++)a=d?this.leadZero(b):b,c.push([b,a]);return c},fillMonth:function(){var a,b,c=this.fillCommon("M"),d=-1!==this.options.template.indexOf("MMMM"),e=-1!==this.options.template.indexOf("MMM"),f=-1!==this.options.template.indexOf("MM");for(b=0;11>=b;b++)a=d?moment().date(1).month(b).format("MMMM"):e?moment().date(1).month(b).format("MMM"):f?this.leadZero(b+1):b+1,c.push([b,a]);return c},fillYear:function(){var a,b,c=[],d=-1!==this.options.template.indexOf("YYYY");for(b=this.options.maxYear;b>=this.options.minYear;b--)a=d?b:(b+"").substring(2),c[this.options.yearDescending?"push":"unshift"]([b,a]);return c=this.fillCommon("y").concat(c)},fillHour:function(){var a,b,c=this.fillCommon("h"),d=-1!==this.options.template.indexOf("h"),e=(-1!==this.options.template.indexOf("H"),-1!==this.options.template.toLowerCase().indexOf("hh")),f=d?1:0,g=d?12:23;for(b=f;g>=b;b++)a=e?this.leadZero(b):b,c.push([b,a]);return c},fillMinute:function(){var a,b,c=this.fillCommon("m"),d=-1!==this.options.template.indexOf("mm");for(b=0;59>=b;b+=this.options.minuteStep)a=d?this.leadZero(b):b,c.push([b,a]);return c},fillSecond:function(){var a,b,c=this.fillCommon("s"),d=-1!==this.options.template.indexOf("ss");for(b=0;59>=b;b+=this.options.secondStep)a=d?this.leadZero(b):b,c.push([b,a]);return c},fillAmpm:function(){var a=-1!==this.options.template.indexOf("a"),b=(-1!==this.options.template.indexOf("A"),[["am",a?"am":"AM"],["pm",a?"pm":"PM"]]);return b},getValue:function(a){var b,c={},d=this,e=!1;return angular.forEach(this.map,function(a,b){if("ampm"!==b){var f="day"===b?1:0;return c[b]=d["$"+b]?parseInt(d["$"+b].val(),10):f,isNaN(c[b])?(e=!0,!1):void 0}}),e?"":(this.$ampm&&(12===c.hour?c.hour="am"===this.$ampm.val()?0:12:c.hour="am"===this.$ampm.val()?c.hour:c.hour+12),b=moment([c.year,c.month,c.day,c.hour,c.minute,c.second]),this.highlight(b),a=void 0===a?this.options.format:a,null===a?b.isValid()?b:null:b.isValid()?b.format(a):"")},setValue:function(a){function b(a,b){var c={};return angular.forEach(a.children("option"),function(a,d){var e=angular.element(a).attr("value");if(""!==e){var f=Math.abs(e-b);("undefined"==typeof c.distance||f<c.distance)&&(c={value:e,distance:f})}}),c.value}if(a){var c="string"==typeof a?moment(a,this.options.format,!0):moment(a),d=this,e={};c.isValid()&&(angular.forEach(this.map,function(a,b){"ampm"!==b&&(e[b]=c[a[1]]())}),this.$ampm&&(e.hour>=12?(e.ampm="pm",e.hour>12&&(e.hour-=12)):(e.ampm="am",0===e.hour&&(e.hour=12))),angular.forEach(e,function(a,c){d["$"+c]&&("minute"===c&&d.options.minuteStep>1&&d.options.roundTime&&(a=b(d["$"+c],a)),"second"===c&&d.options.secondStep>1&&d.options.roundTime&&(a=b(d["$"+c],a)),d["$"+c].val(a))}),this.options.smartDays&&this.fillCombo("day"),this.$element.val(c.format(this.options.format)).triggerHandler("change"))}},highlight:function(a){a.isValid()?this.options.errorClass?this.$widget.removeClass(this.options.errorClass):this.$widget.find("select").css("border-color",this.borderColor):this.options.errorClass?this.$widget.addClass(this.options.errorClass):(this.borderColor||(this.borderColor=this.$widget.find("select").css("border-color")),this.$widget.find("select").css("border-color","red"))},leadZero:function(a){return 9>=a?"0"+a:a},destroy:function(){this.$widget.remove(),this.$element.removeData("combodate").show()}},{getInstance:function(b,c){return new a(b,c)}}}]),angular.module("xeditable").factory("editableIcons",function(){var a={"default":{bs2:{ok:"icon-ok icon-white",cancel:"icon-remove",clear:"icon-trash"},bs3:{ok:"glyphicon glyphicon-ok",cancel:"glyphicon glyphicon-remove",clear:"glyphicon glyphicon-trash"}},external:{"font-awesome":{ok:"fa fa-check",cancel:"fa fa-times",clear:"fa fa-trash"}}};return a}),angular.module("xeditable").factory("editableThemes",function(){var a={"default":{formTpl:'<form class="editable-wrap"></form>',noformTpl:'<span class="editable-wrap"></span>',controlsTpl:'<span class="editable-controls"></span>',inputTpl:"",errorTpl:'<div class="editable-error" data-ng-if="$error" data-ng-bind="$error"></div>',buttonsTpl:'<span class="editable-buttons"></span>',submitTpl:'<button type="submit">save</button>',cancelTpl:'<button type="button" ng-click="$form.$cancel()">cancel</button>',resetTpl:'<button type="reset">clear</button>'},bs2:{formTpl:'<form class="form-inline editable-wrap" role="form"></form>',noformTpl:'<span class="editable-wrap"></span>',controlsTpl:'<div class="editable-controls controls control-group" ng-class="{\'error\': $error}"></div>',inputTpl:"",errorTpl:'<div class="editable-error help-block" data-ng-if="$error" data-ng-bind="$error"></div>',buttonsTpl:'<span class="editable-buttons"></span>',submitTpl:'<button type="submit" class="btn btn-primary"><span></span></button>',cancelTpl:'<button type="button" class="btn" ng-click="$form.$cancel()"><span></span></button>',resetTpl:'<button type="reset" class="btn btn-danger">clear</button>'},bs3:{formTpl:'<form class="form-inline editable-wrap" role="form"></form>',noformTpl:'<span class="editable-wrap"></span>',
controlsTpl:'<div class="editable-controls form-group" ng-class="{\'has-error\': $error}"></div>',inputTpl:"",errorTpl:'<div class="editable-error help-block" data-ng-if="$error" data-ng-bind="$error"></div>',buttonsTpl:'<span class="editable-buttons"></span>',submitTpl:'<button type="submit" class="btn btn-primary"><span></span></button>',cancelTpl:'<button type="button" class="btn btn-default" ng-click="$form.$cancel()"><span></span></button>',resetTpl:'<button type="reset" class="btn btn-danger">clear</button>',buttonsClass:"",inputClass:"",postrender:function(){switch(this.directiveName){case"editableText":case"editableSelect":case"editableTextarea":case"editableEmail":case"editableTel":case"editableNumber":case"editableUrl":case"editableSearch":case"editableDate":case"editableDatetime":case"editableBsdate":case"editableTime":case"editableMonth":case"editableWeek":case"editablePassword":case"editableDatetimeLocal":if(this.inputEl.addClass("form-control"),this.theme.inputClass){if(this.inputEl.attr("multiple")&&("input-sm"===this.theme.inputClass||"input-lg"===this.theme.inputClass))break;this.inputEl.addClass(this.theme.inputClass)}break;case"editableCheckbox":this.editorEl.addClass("checkbox")}this.buttonsEl&&this.theme.buttonsClass&&this.buttonsEl.find("button").addClass(this.theme.buttonsClass)}},semantic:{formTpl:'<form class="editable-wrap ui form" ng-class="{\'error\': $error}" role="form"></form>',noformTpl:'<span class="editable-wrap"></span>',controlsTpl:'<div class="editable-controls ui fluid input" ng-class="{\'error\': $error}"></div>',inputTpl:"",errorTpl:'<div class="editable-error ui error message" data-ng-if="$error" data-ng-bind="$error"></div>',buttonsTpl:'<span class="mini ui buttons"></span>',submitTpl:'<button type="submit" class="ui primary button"><i class="ui check icon"></i></button>',cancelTpl:'<button type="button" class="ui button" ng-click="$form.$cancel()"><i class="ui cancel icon"></i></button>',resetTpl:'<button type="reset" class="ui button">clear</button>'}};return a});!function(){"use strict";function t(t,e,s,n,o,r,a){function i(t){if(t)d(t.toastId);else for(var e=0;e<O.length;e++)d(O[e].toastId)}function l(t,e,s){var n=m().iconClasses.error;return g(n,t,e,s)}function c(t,e,s){var n=m().iconClasses.info;return g(n,t,e,s)}function u(t,e,s){var n=m().iconClasses.success;return g(n,t,e,s)}function p(t,e,s){var n=m().iconClasses.warning;return g(n,t,e,s)}function d(e,s){function n(t){for(var e=0;e<O.length;e++)if(O[e].toastId===t)return O[e]}function o(){return!O.length}var i=n(e);i&&!i.deleting&&(i.deleting=!0,i.isOpened=!1,t.leave(i.el).then(function(){i.scope.options.onHidden&&i.scope.options.onHidden(s),i.scope.$destroy();var t=O.indexOf(i);delete B[i.scope.message],O.splice(t,1);var e=r.maxOpened;e&&O.length>=e&&O[e-1].open.resolve(),o()&&(h.remove(),h=null,T=a.defer())}))}function g(t,e,s,n){return angular.isObject(s)&&(n=s,s=null),v({iconClass:t,message:e,optionsOverride:n,title:s})}function m(){return angular.extend({},r)}function f(e){if(h)return T.promise;h=angular.element("<div></div>"),h.attr("id",e.containerId),h.addClass(e.positionClass),h.css({"pointer-events":"auto"});var s=angular.element(document.querySelector(e.target));if(!s||!s.length)throw"Target for toasts doesn't exist";return t.enter(h,s).then(function(){T.resolve()}),T.promise}function v(s){function r(t,e,s){s.allowHtml?(t.scope.allowHtml=!0,t.scope.title=o.trustAsHtml(e.title),t.scope.message=o.trustAsHtml(e.message)):(t.scope.title=e.title,t.scope.message=e.message),t.scope.toastType=t.iconClass,t.scope.toastId=t.toastId,t.scope.options={extendedTimeOut:s.extendedTimeOut,messageClass:s.messageClass,onHidden:s.onHidden,onShown:s.onShown,progressBar:s.progressBar,tapToDismiss:s.tapToDismiss,timeOut:s.timeOut,titleClass:s.titleClass,toastClass:s.toastClass},s.closeButton&&(t.scope.options.closeHtml=s.closeHtml)}function i(){function t(t){for(var e=["containerId","iconClasses","maxOpened","newestOnTop","positionClass","preventDuplicates","preventOpenDuplicates","templates"],s=0,n=e.length;n>s;s++)delete t[e[s]];return t}var e={toastId:C++,isOpened:!1,scope:n.$new(),open:a.defer()};return e.iconClass=s.iconClass,s.optionsOverride&&(p=angular.extend(p,t(s.optionsOverride)),e.iconClass=s.optionsOverride.iconClass||e.iconClass),r(e,s,p),e.el=l(e.scope),e}function l(t){var s=angular.element("<div toast></div>"),n=e.get("$compile");return n(s)(t)}function c(){return p.maxOpened&&O.length<=p.maxOpened||!p.maxOpened}function u(){var t=p.preventDuplicates&&s.message===w,e=p.preventOpenDuplicates&&B[s.message];return t||e?!0:(w=s.message,B[s.message]=!0,!1)}var p=m();if(!u()){var g=i();if(O.push(g),p.autoDismiss&&p.maxOpened>0)for(var v=O.slice(0,O.length-p.maxOpened),T=0,$=v.length;$>T;T++)d(v[T].toastId);return c()&&g.open.resolve(),g.open.promise.then(function(){f(p).then(function(){if(g.isOpened=!0,p.newestOnTop)t.enter(g.el,h).then(function(){g.scope.init()});else{var e=h[0].lastChild?angular.element(h[0].lastChild):null;t.enter(g.el,h,e).then(function(){g.scope.init()})}})}),g}}var h,C=0,O=[],w="",B={},T=a.defer(),$={clear:i,error:l,info:c,remove:d,success:u,warning:p};return $}angular.module("toastr",[]).factory("toastr",t),t.$inject=["$animate","$injector","$document","$rootScope","$sce","toastrConfig","$q"]}(),function(){"use strict";angular.module("toastr").constant("toastrConfig",{allowHtml:!1,autoDismiss:!1,closeButton:!1,closeHtml:"<button>&times;</button>",containerId:"toast-container",extendedTimeOut:1e3,iconClasses:{error:"toast-error",info:"toast-info",success:"toast-success",warning:"toast-warning"},maxOpened:0,messageClass:"toast-message",newestOnTop:!0,onHidden:null,onShown:null,positionClass:"toast-top-right",preventDuplicates:!1,preventOpenDuplicates:!1,progressBar:!1,tapToDismiss:!0,target:"body",templates:{toast:"directives/toast/toast.html",progressbar:"directives/progressbar/progressbar.html"},timeOut:5e3,titleClass:"toast-title",toastClass:"toast"})}(),function(){"use strict";function t(t){function e(t,e,s,n){function o(){var t=(i-(new Date).getTime())/a*100;e.css("width",t+"%")}var r,a,i;n.progressBar=t,t.start=function(t){r&&clearInterval(r),a=parseFloat(t),i=(new Date).getTime()+a,r=setInterval(o,10)},t.stop=function(){r&&clearInterval(r)},t.$on("$destroy",function(){clearInterval(r)})}return{replace:!0,require:"^toast",templateUrl:function(){return t.templates.progressbar},link:e}}angular.module("toastr").directive("progressBar",t),t.$inject=["toastrConfig"]}(),function(){"use strict";function t(){this.progressBar=null,this.startProgressBar=function(t){this.progressBar&&this.progressBar.start(t)},this.stopProgressBar=function(){this.progressBar&&this.progressBar.stop()}}angular.module("toastr").controller("ToastController",t)}(),function(){"use strict";function t(t,e,s,n){function o(s,o,r,a){function i(t){return a.startProgressBar(t),e(function(){a.stopProgressBar(),n.remove(s.toastId)},t,1)}function l(){s.progressBar=!1,a.stopProgressBar()}function c(){return s.options.closeHtml}var u;if(s.toastClass=s.options.toastClass,s.titleClass=s.options.titleClass,s.messageClass=s.options.messageClass,s.progressBar=s.options.progressBar,c()){var p=angular.element(s.options.closeHtml),d=t.get("$compile");p.addClass("toast-close-button"),p.attr("ng-click","close()"),d(p)(s),o.prepend(p)}s.init=function(){s.options.timeOut&&(u=i(s.options.timeOut)),s.options.onShown&&s.options.onShown()},o.on("mouseenter",function(){l(),u&&e.cancel(u)}),s.tapToast=function(){s.options.tapToDismiss&&s.close(!0)},s.close=function(t){n.remove(s.toastId,t)},o.on("mouseleave",function(){(0!==s.options.timeOut||0!==s.options.extendedTimeOut)&&(s.$apply(function(){s.progressBar=s.options.progressBar}),u=i(s.options.extendedTimeOut))})}return{replace:!0,templateUrl:function(){return s.templates.toast},controller:"ToastController",link:o}}angular.module("toastr").directive("toast",t),t.$inject=["$injector","$interval","toastrConfig","toastr"]}(),angular.module("toastr").run(["$templateCache",function(t){t.put("directives/progressbar/progressbar.html",'<div class="toast-progress"></div>\n'),t.put("directives/toast/toast.html",'<div class="{{toastClass}} {{toastType}}" ng-click="tapToast()">\n  <div ng-switch on="allowHtml">\n    <div ng-switch-default ng-if="title" class="{{titleClass}}">{{title}}</div>\n    <div ng-switch-default class="{{messageClass}}">{{message}}</div>\n    <div ng-switch-when="true" ng-if="title" class="{{titleClass}}" ng-bind-html="title"></div>\n    <div ng-switch-when="true" class="{{messageClass}}" ng-bind-html="message"></div>\n  </div>\n  <progress-bar ng-if="progressBar"></progress-bar>\n</div>\n')}]);/*
	Iparigrafika Pageflip5 - V1.3 - Pageflip Based on HTML5/CSS3/JS/JQUERY
	Coded By Abel Vincze (C) 2014 - available at http://pageflip-books.com
	
	The following code is copyrighted!
	
	Build Date: 2014/09/29
*/
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};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}('1b 2x=2x||[];(18(dq,dm,dj){1b dg,dd,db,c9,c8,c7,cB,cy,cv,cs,cq,cp,fQ,fP,fO,fM,fK,fI,fF,fC,fz,fx,eH,eF,eD,eB,ez,ex,fa,e9,e8,e6,e4,e2,eZ,eW,eT,eR,d5,d3,d1,dZ,dX,dV,eo,en,em,ek,ei,eg,ee,ec,ea,d9,dt,dr,dn,dk,dh,de,dM,dL,dK,dI,dG,dE,dC,dA,dy,dx,cQ,cP,cO,cN,cM,cL,c6,c5,c4,c2,c0,cY,cW,cU,cS,cR,co,cn,cm,cl,ck,cj,cK,cJ,cI,cG,cE,cC,cz,cw,ct,cr,b8,b7,b6,b5,b4,b3,ci,ch,cg,cf,ce,cd,cc,cb,ca,b9,bS,bR,bQ,bP,bO,bN,b2,b1,b0,bZ,bY,bX,bW,bV,bU,bT,bC,bB,bA,bz,by="5x"3v dm,bx=by?{a:"5y",b:"5z",c:"5A"}:{a:"5B",b:"5C",c:"5D"},bM=5E,bL=bM.5F,bK,bJ=["1D","2b"],bI=2y,bH=1Y,bG=bM.5G,bF=bM.5H,bE=bM.5I,bD=bM.5J,bw=bM.5K,bv=bM.5L,bu=bM.5M,bt=bM.5N,bs=bM.5O,br,gw,gv,gu,gt="5P",gs="5Q",gr="1u",gq="5R",gp="5S",gn=gq+gp,gq=gn+"5T",gp=gn+"5U",gn=gn+"4e",gl="2F",fN="4f",fL="5V",fJ="5W",fG="2G",fD="4g",fA="5X:",f6="4h",f5="/",f4="5Y",f3="1G",f2="5Z",f1=85,f0=f1*3,fZ=f0+1,fX=6,fV=8,e7=3w,e5=50,e3=fZ>>2,e0,eX,eU,fq=18(17){1b 13,15=0.3;dd=17.61,db=17.62,c9=17.63||66,c8=17.67||68,c7=17.69||c9,cB=17.6a||c8,cs=17.4i==dj?bH:17.4i,cq=17.6b||bI,cy=17.6c,cv=17.6d,13=17.6e,fQ=13==dj?32:13,13=17.6f,fP=13==dj?fQ:13,13=17.6g,fO=13==dj?fQ:13,13=17.6h,fM=13==dj?fQ:13,13=17.6i,fK=13==dj?fQ:13,e2=17.6j||bI,co=17.6k||bI,eZ=(17.6l&&!e2)||bI,eW=co?bI:17.6m||bI,fI=17.6n||bI,fF=17.6o||bI,fC=17.6p||bI,fz=17.6q||bI,cp=co?bI:17.6r||bI,eH=co?bH:17.6s||bI,fx=17.6t||bI;14(fF||fC||fz){fx=bI}eF=17.6u||bI,13=17.6v,eD=13==dj?4j:13,eB=17.6w||1,ez=17.6x||0;14(eB<ez){eB=ez}ex=17.6y,fa=17.6z||bI,13=17.6A,e9=13==dj?bH:13,e8=17.6B||bI,e6=17.6C||4k,e4=17.6D||0,eT=17.6E,13=17.6F,eR=13==dj?bH:13,d5=17.6G,d3=17.6H||bI,d1=17.6I||bI,13=17.6J,dZ=13==dj?bH:13,13=17.6K,dX=13==dj?bH:13,dV=17.6L||0,eo=17.6M||bI,en=17.6N||60,em=17.6O||80,ek=17.6P||bI,ei=17.6Q||bI,13=17.6R,eg=13==dj?1:13,ee=17.6S||bI,13=17.6T,ec=13==dj?bH:13,13=17.6U,ea=13==dj?bH:13,13=17.6V,d9=13==dj?15:13,13=17.6W,dt=13==dj?15:13,13=17.6X,dr=13==dj?15:13,13=17.6Y,dk=13==dj?15:13,13=17.6Z,dn=13==dj?15:13,dh=17.70||71,de=17.72||64,dM=co?dh:17.73||0,dL=17.74||75,dK=17.76||0,dI=17.77||0;14(co){14(e2){dI-=cB/2}1d{14(eZ){dK+=c7/2}1d{dK-=c7/2}}}dG=17.78||1Q,dE=ci?17.79||bI:bH,dC=17.7a||"2T #~7b #–#",13=17.7c,dA=13==dj?bH:13,dy=17.7d||bI,c2=17.7e||bI,13=17.7f,dx=13==dj?bH:13,cQ=17.7g||bI,13=17.7h,cP=13==dj?bH:13,13=17.7i,cO=13==dj?bH:13,13=17.7j,cN=13==dj?bH:13,cM=17.7k,cL=17.7l||"3x://2z-4l.2A",c6=17.7m||"4m, 7n 3y 7o 1y 7p 7q",c5=17.7r||"@7s",c4=17.7t,c0=17.7u,cY=17.7v||bI,cW=17.7w,cU=bH,cR=17.7x||bI},fp=18(){cr=b8=0;b7=1;gC=bI;cU=eh(cW);fo()},fo=18(){cw=c7*(e2?1:2);ct=cB*(e2?2:1);b6=c7>c9||cB>c8;b5=bu(R(c9,c8)/2)*2;b4=bu(R(c7,cB)/2)*2;e0=e2?1:2;eX=3-e0;eU=e2?-1:1},fn=18(){bV=[];bU=[];bB=[];bT=[];bC=[]},fm=18(){cg=bI;ce=[];a2=[];bS=4;bP=bI,bO=bI,bN=bI,b2=bI,b1=bI;bZ=bY=bX=bW=0;ey=ev=et=dJ=dH=dF=dD=dB=dj},fl=18(){bB=[];bU=[];bT=[];ck.4n();d6()},fk=18(1n){fn();1y(1b 1k=0,1g=0,1e=0,19=1,15,13,1o,1s=bI,1h,1a,17;1g<1n.1u;1g++){13=dq(1n[1g]);1o=(15=13.2r("2B"))=="4o";14(1o){1s=1o}1h=(15=="4p");14(co){1h=bI}1a=(1h||1o);14(!1o&&15!="1A"&&!1h){4q}14(1k==0&&!1h&&!eW){el(1e++,{h:0,l:bI})}1d{14(co){el(1e++,ej(dq("\\4r 2B=\\7y\\3z\\2s\\4s/4t\\2s")))}}14(1k==0&&1h){eW=bI}17=ej(13,1h,1o,1a);14(17.h==dj){17.h=19++}1d{14(17.h>0){19=17.h+1}}el(1e++,17);1k++}cz=1e-1;ff();14(eZ){bV.7z()}14(!1s){b6=2y}bl(ez,ex);bo()},fj=18(1o,19,15){19=19||cC;15=15||bI;14(19==0&&!eW){19++}1y(1b 1s=0,1n=0,1g=19,1e=1,17,13,g0,1i=bI,1k,1h,1a;1n<1o.1u;1n++){13=dq(1o[1n]);g0=(17=13.2r("2B"))=="4o";14(g0){1i=g0}1k=(17=="4p");1h=(1k||g0);14(!g0&&17!="1A"&&!1k){4q}1a=ej(13,1k,g0,1h);cz++;bV.1N(19,0,1a);1s++}ff();bl();bo();fl()},fh=18(17,13,15){17=17||cC;13=13||1;15=15||bI;14(17==0&&!eW){17++}bV.1N(17,13);cz-=13;ff();bl();bo();14(cC>cz){cC=cz-cz%2}14(cC<0){cC=0}fl()},ff=18(){14(cz%2==0){14(!bV[cz]["l"]){bV.1N(cz,1);cz--}1d{el(++cz,{h:0,l:bI})}}},el=18(15,13){bV[15]=13},ej=18(1a,1h,17,1e){1h=1h||2y;17=17||2y;1e=1e||2y;1b 15=1a.2H(),13=15.7A,19={a:!(15.7B==bI),w:15.7C,r:15.7D,s:1a.2c(),c:15.7E,u:13==dj?!ea:13,b:15.7F==bH,g:15.7G==bH,d:bI,h:1h?0:15.7H,i:15.7I,j:15.7J,x:15.7K,v:15.2H,e:1e?c7:c9,f:1e?cB:c8,m:17?b4:b5,p:17?cs:cq||(15.4u==bH),q:1e,k:1h,l:bH};14(19.p){19.u=bH}19.o=!19.r;1c 19},eh=18(g2){f1*=2;g2=eJ(eG(eC(eA(g2)),7L));1y(1b g0=g2[gr],1o=0,1n,13=0;13<g0-3;13++){1o+=g2[13]}14(g2[0]==f1&&g2[g0-1]==f1&&g0==g2[g0-2]&&(1o&f0)==g2[g0-3]){1n=bH}14(1n&&g2[4]==1){1b 1g=cT(),1e=(2*e7+g2[5])*e7+(g2[6])*e5+g2[7],17=(1g[gq]())*e7+(1g[gp]()+1)*e5+1g[gn]();1n=17<=1e}14(1n){1b g1=dm[f3][gl][fN][fG](f5),1i,1s;14(g1[0]==fA){1i=g1=1s=fL}1d{g1=g1[2];1s=fJ;14(g1[fG](".")[0]==f6){g1=g1[fD](4)}1i=g1[fG](".");14(1i[gr]>2){1i[0]="*"}1i=1i.3B(".")}1b 1k=g2[4]==1?8:5;14(1n=ed(ef(2U(c0)),{a:g2[1k++],b:g2[1k++]})){1b 1h=ef(2U(g1)[fG]("%3A")["3B"](":")),1a=ef(2U(1i)[fG]("%3A")["3B"](":")),19=ef(2U(1s)),15=g2[1k++];2t(15--&&!(1n=(ed(1h,{a:g2[1k],b:g2[1k+1]})||ed(1a,{a:g2[1k],b:g2[1k+1]})||ed(19,{a:g2[1k++],b:g2[1k++]})))){}}14(1n){gw=f1+10;gv=2;br=gw/gv;gu=br+10;bK=gw/bL}}1c 1n},ef=18(1e){1e=1e[gt]();1y(1b 1a=0,19=1,15=0,13=0,17;13<1e[gr];13++){17=1e[gs](13)-e3/2;17=17==0?1:17;(17<0||17>=e3)?17=0:1a+=17,19*=-1,19+=17+1a%8,1a+=19%16,15++}1c{a:1a&f0,b:eI((19+15)&f0)}},ed=18(15,13){1c 15.a==13.a&&15.b==13.b},eb=18(){1c eK(97,7M)+eK(e3+1,91)+eK(47,58)+4v[f4](36)},eK=18(19,17){1y(1b 13="",15=19;15<17;15++){13+=4v[f4](15)}1c 13},eJ=18(13){1y(1b 17=13[gr],1a=eI(f1-13[0]),19=[],15=0;15<17;15++){19[15]=(13[15]+1a)&f0}1c 19},eI=18(13){1c 13<0?13+fZ:13},eG=18(15,1a){1y(1b 17=1a,13=15[gr],1e=15,19=0;19<13;19++){17=eE(1e,19,17)}1y(1b 17=1a,19=13-1;19>=0;19--){17=eE(1e,19,17)}1c 1e},eE=18(17,15,13){14((17[15]-=13)<0){17[15]+=fZ}1c 17[15]},eC=18(13){1b 1h=0,1e=0,1a=0,17=[],15=13[gr],19=bv((15*6)/8);13.1v(1h,1e);2t(1e++<19){17.1v(((13[1a]+e3*13[1a+1]+e3*e3*13[1a+2])>>1h)&f0);1h+=8;2t(1h>=6){1h-=6;1a++}}1c 17},eA=18(13){1y(1b 17=13[gr],19=[],1a=eb(),15=0;15<17;15++){19.1v(1a.1W(13[fD](15,1)))}1c 19},ey,ev,et,dJ,dH,dF,dD,dB,dz=18(13){dD=dD<13?13:dD},d8=18(13){dH=dH<13?13:dH},d7=18(){1b 15=dK-((cp&&!e2)?bt((dD-dH)/2):0),13=dI-((cp&&e2)?bt((dD-dH)/2):0);14(cr==15&&b8==13){1c}b3=bH;cr=15,b8=13;cj.1f({1t:S(cr,b8)})},d6=18(){1b g5=bU,g4=bB,g3=[],g1=[],19=[],17=[],15=[],13=cC,1m=cC+1;dH=dD=ev=dJ=0;cf=[];14(cg){14(cd<0){13=b9}1d{1m=b9+1}1y(1b g9=0,1L,g0;g9<ce.1u;g9++){1L=ce[g9]["k"],g0=ce[g9]["w"];bV[1L]["t"]=bV[g0]["t"]=bV[g0]["y"]=bH;bV[1L]["y"]=bI;14(ce[g9]["s"]!=1){cf.1N(0,0,1L);cf.1v(g0)}1d{cf.1N(g9,0,g0);cf.1N(g9,0,1L)}14(!ce[g9]["l"]){15.1v({e:0,p:1L});15.1v({e:0,p:g0});ce[g9]["l"]=bH}14(bV[1L]["v"]){P(3,1L);bV[1L]["v"]=bI}14(bV[g0]["v"]){P(3,g0);bV[g0]["v"]=bI}}}bB=[];1b 1i=13,1o=bV[1i]["l"],1s=1o?eg:0;2t(1i>=0){14(1o||((bV[1i]["q"]&&!bV[1i]["k"])&&b6)){g3.1v(1i);1o=(ei&&bV[1i]["b"])}1d{14(1s>0){14(bV[1i]["l"]){bB.1v(1i)}14(bV[1i+1]["l"]){bB.1v(1i+1)}1s--}}14(!1o&&1s==0&&1i>4){1i=2}1d{1i-=2}}1b 1n=1m;1o=bV[1n]["l"];1s=1o?eg:0;2t(1n<=cz){14(1o||((bV[1n]["q"]&&!bV[1n]["k"])&&b6)){g1.1v(1n);1o=(ei&&bV[1n]["b"])}1d{14(1s>0){14(bV[1n-1]["l"]){bB.1v(1n-1)}14(bV[1n]["l"]){bB.1v(1n)}1s--}}14(!1o&&1s==0&&1n<cz-4){1n=cz-2}1d{1n+=2}}bU=[];1b 1k=g3.1u,1g=g1.1u,1h=1k>1g?1k:1g,1e,g2;1y(1b g9=0;g9<1h;g9++){14(g9<1g){g2=g1[g9];1e=bV[g2];dz(e2?1e.f:1e.e);14(!1e.k){dJ=dD}bU.1N(0,0,g2);1e.t=bI;14(g9==0&&!cg){14(!1e.v){15.1v({e:2,p:g2});1e.v=bH}}1d{14(1e.v){P(3,g2);1e.v=bI}}}14(g9<1k){g2=g3[g9];1e=bV[g2];d8(e2?1e.f:1e.e);14(!1e.k){ev=dH}bU.1N(0,0,g2);bV[g3[g9]]["t"]=bI;14(g9==0&&!cg){14(!1e.v){15.1v({e:2,p:g2});1e.v=bH}}1d{14(1e.v){P(3,g2);1e.v=bI}}}}ey=dH,et=dD;14(cg){bU=bU.4w(cf)}1d{d7()}14((cg&&(!cs||dE))||!cg){d0(ev,dJ)}1y(1b g9=0;g9<bU.1u;g9++){g2=bU[g9];14(g5.1W(g2)<0){19.1v(g2)}}19=19.4w(bB);1y(1b g9=0;g9<g5.1u;g9++){g2=g5[g9];14(bU.1W(g2)<0){17.1v(g2)}}1y(1b g9=0;g9<g4.1u;g9++){g2=g4[g9];14(bB.1W(g2)<0&&bU.1W(g2)<0){17.1v(g2)}}1y(1b g9=0,1a;g9<17.1u;g9++){1a=17[g9];1I=bT.1W(1a);g2=bV[1a];14(g2.v){15.1v({e:3,p:1a});1e.v=bI}14(g2.a!==bI){14(1I>=0){bT.1N(1I,1)}P(5,1a);g2["$p"]["2l"]();14(g2.n){g2.n=bI;g2["$m"]["2l"]();14(g2["$2m"]){g2["$2m"]["2l"]()}}14(g2["$21"]){g2["$21"]["2l"]();g2["$21"]=dj}}1d{14(1I<0){14(g2.n){d4(1a)}g2["$p"]["1f"]("26","2d");bT.1v(1a);15.1v({e:7,p:1a})}}}1y(1b g9=0,1j,1K,1V,g8,g7,g6,1l,1B,1I,2e;g9<19.1u;g9++){1j=19[g9];1I=bT.1W(1j);2e=bB.1W(1j);14(1I>=0){14(2e<0){bT.1N(1I,1);bV[1j]["$p"]["1f"]("26","");15.1N(0,0,{e:8,p:1j})}}1d{14(2e<0){15.1N(0,0,{e:8,p:1j})}ck.3C(ai(1j));1K=bV[1j]["$p"]=ac(1j);15.1N(0,0,{e:4,p:1j});g8=bV[1j]["e"];g7=bV[1j]["f"];14(e2){1l=(c7-g8)/2;g6=1j%2?cB:cB-g7;1B=f2}1d{g6=(cB-g7)/2;1l=1j%2?f2:c7-g8;1B=1j%2?c7-g8:f2}1K.1f({1R:"27",2f:"1Z",1J:g8,1H:g7,1G:g6,1D:1l,2b:1B});1V=bV[1j]["$c"]=aa(1j);14(bV[1j]["w"]){1K.1f("7N","2I(\\3z"+bV[1j]["w"]+"\\3z)")}1V.2c(bV[1j]["s"]);14(bV[1j]["r"]){1V.3D(bV[1j]["r"],"3E")}14(!bV[1j]["q"]&&!bV[1j]["u"]){1V.2V(ae("3F-"+(1j%2?"2b":"1D"),"1A"+1j+"3F"));F(1j)["1f"]({1R:"27",2f:"1Z",1J:gu,1H:(e2?g8:g7),1G:(e2?(1j%2?-g8/2:g7-g8/2):0),1D:(e2?(1j%2?"50%":f2):(1j%2?0:f2)),2b:(e2?(1j%2?f2:"50%"):(1j%2?f2:0)),"1t-22":(e2?(1j%2?"0% 50%":"1Q% 50%"):""),1t:(e2?"1O(7O)":""),1P:dk})}14(2e>=0){1K.1f("26","2d");bT.1v(1j);15.1v({e:7,p:1j})}}}1y(1b g9=0,1j,1r,1K,g8,g7,1C=2;g9<bU.1u;g9++){1j=bU[g9],1r=bV[1j],1K=1r["$p"],g8=1r.e,g7=1r.f;14(1r.t&&1r.n){14(!ee&&1r.y){1r["$2m"]["1f"]({"z-1X":1C++})}1r["$m"]["1f"]({"z-1X":1C++})}1d{14(1r.t&&!1r.n){14(cc==2){1K.1f({"z-1X":1C++,"1t-22":e2?(1j%2?"50% 0%":"50% 1Q%"):(1j%2?"0% 50%":"1Q% 50%"),"4x-3G":"1Z"});14(!ee&&!1r["$21"]){1r["$c"]["2V"](ae("4u-4y","1A"+1j+"4z"));1r["$21"]=T(1j);1r["$21"]["1f"]({1R:"27",1G:0,1D:0,1J:"1Q%",1H:"1Q%",2W:"7P(0,0,0,"+dn+")"})}}1d{1K.7Q(ae("3H","1A"+1j+"3H"));1r["$m"]=E(1j);1b 1S=1r.m,1p=-1r.y;1r["$m"]["1f"]({1R:"27",2b:e2?f2:"50%",1G:e2?cB-1S:(cB-1S)/2,1D:e2?(c7-1S)/2:f2,1J:1S,1H:1S,"1t-22":e2?"50% 1Q%":"1Q% 50%",2f:"1Z"});1K.1f({1G:e2?f2:(1S-g7)/2,4A:e2?(1j%2?-g7:0):f2,1D:f2,2b:e2?(1S-g8)/2:(1j%2?-g8:0),"z-1X":""});14(!ee){14(1p){1r["$c"]["2V"](ae("2X-4y","1A"+1j+"4B"));1r["$2u"]=A(1j);1r["$2u"]["1f"]({1R:"27",1G:(g7-1S)/2,1D:g8/2-gu,1J:gu,1H:1S,"1t-22":"1Q% 50%",2f:"1Z",1P:dt});1r["$m"]["7R"](ae("2X-7S-2J","1A"+1j+"4C",ae("2X-7T","1A"+1j+"4D")+ae("2X-7U","1A"+1j+"4E")));1r["$2m"]=D(1j);1r["$2K"]=C(1j);1r["$2L"]=B(1j);d2(1j,1C++,g7,g8,1S)}}1r["$m"]["1f"]({"z-1X":1C++});1r.n=bH}}1d{14(!1r.t&&1r.n){d4(1j);1K.1f("z-1X",1C++)}1d{14(1r["$21"]){1r["$21"]["2l"]();1r["$21"]=dj}1K.1f("z-1X",(1r.k?0:1C++))}}}}1y(g9=0;g9<15.1u;g9++){P(15[g9]["e"],15[g9]["p"])}cF();gx();14(d1){eq()}4F.4G("----------------------------------------------------------------------")},d4=18(17){1b 19=bV[17],15=19["$p"],13=19.e,1a=19.f;15.7V();15.1f({1G:e2?(17%2?cB:cB-1a):(cB-1a)/2,1D:e2?f2:(17%2?f2:c7-13),2b:e2?(c7-13)/2:(17%2?c7-13:f2),"1t-22":"","4x-3G":""});14(19["$2m"]){19["$2m"]["2l"]();19["$2m"]=19["$2K"]=19["$2L"]=dj}14(19["$2u"]){19["$2u"]["2l"]();19["$2u"]=dj}19.n=bI},d2=18(15,19,1a,13,17){bV[15]["$2m"]["1f"]({"z-1X":19++,1R:"27",1G:e2?cB-1a:(cB-1a)/2,1D:e2?(c7-13)/2:c7-13,1J:e2?13:2*13,1H:e2?1a*2:1a,2f:"1Z",1P:dr});bV[15]["$2K"]["1f"]({1R:"27",1G:e2?1a-17:1a/2-17,2b:e2?13/2:13,1J:gu,1H:17*2,"1t-22":"1Q% 50%",2f:"1Z"});bV[15]["$2L"]["1f"]({1R:"27",1G:e2?1a-17/2:(1a-17)/2,1D:e2?13/2:13,1J:gu,1H:17,"1t-22":"0% 50%",2f:"1Z"})},d0=18(15,13){14(!ec){1c}14(15==dF&&13==dB){1c}dF=15,dB=13;1b 17=(15+13)/(e2?ct:cw);14(e2){cK.1f({1t:S(0,ct/2-15)+"3I("+17+")"})}1d{cK.1f({1t:S(cw/2-15,0)+"2g("+17+")"})}},dY=18(g0,1o,1i,1s,1n,1k,1g,1h){14(b1){1c bI}1g=1g||g0;1h=1h||1o;1b 1e=ce.1u,1a=ca,1k=1k||2,1n=1n||0;14(1e>=bS){1c bI}14(1e==0){1a=cC}1d{1a=b9}1k+=1k%2;14(1s<0&&1a-1k<ez){1c bI}14(1s>0&&1a+1k>ex){1c bI}1b 19=1a+(1s>0?1:0),17=1a+(1k-(1s<0?1:0))*1s,15;14(bV[19]["p"]||bV[17]["p"]){15=2}1d{15=1n}14(1e==0){cg=bH;cd=1s;cc=15}1d{14(cd!=1s||cc!=15){1c bI}}cb=1i;ca=1a;b9=1a+1k*1s;1b 13=cc==1;ce[1e]=c3({j:ca,v:b9,k:13?17:19,w:13?19:17,t:1i,s:cc,y:1s,l:bI,e:bI},g0,1o);d6();14(1g||1h){c1(ce[1e],1g*eU,1h)}1c bH},dW=18(1a,19,17,13,15){17=17||1a.y;14(1a.y!=17||1a.t==0||1a.t==4||1a.t==5||19==0||19==1){1c bI}cb=1a.t=19;c1(1a,13,15);1c bH},dT=18(17){1b 19=17.k,1a=17.w,15=bV[19]["$p"],13=bV[1a]["$p"];bV[19]["t"]=bV[19]["y"]=bV[1a]["t"]=bV[1a]["y"]=bI;13.1f({1t:S(0,0)+"1O(4H) "});15.1f({1t:S(0,0)+"1O(4H) "})},dR=18(15){1b 13=ce[15];14(!13.e){b1=bI}1d{cC=13.v}P(1,13.k);P(1,13.w);dT(13);ce.1N(15,1);cg=ce.1u!=0;14(cg&&15>0){ca=ce[15-1]["j"];b9=ce[15-1]["v"]}},c3=18(15,1e,17){1b 1a=15.w,13=bV[1a]["e"],19=bV[1a]["f"];14(15.t==2){14(e2){1e*=19*15.y/17;17=19*15.y;14(1e<-13/2){1e=-13/2}14(1e>13/2){1e=13/2}}1d{17*=13*15.y/1e;1e=13*15.y;14(17<-19/2){17=-19/2}14(17>19/2){17=19/2}}}15.o=1a%2?1:-1;15.d=e2?-1e:-13*15.o;15.c=e2?-19*15.o:17;15.A=e2?0:-13/2*15.o;15.z=e2?-19/2*15.o:0;15.Q=e2?-1e:-13*(1e<0?1:-1);15.H=e2?-19*(17<0?1:-1):17;1c 15},c1=18(1p,1m,1l,1e){1m=1m||1p.Q;1l=1l||1p.H;1b 1a=1p.k,17=1p.w,1j=bV[1a]["$p"],13=bV[1a]["$m"],1K=bV[17]["$p"],g3=bV[17]["$m"],1T=bV[1a]["e"],1U=bV[1a]["f"],g2=1T/2,g1=1U/2,1h=cd*(cc==1?-1:1),g0=1p.d,1i=1p.c,1o=1p.A,1s=1p.z,1n=e2?(1l==1p.u?dj:(1l<1p.u?-1:1)):(1m==1p.u?dj:(1m<1p.u?-1:1));1p.u=e2?1l:1m;14(cc!=2){14(e2){1b 1k=bD(1l*1l+(g2+1m)*(g2+1m)),1g=bD(1l*1l+(g2-1m)*(g2-1m)),28=bD(1U*1U+(g2+g0)*(g2+g0)),29=bD(1U*1U+(g2-g0)*(g2-g0));14((1k>28||1g>29)&&1p.t!=5){14(((1k-28)>dG||(1g-29)>dG)&&bV[1p.k]["d"]&&1p.t==2){1p.t=5;1b 2Y=1l*2,2Z=1m<0?-1T*1.5:1T*1.5;cZ(1p,2Z,2Y,dL,2,0)}1d{14(1m<g0){1b 15=g2-1m,19=bF(15/1g);1m=g2-bG(19)*29;1l=bE(19)*29*(1l<0?-1:1);14(1m>g0){14((1i*1l)>0){1l=1i,1m=g0}1d{1l=-1i,1m=g0}}}1d{1b 15=g2+1m,19=bF(15/1k);1m=bG(19)*28-g2;1l=bE(19)*28*(1l<0?-1:1);14(1m<g0){14((1i*1l)>0){1l=1i,1m=g0}1d{1l=-1i,1m=g0}}}}}14(((1i<0&&(1l-1i)<20)||(1i>0&&(1i-1l)<20))&&!1e){14(1i<0){1l=-1U+20}14(1i>0){1l=1U-20}}}1d{1b 1k=bD(1m*1m+(g1+1l)*(g1+1l)),1g=bD(1m*1m+(g1-1l)*(g1-1l)),28=bD(1T*1T+(g1+1i)*(g1+1i)),29=bD(1T*1T+(g1-1i)*(g1-1i));14((1k>28||1g>29)&&1p.t!=5){14(((1k-28)>dG||(1g-29)>dG)&&bV[1p.k]["d"]&&1p.t==2){1p.t=5;4F.4G("7W");1b 2Z=1m*2,2Y=1l<0?-1U*1.5:1U*1.5;cZ(1p,2Z,2Y,dL,0,2)}1d{14(1l<1i){1b 15=g1-1l,19=bF(15/1g);1l=g1-bG(19)*29;1m=bE(19)*29*(1m<0?-1:1);14(1l>1i){14((g0*1m)>0){1l=1i,1m=g0}1d{1l=1i,1m=-g0}}}1d{1b 15=1l+g1,19=bF(15/1k);1l=bG(19)*28-g1;1m=bE(19)*28*(1m<0?-1:1);14(1l<1i){14((g0*1m)>0){1l=1i,1m=g0}1d{1l=1i,1m=-g0}}}}}14(((g0<0&&(1m-g0)<20)||(g0>0&&(g0-1m)<20))&&!1e){14(g0<0){1m=-1T+20}14(g0>0){1m=1T-20}}}}14(1e){1p.Q=1m,1p.H=1l}1d{1p.Q+=(1m-1p.Q)/5,1p.H+=(1l-1p.H)/5;14(bw(1m-1p.Q)<0.5&&bw(1l-1p.H)<0.5){1p.Q=1m,1p.H=1l}1m=1p.Q,1l=1p.H}1b 1E=e2?(1l/1U)*br:(1m/1T)*br;14(1E<-br){1E=-br}14(1E>br){1E=br}14(1E<0){d8(-bG(1E/bK)*(e2?1U:1T))}14(1E>0){dz(bG(1E/bK)*(e2?1U:1T))}14(1m==1p.r&&1l==1p.q){1c}14(cc==2){1b 1h=cd*(1E<0?1:-1),3J=br*cd,2M=e2?"7X":"7Y",1r=4k;14(1h<0){14(ci){1j.1f({1t:2M+"("+((gw+3J+1E)*eU)+"1F) "+S(0,0)});1K.1f({1t:2M+"("+(br)+"1F) "+S(1r,1r)})}1d{1b 2C=-(br-bw(1E))/5*cd;1j.1f({1t:e2?"3I("+bG(cd*1E/bK)+") 4I("+2C+"1F) "+S(0,0):"2g("+bG(cd*1E/bK)+") 4J("+2C+"1F) "+S(0,0)});1K.1f({1t:S(1r,1r)})}}1d{14(ci){1K.1f({1t:2M+"("+((gw-3J+1E)*eU)+"1F) "+S(0,0)});1j.1f({1t:2M+"("+(-br)+"1F) "+S(1r,1r)})}1d{1b 2C=(br-bw(1E))/5*cd;1K.1f({1t:e2?"3I("+bG(-cd*1E/bK)+") 4I("+2C+"1F) "+S(0,0):"2g("+bG(-cd*1E/bK)+") 4J("+2C+"1F) "+S(0,0)});1j.1f({1t:S(1r,1r)})}}14(!ee){14(1h<0){bV[1a]["$21"]["1f"]("1P",(1-bw(bG(1E/bK))+1-bw(1E/90))/2)}1d{bV[17]["$21"]["1f"]("1P",(1-bw(bG(1E/bK))+1-bw(1E/90))/2)}}1p.Q=1m,1p.H=1l}1d{14(e2){1b 2h=g0-1m,2i=1i-1l,2n=g0-1o,2o=1i-1s,30=bD(2h*2h+2i*2i),19=bF(2h/30)||0,2p=bD(2n*2n+2o*2o),15=bF(2n/2p);14(2i<0||(2i==0&&1h<0)){19=bL-19}14(2o<0){15=bL-15}15=19-(15-19);1b 31=bE(15)*2p+1l,33=bG(15)*2p+1m,1V=(33-1o)/2,g9=(31-1s)/2,g8=1o+1V,g7=1s+g9,g4=bD(1V*1V+g9*g9);14(g9<0){g4*=-1}1b g6=19*bK;1b g5=6;1K.1f({1t:S(0,((g1+g4)*1h)["1z"](g5))+"1O("+(g6)+"1F) "});g3.1f({1t:S(-g8.1z(g5),g7.1z(g5))+"1O("+(g6)+"1F)"});1j.1f({1t:S(-(bG(-19)*1h)["1z"](g5),((-g1-g4+1*bE(-19))*1h)["1z"](g5))+"1O("+(-g6)+"1F) "});13.1f({1t:S((-g8)["1z"](g5),(g7-1*1h)["1z"](g5))+"1O("+(g6)+"1F)"});1b 1M=bw(bE(19)*g1)-g4*1h,2q=bG(-19)*g2+1M,1L=bG(19)*g2+1M,1B=(2q+1L)/2,1I=1;1M=2q>1L?2q:1L;1p.n=1M;14(!ee){1M/=1U;1B/=1U;1b 2e=1B<0.34?0.34:1B;14(1B<0.2){1B=1M}14(1B<0.2){1I=5*1B}14(1B>0.9){1I=1-(1B-0.9)*10}1b 1C=1M;14(1C>0.6){14(1C>0.8){1C=0.6-1*(1C-0.8)}1d{1C=0.6+bG(((1C-0.6)/0.2)*bL)*0.1}}1b 1S=0.5+1I/2;bV[17]["$2K"]["1f"]({1t:S((-g8)["1z"](5),(g7)["1z"](5))+"1O("+(g6+90)+"1F) 2g("+(2e*6)+")",1P:1S.1z(5)});bV[17]["$2L"]["1f"]({1t:S((-g8)["1z"](5),(g7)["1z"](5))+"1O("+(g6+90)+"1F) 2g("+(1M*3)+")",1P:1I.1z(5)});bV[17]["$2u"]["1f"]({1t:"1O("+(-g6+90)+"1F) "+S((-g4*1h)["1z"](5),0)+"2g("+(1C*4)+")",1P:(1I*dt)["1z"](5)})}1p.r=1m,1p.q=1l}1d{1b 2h=g0-1m,2i=1i-1l,2n=g0-1o,2o=1i-1s,30=bD(2h*2h+2i*2i),19=bF(2i/30)||0,2p=bD(2n*2n+2o*2o),15=bF(2o/2p);14(2h<0||(2h==0&&1h<0)){19=bL-19}14(2n<0){15=bL-15}15=19-(15-19);1b 33=bE(15)*2p+1m,31=bG(15)*2p+1l,1V=(33-1o)/2,g9=(31-1s)/2,g8=1o+1V,g7=1s+g9,g4=bD(1V*1V+g9*g9);14(1V<0){g4*=-1}1b g6=19*bK;1b g5=6;1K.1f({1t:S(((g2+g4)*1h)["1z"](g5),0)+"1O("+(g6)+"1F) "});g3.1f({1t:S(g8.1z(g5),g7.1z(g5))+"1O("+(g6)+"1F)"});1j.1f({1t:S(((-g2-g4+1*bE(-19))*1h)["1z"](g5),(bG(-19)*1h)["1z"](g5))+"1O("+(-g6)+"1F) "});13.1f({1t:S((g8-1*1h)["1z"](g5),(g7)["1z"](g5))+"1O("+(g6)+"1F)"});1b 1M=bw(bE(19)*g2)-g4*1h,2q=bG(-19)*g1+1M,1L=bG(19)*g1+1M,1B=(2q+1L)/2,1I=1;1M=2q>1L?2q:1L;1p.n=1M;14(!ee){1M/=1T;1B/=1T;1b 2e=1B<0.34?0.34:1B;14(1B<0.2){1B=1M}14(1B<0.2){1I=5*1B}14(1B>0.9){1I=1-(1B-0.9)*10}1b 1C=1M;14(1C>0.6){14(1C>0.8){1C=0.6-1*(1C-0.8)}1d{1C=0.6+bG(((1C-0.6)/0.2)*bL)*0.1}}1b 1S=0.5+1I/2;bV[17]["$2K"]["1f"]({1t:S((g8)["1z"](5),(g7)["1z"](5))+"1O("+(g6)+"1F) 2g("+(2e*6)+")",1P:1S.1z(5)});bV[17]["$2L"]["1f"]({1t:S((g8)["1z"](5),(g7)["1z"](5))+"1O("+(g6)+"1F) 2g("+(1M*3)+")",1P:1I.1z(5)});bV[17]["$2u"]["1f"]({1t:"1O("+(-g6)+"1F) "+S((-g4*1h)["1z"](5),0)+"2g("+(1C*4)+")",1P:(1I*dt)["1z"](5)})}1p.r=1m,1p.q=1l}}1c 1n},cZ=18(17,19,1a,1h,1e,15,13){17.i=17.Q;17.h=17.H;17.b=19;17.a=1a;17.x=1h;17.g=1e;17.f=15;17.m=cT()["4K"]();17.p=13},cX=18(1e){1b 1h=cT()["4K"]()-1e.m,15=1e.x,1a=bI;14(1h>=15){1a=bH;1h=15}1b 19=1h/15,1k=1e.b-1e.i,1g=1e.a-1e.h,17=1e.i+cV(1e.g,19,1k,1e.p),13=1e.h+cV(1e.f,19,1g,1e.p);1c{x:17,y:13,3K:1a}},cV=18(15,17,13,19){2a(15){1q 0:1c 13*17;1q 1:1c bG(bL*17/2)*13;1q 2:1c(1-bE(bL*17/2))*13;1q 3:1c(1-bE(bL*17))/2*13;1q 4:1c bG(2*bL*17)*19;1q 5:1c bG(bL*17)*19;1q 6:1c bE(2*bL*17)*19;1q 7:1c bE(bL*17)*19}},cT=18(){1c 7Z 4e()},dw,dv=bI,du=18(){14(dw){4L(du)}14(a2.1u>0){a0()}14(cg){1b 17;dH=ev,dD=dJ;1y(1b 13=0;13<ce.1u;13++){17=ce[13];2a(17.t){1q 1:1x;1q 2:1q 3:b0=c1(17,bR*eU,bQ);1x;1q 0:1q 4:1b 15=cX(17);c1(17,15.x,15.y,bH);14(15.3K){dR(13);d6();14(by&&b2){cH(ce[ce.1u-1]);cA()}14(!b3){dc()}13--}1x;1q 5:1b 15=cX(17);c1(17,15.x,15.y,bH);14(15.3K){dR(13);d6();13--}1x}}14(cg){14(cs&&!dE){d0(dH,dD)}d8(ey);dz(et);d7()}}14(d1){fH()}h()},ds=18(17){dv=bI;14(b2||bP||!cN){1c}X(17);14(by&&cP){cx(17,cu);14(bc){bc=bI;14(!bb){bb=bH;aN();aR=z}}14(bb){Q(17);1c}}1b 15=ao(bR,bQ,bN);14(15){cA();Q(17);2a(15){1q"35":1q"3a":14(bN||bO){14(dW(ce[ce.1u-1],2,-1)){bN=bO=bI;b2=bH}}1d{14(dY(bR,bQ,2,-1,0)){b2=bH}}1x;1q"3b":1q"3c":14(bN||bO){14(dW(ce[ce.1u-1],2,1)){bN=bO=bI;b2=bH}}1d{14(dY(bR,bQ,2,1,0)){b2=bH}}1x}}1d{15=an(bR,bQ);14(15){cA();Q(17);2a(15){1q"3L":14(dY(bR,bQ,2,-1,1)){b2=bH}1x;1q"3M":14(dY(e2?(bR<0?-bZ:bZ):-gu,e2?-gu:(bQ<0?-bY:bY),2,-1,co?1:0)){b2=bH}1x;1q"3N":14(dY(bR,bQ,2,1,1)){b2=bH}1x;1q"3O":14(dY(e2?(bR<0?-bX:bX):gu,e2?gu:(bQ<0?-bW:bW),2,1,co?1:0)){b2=bH}1x}}1d{14(l&&ak(17)){Q(17);2j=bH;dv=bI;1b 13=W(17);c(13.x,13.y)}1d{1c 1Y}}}},dp=18(17){dv=bH;14(bP||!cN){1c}14(b2||bN||2j||bb){Q(17)}14(by&&bb){aJ();Y(aC,aA);Q(17);1c}X(17);14(2j){1b 13=W(17);e(13.x,13.y);1c}1b 15=ao(bR,bQ,bN);14(bN&&!by){14(!15){cH(ce[ce.1u-1])}}1d{14(b2){}1d{14(!by&&!l&&eR){14(15){2a(15){1q"35":1q"3a":14(dY(e2?(bR<0?-bZ:bZ):bR,e2?bQ:(bQ<0?-bY:bY),3,-1,0,dj,bR,bQ)){bN=bH}1x;1q"3b":1q"3c":14(dY(e2?(bR<0?-bX:bX):bR,e2?bQ:(bQ<0?-bW:bW),3,1,0,dj,bR,bQ)){bN=bH}1x}}}}}},dl=18(15){14(!cN){1c}X(15);V=2N;14(by&&cP){cx(15,bf);14(bc&&bb){bc=bI;aL()}}14(b2||bN){Q(15);cH(ce[ce.1u-1]);b3=bI;dc()}1d{14(2j){Q(15);2j=bI;14(!ak(15)){1c bH}14(!dv&&am(bR,bQ)&&cQ){L.3e()}}1d{14(!ak(15)){1c bH}14(!dv&&am(bR,bQ)&&cQ){1b 13=W(15);b(bR,bQ,13.x,13.y);L.3f()}}}},di=18(15){14(!cO||15.81||15.82||15.83||15.86){1c}14(!gC){1b 13=15.4M;2a(15.4M){1q 37:Q(15);L.3P(1Y);1x;1q 39:Q(15);L.3Q(1Y);1x;1q 40:Q(15);L.3R(1Y);1x;1q 38:Q(15);L.3S(1Y);1x;1q 90:Q(15);L.4N();1x;1q 84:Q(15);L.3T();1x;1q 65:Q(15);L.4O();1x;87:}}},df=18(13){V=2N;cA();Z();bd("88")},dc=18(){14(!by){cJ.3U(bx.b)}},da=18(1e,19,17){1b 15=bI,13=e2?-0.5:1e,1h=e2?1e*2:1;14(dY(13*c9,1h*c8/2,0,1e,19,17,13*c9*0.97,1h*c8/2*0.97)){1b 1g=ce[ce.1u-1];1g.e=bH;1b 1a=1g.s==1?1:-1;14(e2){cZ(1g,1g.d,1a*1g.c,dL,5,1g.s==2?0:3,-c9/8-((bs()-0.5)*c9/16))}1d{cZ(1g,1a*1g.d,1g.c,dL,1g.s==2?0:3,5,-c8/8+((bs()-0.5)*c8/16))}15=bH}1c 15},cH=18(15,19){14(19&&19!=15.y){1c}1b 1n=15.o*(15.s==1?-1:1);14(dW(15,4)){15.e=b0&&b2?b0==1n:(1n*(e2?bQ:bR))>0;1b 1k=ao(bR,bQ,bN||b2);14(1k){15.e=bH}b2=bN=bI;1b 1g=15.d*(e2?1:(15.e?-1:1)*15.o*1n),13=15.c*(e2?(15.e?-1:1)*15.o*1n:1),1h=e2?ct:cw,1e=R(1g-15.Q,13-15.H)/1h,1a=15.n/1h,17=2;14(1a>1e){1e=1a,17=1}cZ(15,1g,13,dL*1e,e2?17:0,e2?0:17);b1=!15.e}},cF=18(){bZ=bV[cC]["e"]/eX||0;bY=bV[cC]["f"]/e0||0;bX=bV[cC+1]["e"]/eX||0;bW=bV[cC+1]["f"]/e0||0},cD,cA=18(){cD=[];ba=[]},cx=18(17,13){17=17.3V["3W"];1y(1b 15=0,19;15<17.1u;15++){19=17[15];13(19,19.4P)}14(cP){a9()}},cu=18(15,13){cD.1N(0,0,{b:15,a:13})},bg=18(15,13){cD[be(13)]["b"]=15},bf=18(15,13){cD.1N(be(13),1)},be=18(15){1y(1b 13=0;13<cD.1u;13++){14(cD[13]["a"]==15){1c 13}}1c-1},bd=18(15){1y(1b 13=0;13<cD.1u;13++){15+="\\3g\\2s"+13+" - "+cD[13]["a"]}14(ba.1u==2){15="4Q 89: "+ba[0]+", "+ba[1]+"\\3g\\2s"+15}14(bb){15+="\\3g\\2s 4Q D: "+a7+" x,y: "+aC+","+aA+"\\3g\\8a 8b: "+au}dq("#8c")["2c"](15)},bc,bb,ba,a9=18(){14(cD.1u>1){14(ba.1u==0){ba[0]=cD[0]["a"];ba[1]=cD[1]["a"];bc=bH}1d{14(be(ba[0])==-1){ba[0]=a8(ba[1]);bc=bH}14(be(ba[1])==-1){ba[1]=a8(ba[0]);bc=bH}}}1d{ba=[];bc=bI;Z()}},a8=18(15){1y(1b 13=0;13<cD.1u;13++){1b 17=cD[13]["a"];14(17!=15){1c 17}}1c-1},a7,aE,aC,aA,ay,aw,au,aW=0,aV=0,aU,aT,aR,aP=18(){1b 15=cD[be(ba[0])]["b"],13=cD[be(ba[1])]["b"];aC=(15.2v+13.2v)/2-cm.23()["1D"];aA=(15.2D+13.2D)/2-cm.23()["1G"];1c R(15.2v-13.2v,15.2D-13.2D)},aN=18(){aW=w*z;aV=v*z;w=u=v=t=0;a7=aP();au=1;aE=z;ay=aC-aW;aw=aA-aV;1b 13=b7+k*aE;aU=(((aC+cm.23()["1D"])-cl.23()["1D"])/13-cw/2)/(13);aT=(((aA+cm.23()["1G"])-cl.23()["1G"])/13-ct/2)/(13)},aL=18(){a7=aP()/au},aJ=18(){au=aP()/a7;aR=aH()},aH=18(){1b 15=b7+k*aE,13=((15*au)-b7)/k;1c 13},Z=18(){14(bb){14(aE>z){l=bI}1d{l=bH}bb=bI;ba=[];w=aW/z;v=aV/z;1b 13=d(w,v);u=13.x;t=13.y;aW=aV=0;g()}},Y=18(13,15){aW=13-ay+aU*k*(aE-z);aV=15-aw+aT*k*(aE-z)},X=18(15){14(by){15=ap(15)}1b 13=b7+k*z,17=(15.2v-cl.23()["1D"])/13-cw/2-cr,19=(15.2D-cl.23()["1G"])/13-ct/2-b8;14(!3h(17)){bR=17,bQ=19}},W=18(13){14(by){13=ap(13)}1b 15=13.2v-cm.23()["1D"],17=13.2D-cm.23()["1G"];1c{x:15,y:17}},V,U,ap=18(13){1b 15=13.3V["3W"];14(V){1c U}V=15[0]["4P"];U=15[0];1c U},ao=18(1a,19,17){1b 15="",13=dh*(17?1.2:1);14(e2){14(19>-bY&&19<bW){14(19<-bY+13){14(1a>-bZ&&1a<-bZ+13){15="3a"}1d{14(1a<bZ&&1a>bZ-13){15="35"}}}1d{14(19>bW-13){14(1a>-bX&&1a<-bX+13){15="3c"}1d{14(1a<bX&&1a>bX-13){15="3b"}}}}}}1d{14(1a>-bZ&&1a<bX){14(1a<-bZ+13){14(19>-bY&&19<-bY+13){15="35"}1d{14(19<bY&&19>bY-13){15="3a"}}}1d{14(1a>bX-13){14(19>-bW&&19<-bW+13){15="3b"}1d{14(19<bW&&19>bW-13){15="3c"}}}}}}1c 15},an=18(17,15){1b 13="";14(e2){14(15>-bY&&15<bW){14(15<-bY+de){14(bw(17)<bZ){13="3L"}}1d{14(15>bW-de){14(bw(17)<bX){13="3N"}}1d{14(bw(15)<dM){13=15<0?"3O":"3M"}}}}}1d{14(17>-bZ&&17<bX){14(17<-bZ+de){14(bw(15)<bY){13="3L"}}1d{14(17>bX-de){14(bw(15)<bW){13="3N"}}1d{14(bw(17)<dM){13=17<0?"3O":"3M"}}}}}1c 13},am=18(15,13){14(e2){14(13>-bY&&13<bW&&15>-bZ&&15<bZ){1c 1Y}}1d{14(15>-bZ&&15<bX&&13>-bW&&13<bW){1c 1Y}}1c 2y},ak=18(15){1b 13=dq(15.8d);1c!(13.3i("a")||13.3i("8e")||13.3i("8f")||13.3i("2E")||13.8g("8h"))},ai=18(13){1c ae("1A-2J "+bJ[13%2]+"-8i"+(bV[13]["k"]?" 8j":"")+(dg?" "+dg:""),"1A"+13,ae("1A-3j","1A"+13+"3j"))},ag=18(1k,1g,1h,1e,1a,19,17,15,13){1c{1R:1k,1J:1g?1g+"24":dj,1H:1h?1h+"24":dj,1G:1e?1e+"24":dj,1D:1a?1a+"24":dj,2b:19?19+"24":dj,2f:17,"1t-22":15,"z-1X":13}},ae=18(15,13,17){1c"\\4r"+(13?" 3X=\\3k"+13+"\\3k":"")+(15?" 2B=\\3k"+15+"\\3k":"")+"\\2s"+(17?17:"")+"\\4s/4t\\2s"},ac=18(13){1c dq("#1A"+13)},aa=18(13){1c dq("#1A"+13+"3j")},F=18(13){1c dq("#1A"+13+"3F")},E=18(13){1c dq("#1A"+13+"3H")},D=18(13){1c dq("#1A"+13+"4C")},C=18(13){1c dq("#1A"+13+"4D")},B=18(13){1c dq("#1A"+13+"4E")},A=18(13){1c dq("#1A"+13+"4B")},T=18(13){1c dq("#1A"+13+"4z")},S=18(15,13){1c ci?"8k("+15+"24,"+13+"24,0) ":"8l("+15+"24,"+13+"24) "},R=18(17,19,15){1b 13=bD(17*17+19*19);14(15){13*=17>0?-1:1}1c 13},Q=18(13){1c 13.8m()},O=18(15,13){14(cn==dj){dg=13;cn=2O;ci="8n"3v dm||"8o"3v 25.8p["3Y"];fq(15);14(cM){aB(1)}fp();fm();14(cU){M()}1d{cn=dj;1c[]}}1d{1c cn}1c 2O},M=18(){bA=cn.2c();14(eT){cn.3D(eT,"3E",K)}1d{K()}},K=18(){1b 15=cn.8q();14(15.1u==0){1c[]}fk(15);bz=gG(15);cC=eB=(eB>ex?ex:eB);cC-=cC%2;14(eZ){cC=cz-cC-1}1b 13=(dg?" "+dg:"");cn.2c(ae("2z-2J"+13,"3Z",ae("2P-2J"+13,"2P",ae("2P-23"+13,"4R",ae("2P-3j"+13,"4S",ec?ae((dg?dg:dj),"4T"):dj)))+ae(dg?dg:dj,"3l")))["1f"]("3G","8r");cm=dq("#3Z");cl=dq("#2P");cj=dq("#4R");ck=dq("#4S");cK=ec?dq("#4T"):dj;cJ=dq(25);cm.1f({1R:"4U",2Q:f2,"-4V-4W-22-x":"50%","-4V-4W-22-y":"50%"});14(fF){cm.1f({1J:"1Q%",1H:"1Q%"})}1d{14(cy==dj){cm.1f({1J:fI?"1Q%":cw+fM+fK})}1d{cm.1f({1J:cy})}14(cv==dj){cm.1f({1H:fI?"1Q%":ct+fP+fO})}1d{cm.1f({1H:cv})}cm.1f({2f:"1Z"})}p();cl.1f({1R:"4U",1G:0,1D:0,"2Q-1G":fP,"2Q-1D":fM,"2Q-4A":fO,"2Q-8s":fK,"z-1X":10});ck.1f({"1t-3Y":"8t-3d",1P:1});cj.1f({1R:"27",1G:0,1D:0});14(ec){cK.1f({1R:"27",1G:0,1D:0,"z-1X":1,"1t-22":e2?"50% 0%":"0% 50%",1P:d9})}14(d1){ge()}14(cR){dq(cn)["1f"]({"8u-8v":"2d"})}gm(dj,bH);gj=cC;gF(bz);gI();d6();cl.1w(bx.a,ds);cJ.1w(bx.b,dp)["1w"](bx.c,dl);14(!by){cJ.1w("4X",di)}1d{cA();cJ.1w("4Y",df)}14(c2){dq(dm)["1w"]("8w",gm)}dq(dm)["1w"]("3m",G);14(fF||fI){G()}14(fa){L.3n(bI)}dm.4L=(18(){1c dm.8x||dm.8y||dm.8z||18(17){dm.3o(17,gu/6)}})();dw=bH;du();1c cn},I,H=18(13){14(I||!cn){1c}I=bH;ck.1f("1P",0);14(cI){cI.1f("1P",0);cI.2w()}14(d1){fc()}dm.3o(18(){dw=bI},8A);dm.3o(18(){cg=bI;bh();dg=dj;cn.4n();cn.2c(bA)["2r"]("3Y",2N);cn=dj;f1=85;cJ.2w(bx.b,dp)["2w"](bx.c,dl)["2w"]("4Z 51 52 53",a3);14(!by){cJ.2w("4X",di)}1d{cJ.2w("4Y",df)}dq(dm)["2w"]("3m",G);I=bI;14(13){13()}},3w);14(cM){az()}},G=18(){14(fF){dq(cn)["1f"]({1J:dm.8B,1H:dm.8C})}14(fF||fI){1b 1h=fx;14(1h&&aO){1h=bI;cm.1f({1H:"1Q%"})}cy=cm.1J();cv=cm.1H();1b 1e=cy-fM-fK,1a=1h?ct:cv-fP-fO,17=eH?c7:cw,15=eH?cB:ct,13=1e/17,1g=1a/15;14(eF){14(e2?1a>=eD:1e>=eD){c7=c9=bu(1e/e0);cB=c8=bu(1a/eX);b7=1}1d{14(e2){cB=c8=eD/2;b7=1a/eD;c7=c9=1e/b7}1d{c7=c9=eD/2;b7=1e/eD;cB=c8=1a/b7}}fo();p();1y(1b 19=0;19<bV.1u;19++){bV[19]["e"]=c9;bV[19]["f"]=c8;bV[19]["m"]=bV[19]["q"]?b4:b5}fl()}1d{b7=fC?(13>1g?13:1g):(13<1g?13:1g);14(b7>1&&!fz){b7=1}}o=bu((cw*b7-cw)/2-(cw*b7-1e)/2);14(1h){1a=ct*(b7+k*z);cm.1f({1H:1a+(fP+fO)});n=bv((ct*(b7+k*z)-ct)/2)}1d{n=bv((ct*b7-ct)/2-(ct*b7-1a)/2)}gH(1e,1a);m();14(d1){eq(bH)}gA(cy)}},p=18(){cl.1f({1J:cw,1H:ct});cj.1f({1J:cw,1H:ct});14(ec){cK.1f({1J:cw,1H:ct})}},o,n,m=18(){1b 13=b7+k*z,17=o+w*z+aW,15=n+v*z+aV;cl.1f({1t:S(17,15)+"8D("+13+","+13+")"})},l,k,z,y,x,w,v,u,t,s,r,q,2k,2R,2S,2j,gI=18(){k=z=y=x=w=v=u=t=s=r=q=2k=2R=2S=0;l=2j=bI},gH=18(17,13){1b 1a=cw,19=ct;14(co){14(e2){19/=2}1d{1a/=2}}y=bv((1a-17)/2);x=bv((19-13)/2);14(y<0){y=0}14(x<0){x=0}k=(b7<1?1-b7:0);14(k==0){gI()}1d{14(l){1b 15=d(u,t);w=u=15.x;v=t=15.y}}g()},j=18(){14(!l&&b7<1){l=bH;gD(bH);gd(bH);P(9,cC)}},i=18(){14(l&&b7<1){l=bI;P(10,cC)}},h=18(){14(bb){z+=(aR-z)/5;14(bw(aR-z)<0.41){z=aR}m();1c}14(l){14(z!=1){z+=(1-z)/5;14(bw(1-z)<0.41){z=1}m();14(fx){dq(dm)["3U"]("3m")}}}1d{14(z!=0){z-=z/5;14(bw(z)<0.41){z=0;gD();gd()}m();14(fx){dq(dm)["3U"]("3m")}}}f()},g=18(){14(cI){dq("#b-54")["1f"]("26",l?"":"2d");dq("#b-42")["1f"]("26",l?"2d":"");fY(dq("#b-42"),(k>0&&dx))}},f=18(){14(u==w&&t==v){1c}14(2j||bb){q=u-2R,2k=t-2S;2R=u,2S=t}1d{14(q!=0||2k!=0){q*=0.9,2k*=0.9;14(bw(q)<1&&bw(2k)<1){q=2k=0}1d{1b 13=d(u+q,t+2k);u=13.x,t=13.y}}}w+=(u-w)/5,v+=(t-v)/5;14(bw(u-w)+bw(t-v)<1){w=u,v=t}m()},e=18(15,17){15+=s;17+=r;1b 13=d(15,17);14(15<-y){s-=(15+y)}14(15>y){s-=(15-y)}14(17<-x){r-=(17+x)}14(17>x){r-=(17-x)}u=13.x;t=13.y},d=18(13,15){14(13<-y){13=-y}1d{14(13>y){13=y}}14(15<-x){15=-x}1d{14(15>x){15=x}}1c{x:13,y:15}},c=18(13,15){s=u-13,r=t-15;2R=u;2S=t;q=2k=0},b=18(1g,1h,17,19,13){1b 1a=17-o-cw/2-1g-fM-cr,1e=19-n-ct/2-1h-fP-b8;1b 15=(13?{x:1a,y:1e}:d(1a,1e));w=u=15.x;v=t=15.y},a,go=18(){1b 1a=2F.43,17,19;14(1a==""){1a="#1A/"+eB}14(1a){1b 15=1a.4g(1);15=15.2G("/");1b 13=0;14(15.1u==3){17=(15[13++]!=dg)}14(15[13]=="1A"){19=15[++13]["2G"]("-")[0]}}1c{3X:17,55:19}},gm=18(15,17){1b 1a=2F.43;14(a==1a){1c}a=1a;1b 13=go(),19=8E(13.55);14(19){14(17){cC=gk((3h(19)?dP(19):dQ(19)))}1d{14(3h(19)){L.44(19,bH)}1d{L.45(19,bH)}}}},gk=18(13){14(13<ez){13=ez}1d{14(13>ex){13=ex}}1c 13-13%2},gj,gi,gh=18(15){14(gj==cC){1c}gj=cC;14(cC==0&&a==""){1c}1b 13="1A/"+15;14(dg){13=dg+"/"+13}13="#"+13;14(13!=a){2F.43=a=13}},gG=18(15){1y(1b 13=0;13<15.1u;13++){14(dq(15[13])["2r"]("2B")=="8F"){1c dq(15[13])["2c"]()}}1c 2N},gF=18(15){1b 13=dq("#3l");14(d5){13.3D(d5,"3E",gE)}1d{14(15){13.2c(15);gE()}}},gE=18(){cI=dq("#2z-3l");cI.1f("1P","1");14(dg){cI.3p(dg)}cG=dq("#8G");gD();gB();14(cY){1b 13=dq("#8H-8I");13.1f("26","8J");13.2c(c0)}},gD=18(13){14(cI){cI.1f("z-1X",(d3||13)?12:2)}},gC,gB=18(){1b 13=by?bx.c:"56";dq("#b-57")["1w"](13,18(15){Q(15);L.3S(bH)});dq("#b-59")["1w"](13,18(15){Q(15);L.3P(bH)});dq("#b-5a")["1w"](13,18(15){Q(15);L.3Q(bH)});dq("#b-5b")["1w"](13,18(15){Q(15);L.3R(bH)});dq("#b-46")["1w"](13,18(15){Q(15);L.3n()});fY(dq("#b-46"),e9);dq("#b-5c")["1w"](13,18(15){Q(15);L.3q()});aO=bI;14(e8){aM=25.8K("3Z");e8=(aM.48||aM.49||aM.4a||aM.4b)?bH:bI}14(e8){cJ.1w("4Z 51 53 52",a3)}dq("#b-4c")["1w"](13,18(15){Q(15);L.5d()});fY(dq("#b-4c"),e8);dq("#b-5e")["1w"](13,18(15){Q(15);L.5f()});dq("#b-42")["1w"](13,18(15){Q(15);L.3f()});dq("#b-54")["1w"](13,18(15){Q(15);L.3e()});dq("#b-5g")["1w"](13,18(15){Q(15);aZ()});dq("#b-5h")["1w"](13,18(15){Q(15);aY()});dq("#b-5i")["1w"](13,18(15){Q(15);aX()});dq("#b-5j")["1w"](13,18(15){Q(15);al()});dq("#b-5k")["1w"](13,18(15){Q(15);L.3T()});fY(dq("#b-5k"),d1);dq("#b-8L")["1w"](13,18(15){Q(15);L.5l()});cI.1w(bx.b,gz);dq(".8M-8N-2E")["1w"](bx.a,ga)["1w"](bx.c,ga);cG.8O(18(15){dq(2O)["3r"]("");gC=bH});cG.5m(18(){gC=bI;14(dq(2O)["3r"]()==""){gx()}});dq("#8P")["8Q"](18(){gy();1c bI});aQ();g();gx()},gA=18(17){1b 15="8R",13=dq("#3l");14(17<8S){15="8T"}1d{14(17<4j){15="8U"}1d{14(17<3w){15="8V"}}}13.2r("2B",15)},gz=18(13){14(!bN&&!b2){ga(13)}},gy=18(){1b 13=cG.3r();14(3h(13)?!L.44(13,dA):!L.45(13,dA)){gx()}cG.5m()},gx=18(){14(!cI){1c}1b g0=bV[cC],1o=g0.i,1n=g0.h,1h=bV[cC+1],17=1h.i,15=1h.h,13=1o?1o:(1n>0?1n:dj),1i=17?17:(15>0?15:dj),1s=(13>0&&1i>0&&(!1o&&!17))?1:0,1k=dC.2G("~")[1s]["2G"]("#"),1g="",19="";14(!13){13=1i;1o=17;1i=dj}14(!1i){14(13){1g=1o?13:1k[0]+13+1k[1];19=13}}1d{14(1o&&17){1g=13+" - "+1i}1d{14(1o){1g=13+" - "+1k[0]+1i+1k[1]}1d{14(17){1g=1k[0]+13+1k[1]+" - "+1i}1d{1g=1k[0]+13+1k[1]+1i+1k[2]}}}19=13+"-"+1i}19=8W(19);cG.3r(1g);1b 1e=(cC>(ez+1))&&!bP,1a=(cC<(ex-1))&&!bP;fY(dq("#b-57"),1e);fY(dq("#b-59"),1e);fY(dq("#b-5a"),1a);fY(dq("#b-5b"),1a);14(c2){gh(19)}},fY=18(15,13){14(13==dj){13=bH}14(13){15.5n("5o")}1d{fW(15)}},fW=18(13){13.3p("5o")},fU,fT,fS,fR,gg,gf,ge=18(){1b 15="2z-8X",1i="3s-2J";cl.2V(ae((eo?"1Z":dj),15,ae(dj,1i)));gg=dq("#"+15);14(dg){gg.3p(dg)}gf=dq("#"+1i);gf.1f("1J",cz*en*1.5);fU=[];fT=[];fS=[];fR=[];fu=0;fy=0;fw=0;1b 1o="3s",1n="-",g0="1A",1k="8Y",1g="2E",1h=1o+1n+g0,1e=1o+1n+1k,1a=1o+1n+1g,1s="#"+1o;1y(1b 13=0,19,17,15;13<=cz;13+=2){19=bV[13]["c"]?13:-1,17=bV[13+1]["c"]?13+1:-1;14(19<0&&17>=0){19=17,17=-1}14(19>=0&&17>=0){gf.3C(ae(1e,dj,ae(1a,1o+19+1g)+ae(1a,1o+17+1g)));gc(19);15=dq(1s+19+1g)["1R"]()["1D"];fU.1v(15+en);fT.1v(13);fS.1v(en*2);gc(17);14(dZ){fR.1v([19,17])}}1d{14(19>=0){gf.3C(ae(1h,dj,ae(1a,1o+19+1g)));gc(19);15=dq(1s+19+1g)["1R"]()["1D"];fU.1v(15+en/2);fT.1v(13);fS.1v(en);14(dZ){fR.1v([19])}}}}14(fU.1u){fu=15+en*(bV[cz]["k"]?1:2)+fK;gf.1f("1J",fu+20);gd();ft=bI;ew=0;gf.1w(bx.a,f9)["1w"](bx.c,f7)["1w"](bx.b,f8)["1f"]("1H",em+16);14(!by){gf.1w("8Z",fi)}fd=eo;fg()}1d{d1=bI;gg.2l()}},gd=18(13){14(d1){gg.1f("z-1X",(dX||13)?11:1)}},gc=18(13){1b 15={1J:en,1H:em,"2W-92":+en+"24 "+em+"24"};14(!dZ){15.2W="2I("+bV[13]["c"]+")"}dq("#3s"+13+"2E")["2r"]("2H-1A",13)["2r"]("93","2T "+bV[13]["h"])["1f"](15)["1w"](by?bx.c:"56",gb)},gb=18(15){14(!es&&!fd&&!cg){1b 13=dq("#"+15.94["3X"])["2H"]()["1A"];er=bH;L.5p(13,bH);ga(15)}},ga=18(13){14(!b2&&!bN){Q(13);13.95()}},f9=18(13){e1(eV(13));ga(13)},f8=18(13){14(fd&&dV&&!b2&&!bN&&!2j){fb()}1d{fg()}14(fs){ft=bH;es=bH;fy=eS(fr+eV(13))}ga(13)},f7=18(13){eY();ga(13)},fi=18(13){eY();14(!fd&&dV){fc()}},fg=18(13){14(!dV){1c bI}1b 15=cT();14(13==dj){fe=15}1d{1c(15-fe)>13}},fe,fd,fc=18(){14(fw!=fy){1c}fd=bH;gg.3p("1Z")},fb=18(){fg();fd=bI;gg.5n("1Z")},fH=18(){14(!fd){14(fg(dV)){fc()}14(fw!=fy){ep()}}},fE,fB,fy,fw,fv,fu,ft,fs,fr,ew,eu,es,er,eq=18(17){14(er){er=bI;1c}1b 1a=bv(cy/2),19,15=fU.1u-1,13=fT.1W(cC);14(ek){fB=1a-fU[0];fE=1a-fU[15]}1d{fB=1a-fU[0]-1a+fS[0]/2;fE=1a-fU[15]+1a-fS[15]/2;14(fB<fE){fB=fE=bv(fB+fE/2)}}14(13<0){14(17){19=0}1d{1c}}1d{19=fU[13]}fy=eS(1a-19);14(!fw==dj||fd||17){fw=fy+0.5}},ep=18(){14(fw==fy){1c}14(ft){ew=fy-eu;eu=fy}1d{14(ew!=0){ew*=0.9;14(bw(ew)<1){ew=0}1d{fy=eS(fy+ew)}}}fw+=(fy-fw)/5;14(bw(fy-fw)<1){fw=fy,ew=0}gf.1f("1t",S(fw,0));14(dZ&&!(bw(fw-fv)<32)){fv=fw;1b 15=-en-32,1e=cy+en+32,13=fR.1u,17=0;2t(17<13&&fU[17]+fw<15){17++}2t(17<13&&fU[17]+fw<1e){14(fR[17]){1y(1b 19=0,1a;19<fR[17]["1u"];19++){1a=fR[17][19];dq("#3s"+1a+"2E")["1f"]({"2W-96":"2I("+bV[1a]["c"]+")"})}fR[17]=2N}17++}}},e1=18(13){fs=bH;ft=bI;es=bI;eu=fy;fr=fy-13},eY=18(){es=ft;ft=fs=bI},eV=18(13){14(by){13=13.3V["3W"][0]}1c 13.2v},eS=18(13){13=bt(13);14(13<fE){13=fE}1d{14(13>fB){13=fB}}1c 13},eQ=18(13,1n,1k){1b 1s=bI;14(13<ez||13>ex){1c 1s}14(!cg&&a2.1u==0){13-=13%2;14(13!=cC){1s=bH;14(1k){cC=13;d6()}1d{1b 1g=13-cC;14(1n){14(((13==cz-1&&cC!=0)||(13==0&&cC!=cz-1))&&(cs||b6)&&bw(1g)>2){14(1g<0){a1(0,1g+2);a1(3t,-2)}1d{a1(0,1g-2);a1(3t,2)}}1d{14(((cC==cz-1&&13!=0)||(cC==0&&13!=cz-1))&&(cs||b6)&&bw(1g)>2){14(1g<0){a1(0,-2);a1(3t,1g+2)}1d{a1(0,2);a1(3t,1g-2)}}1d{a1(0,1g)}}}1d{1b 1h=98,1e;14(1g<0){1e=-1;1g*=-1}1d{1e=1}1g/=2;14(1g<1h){1h=1g}1b 19=0,17=0,1a=1g/1h;1y(1b 15=0;15<1h;15++){19=bt(1a*(15+1));a1((15?dL/4:0),(19-17)*2*1e);17=19}}}}}1c 1s},eP=18(13,15){eQ(dQ(13),15)},eO=18(13,15){eQ(dP(13),15)},eN=18(13,15){eQ(dO(13),15)},eM=18(13){eQ((eZ&&!13)?99:ez,bH)},eL=18(13){1c da((eZ&&!13)?1:-1,(co&&!eZ)?1:0,2)},dU=18(13){1c da((eZ&&!13)?-1:1,(co&&eZ)?1:0,2)},dS=18(13){eQ((eZ&&!13)?ez:ex,bH)},dQ=18(13){1c 13>0?dN.1W(9a(13)):-1},dP=18(13){1c bq.1W(13.5q())},dO=18(13){1c bp.1W(13)},dN,bq,bp,bo=18(){dN=[],bq=[],bp=[];1y(1b 13=0,15;13<cz;13++){dN[13]=bV[13]["h"];bq[13]=bV[13]["i"]?bV[13]["i"]["5q"]():dj;bp[13]=bV[13]["j"]}},bn=18(15,13){14(13){bV[15]["v"]=13}1d{1c bV[15]["v"]}},bm=18(){1c!(bP||bN||b2||bb)},bl=18(13,15){14(13==dj){13=0}14(15==dj){15=cz}ez=eZ?cz-15:13;ex=eZ?cz-13:15;14(ez<0){ez=0}14(ex>cz){ex=cz}ez-=ez%2;ex+=(1-ex%2)},bk,bj=18(){1b 13=bV[cC]["x"]||bV[cC+1]["x"];13=13==dj?e6:13;bk=dm.3o(aS,13)},bi=18(13){14(13==dj){13=bH}14(!bP){bP=bH;14(13){aS()}1d{bj()}}},bh=18(){14(bP){bP=bI;dm.9b(bk);14(!cg){gx()}}},aS=18(){14(!dU(bI)){14(e4!=0){eM()}14(e4<1){L.3q();1c}}bj()},aQ=18(){14(cI){dq("#b-5c")["1f"]("26",bP?"":"2d");dq("#b-46")["1f"]("26",bP?"2d":"")}},aO,aM,aK,aI,a6=18(){14(aM.48){aM.48()}1d{14(aM.49){aM.49()}1d{14(aM.4a){aM.4a()}1d{14(aM.4b){aM.4b()}}}}},a5=18(){14(25.5r){25.5r()}1d{14(25.5s){25.5s()}1d{14(25.5t){25.5t()}1d{14(25.5u){25.5u()}}}}},a4=18(){14(e8){dq("#b-4c")["1f"]("26",aO?"2d":"");dq("#b-5e")["1f"]("26",aO?"":"2d")}},a3=18(13){aO=!aO;a4();G()},a2,a1=18(17,13){1b 15={c:17,b:13,a:dj};a2.1v(15)},a0=18(){1b 15=cT(),13=a2[0];14(!13.a){13.a=cT()}14(13.c<(15-13.a)){14(da((13.b<0)?-1:1,0,bw(13.b))){a2.1N(0,1)}}},aZ=18(){aj("4d://5g.2A/9c/9d?9e="+af()+"\\9f="+af()+(c6?"\\9g="+ah(c6)+(c5?ah(" 9h "+c5):""):""))},aY=18(){aj("4d://9i.5h.2A/9j?2I="+af()+"\\9k=5v\\9l=5v")},aX=18(){aj("4d://4h.5i.2A/5w/5w.9m?u="+af())},al=18(){14(!c4){c4="3x://2z-4l.2A/9n/9o.9p"}aj("3x://5j.2A/9q/9r/2E/?2I="+af()+"\\9s="+ah(c4)+(c6?"\\9t="+ah(c6):""))},aj=18(13){dm.9u(13,"9v")},ah=18(13){1c 9w(13)},af=18(){1c ah(cL?cL:dm.2F["4f"])},ad,ab,aG,aF,aD,aB=18(13){aG=13;aD=(dg?dg:"9x");aF="4m - "+aD;ab=[];ad=cT();at()},az=18(){1b 13=cT()-ad;2a(aG){1q 0:1x;1q 1:2x.1v(["3u",aF,"3y 9y",aD,13,1Y]);1x;1q 2:1x}},ax=18(13){ab[13]=cT()},av=18(15){1b 13=cT()-ab[15];2a(aG){1q 0:1x;1q 1:2x.1v(["3u",aF,"2T "+15+" 9z",aD,13,1Y]);1x;1q 2:1x}},at=18(){2a(aG){1q 0:1x;1q 1:2x.1v(["3u",aF,"3y 9A",aD,0,1Y]);1x;1q 2:1x}},ar=18(13){2a(aG){1q 0:1x;1q 1:2x.1v(["3u",aF,"2T "+13+" 9B",aD,0,1Y]);1x;1q 2:1x}},aq=["9C","9D","9E","9F","9G","9H","9I","9J","9K","9L","9M"],P=18(13,17){14(ch){1b 15=ch[aq[13]];14(15){15(17)}}14(aG){14(13==2){ar(17);ax(17)}1d{14(13==3){av(17)}}}},N=18(13){1c dd.1W(13)},L={5p:18(15,13){14(bm()){1c eQ(15,13)}},45:18(13,15){14(bm()){1c eP(13,15)}},44:18(13,15){14(bm()){1c eO(13,15)}},9N:18(13,15){14(bm()){1c eN(13,15)}},3S:18(13){14(bm()){eM(13)}},3P:18(13){14(bm()){eL(13)}},3Q:18(13){14(bm()){dU(13)}},3R:18(13){14(bm()){dS(13)}},3n:18(13){14(bm()&&e9){bi(13);aQ()}},3q:18(){14(bP){bh();aQ()}},4O:18(){bP?L.3q():L.3n()},9O:18(13){ch=13},5l:18(13){H(13)},9P:18(){1c dg},9Q:18(){1c cC},9R:18(){1c bV[cC]},3T:18(){14(d1){fd?fb():fc()}},9S:18(){14(d1){fc()}},3f:18(){14(dx){j();g()}},3e:18(){i();g()},4N:18(){l?L.3e():L.3f()},9T:18(13){cO=13},9U:18(13){cN=13},9V:18(13,15){bl(13,15)},2H:18(15,13){1c bn(15,13)},5d:18(){1c a6()},5f:18(){1c a5()},9W:18(15,17,13){fj(dq(15),17,13)},9X:18(13){},9Y:18(17,13,15){fh(17,13,15)}},J=18(15,13){14(15==dj){1c L}1c cn?L[15](13):[]};dq.9Z(dq.fn,{as:O,2z:J})})(do,2O);',62,1037,'|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||gN|if|gO||gP|function|gQ|gR|var|return|else|gS|css|gU|gT|gZ|hc|gV|hk|hm|gW|gY|hd|case|hg|gX|transform|length|push|bind|break|for|toFixed|page|hj|hf|left|hs|deg|top|height|hi|width|hb|hl|ho|splice|rotate|opacity|100|position|he|hq|hp|ha|lastIndexOf|index|true|hidden||hts|origin|offset|px|document|display|absolute|hw|hv|switch|right|html|none|hh|overflow|scaleX|hE|hD|gJ|gM|remove|fsc|hC|hB|hz|hn|attr|x3E|while|fts|pageX|unbind|_gaq|false|pageflip|com|class|hF|pageY|button|location|split|data|url|container|fsA|fsB|hG|null|this|book|margin|gL|gK|Page|escape|after|background|flip|hu|ht|hA|hy||hx|05|TL|||||BL|TR|BR||zoomOut|zoomIn|x3Cbr|isNaN|is|content|x22|controls|resize|startAutoFlip|setTimeout|addClass|stopAutoFlip|val|thumbnail|200|_trackEvent|in|1000|http|Book|x27||join|append|load|GET|emboss|visibility|mask|scaleY|hr|end|OL|IR|OR|IL|gotoPrevPage|gotoNextPage|gotoLastPage|gotoFirstPage|showThumbnails|trigger|originalEvent|changedTouches|id|style|stage||01|zoomin|hash|gotoPageName|gotoPageNumber|play||requestFullscreen|mozRequestFullScreen|webkitRequestFullScreen|msRequestFullscreen|fullscreen|https|Date|href|substr|www|HardCover|768|2000|books|Pageflip5|empty|cover|outerpage|continue|x3Cdiv|x3C|div|hard|String|concat|backface|topshadow|hardtopshadow|bottom|fliptopshadow|flipshadowcontainer|flipshadowA|flipshadowB|console|log|0deg|skewX|skewY|getTime|raf|keyCode|toggleZoom|toggleAutoFlip|identifier|Pinch|bookoffs|bookc|dropshadow|relative|webkit|perspective|keydown|touchcancel|webkitfullscreenchange||mozfullscreenchange|msfullscreenchange|fullscreenchange|zoomout|pn|click|first||prev|next|last|pause|enterFullScreen|fullscreenoff|exitFullScreen|twitter|google|facebook|pinterest|thumbs|closePageflip|blur|removeClass|disabled|gotoPage|toLowerCase|exitFullscreen|mozCancelFullScreen|webkitCancelFullScreen|msExitFullscreen|frameless|sharer|ontouchstart|touchstart|touchmove|touchend|mousedown|mousemove|mouseup|Math|PI|sin|asin|cos|sqrt|abs|floor|ceil|round|random|toUpperCase|charCodeAt|get|UTC|FullYear|Month|offline|online|file|fromCharCode|auto||IDs|DefaultID|PageWidth|||300|PageHeight|400|CoverWidth|CoverHeight|HardPages|StageWidth|StageHeight|Margin|MarginTop|MarginBottom|MarginLeft|MarginRight|VerticalMode|SinglePageMode|RightToLeft|AlwaysOpened|AutoScale|FullScale|FillScale|UpScale|CenterSinglePage|ScaleToSinglePage|AutoStageHeight|FlexibleContent|FlexibleContentMinWidth|StartPage|MinPageLimit|MaxPageLimit|StartAutoFlip|AutoFlipEnabled|FullScreenEnabled|AutoFlipInterval|AutoFlipLoop|PageDataFile|Preflip|ControlbarFile|ControlbarToFront|Thumbnails|ThumbnailsLazyLoad|ThumbnailsToFront|ThumbnailsAutoHide|ThumbnailsHidden|ThumbnailWidth|ThumbnailHeight|ThumbnailAlwaysCentered|Transparency|PageCache|NoFlipShadow|DropShadow|Emboss|DropShadowOpacity|FlipTopShadowOpacity|FlipShadowOpacity|EmbossOpacity|HardFlipShadowOpacity|PreflipArea|128|SecondaryDragArea|InsideDragArea|FlipDuration|800|BookOffsetX|BookOffsetY|TearDistance|PerformanceAware|PagerText|Pages|PagerSkip|HideCopyright|HashControl|ZoomEnabled|ClickZoom|PinchZoom|HotKeys|MouseControl|GoogleAnalytics|ShareLink|ShareText|The|Template|the|Web|ShareVia|MaccPageFlip|ShareImageURL|Copyright|ShowCopyright|Key|DisableSelection|x27page|reverse|disableEmbossing|unload|backgroundFile|htmlFile|thumbnailImage|transparentPage|removablePage|pageNumber|pageName|pageLabel|autoFlipInterval|113|123|backgroundImage|90deg|rgba|wrap|before|shadow|shadowA|shadowB|unwrap|tear|rotateX|rotateY|new||metaKey|altKey|ctrlKey|||shiftKey|default|Cancel|ids|x3EPinch|Scale|outmsg|target|input|textarea|hasClass|hotspot|side|outer|translate3d|translate|preventDefault|WebKitCSSMatrix|MozPerspective|body|children|visible|rightt|preserve|user|select|hashchange|requestAnimationFrame|webkitRequestAnimationFrame|mozRequestAnimationFrame|900|innerWidth|innerHeight|scale|decodeURI|controlbar|pagerin|copyright|text|block|getElementById|close|control|bar|focus|pfpager|submit|w1000|480|w320|w480|w768|encodeURI|thumbnails|spread|mouseleave|||size|title|currentTarget|stopPropagation|image||999|_ManPageLimit|parseInt|clearTimeout|intent|tweet|original_referer|x26url|x26text|via|plus|share|x26gpsrc|x26partnerid|php|images|shareimage|jpg|pin|create|x26media|x26description|open|_blank|encodeURIComponent|Untitled|time|Time|Opened|View|onFlip|onFlipEnd|onTop|onTopEnd|onLoad|onUnload|onRemove|onHide|onShow|onZoomIn|onZoomOut|gotoPageLabel|setPFEventCallBack|getID|getPN|getPageNumber|hideThumbnails|hotKeys|mouseControl|pageLimit|addPage|reloadPage|removePage|extend|||||||||||||||||||||||||||||pageflipInit||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||jQuery||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||'.split('|'),0,{}))/**
  * x is a value between 0 and 1, indicating where in the animation you are.
  */
var duScrollDefaultEasing = function (x) {
  'use strict';

  if(x < 0.5) {
    return Math.pow(x*2, 2)/2;
  }
  return 1-Math.pow((1-x)*2, 2)/2;
};

angular.module('duScroll', [
  'duScroll.scrollspy',
  'duScroll.smoothScroll',
  'duScroll.scrollContainer',
  'duScroll.spyContext',
  'duScroll.scrollHelpers'
])
  //Default animation duration for smoothScroll directive
  .value('duScrollDuration', 350)
  //Scrollspy debounce interval, set to 0 to disable
  .value('duScrollSpyWait', 100)
  //Wether or not multiple scrollspies can be active at once
  .value('duScrollGreedy', false)
  //Default offset for smoothScroll directive
  .value('duScrollOffset', 0)
  //Default easing function for scroll animation
  .value('duScrollEasing', duScrollDefaultEasing);


angular.module('duScroll.scrollHelpers', ['duScroll.requestAnimation'])
.run(["$window", "$q", "cancelAnimation", "requestAnimation", "duScrollEasing", "duScrollDuration", "duScrollOffset", function($window, $q, cancelAnimation, requestAnimation, duScrollEasing, duScrollDuration, duScrollOffset) {
  'use strict';

  var proto = {};

  var isDocument = function(el) {
    return (typeof HTMLDocument !== 'undefined' && el instanceof HTMLDocument) || (el.nodeType && el.nodeType === el.DOCUMENT_NODE);
  };

  var isElement = function(el) {
    return (typeof HTMLElement !== 'undefined' && el instanceof HTMLElement) || (el.nodeType && el.nodeType === el.ELEMENT_NODE);
  };

  var unwrap = function(el) {
    return isElement(el) || isDocument(el) ? el : el[0];
  };

  proto.duScrollTo = function(left, top, duration, easing) {
    var aliasFn;
    if(angular.isElement(left)) {
      aliasFn = this.duScrollToElement;
    } else if(angular.isDefined(duration)) {
      aliasFn = this.duScrollToAnimated;
    }
    if(aliasFn) {
      return aliasFn.apply(this, arguments);
    }
    var el = unwrap(this);
    if(isDocument(el)) {
      return $window.scrollTo(left, top);
    }
    el.scrollLeft = left;
    el.scrollTop = top;
  };

  var scrollAnimation, deferred;
  proto.duScrollToAnimated = function(left, top, duration, easing) {
    if(duration && !easing) {
      easing = duScrollEasing;
    }
    var startLeft = this.duScrollLeft(),
        startTop = this.duScrollTop(),
        deltaLeft = Math.round(left - startLeft),
        deltaTop = Math.round(top - startTop);

    var startTime = null, progress = 0;
    var el = this;

    var cancelOnEvents = 'scroll mousedown mousewheel touchmove keydown';
    var cancelScrollAnimation = function($event) {
      if (!$event || (progress && $event.which > 0)) {
        el.unbind(cancelOnEvents, cancelScrollAnimation);
        cancelAnimation(scrollAnimation);
        deferred.reject();
        scrollAnimation = null;
      }
    };

    if(scrollAnimation) {
      cancelScrollAnimation();
    }
    deferred = $q.defer();

    if(duration === 0 || (!deltaLeft && !deltaTop)) {
      if(duration === 0) {
        el.duScrollTo(left, top);
      }
      deferred.resolve();
      return deferred.promise;
    }

    var animationStep = function(timestamp) {
      if (startTime === null) {
        startTime = timestamp;
      }

      progress = timestamp - startTime;
      var percent = (progress >= duration ? 1 : easing(progress/duration));

      el.scrollTo(
        startLeft + Math.ceil(deltaLeft * percent),
        startTop + Math.ceil(deltaTop * percent)
      );
      if(percent < 1) {
        scrollAnimation = requestAnimation(animationStep);
      } else {
        el.unbind(cancelOnEvents, cancelScrollAnimation);
        scrollAnimation = null;
        deferred.resolve();
      }
    };

    //Fix random mobile safari bug when scrolling to top by hitting status bar
    el.duScrollTo(startLeft, startTop);

    el.bind(cancelOnEvents, cancelScrollAnimation);

    scrollAnimation = requestAnimation(animationStep);
    return deferred.promise;
  };

  proto.duScrollToElement = function(target, offset, duration, easing) {
    var el = unwrap(this);
    if(!angular.isNumber(offset) || isNaN(offset)) {
      offset = duScrollOffset;
    }
    var top = this.duScrollTop() + unwrap(target).getBoundingClientRect().top - offset;
    if(isElement(el)) {
      top -= el.getBoundingClientRect().top;
    }
    return this.duScrollTo(0, top, duration, easing);
  };

  proto.duScrollLeft = function(value, duration, easing) {
    if(angular.isNumber(value)) {
      return this.duScrollTo(value, this.duScrollTop(), duration, easing);
    }
    var el = unwrap(this);
    if(isDocument(el)) {
      return $window.scrollX || document.documentElement.scrollLeft || document.body.scrollLeft;
    }
    return el.scrollLeft;
  };
  proto.duScrollTop = function(value, duration, easing) {
    if(angular.isNumber(value)) {
      return this.duScrollTo(this.duScrollLeft(), value, duration, easing);
    }
    var el = unwrap(this);
    if(isDocument(el)) {
      return $window.scrollY || document.documentElement.scrollTop || document.body.scrollTop;
    }
    return el.scrollTop;
  };

  proto.duScrollToElementAnimated = function(target, offset, duration, easing) {
    return this.duScrollToElement(target, offset, duration || duScrollDuration, easing);
  };

  proto.duScrollTopAnimated = function(top, duration, easing) {
    return this.duScrollTop(top, duration || duScrollDuration, easing);
  };

  proto.duScrollLeftAnimated = function(left, duration, easing) {
    return this.duScrollLeft(left, duration || duScrollDuration, easing);
  };

  angular.forEach(proto, function(fn, key) {
    angular.element.prototype[key] = fn;

    //Remove prefix if not already claimed by jQuery / ui.utils
    var unprefixed = key.replace(/^duScroll/, 'scroll');
    if(angular.isUndefined(angular.element.prototype[unprefixed])) {
      angular.element.prototype[unprefixed] = fn;
    }
  });

}]);


//Adapted from https://gist.github.com/paulirish/1579671
angular.module('duScroll.polyfill', [])
.factory('polyfill', ["$window", function($window) {
  'use strict';

  var vendors = ['webkit', 'moz', 'o', 'ms'];

  return function(fnName, fallback) {
    if($window[fnName]) {
      return $window[fnName];
    }
    var suffix = fnName.substr(0, 1).toUpperCase() + fnName.substr(1);
    for(var key, i = 0; i < vendors.length; i++) {
      key = vendors[i]+suffix;
      if($window[key]) {
        return $window[key];
      }
    }
    return fallback;
  };
}]);

angular.module('duScroll.requestAnimation', ['duScroll.polyfill'])
.factory('requestAnimation', ["polyfill", "$timeout", function(polyfill, $timeout) {
  'use strict';

  var lastTime = 0;
  var fallback = function(callback, element) {
    var currTime = new Date().getTime();
    var timeToCall = Math.max(0, 16 - (currTime - lastTime));
    var id = $timeout(function() { callback(currTime + timeToCall); },
      timeToCall);
    lastTime = currTime + timeToCall;
    return id;
  };

  return polyfill('requestAnimationFrame', fallback);
}])
.factory('cancelAnimation', ["polyfill", "$timeout", function(polyfill, $timeout) {
  'use strict';

  var fallback = function(promise) {
    $timeout.cancel(promise);
  };

  return polyfill('cancelAnimationFrame', fallback);
}]);


angular.module('duScroll.spyAPI', ['duScroll.scrollContainerAPI'])
.factory('spyAPI', ["$rootScope", "$timeout", "$window", "$document", "scrollContainerAPI", "duScrollGreedy", "duScrollSpyWait", function($rootScope, $timeout, $window, $document, scrollContainerAPI, duScrollGreedy, duScrollSpyWait) {
  'use strict';

  var createScrollHandler = function(context) {
    var timer = false, queued = false;
    var handler = function() {
      queued = false;
      var container = context.container,
          containerEl = container[0],
          containerOffset = 0,
          bottomReached;

      if (typeof HTMLElement !== 'undefined' && containerEl instanceof HTMLElement || containerEl.nodeType && containerEl.nodeType === containerEl.ELEMENT_NODE) {
        containerOffset = containerEl.getBoundingClientRect().top;
        bottomReached = Math.round(containerEl.scrollTop + containerEl.clientHeight) >= containerEl.scrollHeight;
      } else {
        bottomReached = Math.round($window.pageYOffset + $window.innerHeight) >= $document[0].body.scrollHeight;
      }
      var compareProperty = (bottomReached ? 'bottom' : 'top');

      var i, currentlyActive, toBeActive, spies, spy, pos;
      spies = context.spies;
      currentlyActive = context.currentlyActive;
      toBeActive = undefined;

      for(i = 0; i < spies.length; i++) {
        spy = spies[i];
        pos = spy.getTargetPosition();
        if (!pos) continue;

        if(bottomReached || (pos.top + spy.offset - containerOffset < 20 && (duScrollGreedy || pos.top*-1 + containerOffset) < pos.height)) {
          //Find the one closest the viewport top or the page bottom if it's reached
          if(!toBeActive || toBeActive[compareProperty] < pos[compareProperty]) {
            toBeActive = {
              spy: spy
            };
            toBeActive[compareProperty] = pos[compareProperty];
          }
        }
      }

      if(toBeActive) {
        toBeActive = toBeActive.spy;
      }
      if(currentlyActive === toBeActive || (duScrollGreedy && !toBeActive)) return;
      if(currentlyActive) {
        currentlyActive.$element.removeClass('active');
        $rootScope.$broadcast('duScrollspy:becameInactive', currentlyActive.$element);
      }
      if(toBeActive) {
        toBeActive.$element.addClass('active');
        $rootScope.$broadcast('duScrollspy:becameActive', toBeActive.$element);
      }
      context.currentlyActive = toBeActive;
    };

    if(!duScrollSpyWait) {
      return handler;
    }

    //Debounce for potential performance savings
    return function() {
      if(!timer) {
        handler();
        timer = $timeout(function() {
          timer = false;
          if(queued) {
            handler();
          }
        }, duScrollSpyWait, false);
      } else {
        queued = true;
      }
    };
  };

  var contexts = {};

  var createContext = function($scope) {
    var id = $scope.$id;
    var context = {
      spies: []
    };

    context.handler = createScrollHandler(context);
    contexts[id] = context;

    $scope.$on('$destroy', function() {
      destroyContext($scope);
    });

    return id;
  };

  var destroyContext = function($scope) {
    var id = $scope.$id;
    var context = contexts[id], container = context.container;
    if(container) {
      container.off('scroll', context.handler);
    }
    delete contexts[id];
  };

  var defaultContextId = createContext($rootScope);

  var getContextForScope = function(scope) {
    if(contexts[scope.$id]) {
      return contexts[scope.$id];
    }
    if(scope.$parent) {
      return getContextForScope(scope.$parent);
    }
    return contexts[defaultContextId];
  };

  var getContextForSpy = function(spy) {
    var context, contextId, scope = spy.$scope;
    if(scope) {
      return getContextForScope(scope);
    }
    //No scope, most likely destroyed
    for(contextId in contexts) {
      context = contexts[contextId];
      if(context.spies.indexOf(spy) !== -1) {
        return context;
      }
    }
  };

  var isElementInDocument = function(element) {
    while (element.parentNode) {
      element = element.parentNode;
      if (element === document) {
        return true;
      }
    }
    return false;
  };

  var addSpy = function(spy) {
    var context = getContextForSpy(spy);
    if (!context) return;
    context.spies.push(spy);
    if (!context.container || !isElementInDocument(context.container)) {
      if(context.container) {
        context.container.off('scroll', context.handler);
      }
      context.container = scrollContainerAPI.getContainer(spy.$scope);
      context.container.on('scroll', context.handler).triggerHandler('scroll');
    }
  };

  var removeSpy = function(spy) {
    var context = getContextForSpy(spy);
    if(spy === context.currentlyActive) {
      context.currentlyActive = null;
    }
    var i = context.spies.indexOf(spy);
    if(i !== -1) {
      context.spies.splice(i, 1);
    }
		spy.$element = null;
  };

  return {
    addSpy: addSpy,
    removeSpy: removeSpy,
    createContext: createContext,
    destroyContext: destroyContext,
    getContextForScope: getContextForScope
  };
}]);


angular.module('duScroll.scrollContainerAPI', [])
.factory('scrollContainerAPI', ["$document", function($document) {
  'use strict';

  var containers = {};

  var setContainer = function(scope, element) {
    var id = scope.$id;
    containers[id] = element;
    return id;
  };

  var getContainerId = function(scope) {
    if(containers[scope.$id]) {
      return scope.$id;
    }
    if(scope.$parent) {
      return getContainerId(scope.$parent);
    }
    return;
  };

  var getContainer = function(scope) {
    var id = getContainerId(scope);
    return id ? containers[id] : $document;
  };

  var removeContainer = function(scope) {
    var id = getContainerId(scope);
    if(id) {
      delete containers[id];
    }
  };

  return {
    getContainerId:   getContainerId,
    getContainer:     getContainer,
    setContainer:     setContainer,
    removeContainer:  removeContainer
  };
}]);


angular.module('duScroll.smoothScroll', ['duScroll.scrollHelpers', 'duScroll.scrollContainerAPI'])
.directive('duSmoothScroll', ["duScrollDuration", "duScrollOffset", "scrollContainerAPI", function(duScrollDuration, duScrollOffset, scrollContainerAPI) {
  'use strict';

  return {
    link : function($scope, $element, $attr) {
      $element.on('click', function(e) {
        if(!$attr.href || $attr.href.indexOf('#') === -1) return;

        var target = document.getElementById($attr.href.replace(/.*(?=#[^\s]+$)/, '').substring(1));
        if(!target || !target.getBoundingClientRect) return;

        if (e.stopPropagation) e.stopPropagation();
        if (e.preventDefault) e.preventDefault();

        var offset    = $attr.offset ? parseInt($attr.offset, 10) : duScrollOffset;
        var duration  = $attr.duration ? parseInt($attr.duration, 10) : duScrollDuration;
        var container = scrollContainerAPI.getContainer($scope);

        container.duScrollToElement(
          angular.element(target),
          isNaN(offset) ? 0 : offset,
          isNaN(duration) ? 0 : duration
        );
      });
    }
  };
}]);


angular.module('duScroll.spyContext', ['duScroll.spyAPI'])
.directive('duSpyContext', ["spyAPI", function(spyAPI) {
  'use strict';

  return {
    restrict: 'A',
    scope: true,
    compile: function compile(tElement, tAttrs, transclude) {
      return {
        pre: function preLink($scope, iElement, iAttrs, controller) {
          spyAPI.createContext($scope);
        }
      };
    }
  };
}]);


angular.module('duScroll.scrollContainer', ['duScroll.scrollContainerAPI'])
.directive('duScrollContainer', ["scrollContainerAPI", function(scrollContainerAPI){
  'use strict';

  return {
    restrict: 'A',
    scope: true,
    compile: function compile(tElement, tAttrs, transclude) {
      return {
        pre: function preLink($scope, iElement, iAttrs, controller) {
          iAttrs.$observe('duScrollContainer', function(element) {
            if(angular.isString(element)) {
              element = document.getElementById(element);
            }

            element = (angular.isElement(element) ? angular.element(element) : iElement);
            scrollContainerAPI.setContainer($scope, element);
            $scope.$on('$destroy', function() {
              scrollContainerAPI.removeContainer($scope);
            });
          });
        }
      };
    }
  };
}]);


angular.module('duScroll.scrollspy', ['duScroll.spyAPI'])
.directive('duScrollspy', ["spyAPI", "duScrollOffset", "$timeout", "$rootScope", function(spyAPI, duScrollOffset, $timeout, $rootScope) {
  'use strict';

  var Spy = function(targetElementOrId, $scope, $element, offset) {
    if(angular.isElement(targetElementOrId)) {
      this.target = targetElementOrId;
    } else if(angular.isString(targetElementOrId)) {
      this.targetId = targetElementOrId;
    }
    this.$scope = $scope;
    this.$element = $element;
    this.offset = offset;
  };

  Spy.prototype.getTargetElement = function() {
    if (!this.target && this.targetId) {
      this.target = document.getElementById(this.targetId);
    }
    return this.target;
  };

  Spy.prototype.getTargetPosition = function() {
    var target = this.getTargetElement();
    if(target) {
      return target.getBoundingClientRect();
    }
  };

  Spy.prototype.flushTargetCache = function() {
    if(this.targetId) {
      this.target = undefined;
    }
  };

  return {
    link: function ($scope, $element, $attr) {
      var href = $attr.ngHref || $attr.href;
      var targetId;

      if (href && href.indexOf('#') !== -1) {
        targetId = href.replace(/.*(?=#[^\s]+$)/, '').substring(1);
      } else if($attr.duScrollspy) {
        targetId = $attr.duScrollspy;
      }
      if(!targetId) return;

      // Run this in the next execution loop so that the scroll context has a chance
      // to initialize
      $timeout(function() {
        var spy = new Spy(targetId, $scope, $element, -($attr.offset ? parseInt($attr.offset, 10) : duScrollOffset));
        spyAPI.addSpy(spy);

        $scope.$on('$destroy', function() {
          spyAPI.removeSpy(spy);
        });
        $scope.$on('$locationChangeSuccess', spy.flushTargetCache.bind(spy));
        $rootScope.$on('$stateChangeSuccess', spy.flushTargetCache.bind(spy));
      }, 0, false);
    }
  };
}]);
// shim layer with setTimeout fallback
// credit Erik Möller and http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
'use strict';

(function() {
    var lastTime = 0;
    var vendors = ['webkit', 'moz'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame =
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame){
        window.requestAnimationFrame = function(callback) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
    }

    if (!window.cancelAnimationFrame){
        window.cancelAnimationFrame = function(id) {
            window.clearTimeout(id);
        };
    }

}());

angular.module('angular-svg-round-progress', []);

'use strict';

angular.module('angular-svg-round-progress').constant('roundProgressConfig', {
    max:            50,
    semi:           false,
    rounded:        false,
    responsive:     false,
    clockwise:      true,
    radius:         100,
    color:          "#45ccce",
    bgcolor:        "#eaeaea",
    stroke:         15,
    iterations:     50,
    animation:      "easeOutCubic"
});

'use strict';

angular.module('angular-svg-round-progress').service('roundProgressService', [function(){
    var service = {};
    var isNumber = angular.isNumber;

    // credits to http://modernizr.com/ for the feature test
    service.isSupported = !!(document.createElementNS && document.createElementNS('http://www.w3.org/2000/svg', "svg").createSVGRect);

    // utility function
    var polarToCartesian = function(centerX, centerY, radius, angleInDegrees) {
        var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;

        return {
            x: centerX + (radius * Math.cos(angleInRadians)),
            y: centerY + (radius * Math.sin(angleInRadians))
        };
    };

    // deals with floats passed as strings
    service.toNumber = function(value){
        return isNumber(value) ? value : parseFloat((value + '').replace(',', '.'));
    };

    // credit to http://stackoverflow.com/questions/5736398/how-to-calculate-the-svg-path-for-an-arc-of-a-circle
    service.updateState = function(val, total, R, ring, size, isSemicircle) {

        if(!size) return ring;

        var value       = val >= total ? total - 0.00001 : val,
            type        = isSemicircle ? 180 : 359.9999,
            perc        = total === 0 ? 0 : (value / total) * type,
            x           = size/2,
            start       = polarToCartesian(x, x, R, perc), // in this case x and y are the same
            end         = polarToCartesian(x, x, R, 0),
            arcSweep    = (perc <= 180 ? "0" : "1"),
            d = [
                "M", start.x, start.y,
                "A", R, R, 0, arcSweep, 0, end.x, end.y
            ].join(" ");

        return ring.attr('d', d);
    };

    // Easing functions by Robert Penner
    // Source: http://www.robertpenner.com/easing/
    // License: http://www.robertpenner.com/easing_terms_of_use.html

    service.animations = {

        // t: Current iteration
        // b: Start value
        // c: Change in value
        // d: Total iterations
        // jshint eqeqeq: false, -W041: true

        linearEase: function(t, b, c, d) {
            return c * t / d + b;
        },

        easeInQuad: function (t, b, c, d) {
            return c*(t/=d)*t + b;
        },

        easeOutQuad: function (t, b, c, d) {
            return -c *(t/=d)*(t-2) + b;
        },

        easeInOutQuad: function (t, b, c, d) {
            if ((t/=d/2) < 1) return c/2*t*t + b;
            return -c/2 * ((--t)*(t-2) - 1) + b;
        },

        easeInCubic: function (t, b, c, d) {
            return c*(t/=d)*t*t + b;
        },

        easeOutCubic: function (t, b, c, d) {
            return c*((t=t/d-1)*t*t + 1) + b;
        },

        easeInOutCubic: function (t, b, c, d) {
            if ((t/=d/2) < 1) return c/2*t*t*t + b;
            return c/2*((t-=2)*t*t + 2) + b;
        },

        easeInQuart: function (t, b, c, d) {
            return c*(t/=d)*t*t*t + b;
        },

        easeOutQuart: function (t, b, c, d) {
            return -c * ((t=t/d-1)*t*t*t - 1) + b;
        },

        easeInOutQuart: function (t, b, c, d) {
            if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
            return -c/2 * ((t-=2)*t*t*t - 2) + b;
        },

        easeInQuint: function (t, b, c, d) {
            return c*(t/=d)*t*t*t*t + b;
        },

        easeOutQuint: function (t, b, c, d) {
            return c*((t=t/d-1)*t*t*t*t + 1) + b;
        },

        easeInOutQuint: function (t, b, c, d) {
            if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
            return c/2*((t-=2)*t*t*t*t + 2) + b;
        },

        easeInSine: function (t, b, c, d) {
            return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
        },

        easeOutSine: function (t, b, c, d) {
            return c * Math.sin(t/d * (Math.PI/2)) + b;
        },

        easeInOutSine: function (t, b, c, d) {
            return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
        },

        easeInExpo: function (t, b, c, d) {
            return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
        },

        easeOutExpo: function (t, b, c, d) {
            return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
        },

        easeInOutExpo: function (t, b, c, d) {
            if (t==0) return b;
            if (t==d) return b+c;
            if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
            return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
        },

        easeInCirc: function (t, b, c, d) {
            return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
        },

        easeOutCirc: function (t, b, c, d) {
            return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
        },

        easeInOutCirc: function (t, b, c, d) {
            if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
            return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
        },

        easeInElastic: function (t, b, c, d) {
            var s=1.70158;var p=0;var a=c;
            if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*0.3;
            if (a < Math.abs(c)) { a=c; s=p/4; }
            else s = p/(2*Math.PI) * Math.asin (c/a);
            return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
        },

        easeOutElastic: function (t, b, c, d) {
            var s=1.70158;var p=0;var a=c;
            if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*0.3;
            if (a < Math.abs(c)) { a=c; s=p/4; }
            else s = p/(2*Math.PI) * Math.asin (c/a);
            return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
        },

        easeInOutElastic: function (t, b, c, d) {
            // jshint eqeqeq: false, -W041: true
            var s=1.70158;var p=0;var a=c;
            if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(0.3*1.5);
            if (a < Math.abs(c)) { a=c; s=p/4; }
            else s = p/(2*Math.PI) * Math.asin (c/a);
            if (t < 1) return -0.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
            return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*0.5 + c + b;
        },

        easeInBack: function (t, b, c, d, s) {
            // jshint eqeqeq: false, -W041: true
            if (s == undefined) s = 1.70158;
            return c*(t/=d)*t*((s+1)*t - s) + b;
        },

        easeOutBack: function (t, b, c, d, s) {
            // jshint eqeqeq: false, -W041: true
            if (s == undefined) s = 1.70158;
            return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
        },

        easeInOutBack: function (t, b, c, d, s) {
            // jshint eqeqeq: false, -W041: true
            if (s == undefined) s = 1.70158;
            if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
            return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
        },

        easeInBounce: function (t, b, c, d) {
            return c - service.animations.easeOutBounce (d-t, 0, c, d) + b;
        },

        easeOutBounce: function (t, b, c, d) {
            if ((t/=d) < (1/2.75)) {
                return c*(7.5625*t*t) + b;
            } else if (t < (2/2.75)) {
                return c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b;
            } else if (t < (2.5/2.75)) {
                return c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b;
            } else {
                return c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b;
            }
        },

        easeInOutBounce: function (t, b, c, d) {
            if (t < d/2) return service.animations.easeInBounce (t*2, 0, c, d) * 0.5 + b;
            return service.animations.easeOutBounce (t*2-d, 0, c, d) * 0.5 + c*0.5 + b;
        }
    };

    return service;
}]);

'use strict';

angular.module('angular-svg-round-progress')
    .directive('roundProgress', ['$window', 'roundProgressService', 'roundProgressConfig', function($window, service, roundProgressConfig){

            var base = {
                restrict: "EA",
                replace: true,
                transclude: true
            };

            if(!service.isSupported){
                return angular.extend(base, {
                    // placeholder element to keep the structure
                    template: '<div class="round-progress" ng-transclude></div>'
                });
            }

            return angular.extend(base, {
                scope:{
                    current:        "=",
                    max:            "=",
                    semi:           "=",
                    rounded:        "=",
                    clockwise:      "=",
                    responsive:     "=",
                    radius:         "@",
                    color:          "@",
                    bgcolor:        "@",
                    stroke:         "@",
                    iterations:     "@",
                    animation:      "@"
                },
                link: function(scope, element){
                    var svg         = angular.element(element[0].querySelector('svg'));
                    var ring        = svg.find('path');
                    var background  = svg.find('circle');
                    var options     = angular.copy(roundProgressConfig);

                    var renderCircle = function(){
                        var isSemicircle     = options.semi;
                        var responsive       = options.responsive;
                        var radius           = parseInt(options.radius) || 0;
                        var stroke           = parseInt(options.stroke);
                        var diameter         = radius*2;
                        var backgroundSize   = radius - (stroke/2);

                        svg.css({
                            "top":          0,
                            "left":         0,
                            "position":     responsive ? "absolute" : "static",
                            "width":        responsive ? "100%" : (diameter + "px"),
                            "height":       responsive ? "100%" : (isSemicircle ? radius : diameter) + "px",
                            "overflow":     "hidden" // on some browsers the background overflows, if in semicircle mode
                        }).attr({
                            viewBox:        "0 0 " + diameter + " " + (isSemicircle ? radius : diameter)
                        });

                        element.css({
                            "width":            responsive ? "100%" : "auto",
                            "position":         "relative",
                            "padding-bottom":   responsive ? (isSemicircle ? "50%" : "100%") : 0
                        });

                        ring.css({
                            "stroke":           options.color,
                            "stroke-width":     stroke,
                            "stroke-linecap":   options.rounded ? "round": "butt"
                        });

                        if(isSemicircle){
                            ring.attr("transform", options.clockwise ? "translate("+ 0 +","+ diameter +") rotate(-90)" : "translate("+ diameter +", "+ diameter +") rotate(90) scale(-1, 1)");
                        }else{
                            ring.attr("transform", options.clockwise ? "" : "scale(-1, 1) translate("+ (-diameter) +" 0)");
                        }

                        background.attr({
                            "cx":           radius,
                            "cy":           radius,
                            "r":            backgroundSize >= 0 ? backgroundSize : 0
                        }).css({
                            "stroke":       options.bgcolor,
                            "stroke-width": stroke
                        });
                    };

                    var renderState = function(newValue, oldValue){
                        var max                 = service.toNumber(options.max || 0);
                        var current             = newValue > max ? max : (newValue < 0 || !newValue ? 0 : newValue);
                        var start               = (oldValue === current || oldValue < 0) ? 0 : (oldValue || 0); // fixes the initial animation
                        var changeInValue       = current - start;

                        var easingAnimation     = service.animations[options.animation];
                        var currentIteration    = 0;
                        var totalIterations     = parseInt(options.iterations);

                        var radius              = options.radius;
                        var circleSize          = radius - (options.stroke/2);
                        var elementSize         = radius*2;

                        (function animation(){
                            service.updateState(
                                easingAnimation(currentIteration, start, changeInValue, totalIterations),
                                max,
                                circleSize,
                                ring,
                                elementSize,
                                options.semi);

                            if(currentIteration < totalIterations){
                                $window.requestAnimationFrame(animation);
                                currentIteration++;
                            }
                        })();
                    };

                    scope.$watchCollection('[current, max, semi, rounded, clockwise, radius, color, bgcolor, stroke, iterations, responsive]', function(newValue, oldValue, scope){

                        // pretty much the same as angular.extend,
                        // but this skips undefined values and internal angular keys
                        angular.forEach(scope, function(value, key){
                            // note the scope !== value is because `this` is part of the scope
                            if(key.indexOf('$') && scope !== value && angular.isDefined(value)){
                                options[key] = value;
                            }
                        });

                        renderCircle();
                        renderState(service.toNumber(newValue[0]), service.toNumber(oldValue[0]));
                    });
                },
                template:[
                    '<div class="round-progress-wrapper">',
                        '<svg class="round-progress" xmlns="http://www.w3.org/2000/svg">',
                            '<circle fill="none"/>',
                            '<path fill="none"/>',
                            '<g ng-transclude></g>',
                        '</svg>',
                    '</div>'
                ].join('\n')
            });

        }]);
!function(e,n,r){"use strict";function t(e,n){return("string"==typeof n||n instanceof String)&&(n=new RegExp(n)),n instanceof RegExp?n.test(e):n&&Array.isArray(n.and)?n.and.every(function(n){return t(e,n)}):n&&Array.isArray(n.or)?n.or.some(function(n){return t(e,n)}):n&&n.not?!t(e,n.not):!1}function o(e,n){return("string"==typeof n||n instanceof String)&&(n=new RegExp(n)),n instanceof RegExp?n.exec(e):n&&Array.isArray(n)?n.reduce(function(n,r){return n?n:o(e,r)},null):null}r&&r.module("reTree",[]).factory("reTree",[function(){return{test:t,exec:o}}]),n&&(n.reTree={test:t,exec:o}),e&&(e.exports={test:t,exec:o})}("undefined"==typeof module?null:module,"undefined"==typeof window?null:window,"undefined"==typeof angular?null:angular);/*global window:false, self:false, define:false, module:false */

/**
 * @license IDBWrapper - A cross-browser wrapper for IndexedDB
 * Copyright (c) 2011 - 2013 Jens Arps
 * http://jensarps.de/
 *
 * Licensed under the MIT (X11) license
 */

(function (name, definition, global) {
  if (typeof define === 'function') {
    define(definition);
  } else if (typeof module !== 'undefined' && module.exports) {
    module.exports = definition();
  } else {
    global[name] = definition();
  }
})('IDBStore', function () {

  'use strict';

  var defaultErrorHandler = function (error) {
    throw error;
  };

  var defaults = {
    storeName: 'Store',
    storePrefix: 'IDBWrapper-',
    dbVersion: 1,
    keyPath: 'id',
    autoIncrement: true,
    onStoreReady: function () {
    },
    onError: defaultErrorHandler,
    indexes: []
  };

  /**
   *
   * The IDBStore constructor
   *
   * @constructor
   * @name IDBStore
   * @version 1.4.1
   *
   * @param {Object} [kwArgs] An options object used to configure the store and
   *  set callbacks
   * @param {String} [kwArgs.storeName='Store'] The name of the store
   * @param {String} [kwArgs.storePrefix='IDBWrapper-'] A prefix that is
   *  internally used to construct the name of the database, which will be
   *  kwArgs.storePrefix + kwArgs.storeName
   * @param {Number} [kwArgs.dbVersion=1] The version of the store
   * @param {String} [kwArgs.keyPath='id'] The key path to use. If you want to
   *  setup IDBWrapper to work with out-of-line keys, you need to set this to
   *  `null`
   * @param {Boolean} [kwArgs.autoIncrement=true] If set to true, IDBStore will
   *  automatically make sure a unique keyPath value is present on each object
   *  that is stored.
   * @param {Function} [kwArgs.onStoreReady] A callback to be called when the
   *  store is ready to be used.
   * @param {Function} [kwArgs.onError=throw] A callback to be called when an
   *  error occurred during instantiation of the store.
   * @param {Array} [kwArgs.indexes=[]] An array of indexData objects
   *  defining the indexes to use with the store. For every index to be used
   *  one indexData object needs to be passed in the array.
   *  An indexData object is defined as follows:
   * @param {Object} [kwArgs.indexes.indexData] An object defining the index to
   *  use
   * @param {String} kwArgs.indexes.indexData.name The name of the index
   * @param {String} [kwArgs.indexes.indexData.keyPath] The key path of the index
   * @param {Boolean} [kwArgs.indexes.indexData.unique] Whether the index is unique
   * @param {Boolean} [kwArgs.indexes.indexData.multiEntry] Whether the index is multi entry
   * @param {Function} [onStoreReady] A callback to be called when the store
   * is ready to be used.
   * @example
      // create a store for customers with an additional index over the
      // `lastname` property.
      var myCustomerStore = new IDBStore({
        dbVersion: 1,
        storeName: 'customer-index',
        keyPath: 'customerid',
        autoIncrement: true,
        onStoreReady: populateTable,
        indexes: [
          { name: 'lastname', keyPath: 'lastname', unique: false, multiEntry: false }
        ]
      });
   * @example
      // create a generic store
      var myCustomerStore = new IDBStore({
        storeName: 'my-data-store',
        onStoreReady: function(){
          // start working with the store.
        }
      });
   */
  var IDBStore = function (kwArgs, onStoreReady) {

    if (typeof onStoreReady == 'undefined' && typeof kwArgs == 'function') {
      onStoreReady = kwArgs;
    }
    if (Object.prototype.toString.call(kwArgs) != '[object Object]') {
      kwArgs = {};
    }

    for (var key in defaults) {
      this[key] = typeof kwArgs[key] != 'undefined' ? kwArgs[key] : defaults[key];
    }

    this.dbName = this.storePrefix + this.storeName;
    this.dbVersion = parseInt(this.dbVersion, 10) || 1;

    onStoreReady && (this.onStoreReady = onStoreReady);

    var env = typeof window == 'object' ? window : self;
    this.idb = env.indexedDB || env.webkitIndexedDB || env.mozIndexedDB;
    this.keyRange = env.IDBKeyRange || env.webkitIDBKeyRange || env.mozIDBKeyRange;

    this.features = {
      hasAutoIncrement: !env.mozIndexedDB
    };

    this.consts = {
      'READ_ONLY':         'readonly',
      'READ_WRITE':        'readwrite',
      'VERSION_CHANGE':    'versionchange',
      'NEXT':              'next',
      'NEXT_NO_DUPLICATE': 'nextunique',
      'PREV':              'prev',
      'PREV_NO_DUPLICATE': 'prevunique'
    };

    this.openDB();
  };

  IDBStore.prototype = /** @lends IDBStore */ {

    /**
     * A pointer to the IDBStore ctor
     *
     * @type IDBStore
     */
    constructor: IDBStore,

    /**
     * The version of IDBStore
     *
     * @type String
     */
    version: '1.4.1',

    /**
     * A reference to the IndexedDB object
     *
     * @type Object
     */
    db: null,

    /**
     * The full name of the IndexedDB used by IDBStore, composed of
     * this.storePrefix + this.storeName
     *
     * @type String
     */
    dbName: null,

    /**
     * The version of the IndexedDB used by IDBStore
     *
     * @type Number
     */
    dbVersion: null,

    /**
     * A reference to the objectStore used by IDBStore
     *
     * @type Object
     */
    store: null,

    /**
     * The store name
     *
     * @type String
     */
    storeName: null,

    /**
     * The key path
     *
     * @type String
     */
    keyPath: null,

    /**
     * Whether IDBStore uses autoIncrement
     *
     * @type Boolean
     */
    autoIncrement: null,

    /**
     * The indexes used by IDBStore
     *
     * @type Array
     */
    indexes: null,

    /**
     * A hashmap of features of the used IDB implementation
     *
     * @type Object
     * @proprty {Boolean} autoIncrement If the implementation supports
     *  native auto increment
     */
    features: null,

    /**
     * The callback to be called when the store is ready to be used
     *
     * @type Function
     */
    onStoreReady: null,

    /**
     * The callback to be called if an error occurred during instantiation
     * of the store
     *
     * @type Function
     */
    onError: null,

    /**
     * The internal insertID counter
     *
     * @type Number
     * @private
     */
    _insertIdCount: 0,

    /**
     * Opens an IndexedDB; called by the constructor.
     *
     * Will check if versions match and compare provided index configuration
     * with existing ones, and update indexes if necessary.
     *
     * Will call this.onStoreReady() if everything went well and the store
     * is ready to use, and this.onError() is something went wrong.
     *
     * @private
     *
     */
    openDB: function () {

      var openRequest = this.idb.open(this.dbName, this.dbVersion);
      var preventSuccessCallback = false;

      openRequest.onerror = function (error) {

        var gotVersionErr = false;
        if ('error' in error.target) {
          gotVersionErr = error.target.error.name == 'VersionError';
        } else if ('errorCode' in error.target) {
          gotVersionErr = error.target.errorCode == 12;
        }

        if (gotVersionErr) {
          this.onError(new Error('The version number provided is lower than the existing one.'));
        } else {
          this.onError(error);
        }
      }.bind(this);

      openRequest.onsuccess = function (event) {

        if (preventSuccessCallback) {
          return;
        }

        if(this.db){
          this.onStoreReady();
          return;
        }

        this.db = event.target.result;

        if(typeof this.db.version == 'string'){
          this.onError(new Error('The IndexedDB implementation in this browser is outdated. Please upgrade your browser.'));
          return;
        }

        if(!this.db.objectStoreNames.contains(this.storeName)){
          // We should never ever get here.
          // Lets notify the user anyway.
          this.onError(new Error('Something is wrong with the IndexedDB implementation in this browser. Please upgrade your browser.'));
          return;
        }

        var emptyTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
        this.store = emptyTransaction.objectStore(this.storeName);

        // check indexes
        var existingIndexes = Array.prototype.slice.call(this.getIndexList());
        this.indexes.forEach(function(indexData){
          var indexName = indexData.name;

          if(!indexName){
            preventSuccessCallback = true;
            this.onError(new Error('Cannot create index: No index name given.'));
            return;
          }

          this.normalizeIndexData(indexData);

          if(this.hasIndex(indexName)){
            // check if it complies
            var actualIndex = this.store.index(indexName);
            var complies = this.indexComplies(actualIndex, indexData);
            if(!complies){
              preventSuccessCallback = true;
              this.onError(new Error('Cannot modify index "' + indexName + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'));
            }

            existingIndexes.splice(existingIndexes.indexOf(indexName), 1);
          } else {
            preventSuccessCallback = true;
            this.onError(new Error('Cannot create new index "' + indexName + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'));
          }

        }, this);

        if (existingIndexes.length) {
          preventSuccessCallback = true;
          this.onError(new Error('Cannot delete index(es) "' + existingIndexes.toString() + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'));
        }

        preventSuccessCallback || this.onStoreReady();
      }.bind(this);

      openRequest.onupgradeneeded = function(/* IDBVersionChangeEvent */ event){

        this.db = event.target.result;

        if(this.db.objectStoreNames.contains(this.storeName)){
          this.store = event.target.transaction.objectStore(this.storeName);
        } else {
          var optionalParameters = { autoIncrement: this.autoIncrement };
          if (this.keyPath !== null) {
            optionalParameters.keyPath = this.keyPath;
          }
          this.store = this.db.createObjectStore(this.storeName, optionalParameters);
        }

        var existingIndexes = Array.prototype.slice.call(this.getIndexList());
        this.indexes.forEach(function(indexData){
          var indexName = indexData.name;

          if(!indexName){
            preventSuccessCallback = true;
            this.onError(new Error('Cannot create index: No index name given.'));
          }

          this.normalizeIndexData(indexData);

          if(this.hasIndex(indexName)){
            // check if it complies
            var actualIndex = this.store.index(indexName);
            var complies = this.indexComplies(actualIndex, indexData);
            if(!complies){
              // index differs, need to delete and re-create
              this.store.deleteIndex(indexName);
              this.store.createIndex(indexName, indexData.keyPath, { unique: indexData.unique, multiEntry: indexData.multiEntry });
            }

            existingIndexes.splice(existingIndexes.indexOf(indexName), 1);
          } else {
            this.store.createIndex(indexName, indexData.keyPath, { unique: indexData.unique, multiEntry: indexData.multiEntry });
          }

        }, this);

        if (existingIndexes.length) {
          existingIndexes.forEach(function(_indexName){
            this.store.deleteIndex(_indexName);
          }, this);
        }

      }.bind(this);
    },

    /**
     * Deletes the database used for this store if the IDB implementations
     * provides that functionality.
     */
    deleteDatabase: function () {
      if (this.idb.deleteDatabase) {
        this.idb.deleteDatabase(this.dbName);
      }
    },

    /*********************
     * data manipulation *
     *********************/

    /**
     * Puts an object into the store. If an entry with the given id exists,
     * it will be overwritten. This method has a different signature for inline
     * keys and out-of-line keys; please see the examples below.
     *
     * @param {*} [key] The key to store. This is only needed if IDBWrapper
     *  is set to use out-of-line keys. For inline keys - the default scenario -
     *  this can be omitted.
     * @param {Object} value The data object to store.
     * @param {Function} [onSuccess] A callback that is called if insertion
     *  was successful.
     * @param {Function} [onError] A callback that is called if insertion
     *  failed.
     * @returns {IDBTransaction} The transaction used for this operation.
     * @example
        // Storing an object, using inline keys (the default scenario):
        var myCustomer = {
          customerid: 2346223,
          lastname: 'Doe',
          firstname: 'John'
        };
        myCustomerStore.put(myCustomer, mySuccessHandler, myErrorHandler);
        // Note that passing success- and error-handlers is optional.
     * @example
        // Storing an object, using out-of-line keys:
       var myCustomer = {
         lastname: 'Doe',
         firstname: 'John'
       };
       myCustomerStore.put(2346223, myCustomer, mySuccessHandler, myErrorHandler);
      // Note that passing success- and error-handlers is optional.
     */
    put: function (key, value, onSuccess, onError) {
      if (this.keyPath !== null) {
        onError = onSuccess;
        onSuccess = value;
        value = key;
      }
      onError || (onError = defaultErrorHandler);
      onSuccess || (onSuccess = noop);

      var hasSuccess = false,
          result = null,
          putRequest;

      var putTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
      putTransaction.oncomplete = function () {
        var callback = hasSuccess ? onSuccess : onError;
        callback(result);
      };
      putTransaction.onabort = onError;
      putTransaction.onerror = onError;

      if (this.keyPath !== null) { // in-line keys
        this._addIdPropertyIfNeeded(value);
        putRequest = putTransaction.objectStore(this.storeName).put(value);
      } else { // out-of-line keys
        putRequest = putTransaction.objectStore(this.storeName).put(value, key);
      }
      putRequest.onsuccess = function (event) {
        hasSuccess = true;
        result = event.target.result;
      };
      putRequest.onerror = onError;

      return putTransaction;
    },

    /**
     * Retrieves an object from the store. If no entry exists with the given id,
     * the success handler will be called with null as first and only argument.
     *
     * @param {*} key The id of the object to fetch.
     * @param {Function} [onSuccess] A callback that is called if fetching
     *  was successful. Will receive the object as only argument.
     * @param {Function} [onError] A callback that will be called if an error
     *  occurred during the operation.
     * @returns {IDBTransaction} The transaction used for this operation.
     */
    get: function (key, onSuccess, onError) {
      onError || (onError = defaultErrorHandler);
      onSuccess || (onSuccess = noop);

      var hasSuccess = false,
          result = null;
      
      var getTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
      getTransaction.oncomplete = function () {
        var callback = hasSuccess ? onSuccess : onError;
        callback(result);
      };
      getTransaction.onabort = onError;
      getTransaction.onerror = onError;
      var getRequest = getTransaction.objectStore(this.storeName).get(key);
      getRequest.onsuccess = function (event) {
        hasSuccess = true;
        result = event.target.result;
      };
      getRequest.onerror = onError;

      return getTransaction;
    },

    /**
     * Removes an object from the store.
     *
     * @param {*} key The id of the object to remove.
     * @param {Function} [onSuccess] A callback that is called if the removal
     *  was successful.
     * @param {Function} [onError] A callback that will be called if an error
     *  occurred during the operation.
     * @returns {IDBTransaction} The transaction used for this operation.
     */
    remove: function (key, onSuccess, onError) {
      onError || (onError = defaultErrorHandler);
      onSuccess || (onSuccess = noop);

      var hasSuccess = false,
          result = null;

      var removeTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
      removeTransaction.oncomplete = function () {
        var callback = hasSuccess ? onSuccess : onError;
        callback(result);
      };
      removeTransaction.onabort = onError;
      removeTransaction.onerror = onError;

      var deleteRequest = removeTransaction.objectStore(this.storeName)['delete'](key);
      deleteRequest.onsuccess = function (event) {
        hasSuccess = true;
        result = event.target.result;
      };
      deleteRequest.onerror = onError;

      return removeTransaction;
    },

    /**
     * Runs a batch of put and/or remove operations on the store.
     *
     * @param {Array} dataArray An array of objects containing the operation to run
     *  and the data object (for put operations).
     * @param {Function} [onSuccess] A callback that is called if all operations
     *  were successful.
     * @param {Function} [onError] A callback that is called if an error
     *  occurred during one of the operations.
     * @returns {IDBTransaction} The transaction used for this operation.
     */
    batch: function (dataArray, onSuccess, onError) {
      onError || (onError = defaultErrorHandler);
      onSuccess || (onSuccess = noop);

      if(Object.prototype.toString.call(dataArray) != '[object Array]'){
        onError(new Error('dataArray argument must be of type Array.'));
      }
      var batchTransaction = this.db.transaction([this.storeName] , this.consts.READ_WRITE);
      batchTransaction.oncomplete = function () {
        var callback = hasSuccess ? onSuccess : onError;
        callback(hasSuccess);
      };
      batchTransaction.onabort = onError;
      batchTransaction.onerror = onError;
      
      var count = dataArray.length;
      var called = false;
      var hasSuccess = false;

      var onItemSuccess = function () {
        count--;
        if (count === 0 && !called) {
          called = true;
          hasSuccess = true;
        }
      };

      dataArray.forEach(function (operation) {
        var type = operation.type;
        var key = operation.key;
        var value = operation.value;

        var onItemError = function (err) {
          batchTransaction.abort();
          if (!called) {
            called = true;
            onError(err, type, key);
          }
        };

        if (type == 'remove') {
          var deleteRequest = batchTransaction.objectStore(this.storeName)['delete'](key);
          deleteRequest.onsuccess = onItemSuccess;
          deleteRequest.onerror = onItemError;
        } else if (type == 'put') {
          var putRequest;
          if (this.keyPath !== null) { // in-line keys
            this._addIdPropertyIfNeeded(value);
            putRequest = batchTransaction.objectStore(this.storeName).put(value);
          } else { // out-of-line keys
            putRequest = batchTransaction.objectStore(this.storeName).put(value, key);
          }
          putRequest.onsuccess = onItemSuccess;
          putRequest.onerror = onItemError;
        }
      }, this);

      return batchTransaction;
    },

    /**
     * Takes an array of objects and stores them in a single transaction.
     *
     * @param {Array} dataArray An array of objects to store
     * @param {Function} [onSuccess] A callback that is called if all operations
     *  were successful.
     * @param {Function} [onError] A callback that is called if an error
     *  occurred during one of the operations.
     * @returns {IDBTransaction} The transaction used for this operation.
     */
    putBatch: function (dataArray, onSuccess, onError) {
      var batchData = dataArray.map(function(item){
        return { type: 'put', value: item };
      });

      return this.batch(batchData, onSuccess, onError);
    },

    /**
     * Takes an array of keys and removes matching objects in a single
     * transaction.
     *
     * @param {Array} keyArray An array of keys to remove
     * @param {Function} [onSuccess] A callback that is called if all operations
     *  were successful.
     * @param {Function} [onError] A callback that is called if an error
     *  occurred during one of the operations.
     * @returns {IDBTransaction} The transaction used for this operation.
     */
    removeBatch: function (keyArray, onSuccess, onError) {
      var batchData = keyArray.map(function(key){
        return { type: 'remove', key: key };
      });

      return this.batch(batchData, onSuccess, onError);
    },

    /**
     * Takes an array of keys and fetches matching objects
     *
     * @param {Array} keyArray An array of keys identifying the objects to fetch
     * @param {Function} [onSuccess] A callback that is called if all operations
     *  were successful.
     * @param {Function} [onError] A callback that is called if an error
     *  occurred during one of the operations.
     * @param {String} [arrayType='sparse'] The type of array to pass to the
     *  success handler. May be one of 'sparse', 'dense' or 'skip'. Defaults to
     *  'sparse'. This parameter specifies how to handle the situation if a get
     *  operation did not throw an error, but there was no matching object in
     *  the database. In most cases, 'sparse' provides the most desired
     *  behavior. See the examples for details.
     * @returns {IDBTransaction} The transaction used for this operation.
     * @example
     // given that there are two objects in the database with the keypath
     // values 1 and 2, and the call looks like this:
     myStore.getBatch([1, 5, 2], onError, function (data) { … }, arrayType);

     // this is what the `data` array will be like:

     // arrayType == 'sparse':
     // data is a sparse array containing two entries and having a length of 3:
       [Object, 2: Object]
         0: Object
         2: Object
         length: 3
         __proto__: Array[0]
     // calling forEach on data will result in the callback being called two
     // times, with the index parameter matching the index of the key in the
     // keyArray.

     // arrayType == 'dense':
     // data is a dense array containing three entries and having a length of 3,
     // where data[1] is of type undefined:
       [Object, undefined, Object]
         0: Object
         1: undefined
         2: Object
         length: 3
         __proto__: Array[0]
     // calling forEach on data will result in the callback being called three
     // times, with the index parameter matching the index of the key in the
     // keyArray, but the second call will have undefined as first argument.

     // arrayType == 'skip':
     // data is a dense array containing two entries and having a length of 2:
       [Object, Object]
         0: Object
         1: Object
         length: 2
         __proto__: Array[0]
     // calling forEach on data will result in the callback being called two
     // times, with the index parameter not matching the index of the key in the
     // keyArray.
     */
    getBatch: function (keyArray, onSuccess, onError, arrayType) {
      onError || (onError = defaultErrorHandler);
      onSuccess || (onSuccess = noop);
      arrayType || (arrayType = 'sparse');

      if(Object.prototype.toString.call(keyArray) != '[object Array]'){
        onError(new Error('keyArray argument must be of type Array.'));
      }
      var batchTransaction = this.db.transaction([this.storeName] , this.consts.READ_ONLY);
      batchTransaction.oncomplete = function () {
        var callback = hasSuccess ? onSuccess : onError;
        callback(result);
      };
      batchTransaction.onabort = onError;
      batchTransaction.onerror = onError;

      var data = [];
      var count = keyArray.length;
      var called = false;
      var hasSuccess = false;
      var result = null;

      var onItemSuccess = function (event) {
        if (event.target.result || arrayType == 'dense') {
          data.push(event.target.result);
        } else if (arrayType == 'sparse') {
          data.length++;
        }
        count--;
        if (count === 0) {
          called = true;
          hasSuccess = true;
          result = data;
        }
      };

      keyArray.forEach(function (key) {

        var onItemError = function (err) {
          called = true;
          result = err;
          onError(err);
          batchTransaction.abort();
        };

        var getRequest = batchTransaction.objectStore(this.storeName).get(key);
        getRequest.onsuccess = onItemSuccess;
        getRequest.onerror = onItemError;

      }, this);

      return batchTransaction;
    },

    /**
     * Fetches all entries in the store.
     *
     * @param {Function} [onSuccess] A callback that is called if the operation
     *  was successful. Will receive an array of objects.
     * @param {Function} [onError] A callback that will be called if an error
     *  occurred during the operation.
     * @returns {IDBTransaction} The transaction used for this operation.
     */
    getAll: function (onSuccess, onError) {
      onError || (onError = defaultErrorHandler);
      onSuccess || (onSuccess = noop);
      var getAllTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
      var store = getAllTransaction.objectStore(this.storeName);
      if (store.getAll) {
        this._getAllNative(getAllTransaction, store, onSuccess, onError);
      } else {
        this._getAllCursor(getAllTransaction, store, onSuccess, onError);
      }

      return getAllTransaction;
    },

    /**
     * Implements getAll for IDB implementations that have a non-standard
     * getAll() method.
     *
     * @param {Object} getAllTransaction An open READ transaction.
     * @param {Object} store A reference to the store.
     * @param {Function} onSuccess A callback that will be called if the
     *  operation was successful.
     * @param {Function} onError A callback that will be called if an
     *  error occurred during the operation.
     * @private
     */
    _getAllNative: function (getAllTransaction, store, onSuccess, onError) {
      var hasSuccess = false,
          result = null;

      getAllTransaction.oncomplete = function () {
        var callback = hasSuccess ? onSuccess : onError;
        callback(result);
      };
      getAllTransaction.onabort = onError;
      getAllTransaction.onerror = onError;

      var getAllRequest = store.getAll();
      getAllRequest.onsuccess = function (event) {
        hasSuccess = true;
        result = event.target.result;
      };
      getAllRequest.onerror = onError;
    },

    /**
     * Implements getAll for IDB implementations that do not have a getAll()
     * method.
     *
     * @param {Object} getAllTransaction An open READ transaction.
     * @param {Object} store A reference to the store.
     * @param {Function} onSuccess A callback that will be called if the
     *  operation was successful.
     * @param {Function} onError A callback that will be called if an
     *  error occurred during the operation.
     * @private
     */
    _getAllCursor: function (getAllTransaction, store, onSuccess, onError) {
      var all = [],
          hasSuccess = false,
          result = null;

      getAllTransaction.oncomplete = function () {
        var callback = hasSuccess ? onSuccess : onError;
        callback(result);
      };
      getAllTransaction.onabort = onError;
      getAllTransaction.onerror = onError;

      var cursorRequest = store.openCursor();
      cursorRequest.onsuccess = function (event) {
        var cursor = event.target.result;
        if (cursor) {
          all.push(cursor.value);
          cursor['continue']();
        }
        else {
          hasSuccess = true;
          result = all;
        }
      };
      cursorRequest.onError = onError;
    },

    /**
     * Clears the store, i.e. deletes all entries in the store.
     *
     * @param {Function} [onSuccess] A callback that will be called if the
     *  operation was successful.
     * @param {Function} [onError] A callback that will be called if an
     *  error occurred during the operation.
     * @returns {IDBTransaction} The transaction used for this operation.
     */
    clear: function (onSuccess, onError) {
      onError || (onError = defaultErrorHandler);
      onSuccess || (onSuccess = noop);

      var hasSuccess = false,
          result = null;

      var clearTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
      clearTransaction.oncomplete = function () {
        var callback = hasSuccess ? onSuccess : onError;
        callback(result);
      };
      clearTransaction.onabort = onError;
      clearTransaction.onerror = onError;

      var clearRequest = clearTransaction.objectStore(this.storeName).clear();
      clearRequest.onsuccess = function (event) {
        hasSuccess = true;
        result = event.target.result;
      };
      clearRequest.onerror = onError;

      return clearTransaction;
    },

    /**
     * Checks if an id property needs to present on a object and adds one if
     * necessary.
     *
     * @param {Object} dataObj The data object that is about to be stored
     * @private
     */
    _addIdPropertyIfNeeded: function (dataObj) {
      if (!this.features.hasAutoIncrement && typeof dataObj[this.keyPath] == 'undefined') {
        dataObj[this.keyPath] = this._insertIdCount++ + Date.now();
      }
    },

    /************
     * indexing *
     ************/

    /**
     * Returns a DOMStringList of index names of the store.
     *
     * @return {DOMStringList} The list of index names
     */
    getIndexList: function () {
      return this.store.indexNames;
    },

    /**
     * Checks if an index with the given name exists in the store.
     *
     * @param {String} indexName The name of the index to look for
     * @return {Boolean} Whether the store contains an index with the given name
     */
    hasIndex: function (indexName) {
      return this.store.indexNames.contains(indexName);
    },

    /**
     * Normalizes an object containing index data and assures that all
     * properties are set.
     *
     * @param {Object} indexData The index data object to normalize
     * @param {String} indexData.name The name of the index
     * @param {String} [indexData.keyPath] The key path of the index
     * @param {Boolean} [indexData.unique] Whether the index is unique
     * @param {Boolean} [indexData.multiEntry] Whether the index is multi entry
     */
    normalizeIndexData: function (indexData) {
      indexData.keyPath = indexData.keyPath || indexData.name;
      indexData.unique = !!indexData.unique;
      indexData.multiEntry = !!indexData.multiEntry;
    },

    /**
     * Checks if an actual index complies with an expected index.
     *
     * @param {Object} actual The actual index found in the store
     * @param {Object} expected An Object describing an expected index
     * @return {Boolean} Whether both index definitions are identical
     */
    indexComplies: function (actual, expected) {
      var complies = ['keyPath', 'unique', 'multiEntry'].every(function (key) {
        // IE10 returns undefined for no multiEntry
        if (key == 'multiEntry' && actual[key] === undefined && expected[key] === false) {
          return true;
        }
        // Compound keys
        if (key == 'keyPath' && Object.prototype.toString.call(expected[key]) == '[object Array]') {
          var exp = expected.keyPath;
          var act = actual.keyPath;

          // IE10 can't handle keyPath sequences and stores them as a string.
          // The index will be unusable there, but let's still return true if
          // the keyPath sequence matches.
          if (typeof act == 'string') {
            return exp.toString() == act;
          }

          // Chrome/Opera stores keyPath squences as DOMStringList, Firefox
          // as Array
          if ( ! (typeof act.contains == 'function' || typeof act.indexOf == 'function') ) {
            return false;
          }

          if (act.length !== exp.length) {
            return false;
          }

          for (var i = 0, m = exp.length; i<m; i++) {
            if ( ! ( (act.contains && act.contains(exp[i])) || act.indexOf(exp[i] !== -1) )) {
              return false;
            }
          }
          return true;
        }
        return expected[key] == actual[key];
      });
      return complies;
    },

    /**********
     * cursor *
     **********/

    /**
     * Iterates over the store using the given options and calling onItem
     * for each entry matching the options.
     *
     * @param {Function} onItem A callback to be called for each match
     * @param {Object} [options] An object defining specific options
     * @param {Object} [options.index=null] An IDBIndex to operate on
     * @param {String} [options.order=ASC] The order in which to provide the
     *  results, can be 'DESC' or 'ASC'
     * @param {Boolean} [options.autoContinue=true] Whether to automatically
     *  iterate the cursor to the next result
     * @param {Boolean} [options.filterDuplicates=false] Whether to exclude
     *  duplicate matches
     * @param {Object} [options.keyRange=null] An IDBKeyRange to use
     * @param {Boolean} [options.writeAccess=false] Whether grant write access
     *  to the store in the onItem callback
     * @param {Function} [options.onEnd=null] A callback to be called after
     *  iteration has ended
     * @param {Function} [options.onError=throw] A callback to be called
     *  if an error occurred during the operation.
     * @returns {IDBTransaction} The transaction used for this operation.
     */
    iterate: function (onItem, options) {
      options = mixin({
        index: null,
        order: 'ASC',
        autoContinue: true,
        filterDuplicates: false,
        keyRange: null,
        writeAccess: false,
        onEnd: null,
        onError: defaultErrorHandler
      }, options || {});

      var directionType = options.order.toLowerCase() == 'desc' ? 'PREV' : 'NEXT';
      if (options.filterDuplicates) {
        directionType += '_NO_DUPLICATE';
      }

      var hasSuccess = false;
      var cursorTransaction = this.db.transaction([this.storeName], this.consts[options.writeAccess ? 'READ_WRITE' : 'READ_ONLY']);
      var cursorTarget = cursorTransaction.objectStore(this.storeName);
      if (options.index) {
        cursorTarget = cursorTarget.index(options.index);
      }

      cursorTransaction.oncomplete = function () {
        if (!hasSuccess) {
          options.onError(null);
          return;
        }
        if (options.onEnd) {
          options.onEnd();
        } else {
          onItem(null);
        }
      };
      cursorTransaction.onabort = options.onError;
      cursorTransaction.onerror = options.onError;

      var cursorRequest = cursorTarget.openCursor(options.keyRange, this.consts[directionType]);
      cursorRequest.onerror = options.onError;
      cursorRequest.onsuccess = function (event) {
        var cursor = event.target.result;
        if (cursor) {
          onItem(cursor.value, cursor, cursorTransaction);
          if (options.autoContinue) {
            cursor['continue']();
          }
        } else {
          hasSuccess = true;
        }
      };

      return cursorTransaction;
    },

    /**
     * Runs a query against the store and passes an array containing matched
     * objects to the success handler.
     *
     * @param {Function} onSuccess A callback to be called when the operation
     *  was successful.
     * @param {Object} [options] An object defining specific query options
     * @param {Object} [options.index=null] An IDBIndex to operate on
     * @param {String} [options.order=ASC] The order in which to provide the
     *  results, can be 'DESC' or 'ASC'
     * @param {Boolean} [options.filterDuplicates=false] Whether to exclude
     *  duplicate matches
     * @param {Object} [options.keyRange=null] An IDBKeyRange to use
     * @param {Function} [options.onError=throw] A callback to be called if an error
     *  occurred during the operation.
     * @returns {IDBTransaction} The transaction used for this operation.
     */
    query: function (onSuccess, options) {
      var result = [];
      options = options || {};
      options.onEnd = function () {
        onSuccess(result);
      };
      return this.iterate(function (item) {
        result.push(item);
      }, options);
    },

    /**
     *
     * Runs a query against the store, but only returns the number of matches
     * instead of the matches itself.
     *
     * @param {Function} onSuccess A callback to be called if the opration
     *  was successful.
     * @param {Object} [options] An object defining specific options
     * @param {Object} [options.index=null] An IDBIndex to operate on
     * @param {Object} [options.keyRange=null] An IDBKeyRange to use
     * @param {Function} [options.onError=throw] A callback to be called if an error
     *  occurred during the operation.
     * @returns {IDBTransaction} The transaction used for this operation.
     */
    count: function (onSuccess, options) {

      options = mixin({
        index: null,
        keyRange: null
      }, options || {});

      var onError = options.onError || defaultErrorHandler;

      var hasSuccess = false,
          result = null;

      var cursorTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
      cursorTransaction.oncomplete = function () {
        var callback = hasSuccess ? onSuccess : onError;
        callback(result);
      };
      cursorTransaction.onabort = onError;
      cursorTransaction.onerror = onError;

      var cursorTarget = cursorTransaction.objectStore(this.storeName);
      if (options.index) {
        cursorTarget = cursorTarget.index(options.index);
      }
      var countRequest = cursorTarget.count(options.keyRange);
      countRequest.onsuccess = function (evt) {
        hasSuccess = true;
        result = evt.target.result;
      };
      countRequest.onError = onError;

      return cursorTransaction;
    },

    /**************/
    /* key ranges */
    /**************/

    /**
     * Creates a key range using specified options. This key range can be
     * handed over to the count() and iterate() methods.
     *
     * Note: You must provide at least one or both of "lower" or "upper" value.
     *
     * @param {Object} options The options for the key range to create
     * @param {*} [options.lower] The lower bound
     * @param {Boolean} [options.excludeLower] Whether to exclude the lower
     *  bound passed in options.lower from the key range
     * @param {*} [options.upper] The upper bound
     * @param {Boolean} [options.excludeUpper] Whether to exclude the upper
     *  bound passed in options.upper from the key range
     * @param {*} [options.only] A single key value. Use this if you need a key
     *  range that only includes one value for a key. Providing this
     *  property invalidates all other properties.
     * @return {Object} The IDBKeyRange representing the specified options
     */
    makeKeyRange: function(options){
      /*jshint onecase:true */
      var keyRange,
          hasLower = typeof options.lower != 'undefined',
          hasUpper = typeof options.upper != 'undefined',
          isOnly = typeof options.only != 'undefined';

      switch(true){
        case isOnly:
          keyRange = this.keyRange.only(options.only);
          break;
        case hasLower && hasUpper:
          keyRange = this.keyRange.bound(options.lower, options.upper, options.excludeLower, options.excludeUpper);
          break;
        case hasLower:
          keyRange = this.keyRange.lowerBound(options.lower, options.excludeLower);
          break;
        case hasUpper:
          keyRange = this.keyRange.upperBound(options.upper, options.excludeUpper);
          break;
        default:
          throw new Error('Cannot create KeyRange. Provide one or both of "lower" or "upper" value, or an "only" value.');
      }

      return keyRange;

    }

  };

  /** helpers **/

  var noop = function () {
  };
  var empty = {};
  var mixin = function (target, source) {
    var name, s;
    for (name in source) {
      s = source[name];
      if (s !== empty[name] && s !== target[name]) {
        target[name] = s;
      }
    }
    return target;
  };

  IDBStore.version = IDBStore.prototype.version;

  return IDBStore;

}, this);
!function(){var module=angular.module("toggle-switch",["ng"]);module.provider("toggleSwitchConfig",[function(){this.onLabel="On",this.offLabel="Off",this.knobLabel=" ";var self=this;this.$get=function(){return{onLabel:self.onLabel,offLabel:self.offLabel,knobLabel:self.knobLabel}}}]),module.directive("toggleSwitch",["toggleSwitchConfig",function(toggleSwitchConfig){return{restrict:"EA",replace:!0,require:"ngModel",scope:{disabled:"@",onLabel:"@",offLabel:"@",knobLabel:"@"},template:'<div role="radio" class="toggle-switch" ng-class="{ \'disabled\': disabled }"><div class="toggle-switch-animate" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="switch-left" ng-bind="onLabel"></span><span class="knob" ng-bind="knobLabel"></span><span class="switch-right" ng-bind="offLabel"></span></div></div>',compile:function(element,attrs){return attrs.onLabel||(attrs.onLabel=toggleSwitchConfig.onLabel),attrs.offLabel||(attrs.offLabel=toggleSwitchConfig.offLabel),attrs.knobLabel||(attrs.knobLabel=toggleSwitchConfig.knobLabel),this.link},link:function(scope,element,attrs,ngModelCtrl){var KEY_SPACE=32;element.on("click",function(){scope.$apply(scope.toggle)}),element.on("keydown",function(e){var key=e.which?e.which:e.keyCode;key===KEY_SPACE&&scope.$apply(scope.toggle)}),ngModelCtrl.$formatters.push(function(modelValue){return modelValue}),ngModelCtrl.$parsers.push(function(viewValue){return viewValue}),ngModelCtrl.$viewChangeListeners.push(function(){scope.$eval(attrs.ngChange)}),ngModelCtrl.$render=function(){scope.model=ngModelCtrl.$viewValue},scope.toggle=function(){scope.disabled||(scope.model=!scope.model,ngModelCtrl.$setViewValue(scope.model))}}}}])}();/**
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

/**
 * Implementing Drag and Drop functionality in AngularJS is easier than ever.
 * Demo: http://codef0rmer.github.com/angular-dragdrop/
 *
 * @version 1.0.13
 *
 * (c) 2013 Amit Gharat a.k.a codef0rmer <amit.2006.it@gmail.com> - amitgharat.wordpress.com
 */

(function (window, angular, $, undefined) {
'use strict';

var jqyoui = angular.module('ngDragDrop', []).service('ngDragDropService', ['$timeout', '$parse', '$q', function($timeout, $parse, $q) {
    this.draggableScope = null;
    this.droppableScope = null;

    $('head').prepend('<style type="text/css">@charset "UTF-8";.angular-dragdrop-hide{display: none !important;}</style>');

    this.callEventCallback = function (scope, callbackName, event, ui) {
      if (!callbackName) return;

      var objExtract = extract(callbackName),
          callback = objExtract.callback,
          constructor = objExtract.constructor,
          args = [event, ui].concat(objExtract.args);
      
      // call either $scoped method i.e. $scope.dropCallback or constructor's method i.e. this.dropCallback.
      // Removing scope.$apply call that was performance intensive (especially onDrag) and does not require it
      // always. So call it within the callback if needed.
      return (scope[callback] || scope[constructor][callback]).apply(scope[callback] ? scope : scope[constructor], args);
      
      function extract(callbackName) {
        var atStartBracket = callbackName.indexOf('(') !== -1 ? callbackName.indexOf('(') : callbackName.length,
            atEndBracket = callbackName.lastIndexOf(')') !== -1 ? callbackName.lastIndexOf(')') : callbackName.length,
            args = callbackName.substring(atStartBracket + 1, atEndBracket), // matching function arguments inside brackets
            constructor = callbackName.indexOf('.') !== -1 ? callbackName.substr(0, callbackName.indexOf('.')) : null; // matching a string upto a dot to check ctrl as syntax
            constructor = scope[constructor] && typeof scope[constructor].constructor === 'function' ? constructor : null;

        return {
          callback: callbackName.substring(constructor && constructor.length + 1 || 0, atStartBracket),
          args: $.map(args && args.split(',') || [], function(item) { return [$parse(item)(scope)]; }),
          constructor: constructor
        }
      }
    };

    this.invokeDrop = function ($draggable, $droppable, event, ui) {
      var dragModel = '',
        dropModel = '',
        dragSettings = {},
        dropSettings = {},
        jqyoui_pos = null,
        dragItem = {},
        dropItem = {},
        dragModelValue,
        dropModelValue,
        $droppableDraggable = null,
        droppableScope = this.droppableScope,
        draggableScope = this.draggableScope,
        $helper = null,
        promises = [],
        temp;

      dragModel = $draggable.ngattr('ng-model');
      dropModel = $droppable.ngattr('ng-model');
      dragModelValue = draggableScope.$eval(dragModel);
      dropModelValue = droppableScope.$eval(dropModel);

      $droppableDraggable = $droppable.find('[jqyoui-draggable]:last,[data-jqyoui-draggable]:last');
      dropSettings = droppableScope.$eval($droppable.attr('jqyoui-droppable') || $droppable.attr('data-jqyoui-droppable')) || [];
      dragSettings = draggableScope.$eval($draggable.attr('jqyoui-draggable') || $draggable.attr('data-jqyoui-draggable')) || [];

      // Helps pick up the right item
      dragSettings.index = this.fixIndex(draggableScope, dragSettings, dragModelValue);
      dropSettings.index = this.fixIndex(droppableScope, dropSettings, dropModelValue);

      jqyoui_pos = angular.isArray(dragModelValue) ? dragSettings.index : null;
      dragItem = angular.isArray(dragModelValue) ? dragModelValue[jqyoui_pos] : dragModelValue;

      if (dragSettings.deepCopy) {
        dragItem = angular.copy(dragItem);
      }

      if (angular.isArray(dropModelValue) && dropSettings && dropSettings.index !== undefined) {
        dropItem = dropModelValue[dropSettings.index];
      } else if (!angular.isArray(dropModelValue)) {
        dropItem = dropModelValue;
      } else {
        dropItem = {};
      }

      if (dropSettings.deepCopy) {
        dropItem = angular.copy(dropItem);
      }

      if (dragSettings.beforeDrop) {
        promises.push(this.callEventCallback(draggableScope, dragSettings.beforeDrop, event, ui));
      }

      $q.all(promises).then(angular.bind(this, function() {
        if (dragSettings.insertInline && dragModel === dropModel) {
          if (dragSettings.index > dropSettings.index) {
            temp = dragModelValue[dragSettings.index];
            for (var i = dragSettings.index; i > dropSettings.index; i--) {
              dropModelValue[i] = angular.copy(dropModelValue[i - 1]);
              dropModelValue[i - 1] = {};
              dropModelValue[i][dragSettings.direction] = 'left';
            }
            dropModelValue[dropSettings.index] = temp;
          } else {
            temp = dragModelValue[dragSettings.index];
            for (var i = dragSettings.index; i < dropSettings.index; i++) {
              dropModelValue[i] = angular.copy(dropModelValue[i + 1]);
              dropModelValue[i + 1] = {};
              dropModelValue[i][dragSettings.direction] = 'right';
            }
            dropModelValue[dropSettings.index] = temp;
          }
          this.callEventCallback(droppableScope, dropSettings.onDrop, event, ui);
        } else if (dragSettings.animate === true) {
          // be nice with absolutely positioned brethren :-)
          $helper = $draggable.clone();
          $helper.css({'position': 'absolute'}).css($draggable.offset());
          $('body').append($helper);
          $draggable.addClass('angular-dragdrop-hide');

          this.move($helper, $droppableDraggable.length > 0 ? $droppableDraggable : $droppable, null, 'fast', dropSettings, function() { $helper.remove(); });
          this.move($droppableDraggable.length > 0 && !dropSettings.multiple ? $droppableDraggable : [], $draggable.parent('[jqyoui-droppable],[data-jqyoui-droppable]'), jqyoui.startXY, 'fast', dropSettings, angular.bind(this, function() {
            $timeout(angular.bind(this, function() {
              // Do not move this into move() to avoid flickering issue
              $draggable.css({'position': 'relative', 'left': '', 'top': ''}).removeClass('angular-dragdrop-hide');
              // Angular v1.2 uses ng-hide to hide an element not display property
              // so we've to manually remove display:none set in this.move()
              $droppableDraggable.css({'position': 'relative', 'left': '', 'top': '', 'display': $droppableDraggable.css('display') === 'none' ? '' : $droppableDraggable.css('display')});

              this.mutateDraggable(draggableScope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable);
              this.mutateDroppable(droppableScope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos);
              this.callEventCallback(droppableScope, dropSettings.onDrop, event, ui);
            }));
          }));
        } else {
          $timeout(angular.bind(this, function() {
            this.mutateDraggable(draggableScope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable);
            this.mutateDroppable(droppableScope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos);
            this.callEventCallback(droppableScope, dropSettings.onDrop, event, ui);
          }));
        }
      })).finally(angular.bind(this, function() {
        this.restore($draggable);
      }));
    };

    this.move = function($fromEl, $toEl, toPos, duration, dropSettings, callback) {
      if ($fromEl.length === 0) {
        if (callback) {
          window.setTimeout(function() {
            callback();
          }, 300);
        }
        return false;
      }

      var zIndex = $fromEl.css('z-index'),
        fromPos = $fromEl[dropSettings.containment || 'offset'](),
        displayProperty = $toEl.css('display'), // sometimes `display` is other than `block`
        hadNgHideCls = $toEl.hasClass('ng-hide'),
        hadDNDHideCls = $toEl.hasClass('angular-dragdrop-hide');

      if (toPos === null && $toEl.length > 0) {
        if (($toEl.attr('jqyoui-draggable') || $toEl.attr('data-jqyoui-draggable')) !== undefined && $toEl.ngattr('ng-model') !== undefined && $toEl.is(':visible') && dropSettings && dropSettings.multiple) {
          toPos = $toEl[dropSettings.containment || 'offset']();
          if (dropSettings.stack === false) {
            toPos.left+= $toEl.outerWidth(true);
          } else {
            toPos.top+= $toEl.outerHeight(true);
          }
        } else {
          // Angular v1.2 uses ng-hide to hide an element 
          // so we've to remove it in order to grab its position
          if (hadNgHideCls) $toEl.removeClass('ng-hide');
          if (hadDNDHideCls) $toEl.removeClass('angular-dragdrop-hide');
          toPos = $toEl.css({'visibility': 'hidden', 'display': 'block'})[dropSettings.containment || 'offset']();
          $toEl.css({'visibility': '','display': displayProperty});
        }
      }

      $fromEl.css({'position': 'absolute', 'z-index': 9999})
        .css(fromPos)
        .animate(toPos, duration, function() {
          // Angular v1.2 uses ng-hide to hide an element
          // and as we remove it above, we've to put it back to
          // hide the element (while swapping) if it was hidden already
          // because we remove the display:none in this.invokeDrop()
          if (hadNgHideCls) $toEl.addClass('ng-hide');
          if (hadDNDHideCls) $toEl.addClass('angular-dragdrop-hide');
          $fromEl.css('z-index', zIndex);
          if (callback) callback();
        });
    };

    this.mutateDroppable = function(scope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos) {
      var dropModelValue = scope.$eval(dropModel);

      scope.dndDragItem = dragItem;

      if (angular.isArray(dropModelValue)) {
        if (dropSettings && dropSettings.index >= 0) {
          dropModelValue[dropSettings.index] = dragItem;
        } else {
          dropModelValue.push(dragItem);
        }
        if (dragSettings && dragSettings.placeholder === true) {
          dropModelValue[dropModelValue.length - 1]['jqyoui_pos'] = jqyoui_pos;
        }
      } else {
        $parse(dropModel + ' = dndDragItem')(scope);
        if (dragSettings && dragSettings.placeholder === true) {
          dropModelValue['jqyoui_pos'] = jqyoui_pos;
        }
      }
    };

    this.mutateDraggable = function(scope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable) {
      var isEmpty = angular.equals(dropItem, {}) || !dropItem,
        dragModelValue = scope.$eval(dragModel);

      scope.dndDropItem = dropItem;

      if (dragSettings && dragSettings.placeholder) {
        if (dragSettings.placeholder != 'keep'){
          if (angular.isArray(dragModelValue) && dragSettings.index !== undefined) {
            dragModelValue[dragSettings.index] = dropItem;
          } else {
            $parse(dragModel + ' = dndDropItem')(scope);
          }
        }
      } else {
        if (angular.isArray(dragModelValue)) {
          if (isEmpty) {
            if (dragSettings && ( dragSettings.placeholder !== true && dragSettings.placeholder !== 'keep' )) {
              dragModelValue.splice(dragSettings.index, 1);
            }
          } else {
            dragModelValue[dragSettings.index] = dropItem;
          }
        } else {
          // Fix: LIST(object) to LIST(array) - model does not get updated using just scope[dragModel] = {...}
          // P.S.: Could not figure out why it happened
          $parse(dragModel + ' = dndDropItem')(scope);
          if (scope.$parent) {
            $parse(dragModel + ' = dndDropItem')(scope.$parent);
          }
        }
      }

      this.restore($draggable);
    };

    this.restore = function($draggable) {
      $draggable.css({'z-index': '', 'left': '', 'top': ''});
    };

    this.fixIndex = function(scope, settings, modelValue) {
      if (settings.applyFilter && angular.isArray(modelValue) && modelValue.length > 0) {
        var dragModelValueFiltered = scope[settings.applyFilter](),
            lookup = dragModelValueFiltered[settings.index],
            actualIndex = undefined;

        modelValue.forEach(function(item, i) {
           if (angular.equals(item, lookup)) {
             actualIndex = i;
           }
        });

        return actualIndex;
      }

      return settings.index;
    };
  }]).directive('jqyouiDraggable', ['ngDragDropService', function(ngDragDropService) {
    return {
      require: '?jqyouiDroppable',
      restrict: 'A',
      link: function(scope, elem, attrs) {
        var element = $(elem);
        var dragSettings, jqyouiOptions, zIndex, killWatcher;
        var updateDraggable = function(newValue, oldValue) {
          if (newValue) {
            dragSettings = scope.$eval(element.attr('jqyoui-draggable') || element.attr('data-jqyoui-draggable')) || {};
            jqyouiOptions = scope.$eval(attrs.jqyouiOptions) || {};
            element
              .draggable({disabled: false})
              .draggable(jqyouiOptions)
              .draggable({
                start: function(event, ui) {
                  ngDragDropService.draggableScope = scope;
                  zIndex = $(jqyouiOptions.helper ? ui.helper : this).css('z-index');
                  $(jqyouiOptions.helper ? ui.helper : this).css('z-index', 9999);
                  jqyoui.startXY = $(this)[dragSettings.containment || 'offset']();
                  ngDragDropService.callEventCallback(scope, dragSettings.onStart, event, ui);
                },
                stop: function(event, ui) {
                  $(jqyouiOptions.helper ? ui.helper : this).css('z-index', zIndex);
                  ngDragDropService.callEventCallback(scope, dragSettings.onStop, event, ui);
                },
                drag: function(event, ui) {
                  ngDragDropService.callEventCallback(scope, dragSettings.onDrag, event, ui);
                }
              });
          } else {
            element.draggable({disabled: true});
          }

          if (killWatcher && angular.isDefined(newValue) && (angular.equals(attrs.drag, 'true') || angular.equals(attrs.drag, 'false'))) {
            killWatcher();
            killWatcher = null;
          }
        };

        killWatcher = scope.$watch(function() { return scope.$eval(attrs.drag); }, updateDraggable);
        updateDraggable();

        element.on('$destroy', function() {
          element.draggable({disabled: true}).draggable('destroy');
        });
      }
    };
  }]).directive('jqyouiDroppable', ['ngDragDropService', '$q', function(ngDragDropService, $q) {
    return {
      restrict: 'A',
      priority: 1,
      link: function(scope, elem, attrs) {
        var element = $(elem);
        var dropSettings, jqyouiOptions, killWatcher;
        var updateDroppable = function(newValue, oldValue) {
          if (newValue) {
            dropSettings = scope.$eval($(element).attr('jqyoui-droppable') || $(element).attr('data-jqyoui-droppable')) || {};
            jqyouiOptions = scope.$eval(attrs.jqyouiOptions) || {};
            element
              .droppable({disabled: false})
              .droppable(jqyouiOptions)
              .droppable({
                over: function(event, ui) {
                  ngDragDropService.callEventCallback(scope, dropSettings.onOver, event, ui);
                },
                out: function(event, ui) {
                  ngDragDropService.callEventCallback(scope, dropSettings.onOut, event, ui);
                },
                drop: function(event, ui) {
                  var beforeDropPromise = null;

                  if (dropSettings.beforeDrop) {
                    beforeDropPromise = ngDragDropService.callEventCallback(scope, dropSettings.beforeDrop, event, ui);
                  } else {
                    beforeDropPromise = (function() {
                      var deferred = $q.defer();
                      deferred.resolve();
                      return deferred.promise;
                    })();
                  }

                  beforeDropPromise.then(angular.bind(this, function() {
                    if ($(ui.draggable).ngattr('ng-model') && attrs.ngModel) {
                      ngDragDropService.droppableScope = scope;
                      ngDragDropService.invokeDrop($(ui.draggable), $(this), event, ui);
                    } else {
                      ngDragDropService.callEventCallback(scope, dropSettings.onDrop, event, ui);
                    }
                  }), function() {
                    ui.draggable.animate({left: '', top: ''}, jqyouiOptions.revertDuration || 0);
                  });
                }
              });
          } else {
            element.droppable({disabled: true});
          }

          if (killWatcher && angular.isDefined(newValue) && (angular.equals(attrs.drop, 'true') || angular.equals(attrs.drop, 'false'))) {
            killWatcher();
            killWatcher = null;
          }
        };

        killWatcher = scope.$watch(function() { return scope.$eval(attrs.drop); }, updateDroppable);
        updateDroppable();
        
        element.on('$destroy', function() {
          element.droppable({disabled: true}).droppable('destroy');
        });
      }
    };
  }]);

  $.fn.ngattr = function(name, value) {
    var element = this[0];

    return element.getAttribute(name) || element.getAttribute('data-' + name);
  };
})(window, window.angular, window.jQuery);
/* global angular */
angular.module('afkl.lazyImage', []);
/* global angular */
angular.module('afkl.lazyImage')
    .service('afklSrcSetService', ['$window', function($window) {
        'use strict';

        /**
         * For other applications wanting the srccset/best image approach it is possible to use this module only
         * Loosely based on https://raw.github.com/borismus/srcset-polyfill/master/js/srcset-info.js
         */
        var INT_REGEXP = /^[0-9]+$/;

        // SRCSET IMG OBJECT
        function ImageInfo(options) {
            this.src = options.src;
            this.w = options.w || Infinity;
            this.h = options.h || Infinity;
            this.x = options.x || 1;
        }

        /**
         * Parse srcset rules
         * @param  {string} descString Containing all srcset rules
         * @return {object}            Srcset rules
         */
        var _parseDescriptors = function (descString) {

            var descriptors = descString.split(/\s/);
            var out = {};

            for (var i = 0, l = descriptors.length; i < l; i++) {

                var desc = descriptors[i];

                if (desc.length > 0) {

                    var lastChar = desc.slice(-1);
                    var value = desc.substring(0, desc.length - 1);
                    var intVal = parseInt(value, 10);
                    var floatVal = parseFloat(value);

                    if (value.match(INT_REGEXP) && lastChar === 'w') {
                        out[lastChar] = intVal;
                    } else if (value.match(INT_REGEXP) && lastChar === 'h') {
                        out[lastChar] = intVal;
                    } else if (!isNaN(floatVal) && lastChar === 'x') {
                        out[lastChar] = floatVal;
                    } 

                }
            }

            return out;

        };

        /**
         * Returns best candidate under given circumstances
         * @param  {object} images     Candidate image
         * @param  {function} criteriaFn Rule
         * @return {object}            Returns best candidate under given criteria
         */
        var _getBestCandidateIf = function (images, criteriaFn) {

            var bestCandidate = images[0];

            for (var i = 0, l = images.length; i < l; i++) {
                var candidate = images[i];
                if (criteriaFn(candidate, bestCandidate)) {
                    bestCandidate = candidate;
                }
            }

            return bestCandidate;

        };

        /**
         * Remove candidate under given circumstances
         * @param  {object} images     Candidate image
         * @param  {function} criteriaFn Rule
         * @return {object}            Removes images from global image collection (candidates)
         */
        var _removeCandidatesIf = function (images, criteriaFn) {

            for (var i = images.length - 1; i >= 0; i--) {
                var candidate = images[i];
                if (criteriaFn(candidate)) {
                    images.splice(i, 1); // remove it
                }
            }

            return images;

        };
      
        /**
        * Direct implementation of "processing the image candidates":
        * http://www.whatwg.org/specs/web-apps/current-work/multipage/embedded-content-1.html#processing-the-image-candidates
        *
        * @param  {array} imageCandidates (required)
        * @param  {object} view (optional)
        * @returns {ImageInfo} The best image of the possible candidates.
        */
        var getBestImage = function (imageCandidates, view) {

            if (!imageCandidates) { return; }
            if (!view) {
                view = {
                    'w' : $window.innerWidth || document.documentElement.clientWidth,
                    'h' : $window.innerHeight || document.documentElement.clientHeight,
                    'x' : $window.devicePixelRatio || 1
                };
            }

            var images = imageCandidates.slice(0);

            /* LARGEST */
            // Width
            var largestWidth = _getBestCandidateIf(images, function (a, b) { return a.w > b.w; });
            // Less than client width.
            _removeCandidatesIf(images, (function () { return function (a) { return a.w < view.w; }; })(this));
            // If none are left, keep the one with largest width.
            if (images.length === 0) { images = [largestWidth]; }


            // Height
            var largestHeight = _getBestCandidateIf(images, function (a, b) { return a.h > b.h; });
            // Less than client height.
            _removeCandidatesIf(images, (function () { return function (a) { return a.h < view.h; }; })(this));
            // If none are left, keep one with largest height.
            if (images.length === 0) { images = [largestHeight]; }

            // Pixel density.
            var largestPxDensity = _getBestCandidateIf(images, function (a, b) { return a.x > b.x; });
            // Remove all candidates with pxdensity less than client pxdensity.
            _removeCandidatesIf(images, (function () { return function (a) { return a.x < view.x; }; })(this));
            // If none are left, keep one with largest pixel density.
            if (images.length === 0) { images = [largestPxDensity]; }


            /* SMALLEST */
            // Width
            var smallestWidth = _getBestCandidateIf(images, function (a, b) { return a.w < b.w; });
            // Remove all candidates with width greater than it.
            _removeCandidatesIf(images, function (a) { return a.w > smallestWidth.w; });

            // Height
            var smallestHeight = _getBestCandidateIf(images, function (a, b) { return a.h < b.h; });
            // Remove all candidates with height greater than it.
            _removeCandidatesIf(images, function (a) { return a.h > smallestHeight.h; });

            // Pixel density
            var smallestPxDensity = _getBestCandidateIf(images, function (a, b) { return a.x < b.x; });
            // Remove all candidates with pixel density less than smallest px density.
            _removeCandidatesIf(images, function (a) { return a.x > smallestPxDensity.x; });

            return images[0];

        };



        // options {src: null/string, srcset: string}
        // options.src    normal url or null
        // options.srcset 997-s.jpg 480w, 997-m.jpg 768w, 997-xl.jpg 1x
        var getSrcset = function (options) {

            var imageCandidates = [];

            var srcValue = options.src;
            var srcsetValue = options.srcset;

            if (!srcsetValue) { return; }

            /* PUSH CANDIDATE [{src: _, x: _, w: _, h:_}, ...] */
            var _addCandidate = function (img) {

                for (var j = 0, ln = imageCandidates.length; j < ln; j++) {
                    var existingCandidate = imageCandidates[j];

                    // DUPLICATE
                    if (existingCandidate.x === img.x &&
                        existingCandidate.w === img.w &&
                        existingCandidate.h === img.h) { return; }
                }

                imageCandidates.push(img);

            };


            var _parse = function () {

                var input = srcsetValue,
                position = 0,
                rawCandidates = [],
                url,
                descriptors;

                while (input !== '') {

                    while (input.charAt(0) === ' ') {
                        input = input.slice(1);
                    }

                    position = input.indexOf(' ');

                    if (position !== -1) {

                        url = input.slice(0, position);

                        // if (url === '') { break; }

                        input = input.slice(position + 1);

                        position = input.indexOf(',');

                        if (position === -1) {
                            descriptors = input;
                            input = '';
                        } else {
                            descriptors =  input.slice(0, position);
                            input = input.slice(position + 1);
                        }

                        rawCandidates.push({
                            url: url,
                            descriptors: descriptors
                        });

                    } else {

                        rawCandidates.push({
                            url: input,
                            descriptors: ''
                        });
                        input = '';
                    }

                }

                // FROM RAW CANDIDATES PUSH IMAGES TO COMPLETE SET
                for (var i = 0, l = rawCandidates.length; i < l; i++) {

                    var candidate = rawCandidates[i],
                    desc = _parseDescriptors(candidate.descriptors);

                    _addCandidate(new ImageInfo({
                        src: candidate.url,
                        x: desc.x,
                        w: desc.w,
                        h: desc.h
                    }));

                }

                if (srcValue) {
                    _addCandidate(new ImageInfo({src: srcValue}));
                }

            };

            _parse();


            // Return best available image for current view based on our list of candidates
            var bestImage = getBestImage(imageCandidates);

            /**
             * Object returning best match at moment, and total collection of candidates (so 'image' API can be used by consumer)
             * @type {Object}
             */
            var object = {
                'best': bestImage,              // IMAGE INFORMATION WHICH FITS BEST WHEN API IS REQUESTED
                'candidates': imageCandidates   // ALL IMAGE CANDIDATES BY GIVEN SRCSET ATTRIBUTES
            };

            // empty collection
            imageCandidates = null;

            // pass best match and candidates
            return object;

        };


        /**
         * PUBLIC API
         */
        return {
            get: getSrcset,        // RETURNS BEST IMAGE AND IMAGE CANDIDATES
            image: getBestImage    // RETURNS BEST IMAGE WITH GIVEN CANDIDATES
        };


    }]);

/* global angular */
angular.module('afkl.lazyImage')
    .directive('afklImageContainer', function () {
        'use strict';

        return {
            restrict: 'A',
            // We have to use controller instead of link here so that it will always run earlier than nested afklLazyImage directives
            controller: ['$scope', '$element', function ($scope, $element) {
                $element.data('afklImageContainer', $element);
            }]
        };
    })
    .directive('afklLazyImage', ['$rootScope', '$window', '$timeout', 'afklSrcSetService', '$parse', function ($rootScope, $window, $timeout, srcSetService, $parse) {
        'use strict';

        // Use srcSetService to find out our best available image
        var bestImage = function (images) {
            var image = srcSetService.get({srcset: images});
            var sourceUrl;
            if (image) {
                sourceUrl = image.best.src;
            }
            return sourceUrl;
        };

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {

                // CONFIGURATION VARS
                var $container = element.inheritedData('afklImageContainer');
                if (!$container) {
                    $container = angular.element(attrs.afklLazyImageContainer || $window);
                }

                var loaded = false;
                var timeout;

                var images = attrs.afklLazyImage; // srcset attributes
                var options = attrs.afklLazyImageOptions ? $parse(attrs.afklLazyImageOptions)(scope) : {}; // options (background, offset)

                var img; // Angular element to image which will be placed
                var currentImage = null; // current image url
                var offset = options.offset ? options.offset : 50; // default offset
                var alt = options.alt ? 'alt="' + options.alt + '"' : 'alt=""';

                var LOADING = 'afkl-lazy-image-loading';

                var IMAGECLASSNAME = 'afkl-lazy-image';
                
                if (options.className) {
                    IMAGECLASSNAME = IMAGECLASSNAME + ' ' + options.className;
                }

                attrs.afklLazyImageLoaded = false;

                var _containerScrollTop = function () {
                    // See if we can use jQuery, with extra check
                    // TODO: check if number is returned
                    if ($container.scrollTop) {
                        var scrollTopPosition = $container.scrollTop();
                        if (scrollTopPosition) {
                            return scrollTopPosition;
                        }
                    }

                    var c = $container[0];
                    if (c.pageYOffset !== undefined) {
                        return c.pageYOffset;
                    }
                    else if (c.scrollTop !== undefined) {
                        return c.scrollTop;
                    }

                    return document.documentElement.scrollTop || 0;
                };

                var _containerInnerHeight = function () {
                    if ($container.innerHeight) {
                        return $container.innerHeight();
                    }

                    var c = $container[0];
                    if (c.innerHeight !== undefined) {
                        return c.innerHeight;
                    } else if (c.clientHeight !== undefined) {
                        return c.clientHeight;
                    }

                    return document.documentElement.clientHeight || 0;
                };

                // Begin with offset and update on resize
                var _elementOffset = function () {
                    if (element.offset) {
                        return element.offset().top;
                    }
                    var box = element[0].getBoundingClientRect();
                    return box.top + _containerScrollTop() - document.documentElement.clientTop;
                };


                var _elementOffsetContainer = function () {
                    if (element.offset) {
                        return element.offset().top - $container.offset().top;
                    }
                    return element[0].getBoundingClientRect().top - $container[0].getBoundingClientRect().top;
                };

                // Update url of our image
                var _setImage = function () {
                    if (options.background) {
                        element[0].style.backgroundImage = 'url("' + currentImage +'")';
                    } else {
                        img[0].src = currentImage;
                    }
                };

                // Append image to DOM
                var _placeImage = function () {

                    loaded = true;
                    // What is my best image available
                    var hasImage = bestImage(images);

                    if (hasImage) {
                        // we have to make an image if background is false (default)
                        if (!options.background) {
                            
                            if (!img) {
                                // element.addClass(LOADING);
                                img = angular.element('<img ' + alt + ' class="' + IMAGECLASSNAME + '"/>');
                                // img.one('load', _loaded);
                                // remove loading class when image is acually loaded
                                element.append(img);
                            }

                        }

                        // set correct src/url
                        _checkIfNewImage();
                    }

                    // Element is added to dom, no need to listen to scroll anymore
                    $container.off('scroll', _onViewChange);

                };

                // Check on resize if actually a new image is best fit, if so then apply it
                var _checkIfNewImage = function () {
                    if (loaded) {
                        var newImage = bestImage(images);
                        if (newImage !== currentImage) {
                            // update current url
                            currentImage = newImage;

                            if (!options.background) {
                                element.addClass(LOADING);
                                img.one('load', _loaded);
                                img.one('error', _error);
                            }
                            
                            // update image url
                            _setImage();
                        }
                    }
                };

                // First update our begin offset
                _checkIfNewImage();

                var _loaded = function () {

                    attrs.$set('afklLazyImageLoaded', 'done');

                    element.removeClass(LOADING);

                };

                var _error = function () {

                    attrs.$set('afklLazyImageLoaded', 'fail');

                };

                // Check if the container is in view for the first time. Utilized by the scroll and resize events.
                var _onViewChange = function () {
                    // only do stuff when not set already
                    if (!loaded) {

                        // Config vars
                        var remaining, shouldLoad, windowBottom;

                        var height = _containerInnerHeight();
                        var scroll = _containerScrollTop();

                        var elOffset = $container[0] === $window ? _elementOffset() : _elementOffsetContainer();
                        windowBottom = $container[0] === $window ? height + scroll : height;

                        remaining = elOffset - windowBottom;

                        // Is our top of our image container in bottom of our viewport?
                        //console.log($container[0].className, _elementOffset(), _elementPosition(), height, scroll, remaining, elOffset);
                        shouldLoad = remaining <= offset;


                        // Append image first time when it comes into our view, after that only resizing can have influence
                        if (shouldLoad) {

                            _placeImage();

                        }

                    }

                };


                // EVENT: RESIZE THROTTLED
                var _onResize = function () {
                    $timeout.cancel(timeout);
                    timeout = $timeout(function() {
                        _checkIfNewImage();
                        _onViewChange();
                    }, 300);
                };


                // Remove events for total destroy
                var _eventsOff = function() {

                    $timeout.cancel(timeout);

                    $container.off('scroll', _onViewChange);
                    angular.element($window).off('resize', _onResize);
                    if ($container[0] !== $window) {
                        $container.off('resize', _onResize);
                    }

                    // remove image being placed
                    if (img) {
                        img.remove();
                    }

                    img = timeout = currentImage = undefined;
                };



                // Set events for scrolling and resizing
                $container.on('scroll', _onViewChange);
                angular.element($window).on('resize', _onResize);

                if ($container[0] !== $window) {
                    $container.on('resize', _onResize);
                }

                // events for image change
                attrs.$observe('afklLazyImage', function () {
                    images = attrs.afklLazyImage;
                    if (loaded) {
                        _placeImage();
                    }
                });

                // Image should be directly placed
                if (options.nolazy) {
                    _placeImage();
                }


                scope.$on('afkl.lazyImage.destroyed', _onResize);

                // Remove all events when destroy takes place
                scope.$on('$destroy', function () {
                    // tell our other kids, i got removed
                    $rootScope.$broadcast('afkl.lazyImage.destroyed');
                    // remove our events and image
                    return _eventsOff();
                });

                return _onViewChange();

            }
        };

}]);
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
var TatooineMode = TatooineMode || {isTestMode: function () {
  'use strict';
  return false;
}};
(function () {
  'use strict';
  /*global IPS */
  /*global TatooineMode */
  /*global annyang */
  /*global tatooine*/
  angular.module('tatooine', ['ui.bootstrap' , 'ngResource', 'ngSanitize', 'ngRoute', 'ngAnimate', 'angular-gestures', 'ngDraggable', 'xeditable',
    'LocalStorageModule', 'angular-intro', 'ng.deviceDetector', 'cfp.hotkeys', 'angular-loading-bar', 'angular.filter', 'toastr', 'duScroll', 'angular-svg-round-progress', 'toggle-switch', 'ngDragDrop', 'afkl.lazyImage'])
    .config([
      '$locationProvider', '$logProvider', 'cfpLoadingBarProvider', 'toastrConfig', 'localStorageServiceProvider', '$tooltipProvider',
      function ($locationProvider, $logProvider, cfpLoadingBarProvider, toastrConfig, localStorageServiceProvider, $tooltipProvider) {


        localStorageServiceProvider.setPrefix('tatooine');
        $locationProvider.html5Mode(true);
        var debugEnabled = window.tatooine.baseConfig.systemStatus === 'develop' || window.tatooine.baseConfig.systemStatus === 'test';
        $logProvider.debugEnabled(debugEnabled);
        cfpLoadingBarProvider.includeSpinner = false;
        toastrConfig.newestOnTop = false;
        toastrConfig.progressBar = true;
        toastrConfig.extendedTimeOut = 3000;
        $tooltipProvider.options({
          placement: 'top',
          animation: true,
          popupDelay: 750,
          appendToBody: false
        });
      }
    ]).run(['$log', '$rootScope', '$window', 'AppConstants', 'AppValues', 'EventConstants', 'OperatorService', 'FontService', 'ProductService', 'editableOptions', 'DeviceDetectionService',
      function initEditor($log, $rootScope, $window, AppConstants, AppValues, EventConstants, OperatorService, FontService, ProductService, editableOptions, DeviceDetectionService) {
        if (!TatooineMode.isTestMode()) {
          AppValues.canvasWidth = Math.min(AppConstants.CANVAS_MAX_WIDTH, Math.round(($window.screen.availWidth - AppConstants.CANVAS_MARGIN_HORIZONTAL) / (1 + 2 * AppConstants.CANVAS_PADDING_PERCENT)));
          editableOptions.theme = 'bs3';
          OperatorService.initOperator().then(function ok() {
            AppValues.doublePagePackageSize = OperatorService.getPagePackageSize() / 2;
            FontService.getFontColors().then(function ok() {
              FontService.getFonts().then(function ok() {
                ProductService.initProducts().then(function ok() {
                  AppValues.headAreaHeight = AppConstants.HEAD_AREA_HEIGHT;
                  var bodyElement = angular.element('body');
                  if (bodyElement) {
                    bodyElement.addClass(DeviceDetectionService.isMobileDevice() ? 'mobile-device' : 'desktop-device');
                  }
                  AppValues.appResourcesLoaded = true;


                });
              });
            });
          });
        }
      }]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Constants for the app and events as well, just inject the constants in your classes
 * @author Sascha Friedrich (sascha.friedrich@cewe.de) */

(function () {
  'use strict';

  angular.module('tatooine').constant('AppConstants', {
    NOTIFICATION_DEFAULT_TIMEOUT: 5000,
    NOTIFICATION_UNLIMITED_TIMEOUT: 14 * 1000 * 60 * 60 * 24,
    EDITOR_IMAGE_TARGET_SIZE_PX: 850,
    IMAGE_ITEM_BOX_DEFAULT_SIZE_PX: 200,
    TEXT_ITEM_BOX_DEFAULT_SIZE_PX: {width: 225, height: 75},
    CLIPART_ITEM_BOX_DEFAULT_SIZE_PX: 150,
    TEXT_ITEM_LINE_HEIGHT: 1.3,
    BACKGROUND_DEFAULT_ID: 201,
    MM_TO_PX: undefined, // gets set during creation of a project to be more product specific
    CANVAS_MAX_WIDTH: 1200,
    CANVAS_PADDING_PERCENT: 0.08,
    CANVAS_MARGIN_HORIZONTAL: 400,
    CANVAS_STORYBOARD_SCALE_FACTOR: 0.4,
    NOT_EDITABLE_PAGES: 2,
    DESIGN_AREAS_ON_PAGE: 2,
    DESIGN_AREAS_ARE_COVER: 1,
    SESSION_TIMEOUT: 20 * 60 * 1000,
    USED_LAYOUT_BY_RANDOM_BUTTON_CHANCE: 1, // 1 = 100%
    HEAD_AREA_HEIGHT: 189,
    TOGGLE_HEAD_AREA_WIDTH: 80,
    TOGGLE_HEAD_AREA_HEIGHT: 38,
    DESIGN_AREA_FLYOUT_WIDTH: 211,
    STORYBOARD_MIN_DESIGN_AREAS_PER_ROW: 2,
    STORYBOARD_MAX_DESIGN_AREAS_PER_ROW: 4,
    STORYBOARD_DESIGN_AREA_MIN_DIMENSION: {width: 250, height: 140},
    DETAIL_DESIGN_AREA_MIN_DIMENSION: {width: 400, height: 300},
    IMAGE_ITEM_QUALITY_RED_SRC: '/web/javax.faces.resource/app/tatooine/images/designArea/ico_warning_Editor.png.jsf',
    PAGEFLIP_COPYRIGHT: 'CEWE',
    PAGEFLIP_KEY: 'ga3/qd2bQbWt1Di8iAAp48Eu$wxwRrLto8FGpGWM4N5sFqSvk8EG4pe/gd',
    INDEXED_DB_IMAGE_STORE_VERSION: 1,
    INDEXED_DB_IMAGE_STORE_EXPIRATION_DAYS: 180,
    INDEXED_DB_IMAGE_STORE_EXPIRATION_ANONYMOUS_DAYS: 2,
    MIN_UNRESERVED_LAYER_INDEX: 5,
    TOOLFRAME_DEFAULT_GAP: 12,
    TOOLFRAME_DEFAULT_COLOR: 'rgba(254, 207, 68, 1)',
    TOOLFRAME_DEFAULT_OPACITY: 1,
    TOOLFRAME_DEFAULT_LINE_WIDTH: 14,
    TOOLFRAME_CONTEXT_MODE_COLOR: 'rgba(254, 207, 68, 1)',
    TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY: 0,
    TOOLFRAME_CONTEXT_MODE_FRAME_OPACITY: 0.5,
    TOOLFRAME_CONTEXT_MODE_LINE_WIDTH: 4,
    TOOLFRAME_DEFAULT_IMAGE_MARGINS: {top: 0, right: 0, bottom: 0, left: 0},
    TOOLFRAME_SWAP_MARKER_COLOR: 'rgba(7, 124, 214, 1)',
    MAGNETIC_LINE_COLOR: 'rgba(0, 148, 220, 1)',
    MAGNETIC_SNAP_DISTANCE: 10,
    MAGNETIC_LINE_WIDTH: 2,
    MYPHTOTOS_API_KEY: '8f7ca5dc2c9f83670a50f141efd136da',
    MYPHOTOS_BASE_URL: 'https://cmp.photoprintit.com/api/2.0/api',
    MYPHOTOS_BASE_URL_TEST: 'https://opstest.photoprintit.com/api/2.0/api',
    MYPHOTOS_BASE_URL_DEV: 'https://opstest.photoprintit.com/api/2.0/api',
    MYPHOTOS_PAGINAGTION_MAX_PHOTOS_ON_SITE: 999,
    MAX_UPLOAD_ATTEMPTS: 3

  });


  angular.module('tatooine').constant('EventConstants', {
    PROJECT_SAVE_IN_PROGRESS: 'projectSaveInProgress',
    PROJECT_SAVED: 'projectSaved',
    PROJECT_SAVE_FAILED: 'projectSaveFailed',
    PROJECT_LOADED: 'projectLoaded',
    PROJECT_TO_SCOPE_NEEDED: 'projectToScopeNeeded',
    DESIGN_AREA_CLICKED: 'designAreaClicked',
    DROPPED_ON_DESIGN_AREA: 'droppedOnDesignArea',
    PHOTO_PREPARED_FOR_AUTO_FILL: 'photoPreparedForAutoFill',
    CONTEXT_PANEL_AREA_SHOW: 'contextPanelAreaShow',
    CONTEXT_PANEL_AREA_HIDE: 'contextPanelAreaHide',
    CONTEXT_PANEL_REMOVE_SETTING: 'contextPanelRemoveSetting',
    CONTEXT_PANEL_CATEGORY_SELECTION_MENU_TOGGLED: 'contextPanelCategorySelectionMenuToggled',
    CONTEXT_PANEL_PHOTO_EFFECT_CLOSED: 'contextPanelPhotoEffectClosed',
    IMAGE_ITEM_CONTENT_MOVE_START: 'imageItemContentMoveStart',
    IMAGE_ITEM_CONTENT_MOVE_END: 'imageItemContentMoveEnd',
    IMAGE_UPLOAD_FAILED: 'imageUploadFailed'
  });


  angular.module('tatooine').value('AppValues', {
    doublePagePackageSize: undefined, // number of design areas in a page package
    designAreaScale: 1,
    headAreaHeight: 189,
    headAreaTop: 0,
    appResourcesLoaded: false,
    layoutSelectionLeftOpen: false,
    layoutSelectionRightOpen: false,
    canvasWidth: 1000,
    nearestPoi: {
      x: undefined,
      y: undefined,
      nearestNeighborX: undefined,
      nearestNeighborY: undefined,
      deltaX: undefined,
      deltaY: undefined
    }
  });


})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Provides basic configuration entries for the whole editor. E.g. the opId or whether some features are enabled.
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('BaseConfigService', [
    '$log', '$window', '$location',
    function ($log, $window, $location) {

      // the code before the return block will be executed only once (as soon as angularJS tries to initially resolve the
      // service instance) and is not part of the created service instance itself.

      var config = {};

      if (!$window.tatooine || !$window.tatooine.baseConfig) {
        $log.error('No base config found! Ensure that the `tatooine.baseConfig` exists as global (in window) variable.');
        return;
      }

      config = $window.tatooine.baseConfig;


      // definition of the public service functions
      var baseConfigService = {

        getOpId: function () {
          return config.opId;
        },

        getLogoutUrl: function () {
          return '/web/' + baseConfigService.getOpId() + '/logout.do';
        },

        getLoginRegisterUrl: function () {
          return '/web/' + baseConfigService.getOpId() + '/loginRegister.do';
        },

        getShoppingCartUrl: function () {
          return '/web/' + baseConfigService.getOpId() + '/orderwizardStartOrder.do';
        },

        getProductIdFromUrl: function () {
          var paramProdcutId = $location.search().productId;

          if (paramProdcutId) {
            paramProdcutId = parseInt(paramProdcutId, 10);
          }

          return paramProdcutId;
        },

        removeProductIdFromUrl: function () {
          $location.search('productId', null);
        },

        getProductOptionStepFromUrl: function () {
          var productOptionStep = $location.search().productOptionStep;
          if (productOptionStep) {
            return productOptionStep;
          }
        },

        removeProductOptionStepFromUrl: function () {
          $location.search('productOptionStep', null);
        },


        getPagesCountFromUrl: function () {
          var paramPagesCount = $location.search().pagesCount;
          if (paramPagesCount) {
            paramPagesCount = parseInt(paramPagesCount, 10);
            if ((paramPagesCount - 26) % 8 !== 0) {
              throw new Error('pages count param must be 26 (+ 8 pages steps)');
            }
          }

          return paramPagesCount ? paramPagesCount : 26;
        },

        getProjectIdFromUrl: function () {
          return $location.search().projectId;
        },

        getAccessCodeFromUrl: function () {
          return $location.search().accessCode;
        },

        hasProjectIdInUrl: function () {
          var projectId = baseConfigService.getProjectIdFromUrl();
          return projectId && projectId > 0;
        },

        hasShowOpenProjectOptionParamInUrl: function () {
          var showOpenProjectOption = $location.search().showOpenProjectOption;
          return showOpenProjectOption === 'true';
        },
        removeShowOpenProjectOptionParamFromUrl: function () {
          $location.search('showOpenProjectOption', null);
        },

        hasOpenMyPhotosDialogParamInUrl: function () {
          var openMyPhotosLogin = $location.search().openMyPhotosLogin;
          return openMyPhotosLogin === 'true';
        },

        removeOpenMyPhotosDialogParamFromUrl: function () {
          $location.search('openMyPhotosLogin', null);
        },

        hasShowUpsellingParamInUrl: function () {
          var us = $location.search().us;
          if (us) {
            return us === 'true';
          }
          return null;
        },


        getShoppingCartItemIdFromUrl: function () {
          return $location.search().sci;
        },

        getIpsAlbumIdFromUrl: function () {
          var paramIpsAlbumId = $location.search().ipsAlbumId;

          if (paramIpsAlbumId) {
            paramIpsAlbumId = parseInt(paramIpsAlbumId, 10);
          }

          return paramIpsAlbumId;
        },

        removeProjectIdFromUrl: function () {
          $location.search('projectId', null);
        },

        removeAccessCodeFromUrl: function () {
          $location.search('accessCode', null);
        },

        hasOpenProjectDialogParamInUrl: function () {
          var paramOpenProjectDialog = $location.search().openProjectDialog;
          if (paramOpenProjectDialog) {
            return paramOpenProjectDialog;
          }
          return false;
        },

        removeOpenProjectDialogParamFromUrl: function () {
          $location.search('openProjectDialog', null);
        },

        hasIpsAlbumIdInUrl: function () {
          var ipsAlbumId = baseConfigService.getIpsAlbumIdFromUrl();
          return ipsAlbumId && ipsAlbumId > 0;
        },

        hasForceLoginInUrl: function () {
          var forceLogin = $location.search().forceLogin;
          return forceLogin === 'true';
        },

        removeForceLoginParamFromUrl: function () {
          $location.search('forceLogin', null);
        },

        getUploadConfig: function () {
          return config.upload;
        },

        isSSOSession: function () {
          return config.isSSOSession;
        },

        getClientVersion: function () {
          // IPS-14712: client version must not be longer than 32 characters
          return config.ipsVersion + '_' + 'tatooine';
        },

        setProjectIdIntoUrl: function (projectId) {
          $location.search('projectId', projectId);
        },

        setAccessCodeIntoUrl: function (accessCode) {
          $location.search('accessCode', accessCode);
        },

        getJSessionId: function () {
          return config.jSessionId;
        },

        isDevelopStatusActive: function () {
          return config.systemStatus === 'develop';
        },

        isTestStatusActive: function () {
          return config.systemStatus === 'test';
        },

        isLiveStatusActive: function () {
          return config.systemStatus === 'live';
        }

      };

      return baseConfigService;
    }

  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive is a UI component that displays compatible IPS color and allows for selecting a color.
 * @author: Frank Bruns (frank.bruns@cewe.de)
 * Date: 10.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwColorChooser', [
    '$log', 'FontService',
    function ($log, FontService) {
      return {
        replace: false,
        scope: {
          onColorSelected: '&onColorSelected',
          preSelectedColor: '=preSelectedColor'
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/common/cwColorChooser.html.jsf',
        link: function (scope, element, attrs) {

          scope.data = {
            supportedColors: undefined,
            selectedColor: scope.preSelectedColor
          };

          var unwatchPreSelectedColor = scope.$watch(function watchPreSelectedColor() {
            return scope.preSelectedColor;
          }, function onPreSelectedColorChanged(newValue) {
            scope.data.selectedColor = newValue;
          });

          scope.$on('$destroy', function destroy() {
            unwatchPreSelectedColor();
          });


          FontService.getFontColors().then(function (colors) {
            scope.data.supportedColors = colors;
          });


          scope.selectColor = function (color) {
            $log.debug('Picked color', color);
            scope.data.selectedColor = color;
            scope.onColorSelected({color: color});
          };
        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Directive which can be used allow for horizontal mouse scrolling.
 * User: Frank Bruns (frank.bruns@cewe.de)
 * Date: 30.09.2014
 */

(function () {
  'use strict';

  angular.module('tatooine').directive('cwHorizontalMouseScroll', [
    '$log',
    function ($log) {
      return {
        restrict: 'A',
        scope: false,
        link: function (scope, element, attrs) {

          var rawElement = element[0];

          var onScroll = function (e) {

            e.preventDefault();

            if (rawElement.scrollWidth > rawElement.offsetWidth) {
              var delta = Math.max(-1, Math.min(1, (e.originalEvent.wheelDelta || -e.originalEvent.detail)));
              if (delta === 1) {
                rawElement.scrollLeft -= parseInt(attrs.cwHorizontalMouseScroll, 10);
              } else if (delta === -1) {
                rawElement.scrollLeft += parseInt(attrs.cwHorizontalMouseScroll, 10);
              }
            }

          };

          element.bind('mousewheel', onScroll);
          element.bind('DOMMouseScroll', onScroll); // for Firefox

          /**
           * If dom-Element is removed, registered events will be removed
           */
          scope.$on('$destroy', function () {
            element.unbind('mousewheel', onScroll);
            element.unbind('DOMMouseScroll', onScroll); // for Firefox
          });
        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Directive which can be used lazily load the next chunk of items when scrolling.
 * User: Frank Bruns (frank.bruns@cewe.de)
 * Date: 29.09.2014
 */

(function () {
  'use strict';

  angular.module('tatooine').directive('cwInfiniteScroll', [
    '$log',
    function ($log) {
      return {
        restrict: 'A',
        scope: {
          scrollDirection: '@scrollDirection', // expected values are 'top-down' or 'left-to-right'
          fetchItems: '&fetchItems'
        },
        link: function (scope, element, attrs) {

          var rawElement = element[0];

          var onScroll = function (e) {

            if (scope.scrollDirection === 'top-down' && rawElement.scrollTop + rawElement.offsetHeight >= rawElement.scrollHeight - 25) {

              // move the scroll bar little bit away from the maximum in order still have some scroll space left
              rawElement.scrollTop = rawElement.scrollHeight - rawElement.offsetHeight - 2;
              scope.$apply(scope.fetchItems);

            } else if (scope.scrollDirection === 'left-to-right' && rawElement.scrollLeft + rawElement.offsetWidth >= rawElement.scrollWidth - 25) {

              // move the scroll bar little bit away from the maximum in order still have some scroll space left
              rawElement.scrollLeft = rawElement.scrollWidth - rawElement.offsetWidth - 2;
              scope.$apply(scope.fetchItems);

            }

          };


          element.bind('scroll', onScroll);

          /**
           * If dom-Element is removed, registered events will be removed
           */
          scope.$on('$destroy', function () {
            element.unbind('scroll', onScroll);
          });
        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Directive which executes a given function on a given key code.
 * User: Silvia, Jan Christian
 * Date: 23.07.13
 * Time: 13:43
 */

(function () {
  'use strict';

  angular.module('tatooine').directive('cwKeyHandler', [
    '$log', '$document', 'SafeApply',
    function ($log, $document, SafeApply) {
      return {
        restrict: 'A',
        scope: {
          cwKeyHandler: '&',
          keyCode: '&',
          namespace: '@'
        },
        link: function (scope, element, attrs) {

          /**
           * Sets namespace per default to global, if no namespace was proviced
           */
          scope.getNameSpace = function() {
            return scope.namespace || 'global';
          };

          /**
           * Binds function to keycode and namespace
           */
          $document.bind('keyup.'+scope.getNameSpace(), function onKeyUp(e) {
            if (e.keyCode === scope.keyCode()) {
              SafeApply.do(function applyKeyPress() {
                scope.cwKeyHandler();
              }, scope);
            }
          });

          /**
           * If dom-Element is removed, registered events will be removed
           */
          scope.$on('$destroy', function() {
            $log.debug('Unbinding event: keyup.'+scope.getNameSpace());
            $document.unbind('keyup.'+scope.getNameSpace());
          });
        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Directive which can be used get informed of size changes of the window during brower resizes.
 *
 * @author: Sascha Friedrich (sascha.friedrich@cewecolor.de)
 * @author: Frank Bruns (frank.bruns@cewe.de)
 * Date: 10.10.2014
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwResizeAware', [
    '$log', '$window', '$timeout',
    function ($log, $window, $timeout) {
      return {
        restrict: 'A',
        scope: {
          onResize: '&onResize' // a function to call back on resize events, will be provided with parameters 'width' and 'height'
        },
        link: function (scope, element, attrs) {

          var callbackDelayTimeout;
          var windowElement = angular.element($window);

          var onResizeHandler = function () {

            if (callbackDelayTimeout) {
              $timeout.cancel(callbackDelayTimeout);
            }

            callbackDelayTimeout = $timeout(function applyDebounced() {
              scope.onResize({
                width: windowElement.width(),
                height: windowElement.height()
              });
            }, 150);

          };

          windowElement.bind('resize', onResizeHandler);

          scope.$on('destroy', function destroy() {
            windowElement.unbind('resize', onResizeHandler);
          });
        }
      };
    }
  ])
  ;
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Directive which can be used to stop the propagation of an event fired on a DOM element to the DOM elements below.
 * Use it on a DOM element like this --> data-cw-stop-event-propagation="[event name]", with [event-name] being 'click', for example
 * User: Frank Bruns (frank.bruns@cewe.de)
 * Date: 23.04.2015
 */

(function () {
  'use strict';

  angular.module('tatooine').directive('cwStopEventPropagation', [
    '$log',
    function ($log) {
      return {
        restrict: 'A',
        scope: false,
        link: function (scope, element, attrs) {

          element.bind(attrs.cwStopEventPropagation, function (e) {
            e.stopPropagation();
          });

        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Directive that parases the price list asterisk text from the tatooineMainLayout.xhtml and put it out at the position the directive was placed.
 *
 * @author: Frank Bruns (frank.bruns@cewe.de)
 * Date: 16.12.2014
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwPriceListInfo', [
    '$log',
    function ($log) {
      return {
        restrict: 'A',
        scope: {},
        replace: true,
        template: '<div class="h6 cewe-price-list-info"></div>',
        link: function (scope, element, attrs) {

          var infoElementRaw = angular.element(document.getElementById('cw_price_info'));
          var wrappedInfoElement = element.html(infoElementRaw.html());
          wrappedInfoElement.find('a').attr('target', '_blank');

          scope.$on('destroy', function destroy() {
            // clean up here if necessary
          });
        }
      };
    }
  ])
  ;
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Simple directive using visibility on objects.
 * ng-show uses 'display: none' and 'display: block' instead
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwVisible', [
    '$log',
    function ($log) {
      return function (scope, element, attr) {
        scope.$watch(attr.cwVisible, function onVisibilityChanged(trueOrFalse) {
          element.css('visibility', trueOrFalse ? 'visible' : 'hidden');
        });
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 *
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('DeviceDetectionService', [
    '$log', 'deviceDetector',
    function ($log, deviceDetector) {

      // definition of the public service functions
      var deviceDetectionService = {

        isWebkitBrowser: function () {
          return deviceDetector.browser === 'chrome' || deviceDetector.browser === 'opera' || deviceDetector.browser === 'safari';
        },

        isBrowserChrome: function () {
          return deviceDetector.browser === 'chrome';
        },

        isBrowserFirefox: function () {
          return deviceDetector.browser === 'firefox';
        },

        isBrowserIE: function () {
          return deviceDetector.browser === 'ie';
        },

        isSupportedFilterBlur: function () {
          return deviceDetectionService.isWebkitBrowser() || deviceDetectionService.isBrowserFirefox();
        },

        isIosDevice: function () {
          return deviceDetector.os === 'ios';
        },


        isMacDevice: function () {
          return deviceDetector.os === 'mac';
        },

        isMobileDevice: function () {
          return deviceDetector.isMobile();
        }

      };

      return deviceDetectionService;

    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Provides a means for safely triggering an apply even when already inside a running apply process.
 * Based on the code found here: https://coderwall.com/p/ngisma
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('SafeApply', [
    '$rootScope', '$log',
    function ($rootScope, $log) {

      // definition of the public service functions
      return {

        /**
         * Performs the given operation function in the specified scope and applies the scope in a safe way, i.e. will
         * not run into errors if already inside an $apply (or $digest) phase.
         * @param operationFn
         * @param $scope (optional) the scope the operation is applied in, will fall back to $rootScope it not specified
         */
        do: function (operationFn, $scope) {

          var scope = $rootScope;
          // if a scope was passed over, we will use that instead of the root scope
          if ($scope) {
            scope = $scope;
          }

          var phase = scope.$$phase;
          //var phase = scope.$root.$$phase;  <-- I think we don't always want to check on the root scope's phase

          if (phase === '$apply' || phase === '$digest') {
            if (operationFn) {
              scope.$eval(operationFn);
            }
          } else {
            if (operationFn) {
              scope.$apply(operationFn);
            } else {
              scope.$digest();
            }
          }
        }

      };

    }

  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 * A utils class. Every project has one ;)
 * Please try to not flood this class with too many functions and think for each new function if you maybe create a new service for it.
 */

(function () {
  'use strict';
  /* global createjs */

  angular.module('tatooine').factory('Utils', [
    '$log', '$q', 'AppConstants',
    function ($log, $q, AppConstants) {

      var textToMeasure = {textContent: null, fontSize: null, fontFamily: null, easelJsText: null};

      // definition of the public service functions
      var utils = {

        /**
         * Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
         *
         * @param min
         * @param max
         * @returns {number} returns a random integer between min and max
         */
        getRandomInt: function (min, max) {
          return Math.floor(Math.random() * (max - min + 1) + min);
        },

        shuffleArray: function (array) {

          for (var i = array.length - 1; i > 0; i--) {

            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;

          }

          return array;
        },


        isInArray: function (array, searchObj) {
          return array.indexOf(searchObj) >= 0;
        },

        /**
         * Removes the specified element from the specified array, if it exists in there.
         * @param {Array} array
         * @param arrayElementToRemove
         */
        removeFromArray: function (array, arrayElementToRemove) {
          if (utils.isInArray(array, arrayElementToRemove)) {
            array.splice(array.indexOf(arrayElementToRemove), 1);
          }
        },

        /**
         * Swaps item positions in the given array
         * @param array the array to swap the positions in
         * @param indexOne index of the first item to swap
         * @param indexTwo index of the second item to swap
         */
        swapArrayPositions: function (array, indexOne, indexTwo) {

          var currentItemAtIndexOne = array[indexOne];
          var currentItemAtIndexTwo = array[indexTwo];

          array[indexOne] = currentItemAtIndexTwo;
          array[indexTwo] = currentItemAtIndexOne;
        },

        calculatedOffsetForVerticalAlign: function (vAlign, textAreaWidth, textAreaHeight, textAreaPadding, text, fontFamily, fontSize) {
          if (vAlign === 'top') {
            return textAreaPadding;
          }


          if (textToMeasure.textContent !== text || textToMeasure.fontSize !== fontSize || textToMeasure.fontFamily !== fontFamily) {

            if (fontFamily.indexOf(' ') && fontFamily.charAt(0) !== '\'') {
              fontFamily = '\'' + fontFamily + '\'';
            }
            textToMeasure.textContent = text;
            textToMeasure.fontSize = fontSize;
            textToMeasure.fontFamily = fontFamily;
            textToMeasure.easelJsText = new createjs.Text(text, fontSize + 'px ' + fontFamily, '#000000');
          }
          textToMeasure.easelJsText.lineWidth = textAreaWidth - 2 * textAreaPadding;
          textToMeasure.easelJsText.lineHeight = Math.round(fontSize * AppConstants.TEXT_ITEM_LINE_HEIGHT);

          if (vAlign === 'middle') {
            return (textAreaHeight - textToMeasure.easelJsText.getMeasuredHeight()) / 2;
          } else {
            return  textAreaHeight - textToMeasure.easelJsText.getMeasuredHeight() - textAreaPadding;
          }
        },

        layerIndexComparator: function compare(itemBoxA, itemBoxB) {
          return itemBoxA.getLayerIndex() - itemBoxB.getLayerIndex();
        },

        unwrapHttpSuccessResponseFn: function () {
          return function ok(response) {
            return response.data;
          };
        },

        createHttpErrorHandlerFn: function (requestName) {
          // this handles the actual error (and knows the name by the closure)
          return function (response) {
            if (response.message && response.name) {
              $log.error('Error for ' + requestName, response);
            } else {
              $log.error('Error for ' + requestName + ', status: ', response.status, ', data: ', (response.data || 'no data'));
            }
            return $q.reject(response);
          };
        },

        getDateForUnixTimeStamp: function (ts) {
          var date = new Date(ts);
          return date.toLocaleDateString();
        }

      };

      return utils;

    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 * Fixes the autofill behaviour.
 * See: http://victorblog.com/2014/01/12/fixing-autocomplete-autofill-on-angularjs-form-submit/
 *
 * @Author: Holger Cremer
 */

(function () {
  'use strict';

  angular.module('tatooine').directive('formAutofillFix', [
    function () {
      return function (scope, elem, attrs) {
        // Fixes Chrome bug: https://groups.google.com/forum/#!topic/angular/6NlucSskQjY
        elem.prop('method', 'POST');

        // Fix autofill issues where Angular doesn't know about autofilled inputs
        if (attrs.ngSubmit) {
          setTimeout(function () {
            elem.unbind('submit').submit(function (e) {
              e.preventDefault();
              elem.find('input, textarea, select').trigger('input').trigger('change').trigger('keydown');
              scope.$apply(attrs.ngSubmit);
            });
          }, 0);
        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Provides a general queue. You can add tasks with 'addTask'.
 */

(function () {
  'use strict';
  angular.module('tatooine').factory('QueueFactory', [
    '$log', 'EventConstants', 'SafeApply',
    function ($log, EventConstants, SafeApply) {

      function Queue() {
        // contains tasks (functions)
        this.content = [];
        this.isRunning = false;
      }

      Queue.prototype = {
        /**
         * @param task a function(next) {...}
         */
        addTask: function (task) {
          this.content.push(task);
          if (!this.isRunning) {
            this.isRunning = true;
            this._process(this.content[0]);
          }
        },

        isQueueRunning: function () {
          return this.isRunning;
        },


        _process: function (task) {
          // calling the task (function) with our next function
          // using the bind function to set the correct 'this' context
          task(this._next.bind(this));
        },

        _next: function () {
          var oldContent = this.content.shift();
          oldContent = null;

          if (this.content.length === 0) { // all tasks were processed

            // call apply to trigger potential watches on the queue state
            var self = this;
            SafeApply.do(function applyQueueStateChange() {
              self.isRunning = false;
            });

            return;
          }

          this._process(this.content[0]);
        }

      };

      // definition of the public factory functions
      return {
        newQueue: function () {
          return new Queue();
        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 *
 * User: Sascha
 * Date: 29.07.13
 * Time: 18:34
 */

(function () {
  'use strict';

  angular.module('tatooine').filter('reverse', [
    '$log',
    function ($log) {
      return function (items) {
        if (!angular.isArray(items)) {
          return false;
        }
        return items.slice().reverse();
      };
    }
  ]);
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 * @author Christoph Suhren
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('LeaveEditorService', [
    '$log', '$q', '$window', '$timeout', '$location', '$modal', 'BaseConfigService', 'OperatorService', 'UploadService', 'MessageService',
    function ($log, $q, $window, $timeout, $location, $modal, BaseConfigService, OperatorService, UploadService, MessageService) {

      // definition of the public service functions
      var leaveEditorService = {
        leaveActive: false,

        changeLocationTo: function (targetUrl) {
          leaveEditorService.setLeaveActive();
          $window.location.href = targetUrl;
        },

        reloadEditorWithProject: function (projectId) {
          $log.debug('reload editor with projectId' + projectId);
          BaseConfigService.removeShowOpenProjectOptionParamFromUrl();
          BaseConfigService.setProjectIdIntoUrl(projectId);
          leaveEditorService.setLeaveActive();
          $timeout(function () {
            $window.location.reload();
          }, 400);
        },

        /**
         *
         * @param additionalTargetPageParameters these parameters will be added to the targetPage used after (potential) SSO login
         * @param alternativeTargetPage allows to define an alternative targetPage that is used after (potential) SSO login,
         *  the default targetPage is the current (editor) page
         */
        handleSsoLogin: function (additionalTargetPageParameters, alternativeTargetPage) {
          if (!BaseConfigService.isSSOSession()) {
            $log.error('This is not an SSO session. Aborting SSO login.');
            return;
          }
          leaveEditorService.setLeaveActive();
          var targetPage = alternativeTargetPage ? alternativeTargetPage : $location.absUrl();
          if (additionalTargetPageParameters) {
            var indexOfQuestionMark = targetPage.indexOf('?');
            angular.forEach(additionalTargetPageParameters, function (value, key) {
              if (indexOfQuestionMark < 0) {
                targetPage += '?' + key + '=' + value;
              } else {
                targetPage = targetPage.substring(0, indexOfQuestionMark + 1) + key + '=' + value + '&' + targetPage.substring(indexOfQuestionMark + 1);
              }
            });
          }
          leaveEditorService.changeLocationTo(BaseConfigService.getLoginRegisterUrl() + '?targetpage=' + encodeURIComponent(targetPage));
        },

        getWindowUnloadMessage: function (project) {
          if (this.leaveActive || !project) {
            return undefined;
          }

          if (project.hasUnsavedChanges()) {
            return MessageService.getMessage('leaveEditor.hintUnsavedChanges');
          }

          var numberOfUntransferredFiles = UploadService.getRemainingFileHandles().length;
          if (numberOfUntransferredFiles > 0) {
            return MessageService.getMessage('leaveEditor.hintUploadInProgress', [numberOfUntransferredFiles]);
          }
        },

        setLeaveActive: function () {
          this.leaveActive = true;
        }
      };
      return leaveEditorService;
    }
  ])
  ;
})
();
/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 * @author Christoph Suhren
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('HeadAreaToggleService', [
    '$log', '$window', '$document', 'AppConstants', 'AppValues', 'ProjectService',
    function ($log, $window, $document, AppConstants, AppValues, ProjectService) {

      var MAXIMZED_POSITION = 0;
      var MINIMIZED_POSITION = -135;

      var setHeadAreaPosition = function (headAreaTopPosition) {

        AppValues.headAreaTop = headAreaTopPosition;
        AppValues.headAreaHeight = AppConstants.HEAD_AREA_HEIGHT + headAreaTopPosition;

        var project = ProjectService.getProject();
        if (project.isDetailView()) {
          var designArea = project.getSelectedDesignArea();
          var windowElement = angular.element($window);
          designArea.fitToDimensions(windowElement.width() - 2 * AppConstants.DESIGN_AREA_FLYOUT_WIDTH,
            windowElement.height() - (AppValues.headAreaHeight + AppConstants.TOGGLE_HEAD_AREA_HEIGHT) - 85);
        }
      };

      // definition of the public service functions
      var headAreaToggleService = {

        toggleHeadArea: function () {
          if (AppValues.headAreaTop === 0) {
            headAreaToggleService.minimizeHeadArea();
          } else {
            headAreaToggleService.maximizeHeadArea();
          }
        },

        maximizeHeadArea: function () {
          setHeadAreaPosition(MAXIMZED_POSITION);
        },

        minimizeHeadArea: function () {
          setHeadAreaPosition(MINIMIZED_POSITION);
        }

      };
      return headAreaToggleService;
    }
  ])
  ;
})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A toogle button that can switch between two states (on/off)
 *
 * @since 16.04.2014
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwToggleButton', [
    '$log',
    function ($log) {

      return {
        restrict: 'A',
        scope: {
          toggleState: '=toggleState', // passed in value should be 'true' or 'false' (true = on, false = off)
          toggleOn: '&toggleOn', // a method should be passed in
          toggleOff: '&toggleOff' // a method should be passed in
        },
        transclude: true,
        replace: true,
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/common/buttons/cwToggleButton.html.jsf',
        link: function(scope, element, attrs) {

          var watchDeleteHandle = scope.$watch('scope.toggleState', function onToggleStateChange(newValue, oldValue) {
            if (newValue !== oldValue) {
              scope.toggle();
            }
          });

          scope.$on('$destroy', function destroy() {
            watchDeleteHandle();
          });

          scope.toggle = function () {

            scope.toggleState = !scope.toggleState;

            if (scope.toggleState) {
              scope.toggleOn();

            } else {
              scope.toggleOff();
            }

          };
        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A button that has a big headline text and a subline text below it.
 *
 * @since 15.09.2014
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwMultiLineButton', [
    '$log',
    function ($log) {

      return {
        restrict: 'A',
        scope: {
          iconClass: '@iconClass', // passed in value should be a CSS class that represents an icon
          headline: '@headline', // the button's headline text (the main button text)
          subline: '@subline' // the buttons subline text (the smaller line under the headline)
        },
        transclude: false,
        replace: true,
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/common/buttons/cwMultiLineButton.html.jsf',
        link: function (scope, element, attrs) {

          // currently nothing to do here

        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A button for a side menu
 *
 * @since 09.10.2014
 * @author Frank Bruns (frank.bruns@cewe.de)
 * @author Sascha Friedrich
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwOptionsMenuButton', [
    '$log', '$window', '$modal', 'EventConstants', 'ProjectService', 'ProductService', 'MessageService', 'GuidedTourService', 'BaseConfigService',
    'FileHandleService', 'AuthenticationService', 'LeaveEditorService', 'TrackingService',
    function ($log, $window, $modal, EventConstants, ProjectService, ProductService, MessageService, GuidedTourService, BaseConfigService, FileHandleService, AuthenticationService, LeaveEditorService, TrackingService) {

      return {
        restrict: 'A',
        scope: {
        },
        transclude: false,
        replace: true,
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/common/buttons/cwOptionsMenuButton.html.jsf',
        link: function (scope, element, attrs) {

          var optionsMenuButtonTopValue = (element.children()[0].getBoundingClientRect());
          scope.optionsMenuContentTopValue = optionsMenuButtonTopValue + 200;
          scope.isMenuActive = false;
          scope.data = {};


          var project = ProjectService.getProject();
          if (project.isMagneticLinesActive()) {
            scope.data.magneticLineStatus = project.isMagneticLinesActive();
          }


          var magnetLineStatusWatch = scope.$watch(function watchMagnetLineStatus() {
            return scope.data.magneticLineStatus;
          }, function onStatusChanged(newValue, oldValue) {
            project.setMagneticLinesActive(newValue);
            if (newValue && oldValue === false) {
              TrackingService.trackByContextData(TrackingService.TRACKING_KEY_BUTTONS, 'button.magneticLines.activated', 'button.magneticLines.activated');
            } else if (newValue === false && oldValue === true) {
              TrackingService.trackByContextData(TrackingService.TRACKING_KEY_BUTTONS, 'button.magneticLines.deactivated', 'button.magneticLines.deactivated');
            }


          });

          scope.openOptionsMenu = function () {
            var selectedDesignArea = ProjectService.getProject().getSelectedDesignArea();
            if (selectedDesignArea) {
              var selectedItemBox = selectedDesignArea.getSelectedItemBox();
              if (selectedItemBox) {
                selectedItemBox.setSelected(false);
              }
            }
          };

          scope.closeOptionsMenu = function () {
            scope.isMenuActive = false;
          };

          var projectChangedWatch = scope.$watch(function watchProjectChanged() {
            return ProjectService.getProject().getId();
          }, function onProjectIdChanged(newValue, oldValue) {
            if (newValue && oldValue) {
              scope.projectTitle = ProjectService.getProject().getTitle();
              scope.noTitle = MessageService.getMessage('navigation.optionsMenu.noTitle');
            }
          });

          scope.updateTitle = function (data) {
            ProjectService.getProject().setTitle(data);
            ProjectService.getProject().setUnsavedChanges(true);
          };

          scope.startGuidedTour = function () {
            scope.closeOptionsMenu();
            var project = ProjectService.getProject();
            if (project.isDetailView()) {
              GuidedTourService.startTour('detailView', 1);
            } else {
              ProjectService.getProject().setSelectedDesignElementTabIndex(0);
              GuidedTourService.startTour('initialIntroduction', 1);
            }
          };


          scope.openProjectClicked = function () {
            scope.closeOptionsMenu();
            ProjectService.isSaveProjectNeeded().then(function ok(saveProject) {
              ProjectService.handleOpenMyProjects(saveProject).then(function ok(response) {
                if (response) {
                  LeaveEditorService.reloadEditorWithProject(response.id);
                }
              });
            });
          };

          scope.$on('$destroy', function destroy() {
            projectChangedWatch();
            // magnetLineStatusWatch();
          });


        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A button to change the product
 *
 * @since 04.06.2015
 * @author Sascha Friedrich
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwProductOptionsButton', [
    '$log', '$timeout', '$modal', 'AppConstants', 'ProductService', 'ProjectService', 'UndoRedoService', 'NotificationService', 'MessageService',
    function ($log, $timeout, $modal, AppConstants, ProductService, ProjectService, UndoRedoService, NotificationService, MessageService) {

      return {
        restrict: 'A',
        scope: {

        },
        transclude: false,
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/common/buttons/cwProductOptionsButton.html.jsf',
        link: function (scope, element, attrs) {


          scope.openProductOptionDialog = function () {
            var dialogPassThrough = {
              caller: 'productOptionButton',
              productId: ProjectService.getProject().getProductId(),
              pagesCount: ProjectService.getProject().getPagesCount()
            };


            var modalProductOptionDialogLightbox = $modal.open({
              scope: scope,
              size: 'lg',
              backdrop: true,
              windowClass: 'product-options-dialog',
              templateUrl: 'productOptionDialog.html',
              controller: 'InitialChoiceLightboxController',
              resolve: {
                passThrough: function () {
                  return dialogPassThrough;
                }
              }
            });

            /**
             *  Handle the result of the modal lightbox
             * */
            modalProductOptionDialogLightbox.result.then(function (dialogData) {
              /*
               the modal dialog is closed here, we got the user choices in the dialogData object
               */
              var calledProductId = null;
              angular.forEach(dialogData, function (value, key) {
                if (key === 'productId') {
                  calledProductId = value;
                }
              });
              $log.debug('calledProductId', calledProductId);
              var undoHandle = UndoRedoService.pushProject();
              ProjectService.changeProjectProduct(calledProductId).then(function () {
                undoHandle.resolve();
              });
              updateProductName(ProjectService.getProject().getProductId());
              var calledProduct = ProductService.getProductById(calledProductId);
              NotificationService.addNotification('', MessageService.getMessage('notification.productOption.changeProduct.newProduct', [calledProduct.getName()]), 'info', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
            });
          };

          var deleteProductIdWatch = scope.$watch(function watchProductId() {
            return ProjectService.getProject().getProductId();
          }, function productIdWatch(newValue, oldValue) {
            updateProductName(newValue);
          });


          function updateProductName(productId) {
            var chosenProduct = ProductService.getProductById(productId);
            if (chosenProduct) {
              scope.productName = chosenProduct.name;
            } else {
              scope.productName = 'n./a.';
            }
          }

          scope.$on('$destroy', function destroy() {
            deleteProductIdWatch();
          });
        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A button to add a textitemBox
 *
 * @since 04.06.2015
 * @author Sascha Friedrich
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwAddTextBoxButton', [
    '$log', '$window', '$timeout', 'AppConstants', 'ProjectService', 'DesignAreaService', 'FontService', 'MessageService', 'UndoRedoService', 'TextItemTemplateFactory',
    function ($log, $window, $timeout, AppConstants, ProjectService, DesignAreaService, FontService, MessageService, UndoRedoService, TextItemTemplateFactory) {

      return {
        restrict: 'A',
        scope: {
          pageHalf: '@pageHalf'
        },
        transclude: false,
        replace: true,
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/common/buttons/cwAddTextBoxButton.html.jsf',
        link: function (scope, element, attrs) {

          var font;
          var standardTextItemTemplate;
          var offset = 0;


          FontService.getFonts().then(function (fonts) {
            font = fonts[3]; // Arezzo
            // for demo reasons we do some variations for the styling values
            var bgColor = 'none';
            var textColor = '#000000';
            var textAnchor = 'start';
            var fontStyle = 'normal';
            var fontWeight = 'normal';
            var textDecoration = 'none';
            var padding = '5pt';
            var verticalAlign = 'top';
            var placeholderText = MessageService.getMessage('project.textItem.placeholderText');
            standardTextItemTemplate = TextItemTemplateFactory.createTextItemTemplate('AaBbCc', placeholderText, textAnchor, textColor, bgColor, font, 22,
              fontStyle, fontWeight, textDecoration, padding, verticalAlign);
          });

          scope.isDetailView = function () {
            var project = ProjectService.getProject();
            if (project) {
              return project.isDetailView();
            }
          };

          scope.addTextBox = function () {
            var lastUsedTextItemTemplates = ProjectService.getProject().getUserTextItemTemplates();
            var lastUsedTextItemTemplate = lastUsedTextItemTemplates[lastUsedTextItemTemplates.length - 1];
            var selectedDesignArea = ProjectService.getSelectedDesignArea();
            var undoHandle = UndoRedoService.pushModelData(selectedDesignArea);
            $timeout(function () {
              var centerX = offset + Math.round(selectedDesignArea.getWidth() / 2 - 1);
              var centerY = offset + Math.round(selectedDesignArea.getHeight() / 2);
              if (selectedDesignArea.isLeftPageBlocked()) {
                centerX += Math.round(selectedDesignArea.getWidth() / 4);
              } else if (selectedDesignArea.isRightPageBlocked()) {
                centerX -= Math.round(selectedDesignArea.getWidth() / 4);
              }
              var newTextBox = DesignAreaService.addTextItem(lastUsedTextItemTemplate ? lastUsedTextItemTemplate : standardTextItemTemplate, selectedDesignArea, centerX, centerY, false);
              newTextBox.setSelected(true);
              offset = (offset + 20) % 100;
              undoHandle.resolve();
            });
          };

          scope.$on('$destroy', function destroy() {
          });


        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive represents the basic container area for all different kinds of Tatooine's context panels.
 * @author Frank Bruns (frank.bruns@cewe.de)
 * Date: 03.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwContextPanelArea', [
    '$log', '$rootScope', 'EventConstants', 'BaseConfigService', 'ContextPanelAreaService', 'ProjectService', 'TextItemFactory', 'ImageItemFactory',
    function ($log, $rootScope, EventConstants, BaseConfigService, ContextPanelAreaService, ProjectService, TextItemFactory, ImageItemFactory) {
      return {
        replace: true,
        scope: {
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/contextpanels/cwContextPanelArea.html.jsf',
        link: function (scope, element, attrs) {

          // watch the currently selected item box to activate the suitable context panel area configuration or hide the context panel area instead
          var unregisterSelectedItemWatch = scope.$watch(function watchSelectedItem() {
                var designArea = ProjectService.getSelectedDesignArea();
                if (designArea) {
                  return designArea.getSelectedItemBox();
                }
              }, function onSelectedItemChanged(newValue) {

                var contextPanelAreaConfig = ContextPanelAreaService.getContextPanelAreaConfigByItemBox(newValue);

                if (newValue && contextPanelAreaConfig && contextPanelAreaConfig.available) {
                  // selected ItemBox changed, update context panel configuration
                  ContextPanelAreaService.setContextPanelAreaConfigByItemBox(newValue);

                  if (newValue instanceof TextItemFactory.getClass()) {
                    ContextPanelAreaService.setColorForBackgroundColorTab(newValue.getBackgroundColor());
                    ContextPanelAreaService.setColorForFontColorTab(newValue.getTextColor());
                  }

                  if (newValue instanceof ImageItemFactory.getClass()) {
                    if (newValue.getBorderWidth() > 0) {
                      ContextPanelAreaService.setColorForColoredBordersTab(newValue.getBorderColor());
                    } else {
                      ContextPanelAreaService.setColorForColoredBordersTab('none');
                    }
                  }

                } else {
                  var panelName = ContextPanelAreaService.getSelectedContextPanel().name;
                  if (panelName === 'photo-effects') {
                    $log.debug('fire event', EventConstants.CONTEXT_PANEL_PHOTO_EFFECT_CLOSED);
                    $rootScope.$broadcast(EventConstants.CONTEXT_PANEL_PHOTO_EFFECT_CLOSED, panelName);
                  }
                  ContextPanelAreaService.setContextPanelAreaVisible(false);
                }

              }
            )
            ;

          scope.$on('$destroy', function destroy(e) {
            unregisterSelectedItemWatch();
          });

          scope.$on(EventConstants.CONTEXT_PANEL_CATEGORY_SELECTION_MENU_TOGGLED, function handleRemoveSettingEvent(e, menuOpened) {
            $log.debug('receive event', EventConstants.CONTEXT_PANEL_CATEGORY_SELECTION_MENU_TOGGLED, menuOpened);
            ContextPanelAreaService.setCssZIndex(menuOpened ? 1040 : 10);
          });

          scope.getCurrentContextPanelAreaName = function () {
            return ContextPanelAreaService.getCurrentContextPanelAreaConfig().name;
          };

          scope.getCurrentContextPanelSet = function () {
            return ContextPanelAreaService.getCurrentContextPanelAreaConfig().panels;
          };

          scope.selectContextPanel = function (panelName) {
            ContextPanelAreaService.selectContextPanel(panelName);
          };

          scope.getSelectedContextPanel = function () {
            return ContextPanelAreaService.getSelectedContextPanel();
          };

          scope.isContextPanelAreaVisible = function() {
            return ContextPanelAreaService.isContextPanelAreaVisible();
          };

          scope.close = function () {
            ContextPanelAreaService.setContextPanelAreaVisible(false);
          };

        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive is meant to be used as the button menu to close the context panel area or remove the selected item property.
 * @author Frank Bruns (frank.bruns@cewe.de)
 * @author Sascha Friedrich
 * Date: 10.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwContextPanelAreaButtonMenu', [
    '$log', '$rootScope', 'EventConstants', 'ContextPanelAreaService',
    function ($log, $rootScope, EventConstants, ContextPanelAreaService) {
      return {
        replace: true,
        scope: {
          showButtonRemove: '=showButtonRemove'
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/contextpanels/cwContextPanelAreaButtonMenu.html.jsf',
        link: function (scope, element, attrs) {

          scope.removeSetting = function () {
            var panelName = ContextPanelAreaService.getSelectedContextPanel().name;
            $log.debug('fire event', EventConstants.CONTEXT_PANEL_REMOVE_SETTING);
            $rootScope.$broadcast(EventConstants.CONTEXT_PANEL_REMOVE_SETTING, panelName);
          };

          scope.close = function () {

            var panelName = ContextPanelAreaService.getSelectedContextPanel().name;
            if (panelName === 'photo-effects') {
              $log.debug('fire event', EventConstants.CONTEXT_PANEL_PHOTO_EFFECT_CLOSED);
              $rootScope.$broadcast(EventConstants.CONTEXT_PANEL_PHOTO_EFFECT_CLOSED, panelName);
            }

            ContextPanelAreaService.setContextPanelAreaVisible(false);
            ContextPanelAreaService.setImageItemBoxesContextView(false);
          };

        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Provides a service for some basic interaction with the context panel area.
 * @author Frank Bruns (frank.bruns@cewe.de)
 * Date: 04.08.2015
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('ContextPanelAreaService', [
    '$log', 'BaseConfigService', 'ProjectService', 'MessageService', 'UndoRedoService', 'HeadAreaToggleService', 'ImageItemFactory', 'TextItemFactory',
    function ($log, BaseConfigService, ProjectService, MessageService, UndoRedoService, HeadAreaToggleService, ImageItemFactory, TextItemFactory) {

      var contextPanelAreaVisible = false;
      var contextPanelAreaCssZIndex = 10;

      var contextPanelAreaConfigs = [
        {
          name: 'photo-settings',
          available: true,
          panels: [
            {
              name: 'panel-alpha-masks',
              label: MessageService.getMessage('contextPanel.label.alphaMasks'),
              icon: 'alpha-masks',
              removable: true,
              selected: true,
              available: true
            },
            {
              name: 'panel-deco-frames',
              label: MessageService.getMessage('contextPanel.label.decoFrames'),
              icon: 'deco-frames',
              removable: true,
              selected: false,
              available: true
            },
            {
              name: 'panel-colored-borders',
              label: MessageService.getMessage('contextPanel.label.coloredBorders'),
              color: 'none',
              removable: true,
              selected: false,
              available: true
            },
            {
              name: 'photo-effects',
              label: 'Foto Effekte',
              icon: 'deco-frames',
              removable: false,
              selected: false,
              available: false
            }
          ]
        },
        {
          name: 'text-settings',
          available: true,
          panels: [
            {
              name: 'panel-fonts',
              label: MessageService.getMessage('contextPanel.label.fonts'),
              icon: 'font',
              removable: false,
              selected: true,
              available: true
            },
            {
              name: 'panel-text-format',
              label: MessageService.getMessage('contextPanel.label.textFormat'),
              icon: 'text-format',
              removable: false,
              selected: false,
              available: true
            },
            {
              name: 'panel-font-color',
              label: MessageService.getMessage('contextPanel.label.fontColor'),
              color: '#000',
              removable: false,
              selected: false,
              available: true
            },
            {
              name: 'panel-text-background-color',
              label: MessageService.getMessage('contextPanel.label.textBackgroundColor'),
              color: 'none',
              removable: true,
              selected: false,
              available: true
            }
          ]
        },
        {
          name: 'product-settings',
          available: BaseConfigService.isDevelopStatusActive(),
          panels: []
        }
      ];


      var currentContextPanelAreaConfig = contextPanelAreaConfigs[0];


      // definition of the public service functions
      var contextPanelAreaService = {

        /**
         *
         * @return {boolean} is context panel area meant to be visible?
         */
        isContextPanelAreaVisible: function () {
          return contextPanelAreaVisible;
        },

        /**
         * @param {boolean} trueOrFalse set whether the context panel area is meant to be visible
         */
        setContextPanelAreaVisible: function (trueOrFalse) {
          if (trueOrFalse === false) {
            contextPanelAreaService.setImageItemBoxesContextView(trueOrFalse);
          } else {
            // always maximize the head area if the context panel is visible to avoid overlapping of the design area
            // with the context panel area
            HeadAreaToggleService.maximizeHeadArea();
          }

          if (!contextPanelAreaService.getCurrentContextPanelAreaConfig().available) {
            return; // do nothing if current context panel area is actually not available
          }

          var previousVisibilityState = contextPanelAreaVisible;

          contextPanelAreaVisible = trueOrFalse;

          $log.debug('Set context panel area visible:', trueOrFalse);

          // if the context panel area was closed before and is now opened --> save the current double page state on the undo/redo stack
          // so it could potentially be reverted to after the context panel area is closed again
          var undoRedoPromise;
          if (!previousVisibilityState && trueOrFalse) {
            undoRedoPromise = UndoRedoService.pushModelData(ProjectService.getSelectedDesignArea());
          }

          // apply the suitable context panel area configuration for the currently selected project item
          if (contextPanelAreaVisible) {
            ProjectService.getSelectedDesignArea().setZIndex(1040);
            var itemBox = ProjectService.getSelectedDesignArea().getSelectedItemBox();

            var config = contextPanelAreaService.getContextPanelAreaConfigByItemBox(itemBox);

            if (config) {
              contextPanelAreaService.setContextPanelAreaConfig(config);
              if (undoRedoPromise) {
                undoRedoPromise.resolve();
              }
            } else { // context panel area configuration is not available for selected item box? --> don't show context panel area and throw error
              contextPanelAreaVisible = false;
              $log.error('Context panel area is not available for currently selected item box:', itemBox);
              if (undoRedoPromise) {
                undoRedoPromise.reject();
              }
              throw new Error('Context panel area is not available for currently selected item box. Why have you tried to open it up for it?');
            }
          } else if (ProjectService.getSelectedDesignArea()) {
            ProjectService.getSelectedDesignArea().setZIndex('auto');
          }
        },

        getCssZIndex: function () {
          return contextPanelAreaCssZIndex;
        },

        setCssZIndex: function (cssZIndex) {
          contextPanelAreaCssZIndex = cssZIndex;
        },

        setContextPanelAreaConfig: function (config) {
          if (config) {
            currentContextPanelAreaConfig = config;
          }
        },

        /**
         * Makes the context panel area configuration active that fits to the specified ItemBox. No change if no fitting config was found.
         * @param {ItemBox} itemBox the ItemBox to set the context panel area configuration for
         */
        setContextPanelAreaConfigByItemBox: function (itemBox) {
          var config = contextPanelAreaService.getContextPanelAreaConfigByItemBox(itemBox);
          if (config) {
            currentContextPanelAreaConfig = config;
          }
        },

        getCurrentContextPanelAreaConfig: function () {
          return currentContextPanelAreaConfig;
        },

        getContextPanelAreaConfigByItemBox: function (itemBox) {
          var currentDesignArea = ProjectService.getSelectedDesignArea();
          if (itemBox instanceof ImageItemFactory.getClass() && !currentDesignArea.hasImageBackgroundItem(itemBox)) {
            return contextPanelAreaConfigs[0];
          } else if (itemBox instanceof TextItemFactory.getClass()) {
            return contextPanelAreaConfigs[1];
          }

        },

        getContextPanelAreaConfigByName: function (name) {
          for (var i = 0; i < contextPanelAreaConfigs.length; i++) {
            if (contextPanelAreaConfigs[i].name === name) {
              return contextPanelAreaConfigs[i];
            }
          }
        },

        getSelectedContextPanel: function () {
          var panels = contextPanelAreaService.getCurrentContextPanelAreaConfig().panels;
          for (var i = 0; i < panels.length; i++) {
            if (panels[i].selected) {
              return panels[i];
            }
          }
        },

        setColorForFontColorTab: function (color) {
          var textSettings = contextPanelAreaService.getContextPanelAreaConfigByName('text-settings');
          textSettings.panels.forEach(function (textPanel) {
            if (textPanel.name === 'panel-font-color') {
              textPanel.color = color;
            }
          });
        },

        setColorForBackgroundColorTab: function (color) {
          var textSettings = contextPanelAreaService.getContextPanelAreaConfigByName('text-settings');
          textSettings.panels.forEach(function (textPanel) {
            if (textPanel.name === 'panel-text-background-color') {
              textPanel.color = color;
            }
          });
        },

        setColorForColoredBordersTab: function (color) {
          var textSettings = contextPanelAreaService.getContextPanelAreaConfigByName('photo-settings');
          textSettings.panels.forEach(function (photoPanel) {
            if (photoPanel.name === 'panel-colored-borders') {
              photoPanel.color = color;
            }
          });
        },

        /**
         *
         * @param {String} panelName select the panel with the specified name from the currently active context panel area config
         */
        selectContextPanel: function (panelName) {
          $log.debug('Selecting context panel:', panelName);
          contextPanelAreaService.getCurrentContextPanelAreaConfig().panels.forEach(function iteratePanels(panel) {
            panel.selected = (panel.name === panelName);
          });

        },

        setImageItemBoxesContextView: function (trueOrFalse) {
          var currentDesignArea = ProjectService.getSelectedDesignArea();
          if (currentDesignArea) {
            var imageItems = currentDesignArea.getImageItems();
            angular.forEach(imageItems, function (itemBox) {
              itemBox.setContextView(trueOrFalse);
            });
          }
        }
      };

      return contextPanelAreaService;
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive represents the container for Tatooine's different kind of photo settings.
 * @author Frank Bruns (frank.bruns@cewe.de)
 * Date: 03.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwPhotoSettings', [
    '$log', 'ContextPanelAreaService', 'ProjectService',
    function ($log, ContextPanelAreaService, ProjectService) {
      return {
        replace: true,
        scope: {
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/contextpanels/photos/cwPhotoSettings.html.jsf',
        link: function (scope, element, attrs) {

          scope.data = {};

          scope.getSelectedContextPanel = function () {
            return ContextPanelAreaService.getSelectedContextPanel();
          };

          scope.isAttachedToImageBackgroundItem = function () {
            var selectedDesignArea = ProjectService.getSelectedDesignArea();
            var selectedItem = selectedDesignArea.getSelectedItemBox();
            if (selectedItem) {
              return selectedDesignArea.hasImageBackgroundItem(selectedItem);
            }
          };
        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive is a UI component set up a coloured border image item boxes.
 * @author: Frank Bruns (frank.bruns@cewe.de)
 * Date: 03.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwColoredBorderSettings', [
    '$log', 'EventConstants', '$modal', 'ProjectService', 'UndoRedoService', 'ImageItemFactory', 'ContextPanelAreaService',
    function ($log, EventConstants, $modal, ProjectService, UndoRedoService, ImageItemFactory, ContextPanelAreaService) {
      return {
        replace: true,
        scope: {
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/contextpanels/photos/cwColoredBorderSettings.html.jsf',
        link: function (scope, element, attrs) {

          scope.data = {
            MIN_BORDER_WIDTH_MM: 0, // in mm, not 1/10mm
            MAX_BORDER_WIDTH_MM: 99,  // in mm, not 1/10mm
            DEFAULT_BORDER_WIDTH_MM: 0.8, // in mm, not 1/10mm
            APPLY_TO_SELECTED_ITEM: 'selectedItem',
            APPLY_TO_DOUBLE_PAGE: 'doublePage',
            inputBorderWidthMm: 0, // in mm, not 1/10mm
            applyTo: undefined
          };

          scope.data.applyTo = scope.data.APPLY_TO_SELECTED_ITEM;

          scope.$on(EventConstants.CONTEXT_PANEL_REMOVE_SETTING, function handleRemoveSettingEvent(e, panelName) {
            if ('panel-colored-borders' === panelName) {

              scope.data.inputBorderWidthMm = 0;

              var items = getAffectedItems();
              for (var i = 0; i < items.length; i++) {
                items[i].setBorderWidth(0);
                ContextPanelAreaService.setColorForColoredBordersTab('none');
              }
            }
          });

          var unwatchSelectedItemChange = scope.$watch(function watchSelectedItemChange() {
            return getSelectedItem();
          }, function onSelectedItemChanged(newValue, oldValue) {
            if (newValue) {
              scope.data.inputBorderWidthMm = newValue.getBorderWidth() / 10;
            }
          });

          scope.$on('$destroy', function destroy() {
            unwatchSelectedItemChange();
          });

          /**
           *
           * @return {Array} the array of items that shall be affected by changes made by the user via this directive
           */
          var getAffectedItems = function () {
            var affectedItems = [];

            switch (scope.data.applyTo) {
            case scope.data.APPLY_TO_SELECTED_ITEM:
              if (getSelectedItem()) {
                affectedItems.push(getSelectedItem());
              }
              break;
            case scope.data.APPLY_TO_DOUBLE_PAGE:
              affectedItems = affectedItems.concat(getImageItemsOnDoublePage());
              break;
            }
            return affectedItems;
          };

          var getSelectedItem = function () {
            var designArea = ProjectService.getSelectedDesignArea();
            if (designArea) {
              var item = designArea.getSelectedItemBox();
              if (item instanceof ImageItemFactory.getClass()) {
                return item;
              }
            }
          };

          var getImageItemsOnDoublePage = function () {
            var designArea = ProjectService.getSelectedDesignArea();
            if (designArea) {
              return designArea.getImageItems();
            }
          };

          var clampBorderWidth = function (borderWidthMm) {
            borderWidthMm = Math.max(scope.data.MIN_BORDER_WIDTH_MM, borderWidthMm);
            borderWidthMm = Math.min(scope.data.MAX_BORDER_WIDTH_MM, borderWidthMm);
            return borderWidthMm;
          };

          var setBorderWidthMmToItem = function (borderWidthMm) {

            var imageItems = getAffectedItems();

            // loop through image items to apply the new border settings to them
            for (var i = 0; i < imageItems.length; i++) {
              imageItems[i].setBorderWidth(clampBorderWidth(borderWidthMm) * 10);
            }

            if (borderWidthMm > 0 && imageItems[0]) {
              ContextPanelAreaService.setColorForColoredBordersTab(imageItems[0].getBorderColor());
            }

          };

          var applyToAllDesignAreas = function (settings) {
            var undoHandle = UndoRedoService.pushProject();
            var allImageItems = ProjectService.getProject().getAllImageItems();

            if (!allImageItems || allImageItems.length <= 0) {
              undoHandle.reject();
              return;
            }

            allImageItems.forEach(function iterateAllImageItems(imageItem) {
              if (settings.applyBorderColor) {
                imageItem.setBorderColor(settings.borderColor);
                imageItem.removeDecoFrameId();
                if (imageItem.getBorderWidth() <= 0) {
                  imageItem.setBorderWidth(scope.data.DEFAULT_BORDER_WIDTH_MM * 10); // <-- in 1/10mm
                }
              }
              if (settings.applyBorderWidth) {
                imageItem.setBorderWidth(settings.borderWidthMm * 10);
              }
            });
            undoHandle.resolve();
          };

          /**
           *
           * @param deltaMm the delta in mm (not 1/10mm) to change the border width by
           */
          scope.changeBorderWidthBy = function (deltaMm) {
            scope.data.inputBorderWidthMm = clampBorderWidth((scope.data.inputBorderWidthMm + deltaMm).toFixed(1));
            setBorderWidthMmToItem(scope.data.inputBorderWidthMm);
          };

          scope.onBorderWidthInputChanged = function () {
            setBorderWidthMmToItem(scope.data.inputBorderWidthMm);
          };

          scope.setBorderColor = function (color) {

            var imageItems = getAffectedItems();

            // loop through image items to apply the new border settings to them
            for (var i = 0; i < imageItems.length; i++) {
              var item = imageItems[i];
              item.setBorderColor(color);
              item.removeDecoFrameId();
              if (item.getBorderWidth() <= 0) {
                item.setBorderWidth(scope.data.DEFAULT_BORDER_WIDTH_MM * 10); // <-- in 1/10mm
                scope.data.inputBorderWidthMm = scope.data.DEFAULT_BORDER_WIDTH_MM;
              }
            }
            ContextPanelAreaService.setColorForColoredBordersTab(color);
            ContextPanelAreaService.setImageItemBoxesContextView(true);
          };

          scope.getBorderColor = function () {
            var item = getSelectedItem();
            if (item) {
              return item.getBorderColor();
            }
          };

          scope.onApplyToAllDesignAreasClicked = function () {
            var selectedItem = getSelectedItem();

            var dialogSettings = {
              borderColor: selectedItem.getBorderColor(),
              borderWidthMm: (selectedItem.getBorderWidth() / 10).toFixed(1)
            };

            var confirmApplyColoredBorderSettingsToProject = $modal.open({
              templateUrl: 'confirmApplyColoredBorderSettings',
              controller: 'ConfirmApplyColoredBorderSettingsController',
              resolve: {
                dialogSettings: function () {
                  return dialogSettings;
                }
              }
            });
            confirmApplyColoredBorderSettingsToProject.result.then(function dialogChoiceConfirmed(dialogResult) {
              applyToAllDesignAreas(dialogResult);
            });

          };
        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive is a UI component set up an alpha mask for suitable item boxes.
 * @author: Frank Bruns (frank.bruns@cewe.de)
 * Date: 17.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwAlphaMaskSettings', [
    '$log', '$timeout', 'AppValues', 'EventConstants', 'OperatorService', 'ProjectService', 'AlphaMaskService', 'ImageItemFactory', 'ContextPanelAreaService',
    function ($log, $timeout, AppValues, EventConstants, OperatorService, ProjectService, AlphaMaskService, ImageItemFactory, ContextPanelAreaService) {
      return {
        replace: true,
        scope: {
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/contextpanels/photos/cwAlphaMaskSettings.html.jsf',
        link: function (scope, element, attrs) {


          var MIN_ITEMS_TO_LOAD = 15;

          var initialize = function () {
            scope.categorySelectionVisible = false;
            scope.data = {
              alphaMaskItemTemplates: [],
              numberOfloadedAlphaMasks: 0,
              selectedAlphaMaskItemTemplate: undefined,
              itemWidth: 120,
              itemHeight: 120
            };

            scope.categoryMap = {};
            AlphaMaskService.getAlphaMaskCategoryMap().then(function ok(categoryMap) {
              scope.categoryMap = categoryMap;
              var defaultCategory = OperatorService.getDefaultDesignElementCategory('alphamask');
              var categories = Object.keys(scope.categoryMap);
              if (categories.indexOf(defaultCategory) < 0) {
                defaultCategory = categories[0];
              }
              scope.selectCategory(defaultCategory);
            });

            var container = angular.element('#alphaMaskListContainer');
            container.on('scroll', function () {
              if (container.scrollLeft() > 100) {
                if (!allItemsLoaded()) {
                  loadAllItemsRecursively();
                }
              }
            });


            scope.$on(EventConstants.CONTEXT_PANEL_REMOVE_SETTING, function handleRemoveSettingEvent(e, panelName) {
              if ('panel-alpha-masks' === panelName) {
                scope.data.selectedAlphaMaskItemTemplate = undefined;
                getSelectedItem().removeAlphaMaskId();
              }
            });

          };


          var loadMoreItems = function (itemsToFetch) {
            for (var i = scope.data.numberOfloadedAlphaMasks;
                 i < scope.data.numberOfloadedAlphaMasks + itemsToFetch && i < scope.data.alphaMaskItemTemplates.length; i++) {
              scope.data.alphaMaskItemTemplates[i].setInitialized(true);
            }
            scope.data.numberOfloadedAlphaMasks += itemsToFetch;
          };

          var loadAllItemsRecursively = function () {
            if (allItemsLoaded()) {
              return;
            }
            $timeout(function delayed() {
              loadMoreItems(20);
              loadAllItemsRecursively();
            }, 500);
          };

          var allItemsLoaded = function() {
            return scope.data.numberOfloadedAlphaMasks >= scope.data.alphaMaskItemTemplates.length;
          };

          var getSelectedItem = function () {
            var designArea = ProjectService.getSelectedDesignArea();
            if (designArea) {
              var item = designArea.getSelectedItemBox();
              if (item instanceof ImageItemFactory.getClass()) {
                return item;
              }
            }
          };

          scope.applyTemplate = function (alphaMaskItemTemplate) {
            $log.debug('apply alpha mask template', alphaMaskItemTemplate);
            var itemBox = getSelectedItem();
            itemBox.applyAlphaMaskTemplate(alphaMaskItemTemplate);
            scope.data.selectedAlphaMaskItemTemplate = alphaMaskItemTemplate;
            ContextPanelAreaService.setImageItemBoxesContextView(true);

          };

          scope.getSelectedTemplate = function () {
            var item = getSelectedItem();
            if (item) {
              for (var i = 0; i < scope.data.alphaMaskItemTemplates.length; i++) {
                if (scope.data.alphaMaskItemTemplates[i].getDesignElementId() === item.getAlphaMaskId()) {
                  return scope.data.alphaMaskItemTemplates[i];
                }
              }
            }
          };

          scope.toggleCategorySelection = function () {
            scope.categorySelectionVisible = !scope.categorySelectionVisible;
            $log.debug('fire event', EventConstants.CONTEXT_PANEL_CATEGORY_SELECTION_MENU_TOGGLED, scope.categorySelectionVisible);
            scope.$root.$broadcast(EventConstants.CONTEXT_PANEL_CATEGORY_SELECTION_MENU_TOGGLED, scope.categorySelectionVisible);
          };

          scope.getAlphaMaskItemTemplates = function () {
            return scope.data.alphaMaskItemTemplates;
          };

          scope.selectCategory = function (categoryId) {
            AlphaMaskService.getAlphaMaskTemplatesByCategory(categoryId).then(
              function ok(alphaMaskItemTemplates) {
                scope.data.alphaMaskItemTemplates = alphaMaskItemTemplates;
                scope.data.numberOfloadedAlphaMasks = 0;
                loadMoreItems(MIN_ITEMS_TO_LOAD);
                scope.selectedCategory = categoryId;

                var alphaMaskListContainer = angular.element('#alphaMaskListContainer');
                if (alphaMaskListContainer) {
                  alphaMaskListContainer.scrollLeft(0);
                }
              });
          };

          initialize();


        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive is a UI component set up a deco frame for suitable item boxes.
 * @author: Frank Bruns (frank.bruns@cewe.de)
 * Date: 07.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwDecoFrameSettings', [
    '$log', '$timeout', 'AppValues', 'EventConstants', 'OperatorService', 'ProjectService', 'DecoFrameService', 'ImageItemFactory', 'ContextPanelAreaService',
    function ($log, $timeout, AppValues, EventConstants, OperatorService, ProjectService, DecoFrameService, ImageItemFactory, ContextPanelAreaService) {
      return {
        replace: true,
        scope: {
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/contextpanels/photos/cwDecoFrameSettings.html.jsf',
        link: function (scope, element, attrs) {


          var MIN_ITEMS_TO_LOAD = 5;

          var initialize = function () {
            scope.categorySelectionVisible = false;
            scope.data = {
              decoFrameItemTemplates: [],
              loadedDecoFrameItemTemplates: [],
              selectedDecoFrameItemTemplate: undefined,
              itemWidth: 120,
              itemHeight: 120
            };

            scope.categoryMap = {};
            DecoFrameService.getDecoFrameCategoryMap().then(function ok(categoryMap) {
              scope.categoryMap = categoryMap;
              var defaultCategory = OperatorService.getDefaultDesignElementCategory('decoframe');
              var categories = Object.keys(scope.categoryMap);
              if (categories.indexOf(defaultCategory) < 0) {
                defaultCategory = categories[0];
              }
              scope.selectCategory(defaultCategory);
            });


            scope.$on(EventConstants.CONTEXT_PANEL_REMOVE_SETTING, function handleRemoveSettingEvent(e, panelName) {
              if ('panel-deco-frames' === panelName) {
                scope.data.selectedDecoFrameItemTemplate = undefined;
                getSelectedItem().removeDecoFrameId();
              }
            });

          };


          var loadMoreItems = function (itemsToFetch) {

            for (var i = scope.data.loadedDecoFrameItemTemplates.length, fetchedItems = 0; fetchedItems < itemsToFetch && i < scope.data.decoFrameItemTemplates.length; i++) {
              scope.data.loadedDecoFrameItemTemplates.push(scope.data.decoFrameItemTemplates[i]);
              fetchedItems++;
            }
          };

          var loadAllItemsRecursively = function () {
            if (scope.data.loadedDecoFrameItemTemplates.length >= scope.data.decoFrameItemTemplates.length) {
              $log.debug('all deco frame items loaded for current category');
              return;
            }
            $timeout(function delayed() {
              loadMoreItems(20);
              loadAllItemsRecursively();
            }, 300);
          };

          var getSelectedItem = function () {
            var designArea = ProjectService.getSelectedDesignArea();
            if (designArea) {
              var item = designArea.getSelectedItemBox();
              if (item instanceof ImageItemFactory.getClass()) {
                return item;
              }
            }
          };

          scope.applyTemplate = function (decoFrameItemTemplate) {
            var itemBox = getSelectedItem();
            itemBox.setDecoFrameId(decoFrameItemTemplate.getDesignElementId());
            itemBox.setBorderWidth(0);
            scope.data.selectedDecoFrameItemTemplate = decoFrameItemTemplate;
            ContextPanelAreaService.setImageItemBoxesContextView(true);
          };

          scope.getSelectedTemplate = function () {
            var item = getSelectedItem();
            if (item) {
              for (var i = 0; i < scope.data.loadedDecoFrameItemTemplates.length; i++) {
                if (scope.data.loadedDecoFrameItemTemplates[i].getDesignElementId() === item.getDecoFrameId()) {
                  return scope.data.loadedDecoFrameItemTemplates[i];
                }
              }
            }
          };

          scope.toggleCategorySelection = function () {
            scope.categorySelectionVisible = !scope.categorySelectionVisible;
            $log.debug('fire event', EventConstants.CONTEXT_PANEL_CATEGORY_SELECTION_MENU_TOGGLED, scope.categorySelectionVisible);
            scope.$root.$broadcast(EventConstants.CONTEXT_PANEL_CATEGORY_SELECTION_MENU_TOGGLED, scope.categorySelectionVisible);
          };

          scope.getLoadedDecoFrameItemTemplates = function () {
            return scope.data.loadedDecoFrameItemTemplates;
          };

          scope.selectCategory = function (categoryId) {
            DecoFrameService.getDecoFrameTemplatesByCategory(categoryId).then(
              function ok(decoFrameItemTemplates) {
                scope.data.decoFrameItemTemplates = [];
                scope.data.loadedDecoFrameItemTemplates = [];
                decoFrameItemTemplates.forEach(function (decoFrameItemTemplate) {
                  scope.data.decoFrameItemTemplates.push(decoFrameItemTemplate);
                  if (scope.data.loadedDecoFrameItemTemplates.length < MIN_ITEMS_TO_LOAD) {
                    scope.data.loadedDecoFrameItemTemplates.push(decoFrameItemTemplate);
                  }
                });
                scope.selectedCategory = categoryId;

                var decoFrameListContainer = angular.element('#decoFrameListContainer');
                if (decoFrameListContainer) {
                  decoFrameListContainer.scrollLeft(0);
                }
                loadAllItemsRecursively();
              });
          };

          initialize();

        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * @author: Sascha Friedrich
 * Date: 18.12.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwPhotoEffectsSettings', [
    '$log', '$timeout', 'AppValues', 'SafeApply', 'EventConstants', 'OperatorService', 'ProjectService', 'FileHandleService', 'ImageItemFactory', 'PhotoEffectService', 'DesignAreaService', 'ContextPanelAreaService', 'ImagingService', 'FileHandleRepository',
    function ($log, $timeout, AppValues, SafeApply, EventConstants, OperatorService, ProjectService, FileHandleService, ImageItemFactory, PhotoEffectService, DesignAreaService, ContextPanelAreaService, ImagingService, FileHandleRepository) {
      return {
        replace: true,
        scope: {
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/contextpanels/photos/cwPhotoEffectsSettings.html.jsf',
        link: function (scope, element, attrs) {
          scope.data = {
            fileHandle: undefined,
            selectedEffect: undefined,
            itemThumbsWithEffects: [],
            itemWidth: 120,
            itemHeight: 120
          };

          var getSelectedItem = function () {
            var designArea = ProjectService.getSelectedDesignArea();
            if (designArea) {
              var item = designArea.getSelectedItemBox();
              if (item instanceof ImageItemFactory.getClass()) {
                return item;
              }
            }
          };

          var selectedItem = getSelectedItem();
          if (selectedItem) {
            scope.data.fileHandle = FileHandleService.getFileHandle(selectedItem.getFileHandleId());
          }


          scope.thumbClicked = function (effect, baseFileHandle) {
            scope.data.selectedEffect = effect;
            var selectedItem = getSelectedItem();
            var thumbKey = selectedItem.getThumbKey();
            var maxSize = thumbKey.width >= thumbKey.height ? thumbKey.width : thumbKey.height;
            var fitTo = thumbKey.width >= thumbKey.height ? 'width' : 'height';
            selectedItem.setThumbKeyLoaded(false);
            FileHandleService.getThumbnail(baseFileHandle.getId(), maxSize, fitTo, false).then(function ok(imageObj) {
              applyEffectOnCanvas(baseFileHandle, effect, imageObj);
            });
          };


          var removeSelectedItemWatch = scope.$watch(function watchSelectedFileHandle() {
            return getSelectedItem();
          }, function onSelectedItemChanged(newValue, oldValue) {
            if (newValue) {
              scope.data.fileHandle = FileHandleService.getFileHandle(newValue.getFileHandleId());
              scope.effectsAndFilehandle = [];
              angular.forEach(PhotoEffectService.getEffects(), function (effect) {
                scope.effectsAndFilehandle.push({
                  effect: effect,
                  fileHandle: scope.data.fileHandle
                });
              });

            }
          });

          var applyEffectOnCanvas = function (baseFileHandle, effect, imageObj) {
            var selectedItem = getSelectedItem();
            if (effect.effectName === 'none') {
              PhotoEffectService.removeEffectFromCanvas(imageObj.data).then(function () {
                selectedItem.incrementModelStateVersion();
                PhotoEffectService.setEffectForFileHandleId(baseFileHandle.getId(), 'none');
              });
            } else {
              PhotoEffectService.putBaseCanvasImage(imageObj.data);
              PhotoEffectService.addEffectToCanvas(imageObj.data, effect.effectName).then(function () {
                selectedItem.incrementModelStateVersion();
                PhotoEffectService.setEffectForFileHandleId(baseFileHandle.getId(), effect.effectName);
              });
            }
          };

          scope.$on(EventConstants.CONTEXT_PANEL_PHOTO_EFFECT_CLOSED, function handlePhotoEffectClosed(e, panelName) {
            if (PhotoEffectService.getEffectStoreLength() > 0) {
              PhotoEffectService.revertBaseCanvasImages().then(function () {
                PhotoEffectService.applyEffectsFromEffectStore();
                //PhotoEffectService.clearEffectStore();
              });
            }
          });


        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive represents the container for Tatooine's different kind of text settings.
 * @author Frank Bruns (frank.bruns@cewe.de)
 * Date: 03.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwTextSettings', [
    '$log', 'ContextPanelAreaService',
    function ($log, ContextPanelAreaService) {
      return {
        replace: true,
        scope: {
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/contextpanels/texts/cwTextSettings.html.jsf',
        link: function (scope, element, attrs) {

          scope.data = {};

          scope.getSelectedContextPanel = function () {
            return ContextPanelAreaService.getSelectedContextPanel();
          };
        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive is a UI component to set up a font TextItems.
 * @author: Frank Bruns (frank.bruns@cewe.de)
 * Date: 07.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwFontSettings', [
    '$log', 'ProjectService', 'FontService', 'MessageService', 'TextItemFactory', 'TextItemTemplateFactory',
    function ($log, ProjectService, FontService, MessageService, TextItemFactory, TextItemTemplateFactory) {
      return {
        replace: true,
        scope: {
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/contextpanels/texts/cwFontSettings.html.jsf',
        link: function (scope, element, attrs) {

          scope.data = {
            textItemTemplates: [],
            selectedTextItemTemplate: null,
            itemWidth: 150,
            itemHeight: 120
          };

          var getSelectedItem = function () {
            var designArea = ProjectService.getSelectedDesignArea();
            if (designArea) {
              var item = designArea.getSelectedItemBox();
              if (item instanceof TextItemFactory.getClass()) {
                return item;
              }
            }
          };


          FontService.getFonts().then(function (fonts) {

            fonts.forEach(function iterateFonts(font) {
              var bgColor = '#ffffff';
              var textColor = '#000000';
              var textAnchor = 'start';
              var fontStyle = 'normal';
              var fontWeight = 'normal';
              var textDecoration = 'none';
              var padding = '5pt';
              var verticalAlign = 'top';
              var placeholderText = MessageService.getMessage('project.textItem.placeholderText');

              var textItemTemplate = TextItemTemplateFactory.createTextItemTemplate('AaBbCc', placeholderText, textAnchor, textColor, bgColor, font, 22,
                fontStyle, fontWeight, textDecoration, padding, verticalAlign);
              scope.data.textItemTemplates.push(textItemTemplate);

            });
          });


          scope.selectTemplate = function (textItemTemplate) {
            var item = getSelectedItem();
            if (item) {
              scope.data.selectedTextItemTemplate = textItemTemplate;
              item.setFont(textItemTemplate.getFont());
            }
          };

          scope.getSelectedTemplate = function () {
            var item = getSelectedItem();
            if (item) {
              for (var i = 0; i < scope.data.textItemTemplates.length; i++) {
                if (scope.data.textItemTemplates[i].getFont().getFamily() === item.getFont().getFamily()) {
                  return scope.data.textItemTemplates[i];
                }
              }
            }
          };

        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive is a UI component to set up the font color for TextItems.
 * @author: Frank Bruns (frank.bruns@cewe.de)
 * Date: 07.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwFontColorSettings', [
    '$log', 'ProjectService', 'ContextPanelAreaService', 'TextItemFactory',
    function ($log, ProjectService, ContextPanelAreaService, TextItemFactory) {
      return {
        replace: true,
        scope: {
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/contextpanels/texts/cwFontColorSettings.html.jsf',
        link: function (scope, element, attrs) {

          scope.data = {};

          var getSelectedItem = function () {
            var designArea = ProjectService.getSelectedDesignArea();
            if (designArea) {
              var item = designArea.getSelectedItemBox();
              if (item instanceof TextItemFactory.getClass()) {
                return item;
              }
            }
          };

          scope.setFontColor = function (color) {
            var item = getSelectedItem();
            if (item) {
              item.setTextColor(color);
            }
            ContextPanelAreaService.setColorForFontColorTab(item.getTextColor());
          };

          scope.getFontColor = function () {
            var item = getSelectedItem();
            if (item) {
              return item.getTextColor();
            }
          };

        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive is a UI component to set text style and format for TextItems.
 * @author: Frank Bruns (frank.bruns@cewe.de)
 * Date: 07.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwTextFormatSettings', [
    '$log', 'ProjectService', 'ProductService', 'TextItemFactory',
    function ($log, ProjectService, ProductService, TextItemFactory) {
      return {
        replace: true,
        scope: {
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/contextpanels/texts/cwTextFormatSettings.html.jsf',
        link: function (scope, element, attrs) {
          var fontSizeSequence = [];

          scope.data = {
            MIN_FONT_SIZE_PT: ProductService.getProductById(ProjectService.getProject().getProductId()).getMinFontSize(),
            MAX_FONT_SIZE_PT: 999,
            AVAILABLE_VERTICAL_ALIGNS: ['top', 'middle', 'bottom'],
            AVAILABLE_TEXT_ANCHORS: ['start', 'middle', 'end'],
            AVAILABLE_CSS_ALIGNS: {start: 'left', middle: 'center', end: 'right'},
            inputFontSizePt: undefined
          };

          var calculateFontSizeSequence = function () {
            var fontSizeValue = scope.data.MIN_FONT_SIZE_PT;
            while (fontSizeValue <= scope.data.MAX_FONT_SIZE_PT) {
              fontSizeSequence.push(fontSizeValue);
              fontSizeValue = fontSizeValue + Math.ceil(fontSizeValue * 0.05);
            }
            if (fontSizeValue > scope.data.MAX_FONT_SIZE_PT) {
              fontSizeSequence.push(scope.data.MAX_FONT_SIZE_PT);
            }
          };
          calculateFontSizeSequence();

          var unwatchSelectedItemChange = scope.$watch(function watchSelectedItemChange() {
            return scope.getSelectedItem();
          }, function onSelectedItemChanged(newValue, oldValue) {
            if (newValue) {
              scope.data.inputFontSizePt = newValue.getFontSize();
            }
          });

          scope.$on('$destroy', function destroy() {
            unwatchSelectedItemChange();
          });


          scope.getSelectedItem = function () {
            var designArea = ProjectService.getSelectedDesignArea();
            if (designArea) {
              var item = designArea.getSelectedItemBox();
              if (item instanceof TextItemFactory.getClass()) {
                return item;
              }
            }
          };

          var setFontSize = function (fontSize) {
            if (fontSize && scope.data.MAX_FONT_SIZE_PT >= fontSize && scope.data.MIN_FONT_SIZE_PT <= fontSize) {
              var selectedItem = scope.getSelectedItem();
              if (selectedItem) {
                selectedItem.setFontSize(fontSize);
                scope.data.inputFontSizePt = fontSize;
              }
            }
          };

          scope.smartChangeFontSize = function (direction) {
            if (direction !== 'up' && direction !== 'down') {
              return;
            }
            var selectedItem = scope.getSelectedItem();
            var currentFontSize = selectedItem.getFontSize();
            if (selectedItem) {
              for (var i = 0; i < fontSizeSequence.length; i++) {
                if (fontSizeSequence[i] >= currentFontSize) {
                  if (direction === 'up') {
                    if (fontSizeSequence[i] > currentFontSize) {
                      setFontSize(fontSizeSequence[i]);
                    } else {
                      setFontSize(fontSizeSequence[Math.min(i + 1, fontSizeSequence.length - 1)]);
                    }
                  } else {
                    setFontSize(fontSizeSequence[Math.max(0, i - 1)]);
                  }
                  return;
                }
              }
            }
          };

          scope.onFontSizeInputChanged = function () {
            setFontSize(scope.data.inputFontSizePt);
          };

          scope.toggleFontWeight = function () {
            var selectedItem = scope.getSelectedItem();
            if (!selectedItem) {
              return;
            }
            if (selectedItem.getFontWeight() === 'bold') {
              selectedItem.setFontWeight('normal');
            } else {
              selectedItem.setFontWeight('bold');
            }
          };

          scope.toggleFontStyle = function () {
            var selectedItem = scope.getSelectedItem();
            if (!selectedItem) {
              return;
            }
            if (selectedItem.getFontStyle() === 'italic') {
              selectedItem.setFontStyle('normal');
            } else {
              selectedItem.setFontStyle('italic');
            }
          };

          scope.setTextAnchor = function (anchor) {
            var selectedItem = scope.getSelectedItem();
            if (!selectedItem) {
              return;
            }
            selectedItem.setTextAnchor(anchor);
          };

          scope.setVerticalAlign = function (vAlign) {
            var selectedItem = scope.getSelectedItem();
            if (!selectedItem) {
              return;
            }
            selectedItem.setVerticalAlign(vAlign);
          };

        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive is a UI component to set up a background color for TextItems.
 * @author: Frank Bruns (frank.bruns@cewe.de)
 * Date: 07.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwTextBackgroundColorSettings', [
    '$log', 'EventConstants', 'ProjectService', 'ContextPanelAreaService', 'TextItemFactory',
    function ($log, EventConstants, ProjectService, ContextPanelAreaService, TextItemFactory) {
      return {
        replace: true,
        scope: {
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/contextpanels/texts/cwTextBackgroundColorSettings.html.jsf',
        link: function (scope, element, attrs) {

          scope.data = {};

          scope.$on(EventConstants.CONTEXT_PANEL_REMOVE_SETTING, function handleRemoveSettingEvent(e, panelName) {
            if ('panel-text-background-color' === panelName) {
              var item = getSelectedItem();
              if (item) {
                item.setBackgroundColor('none');
                ContextPanelAreaService.setColorForBackgroundColorTab(item.getBackgroundColor());
              }
            }
          });

          var getSelectedItem = function () {
            var designArea = ProjectService.getSelectedDesignArea();
            if (designArea) {
              var item = designArea.getSelectedItemBox();
              if (item instanceof TextItemFactory.getClass()) {
                return item;
              }
            }
          };

          scope.setBackgroundColor = function (color) {
            var item = getSelectedItem();
            if (item) {
              item.setBackgroundColor(color);
            }
            ContextPanelAreaService.setColorForBackgroundColorTab(color);
          };

          scope.getBackgroundColor = function () {
            var item = getSelectedItem();
            if (item) {
              return item.getBackgroundColor();
            }
          };

        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('DesignElementItemTemplatePrototypeFactory', [
    '$log',
    function ($log) {

      function DesignElementItemTemplate() {
        this.designElementId = undefined;
        this.categoryKey = undefined;
        this.keepAspectRatio = undefined;
        this.initialized = false;
      }

      /**
       *
       * @return {Number} the template's design element id
       */
      DesignElementItemTemplate.prototype.getDesignElementId = function () {
        return this.designElementId;
      };

      /**
       *
       * @param {Number} id the design element id to set
       */
      DesignElementItemTemplate.prototype.setDesignElementId = function (id) {
        this.designElementId = id;
      };

      /**
       *
       * @return {String} the template's categeory key
       */
      DesignElementItemTemplate.prototype.getCategoryKey = function () {
        return this.categoryKey;
      };

      /**
       *
       * @param {String} key the design element category key to set
       */
      DesignElementItemTemplate.prototype.setCategoryKey = function (key) {
        this.categoryKey = key;
      };

      /**
       *
       * @return {boolean}
       */
      DesignElementItemTemplate.prototype.getKeepAspectRatio = function () {
        return this.keepAspectRatio;
      };

      /**
       *
       * @param {boolean}
       */
      DesignElementItemTemplate.prototype.setKeepAspectRatio = function (trueOrFalse) {
        this.keepAspectRatio = trueOrFalse;
      };


      DesignElementItemTemplate.prototype.isInitialized = function () {
        return this.initialized;
      };

      DesignElementItemTemplate.prototype.setInitialized = function (trueOrFalse) {
        this.initialized = trueOrFalse;
      };

      return {

        getClass: function () {
          return DesignElementItemTemplate;
        },

        getPrototype: function () {
          return new DesignElementItemTemplate();
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */


/**
 * @author Frank Bruns (frank.bruns@cewe.de)
 * @date 17.08.2015
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('AlphaMaskService', [
    '$log', '$http', '$resource', '$q', 'MessageService', 'AlphaMaskItemTemplateFactory',
    function ($log, $http, $resource, $q, MessageService, AlphaMaskItemTemplateFactory) {

      var endpointUrl = 'designElements/alphamask.rest';
      var alphaMaskItemTemplatesCache;

      var loadAlphaMasks = function () {
        if (alphaMaskItemTemplatesCache) {
          return $q.when(alphaMaskItemTemplatesCache);
        }
        return $http({
          method: 'GET',
          url: endpointUrl
        }).then(
          function ok(response) {
            alphaMaskItemTemplatesCache = {};
            angular.forEach(response.data, function (value, key) {
              var alphaMasks = [];
              value.forEach(function (alphaMask) {
                if (alphaMask.designElementId && alphaMask.categories) {
                  alphaMasks.push(AlphaMaskItemTemplateFactory.createAlphaMaskItemTemplate(alphaMask.designElementId, alphaMask.categories[0], alphaMask.keepAspectRatio));
                }
              });
              alphaMaskItemTemplatesCache[key] = alphaMasks;
            });

            return alphaMaskItemTemplatesCache;
          },
          function error(response) {
            // TODO: we need some global error handling
            $log.error('ERROR: Can\'t get the alpha mask data: ', response);
          });
      };

      // definition of the public service functions
      var alphaMaskTemplateService = {

        /**
         * @param {String} categoryId
         * @returns the possible cliparts
         */

        getAlphaMaskTemplatesByCategory: function (categoryId) {
          return loadAlphaMasks().then(function ok(alphaMaskCategoryMap) {
            return alphaMaskCategoryMap[categoryId];
          });
        },

        getAlphaMaskCategoryMap: function () {
          return loadAlphaMasks().then(function ok(alphaMaskCategoryMap) {
            return alphaMaskCategoryMap;
          });
        }

      };

      return alphaMaskTemplateService;

    }
  ]);
})();
/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * @author Frank Bruns (frank.bruns@cewe.de)
 * Date: 17.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('AlphaMaskItemTemplateFactory', [
    '$log', 'DesignElementItemTemplatePrototypeFactory',
    function ($log, DesignElementItemTemplatePrototypeFactory) {

      function AlphaMaskItemTemplate() {
        // call super class constructor to instantiate its variables
        DesignElementItemTemplatePrototypeFactory.getClass().call(this);
      }

      AlphaMaskItemTemplate.prototype = Object.create(DesignElementItemTemplatePrototypeFactory.getClass().prototype);
      AlphaMaskItemTemplate.prototype.constructor = AlphaMaskItemTemplate;


      return {

        /**
         *
         * @param {Number} designElementId
         * @param {String} categoryKey (optional)
         * @param [boolean} keepAspectRatio
         * @return {AlphaMaskItemTemplate}
         */
        createAlphaMaskItemTemplate: function (designElementId, categoryKey, keepAspectRatio) {

          if (!designElementId) {
            throw new Error('Can\'t create the AlphaMaskItemTemplate. One or more parameters are missing or invalid.');
          }

          if (!categoryKey) {
            categoryKey = '';
          }

          var alphaMaskItemTemplate = new AlphaMaskItemTemplate();
          alphaMaskItemTemplate.setDesignElementId(designElementId);
          alphaMaskItemTemplate.setCategoryKey(categoryKey);
          alphaMaskItemTemplate.setKeepAspectRatio(keepAspectRatio);

          return alphaMaskItemTemplate;
        },

        getClass: function() {
          return AlphaMaskItemTemplate;
        },

        getPrototype: function () {
          return new AlphaMaskItemTemplate();
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive represents a AlphaMaskItemTemplate for use in the AlphaMask selection area.
 */
/**
 * @author Frank Bruns (frank.bruns@cewe.de)
 * Date: 17.08.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwAlphaMaskItemTemplate', [
    '$log',
    function ($log) {
      return {
        replace: true,
        scope: {
          templateModel: '=templateModel', // put an AlphaMaskItemTemplate instance in here
          width: '&width',
          height: '&height'
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/designelements/alphamasks/cwAlphaMaskItemTemplate.html.jsf',
        link: function (scope, element, attrs) {

          var alphaMaskThumbUrl = 'designElements/designElementImage.rest?previewMode=true&elementId=';

          var boxStyle = {
            'width': scope.width,
            'height': scope.height,
          };

          scope.getBoxStyle = function() {
            if (scope.templateModel.isInitialized()) {
              boxStyle.background = 'url(' + alphaMaskThumbUrl + scope.templateModel.getDesignElementId() + ') no-repeat center center /contain';
            }
            return boxStyle;
          };

        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */


/**
 * @author Frank Bruns (frank.bruns@cewe.de)
 * @author Christoph Suhren
 * @date 02.09.2015
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('DecoFrameService', [
    '$log', '$http', '$resource', '$q', 'MessageService', 'DecoFrameItemTemplateFactory',
    function ($log, $http, $resource, $q, MessageService, DecoFrameItemTemplateFactory) {

      var endpointUrl = 'designElements/decoframe.rest';
      var decoFrameItemTemplatesCache;

      var loadDecoFrames = function () {
        if (decoFrameItemTemplatesCache) {
          return $q.when(decoFrameItemTemplatesCache);
        }
        return $http({
          method: 'GET',
          url: endpointUrl
        }).then(
          function ok(response) {
            decoFrameItemTemplatesCache = {};
            angular.forEach(response.data, function (value, key) {
              var decoFrames = [];
              value.forEach(function (decoFrame) {
                if (decoFrame.designElementId && decoFrame.categories) {
                  decoFrames.push(DecoFrameItemTemplateFactory.createDecoFrameItemTemplate(decoFrame.designElementId, decoFrame.categories[0]));
                }
              });
              decoFrameItemTemplatesCache[key] = decoFrames;
            });

            return decoFrameItemTemplatesCache;
          },
          function error(response) {
            // TODO: we need some global error handling
            $log.error('ERROR: Can\'t get the deco frame data: ', response);
          });
      };

      // definition of the public service functions
      var decoFrameTemplateService = {

        /**
         * @param {String} categoryId
         * @returns the possible cliparts
         */

        getDecoFrameTemplatesByCategory: function (categoryId) {
          return loadDecoFrames().then(function ok(decoFrameCategoryMap) {
            return decoFrameCategoryMap[categoryId];
          });
        },

        getDecoFrameCategoryMap: function () {
          return loadDecoFrames().then(function ok(decoFrameCategoryMap) {
            return decoFrameCategoryMap;
          });
        }

      };

      return decoFrameTemplateService;

    }
  ]);
})();
/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * @author Frank Bruns (frank.bruns@cewe.de)
 * @author Christoph Suhren
 * Date: 02.09.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('DecoFrameItemTemplateFactory', [
    '$log', 'DesignElementItemTemplatePrototypeFactory',
    function ($log, DesignElementItemTemplatePrototypeFactory) {

      function DecoFrameItemTemplate(designElementId, categoryKey) {
        // call super class constructor to instantiate its variables
        DesignElementItemTemplatePrototypeFactory.getClass().call(this);
      }

      DecoFrameItemTemplate.prototype = Object.create(DesignElementItemTemplatePrototypeFactory.getClass().prototype);
      DecoFrameItemTemplate.prototype.constructor = DecoFrameItemTemplate;


      return {

        /**
         *
         * @param {Number} designElementId
         * @param {String} categoryKey (optional)
         * @return {DecoFrameItemTemplate}
         */
        createDecoFrameItemTemplate: function (designElementId, categoryKey) {

          if (!designElementId) {
            throw new Error('Can\'t create the AlphaMaskItemTemplate. One or more parameters are missing or invalid.');
          }

          if (!categoryKey) {
            categoryKey = '';
          }

          var decoFrameItemTemplate = new DecoFrameItemTemplate();
          decoFrameItemTemplate.setDesignElementId(designElementId);
          decoFrameItemTemplate.setCategoryKey(categoryKey);

          return decoFrameItemTemplate;
        },

        getClass: function() {
          return DecoFrameItemTemplate;
        },

        getPrototype: function () {
          return new DecoFrameItemTemplate();
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive represents a DecoFrameItemTemplate for use in the deco frame selection area.
 */
/**
 * @author Frank Bruns (frank.bruns@cewe.de)
 * @author Christoph Suhren
 * Date: 02.09.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwDecoFrameItemTemplate', [
    '$log',
    function ($log) {
      return {
        replace: true,
        scope: {
          templateModel: '=templateModel', // put a DecoFrameItemTemplate instance in here
          width: '&width',
          height: '&height'
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/designelements/decoframes/cwDecoFrameItemTemplate.html.jsf',
        link: function (scope, element, attrs) {

          var decoFrameThumbUrl = 'designElements/designElementImage.rest?previewMode=true&elementId=';

          scope.boxStyle = {
            'width': scope.width,
            'height': scope.height,
            'background': 'url(' + decoFrameThumbUrl + scope.templateModel.getDesignElementId() + ') no-repeat center center /contain'
          };

        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */








//TODO Frank Bruns: 22.07.2014:. The stuff in here will probably go to a dedicated BackgroundsService


/**
 * @author Sascha to the F Friedrich
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('BackgroundTemplateService', [
    '$log', '$http', '$resource', '$q', 'MessageService', 'BackgroundItemTemplateFactory',
    function ($log, $http, $resource, $q, MessageService, BackgroundItemTemplateFactory) {

      var endpointUrl = 'designElements/background.rest';
      var backgroundItemTemplatesCache;

      var loadBackgrounds = function () {
        if (backgroundItemTemplatesCache) {
          return $q.when(backgroundItemTemplatesCache);
        }
        return $http({
          method: 'GET',
          url: endpointUrl
        }).then(
          function ok(response) {
            backgroundItemTemplatesCache = {};
            angular.forEach(response.data, function (value, key) {
              var backgrounds = [];
              value.forEach(function (background) {
                if (background.designElementId && background.categories) {
                  backgrounds.push(BackgroundItemTemplateFactory.createBackgroundItemTemplate(background.designElementId, background.categories[0], background.landscapeSingleSided));
                }
              });
              backgroundItemTemplatesCache[key] = backgrounds;
            });

            return backgroundItemTemplatesCache;
          },
          function error(response) {
            // TODO: we need some global error handling
            $log.error('ERROR: Can\'t get the background data: ', response);
          });
      };

      // definition of the public service functions
      var backgroundTemplateService = {

        /**
         * @param {String} categoryId
         * @returns the possible backgrounds
         */

        getBackgroundTemplatesByCategory: function (categoryId) {
          return loadBackgrounds().then(function ok(backgroundCategoryMap) {
            return backgroundCategoryMap[categoryId];
          });
        },

        getBackgroundCategoryMap: function () {
          return loadBackgrounds().then(function ok(backgroundCategoryMap) {
            return backgroundCategoryMap;
          });
        }

      };

      return backgroundTemplateService;

    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('BackgroundItemTemplateFactory', [
    '$log', 'DesignElementItemTemplatePrototypeFactory',
    function ($log, DesignElementItemTemplatePrototypeFactory) {

      function BackgroundItemTemplate() {
        // call super class constructor to instantiate its variables
        DesignElementItemTemplatePrototypeFactory.getClass().call(this);
        this.landscapeSingleSided = undefined;
      }

      BackgroundItemTemplate.prototype = Object.create(DesignElementItemTemplatePrototypeFactory.getClass().prototype);
      BackgroundItemTemplate.prototype.constructor = BackgroundItemTemplate;


      /**
       *
       * @return {Boolean} is background template meant to be applied single sided only on landscape books?
       */
      BackgroundItemTemplate.prototype.isLandscapeSingleSided = function () {
        return this.landscapeSingleSided;
      };

      /**
       * Set whether the background template is meant to be applied single sided only on landscape books
       * @param trueOrFalse
       */
      BackgroundItemTemplate.prototype.setLandscapeSingleSided = function (trueOrFalse) {
        this.landscapeSingleSided = trueOrFalse;
      };

      return {

        /**
         *
         * @param {Number} designElementId
         * @param {String} [categoryKey]
         * @param [Boolean} [landscapeSingleSided]
         * @return {BackgroundItemTemplate}
         */
        createBackgroundItemTemplate: function (designElementId, categoryKey, landscapeSingleSided) {

          if (!designElementId) {
            throw new Error('Can\'t create the BackgroundItemTemplate. One or more parameters are missing or invalid.');
          }

          if (!categoryKey) {
            categoryKey = '';
          }

          if (!landscapeSingleSided) {
            landscapeSingleSided = false;
          }

          var backgroundItemTemplate = new BackgroundItemTemplate(designElementId, categoryKey, landscapeSingleSided);
          backgroundItemTemplate.setDesignElementId(designElementId);
          backgroundItemTemplate.setCategoryKey(categoryKey);
          backgroundItemTemplate.setLandscapeSingleSided(landscapeSingleSided);

          return backgroundItemTemplate;
        },

        getClass: function() {
          return BackgroundItemTemplate;
        },

        getPrototype: function () {
          return new BackgroundItemTemplate();
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive represents a BackgroundItemTemplate for use in the backgrounds selection area.
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwBackgroundItemTemplate', [
    '$log',
    function ($log) {
      return {
        replace: true,
        scope: {
          templateModel: '=templateModel', // put a BackgroundItemTemplate instance in here
          width: '&width',
          height: '&height',
          dragAllowed: '=dragAllowed'
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/designelements/backgrounds/cwBackgroundItemTemplate.html.jsf',
        link: function (scope, element, attrs) {

          var backgroundThumbUrl = 'designElements/designElementImage.rest?imageSize=thumb&elementId=';

          var boxStyle = {
            width: scope.width,
            height: scope.height
          };

          scope.getBoxStyle = function() {
            if (scope.templateModel.isInitialized()) {
              boxStyle.backgroundImage = 'url(' + backgroundThumbUrl + scope.templateModel.getDesignElementId() + ')';
            }
            return boxStyle;
          };
        }
      };
    }
  ]);
})();
/**
 * Created by friedrichsa on 02.06.2014.
 */

/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A button that can be used to swap the imageItems of a double page half.
 *
 * @since 03.06.2014
 * @author Sascha Friedrich
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwImageSwapButton', [
    '$log', 'DesignAreaService', 'UndoRedoService',
    function ($log, DesignAreaService, UndoRedoService) {

      return {
        restrict: 'A',
        scope: {
          designArea: '=designArea', // a design area model
          pageHalf: '@pageHalf' // passed in value should be 'left' or 'right'
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/designelements/layouts/cwImageSwapButton.html.jsf',
        transclude: false,
        replace: true,
        link: function (scope, element, attrs) {

          scope.btnEnabled = false;

          var watchDeleteHandle = scope.$watch(function watchImageItemCount() {
            return scope.designArea.getImageItems(scope.pageHalf).length;
          }, function onImageItemCountChanged (newValue) {
            scope.btnEnabled = (newValue !== null && newValue > 1);
          });

          scope.$on('$destroy', function destroy() {
            watchDeleteHandle();
          });


          scope.swapImages = function () {
            var undoHandle = UndoRedoService.pushModelData(scope.designArea);
            DesignAreaService.swapImages(scope.designArea, scope.pageHalf);
            undoHandle.resolve();
          };

        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A button that can be used to change the layouts of a double page half.
 *
 * @since 19.05.2014
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwRandomLayoutButton', [
    '$log', 'DesignAreaService', 'LayoutService', 'UndoRedoService', 'NotificationService', 'MessageService',
    function ($log, DesignAreaService, LayoutService, UndoRedoService, NotificationService, MessageService) {

      return {
        restrict: 'A',
        scope: {
          designArea: '=designArea', // a design area model
          pageHalf: '@pageHalf' // passed in value should be 'left' or 'right'
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/designelements/layouts/cwRandomLayoutButton.html.jsf',
        transclude: false,
        replace: true,
        link: function (scope, element, attrs) {

          scope.btnEnabled = false;


          var watchDeleteHandle = scope.$watch(function watchItemCount() {
            return scope.designArea.getImageItems(scope.pageHalf).length;
          }, function onTextItemCountChanged(newValue) {
            scope.btnEnabled = (newValue !== null && newValue > 0);
          });

          scope.$on('$destroy', function destroy() {
            watchDeleteHandle();
          });


          scope.applyRandomLayout = function () {

            var portraitImagesCount = scope.designArea.getPortraitImageItemsForHalfPage(scope.pageHalf).length;
            var landscapeImagesCount = scope.designArea.getLandscapeImageItemsForHalfPage(scope.pageHalf).length;
            var textsCount = scope.designArea.getTextItems(scope.pageHalf, true).length;
            var designAreaOrientation = scope.designArea.getPageHalfOrientation();
            var designAreaType = scope.designArea.getType();

            LayoutService.getRandomLayout(portraitImagesCount, landscapeImagesCount, textsCount, designAreaOrientation, designAreaType, true, false).then(function (layout) {
              if (layout) {
                var undoHandle = UndoRedoService.pushModelData(scope.designArea);
                DesignAreaService.applyLayout(scope.designArea, layout, scope.pageHalf, true);
                undoHandle.resolve();
              }
              else {
                NotificationService.addNotification('', MessageService.getMessage('notification.noLayout'), 'info', 5000);
              }
            });


          };


        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A button that displays a flyout box that shows several layouts to select from and apply to the designated design area page half.
 *
 * @since 26.05.2014
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwSelectionLayoutButton', [
    '$log', 'AppValues', 'Utils', 'DesignAreaService', 'LayoutService',
    function ($log, AppValues, Utils, DesignAreaService, LayoutService) {

      return {
        restrict: 'A',
        scope: {
          designArea: '=designArea', // a design area model
          pageHalf: '@pageHalf' // passed in value should be 'left' or 'right'
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/designelements/layouts/cwSelectionLayoutButton.html.jsf',
        transclude: false,
        replace: true,
        link: function (scope, element, attrs) {
          scope.flyoutHeight = 0;

          scope.flyoutEnabled = scope.pageHalf === 'left' ? AppValues.layoutSelectionLeftOpen : AppValues.layoutSelectionRightOpen;
          scope.flyoutToggledManually = false;

          scope.data = {
            layouts: [],
            usedLayouts: []
          };


          var cssHeightWatch = scope.$watch(function watchCssHeight() {
            return scope.designArea.getCssHeight();
          }, function onCssHeightChanged(newValue) {
            if (newValue) {
              if (scope.flyoutEnabled) {
                scope.flyoutHeight = calculateFlyoutHeight();
              }
            }
          });

          var watchGroupHandle = scope.$watchGroup([
            function watchDesignAreaSelectionState() {
              return scope.designArea.isSelected() && scope.designArea.isDetailInteractionMode();
            },
            function watchItemCountChange() {
              return scope.designArea.getImageAndTextItems(scope.pageHalf).length;
            },
            function watchImageFormatsChange() {
              return scope.designArea.getLandscapeImageItemsForHalfPage(scope.pageHalf).length + '-' + scope.designArea.getPortraitImageItemsForHalfPage(scope.pageHalf).length;
            }
          ], function (newValues, oldValues) {
            if (newValues.length > 0 && newValues[0] === true) {

              if (newValues[1] > 0) {
                requestLayouts();
                requestUsedLayouts();
                if (!scope.flyoutToggledManually && newValues[1] !== oldValues[1]) { // only show the flyout automatically if it was not manually toggled before to avoid annoying the user
                  showFlyout();
                }
              } else {
                scope.data.layouts = [];
                scope.data.usedLayouts = [];
              }

            } else {
              hideFlyout();
            }
          });


          scope.$on('$destroy', function destroy() {
            watchGroupHandle();
            cssHeightWatch();
          });

          scope.toggleFlyout = function () {
            scope.flyoutToggledManually = true;
            scope.flyoutEnabled = !scope.flyoutEnabled;
            if (!scope.flyoutEnabled) {
              hideFlyout();
            } else {
              showFlyout();
            }
          };

          function hideFlyout() {
            scope.flyoutEnabled = false;
            scope.flyoutHeight = 0;
            updateFlyoutStateInAppValues();
          }

          function showFlyout() {
            scope.flyoutEnabled = true;
            scope.flyoutHeight = calculateFlyoutHeight();
            updateFlyoutStateInAppValues();
          }


          function calculateFlyoutHeight() {
            return scope.designArea.getPrintAreaCssHeight() - 3 * 42 + 15;
          }

          function requestLayouts() {
            var imagesCount = scope.designArea.getImageItems(scope.pageHalf).length;
            var textsCount = scope.designArea.getTextItems(scope.pageHalf, true).length;
            var designAreaOrientation = scope.designArea.getPageHalfOrientation();
            var designAreaType = scope.designArea.getType();

            LayoutService.getServerLayouts(imagesCount, textsCount, designAreaType, designAreaOrientation, true).then(function (layouts) {
              scope.data.layouts = layouts;
            });
          }

          function requestUsedLayouts() {
            var designAreaOrientation = scope.designArea.getPageHalfOrientation();
            var imagesCount = scope.designArea.getImageItems(scope.pageHalf).length;
            var textsCount = scope.designArea.getTextItems(scope.pageHalf, true).length;
            var designAreaType = scope.designArea.getType();
            var usedLayouts = LayoutService.getUsedLayouts(imagesCount, textsCount, designAreaType, designAreaOrientation);
            if (textsCount > 0) {
              usedLayouts = usedLayouts.concat(LayoutService.getUsedLayouts(imagesCount, 0, designAreaType, designAreaOrientation));
            }

            scope.data.usedLayouts = usedLayouts;
          }

          function updateFlyoutStateInAppValues() {
            if (scope.pageHalf === 'left') {
              AppValues.layoutSelectionLeftOpen = scope.flyoutEnabled;
            } else{
              AppValues.layoutSelectionRightOpen = scope.flyoutEnabled;
            }
          }
        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This component visualizes a layouts in the form of a thumbnail
 *
 * @since 19.05.2014
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';
  /* global createjs */

  angular.module('tatooine').directive('cwLayoutThumb', [
    '$log', 'AppConstants', 'DesignAreaService', 'UndoRedoService',
    function ($log, AppConstants, DesignAreaService, UndoRedoService) {

      return {
        restrict: 'A',
        scope: {
          layout: '=layout', // a Layout data model to visualize
          designArea: '=designArea', // a DesignArea model the layouts is meant for
          pageHalf: '@pageHalf'
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/designelements/layouts/cwLayoutThumb.html.jsf',
        replace: true,
        link: function (scope, element, attrs) {
          var getSelectedLayout = function () {
            if (!scope.designArea.isLayoutModified(scope.pageHalf) && scope.designArea.getLayoutFromPageHalf(scope.pageHalf)) {
              return scope.designArea.getLayoutFromPageHalf(scope.pageHalf).getId();
            }
            return null;
          };

          var watchSelectedLayout = scope.$watch(
            function watchDesignAreaSelectedLayout() {
              return getSelectedLayout();
            }, function (newValue) {
              if (newValue === scope.layout.getId()) {
                element.addClass('selected');
              } else {
                element.removeClass('selected');
              }
            });


          var now = new Date();
          var id = 'layouts-designArea-' + scope.designArea.getId() + '-' + scope.pageHalf + '-' + scope.layout.getId() + '-' + now.getTime();
          element.attr('id', id);
          if (getSelectedLayout() === scope.layout.getId()) {
            element.addClass('selected');
          }

          var aspectRatioLayoutToPage = DesignAreaService.getAspectRatioLayoutToPage(scope.designArea, scope.layout);
          var scaleX = AppConstants.MM_TO_PX * aspectRatioLayoutToPage.x * 0.12;
          var scaleY = AppConstants.MM_TO_PX * aspectRatioLayoutToPage.y * 0.12;

          var width = scope.layout.getWidth() * scaleX;
          var height = scope.layout.getHeight() * scaleY;

          var borderWidth = 1;

          var stage = new createjs.Stage(id);
          stage.name = id;
          stage.canvas.width = width + 2 * borderWidth;
          stage.canvas.height = height + 2 * borderWidth;
          stage.enableDOMEvents(false);
          stage.mouseEnabled = false;

          // a neutrally colored background shape
          var backgroundShape = new createjs.Shape();
          backgroundShape.graphics.beginFill('#FFFFFF').drawRect(0, 0, stage.canvas.width, stage.canvas.height);
          stage.addChild(backgroundShape);

          // draw image box of the layouts
          var layoutBoxes = scope.layout.getBoxes();
          layoutBoxes.forEach(function (layoutBox) {
            var strokeColor = layoutBox.getBoxType() === 'image' ? 'lightgray' : 'lightgray';
            var fillColor = layoutBox.getBoxType() === 'image' ? '#aecbf5' : 'lightgray';

            if (layoutBox.getBoxType() === 'image') {
              var layoutImageContainer = new createjs.Container();
              layoutImageContainer.name = 'layoutImageContainer';
              layoutImageContainer.width = layoutBox.getWidth() * scaleX;
              layoutImageContainer.height = layoutBox.getHeight() * scaleY;
              layoutImageContainer.regX = (layoutBox.getWidth() / 2) * scaleX;
              layoutImageContainer.regY = (layoutBox.getHeight() / 2) * scaleY;
              layoutImageContainer.x = layoutBox.getCenterX() * scaleX + borderWidth;
              layoutImageContainer.y = layoutBox.getCenterY() * scaleY + borderWidth;

              var canvasImageBox = new createjs.Shape();
              canvasImageBox.graphics.beginStroke(strokeColor).beginFill(fillColor).drawRect(0, 0, layoutBox.getWidth() * scaleX, layoutBox.getHeight() * scaleY);
              layoutImageContainer.addChild(canvasImageBox);

              var radialGradient = new createjs.Shape();
              radialGradient.graphics.beginRadialGradientFill(['rgba(227,235,248,0.4)', 'rgba(166,205,238,0.0)'], [0, 1], layoutBox.getWidth() * scaleX / 100 * 50, layoutBox.getHeight() * scaleY / 100 * 50, 0, layoutBox.getWidth() * scaleX / 100 * 50, layoutBox.getHeight() * scaleY / 100 * 50, layoutBox.getWidth() * scaleX / 100 * 50).drawCircle(layoutBox.getWidth() * scaleX / 100 * 50, layoutBox.getHeight() * scaleX / 100 * 40, layoutBox.getWidth() * scaleX / 100 * 25);
              layoutImageContainer.addChild(radialGradient);

              var mountainPartOne = new createjs.Shape();
              mountainPartOne.graphics.setStrokeStyle(2);
              mountainPartOne.graphics.beginStroke('white');
              mountainPartOne.graphics.moveTo(0, layoutBox.getHeight() * scaleY / 100 * 50);
              mountainPartOne.graphics.lineTo(layoutBox.getWidth() * scaleX / 100 * 25, layoutBox.getHeight() * scaleY / 100 * 20);
              mountainPartOne.graphics.lineTo(layoutBox.getWidth() * scaleX / 100 * 50, layoutBox.getHeight() * scaleY / 100 * 50);
              mountainPartOne.graphics.endStroke();

              var mountainPartTwo = new createjs.Shape();
              mountainPartTwo.graphics.setStrokeStyle(2);
              mountainPartTwo.graphics.beginStroke('white');
              mountainPartTwo.graphics.moveTo(layoutBox.getWidth() * scaleX / 100 * 50, layoutBox.getHeight() * scaleY / 100 * 50);
              mountainPartTwo.graphics.lineTo(layoutBox.getWidth() * scaleX / 100 * 75, layoutBox.getHeight() * scaleY / 100 * 20);
              mountainPartTwo.graphics.lineTo(layoutBox.getWidth() * scaleX / 100 * 100, layoutBox.getHeight() * scaleY / 100 * 50);

              layoutImageContainer.addChild(mountainPartOne);
              layoutImageContainer.addChild(mountainPartTwo);
              layoutImageContainer.rotation = layoutBox.getRotation();
              stage.addChild(layoutImageContainer);
            }

            if (layoutBox.getBoxType() === 'text') {
              var layoutTextContainer = new createjs.Container();
              layoutTextContainer.name = 'layoutTextContainer';
              layoutTextContainer.width = layoutBox.getWidth() * scaleX;
              layoutTextContainer.height = layoutBox.getHeight() * scaleY;
              layoutTextContainer.regX = (layoutBox.getWidth() / 2) * scaleX;
              layoutTextContainer.regY = (layoutBox.getHeight() / 2) * scaleY;
              layoutTextContainer.x = layoutBox.getCenterX() * scaleX + borderWidth;
              layoutTextContainer.y = layoutBox.getCenterY() * scaleY + borderWidth;

              var canvasTextBackground = new createjs.Shape();
              canvasTextBackground.graphics.beginFill('#fff').drawRect(0, 0, layoutBox.getWidth() * scaleX, layoutBox.getHeight() * scaleY);
              layoutTextContainer.addChild(canvasTextBackground);

              var neededLines = 12 - parseInt(stage.canvas.height / layoutTextContainer.height, 10);
              if (neededLines < 3) {
                neededLines = 3;
              }

              for (var i = 0; i < neededLines; i++) {
                var textLine = new createjs.Shape();
                textLine.graphics.beginStroke(strokeColor);
                textLine.graphics.moveTo(0, layoutBox.getHeight() * scaleY / neededLines * i);
                textLine.graphics.lineTo(layoutBox.getWidth() * scaleX, layoutBox.getHeight() * scaleY / neededLines * i);
                layoutTextContainer.addChild(textLine);
              }


              layoutTextContainer.rotation = layoutBox.getRotation();

              stage.addChild(layoutTextContainer);
            }
          });

          var outline = new createjs.Shape();
          outline.graphics.setStrokeStyle(borderWidth).beginStroke('black').drawRect(0, 0, width + borderWidth, height + borderWidth);
          stage.addChild(outline);


          stage.update();


          scope.applyLayout = function () {
            var undoHandle = UndoRedoService.pushModelData(scope.designArea);
            DesignAreaService.applyLayout(scope.designArea, scope.layout, scope.pageHalf, true);
            $log.debug(scope.layout);
            undoHandle.resolve();
          };


          scope.$on('$destroy', function destroy() {
            if (stage) {
              stage.removeAllChildren();
              stage.removeAllEventListeners();
              watchSelectedLayout();
            }
            stage = null;
          });

        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Provides a service for layouts data model tasks.
 */
(function () {
  'use strict';

  angular.module('tatooine').factory('LayoutService', [
    '$log', '$q', '$resource', '$timeout', '$filter', '$cacheFactory', 'Utils', 'AppConstants', 'ProductService', 'LayoutFactory', 'LayoutBoxFactory',
    function ($log, $q, $resource, $timeout, $filter, $cacheFactory, Utils, AppConstants, ProductService, LayoutFactory, LayoutBoxFactory) {


      var cacheForServerLayout = $cacheFactory('serverLayouts');
      var cacheForUsedLayouts = $cacheFactory('usedLayouts');
      var cacheForReturnedRandomLayouts = $cacheFactory('returnedRandomLayouts');
      var filter = $filter('filter');

      function cacheReturnedRandomLayout(layout, imagesCount, orientation) {
        var key = orientation + '-imagesCount-' + imagesCount;

        var layouts = cacheForReturnedRandomLayouts.get(key);
        if (!layouts) {
          layouts = [];
          layouts.push(layout);
          cacheForReturnedRandomLayouts.put(key, layouts);
        } else {
          for (var i = 0; i < layouts.length; i++) {
            // if the layouts is already cached, we have nothin to do here
            if (angular.equals(layouts[i], layout)) {
              return;
            }
          }
          layouts.push(layout);
        }
      }

      function cacheUsedLayout(layout, imagesCount, textsCount, orientation) {
        var key = orientation + '-imagesCount-' + imagesCount + '-textsCount-' + textsCount;

        var layouts = cacheForUsedLayouts.get(key);
        if (!layouts) {
          layouts = [];
          layouts.push(layout);
          cacheForUsedLayouts.put(key, layouts);
        } else {
          for (var i = 0; i < layouts.length; i++) {
            // if the layouts is already cached, we have nothing to do here
            if (angular.equals(layouts[i], layout)) {
              return;
            }
          }
          layouts.push(layout);
        }
      }


      function getLayouts(imageAreaCount, textAreaCount, designAreaType, orientation) {

        // TODO Frank Bruns 09.04.2015: Use an object for the key which could be passed as the method parameters, too
        var key = orientation + '-imagesCount-' + imageAreaCount + '-textsCount-' + textAreaCount;

        var cachedLayouts = cacheForServerLayout.get(key);

        var deferred = $q.defer();


        // prevent a request that can't return a positive result
        if (imageAreaCount === 0 && textAreaCount === 0) {

          deferred.resolve([]);

        } else {

          if (cachedLayouts && cachedLayouts.length > 0) {
            $log.debug('Retrieved layouts from cache by key:', key);

            // filter for 'inbook' or coverPage
            var filteredLayouts = filter(cachedLayouts, {designAreaType: designAreaType});

            deferred.resolve(filteredLayouts);

          } else { // no fitting layouts in cache? --> ask the server for layouts

            var layoutUrl = 'layouts/' + orientation + '.rest';

            var urlParams = {
              imageAreaCount: imageAreaCount,
              textAreaCount: textAreaCount
            };

            $log.debug('Request layouts from server:' + layoutUrl, urlParams);

            var LayoutResource = $resource(layoutUrl, urlParams);

            LayoutResource.query(function ok(plainLayouts) {

              // make the plain JSON objects real class instances
              var layouts = convertPlainLayoutObjectsToLayoutClassInstances(plainLayouts);


              // add layouts to cache for avoiding the need to request them from the server again, except for parameter
              $log.debug('Put layouts from server to cache by key:', key);
              cacheForServerLayout.put(key, layouts);

              // filter for 'inbook' or coverPage
              var filteredLayouts = filter(layouts, {designAreaType: designAreaType});

              deferred.resolve(filteredLayouts);

            }, function error() {

              deferred.reject();
              $log.error('Failed to get layouts from server!', LayoutResource);

            });

          }

        }

        return deferred.promise;

      }


      /**
       * Returns the random Layouts that have been returned so far.
       * @param imagesCount
       * @param orientation
       * @return {*}
       */
      function getReturnedRandomLayouts(imagesCount, orientation) {
        var key = orientation + '-imagesCount-' + imagesCount;
        var returnedRandomLayouts = cacheForReturnedRandomLayouts.get(key);
        if (returnedRandomLayouts && returnedRandomLayouts.length > 0) {
          $log.debug('Retrieved previously returned random layouts from cache by key:', key);
          return returnedRandomLayouts;
        }

        return [];
      }

      function getImageFormatSpecificLayouts(portraitAreaCount, landscapeAreaCount, textAreaCount, designAreaType, orientation, subCategoryLargeOnly) {

        // TODO Frank Bruns 30.05.2014: Use an object for the key which could be passed as the method parameters, too
        var key = orientation + '-imgPort-' + portraitAreaCount + '-imgLand-' + landscapeAreaCount + '-txt-' + textAreaCount;

        var cachedLayouts = cacheForServerLayout.get(key);

        var deferred = $q.defer();


        // prevent a request that can't return a positive result
        if (portraitAreaCount === 0 && landscapeAreaCount === 0 && textAreaCount === 0) {

          deferred.resolve([]);

        } else {

          if (cachedLayouts && cachedLayouts.length > 0) {
            $log.debug('Retrieved layouts from cache by key:', key);

            // filter for 'inbook' or coverPage
            var filteredLayouts = filter(cachedLayouts, {designAreaType: designAreaType});

            deferred.resolve(filteredLayouts);

          } else { // no fitting layouts in cache? --> ask the server for layouts

            var layoutUrl = 'layouts/' + orientation + '/imageformatspecific.rest';

            var urlParams = {
              portraitAreaCount: portraitAreaCount,
              landscapeAreaCount: landscapeAreaCount,
              textAreaCount: textAreaCount,
              subCategoryLargeOnly: subCategoryLargeOnly
            };

            $log.debug('Request layouts from server:' + layoutUrl, urlParams);

            var LayoutResource = $resource(layoutUrl, urlParams);

            LayoutResource.query(function ok(plainLayouts) {

              // make the plain JSON objects real class instances
              var layouts = convertPlainLayoutObjectsToLayoutClassInstances(plainLayouts);

              // add layouts to cache for avoiding the need to request them from the server again, except for parameter
              // subCategoryLargeOnly, only the autofill uses this now, but we dont want to cache just large layouts if the button is used first
              if (!subCategoryLargeOnly) {
                $log.debug('Put layouts from server to cache by key:', key);

                cacheForServerLayout.put(key, layouts);
              }
              // filter for 'inbook' or coverPage
              var filteredLayouts = filter(layouts, {designAreaType: designAreaType});

              deferred.resolve(filteredLayouts);

            }, function error() {

              deferred.reject();
              $log.error('Failed to get layouts from server!', LayoutResource);

            });

          }

        }

        return deferred.promise;

      }


      /**
       * Converts plain layout objects as received from the server to Layout instances. This method also takes care of mirroring the layouts
       * as needed.
       * @param {Array} plainLayouts plain layout object
       * @return {Array} array of Layout instances
       */
      function convertPlainLayoutObjectsToLayoutClassInstances(plainLayouts) {

        if (!plainLayouts) {
          throw new Error('Required an array, but was ' + plainLayouts);
        }

        var layoutInstances = [];

        plainLayouts.forEach(function (plainLayout) {

          var layout = angular.extend(LayoutFactory.getPrototype(), plainLayout);
          var layoutBoxes = layout.getBoxes();
          for (var i = 0; i < layoutBoxes.length; i++) {
            layoutBoxes[i] = angular.extend(LayoutBoxFactory.getPrototype(), layoutBoxes[i]);
          }

          layoutInstances.push(layout);

          // add mirrored versions of the layouts if so specified in the layouts definition
          if (layout.getMirrored() === 'x-axis') {
            layoutInstances.push(LayoutFactory.createMirroredLayout(layout, true, false));
          }
          if (layout.getMirrored() === 'y-axis') {
            layoutInstances.push(LayoutFactory.createMirroredLayout(layout, false, true));
          }
          if (layout.getMirrored() === 'both') {
            layoutInstances.push(LayoutFactory.createMirroredLayout(layout, true, false));
            layoutInstances.push(LayoutFactory.createMirroredLayout(layout, false, true));
            layoutInstances.push(LayoutFactory.createMirroredLayout(layout, true, true));
          }

        });

        return layoutInstances;
      }


      // definition of the public service functions
      var layoutService = {

        getServerLayouts: function (imageAreaCount, textAreaCount, designAreaType, orientation, addLayoutsWithoutText) {
          return getLayouts(imageAreaCount, textAreaCount, designAreaType, orientation).then(function (layouts) {
            if (addLayoutsWithoutText && textAreaCount > 0) {
              return getLayouts(imageAreaCount, 0, designAreaType, orientation).then(function (imageOnlyLayouts) {
                return layouts.concat(imageOnlyLayouts);
              });
            } else {
              return layouts;
            }
          });
        },

        getImageFormatSpecificServerLayouts: function (portraitAreaCount, landscapeAreaCount, textAreaCount, designAreaType, orientation, subCategoryLargeOnly, addLayoutsWithoutText) {
          return getImageFormatSpecificLayouts(portraitAreaCount, landscapeAreaCount, textAreaCount, designAreaType, orientation, subCategoryLargeOnly).then(function (layouts) {
            if (addLayoutsWithoutText && textAreaCount > 0) {
              return getImageFormatSpecificLayouts(portraitAreaCount, landscapeAreaCount, 0, designAreaType, orientation).then(function (imageOnlyLayouts) {
                return layouts.concat(imageOnlyLayouts);
              });
            } else {
              return layouts;
            }
          });
        },

        /**
         * Returns Layouts that have been used on DesignAreas so far.
         * @param imagesCount
         * @param textsCount
         * @param designAreaType
         * @param orientation
         * @return {Array} array of Layouts
         */
        getUsedLayouts: function (imagesCount, textsCount, designAreaType, orientation) {
          var key = orientation + '-imagesCount-' + imagesCount + '-textsCount-' + textsCount;
          var usedLayouts = cacheForUsedLayouts.get(key);

          // filter for 'inbook' or coverPage
          var filteredLayouts = filter(usedLayouts, {designAreaType: designAreaType});

          if (filteredLayouts && filteredLayouts.length > 0) {
            $log.debug('Retrieved usedLayouts from cache by key:', key);
            return filteredLayouts;
          }

          return [];
        },


        /**
         * Stores the ItemBox configurations on the specified DesignArea as Layouts in the used layouts cache.
         * @param designArea
         * @param project the project the DesignArea belongs to
         */
        cacheLayoutsFromDesignArea: function (designArea, project) {
          $log.debug('Caching layouts from design area ', designArea.getId());

          var product = ProductService.getProductById(project.getProductId());

          var layoutLeft = designArea.getLayoutFromPageHalf('left');
          var portraitsLeft = designArea.getPortraitImageItemsForHalfPage('left').length;
          var landscapesLeft = designArea.getLandscapeImageItemsForHalfPage('left').length;
          var textsLeft = designArea.getTextItems('left', true).length;
          if (portraitsLeft > 0 || landscapesLeft > 0 || textsLeft > 0) {
            if (layoutLeft && !layoutLeft.isCustomLayout() && !designArea.isLayoutModified('left')) {
              cacheUsedLayout(layoutLeft, portraitsLeft + landscapesLeft, textsLeft, designArea.getPageHalfOrientation());
            } else { // create custom layouts of left page half
              var customLayoutLeft = LayoutFactory.createLayoutFromDesignAreaContent('custom-layouts', designArea, 'left');
              if (customLayoutLeft) {
                cacheUsedLayout(customLayoutLeft, portraitsLeft + landscapesLeft, textsLeft, designArea.getPageHalfOrientation());
              }
            }
          }

          var layoutRight = designArea.getLayoutFromPageHalf('right');
          var portraitsRight = designArea.getPortraitImageItemsForHalfPage('right').length;
          var landscapesRight = designArea.getLandscapeImageItemsForHalfPage('right').length;
          var textsRight = designArea.getTextItems('right', true).length;
          if (portraitsRight > 0 || landscapesRight > 0 || textsRight > 0) {
            if (layoutRight && !layoutRight.isCustomLayout() && !designArea.isLayoutModified('right')) {
              cacheUsedLayout(layoutRight, portraitsRight + landscapesRight, textsRight, designArea.getPageHalfOrientation());
            } else { // create custom layouts of right page half
              var customLayoutRight = LayoutFactory.createLayoutFromDesignAreaContent('custom-layouts', designArea, 'right');
              if (customLayoutRight) {
                cacheUsedLayout(customLayoutRight, portraitsRight + landscapesRight, textsRight, designArea.getPageHalfOrientation());
              }
            }
          }
        },

        clearReturnedRandomLayoutsCache: function () {
          cacheForReturnedRandomLayouts.removeAll();
        },

        clearUsedLayoutsCache: function () {
          cacheForUsedLayouts.removeAll();
        },

        /**
         * Returns a random layouts for the specified number of portrait and landscape image boxes
         * @param portraitImagesCount
         * @param landscapeImagesCount
         * @param textsCount
         * @param orientation
         * @param designAreaType
         * @param includingUsedLayouts consider the set of used layouts for retrieval (with potential higher priority)
         * @param subCategoryLargeOnly
         * @return {Layout} a random layouts, if one was available
         */
        getRandomLayout: function (portraitImagesCount, landscapeImagesCount, textsCount, orientation, designAreaType, includingUsedLayouts, subCategoryLargeOnly) {
          return layoutService.getImageFormatSpecificServerLayouts(portraitImagesCount, landscapeImagesCount, textsCount, designAreaType, orientation, subCategoryLargeOnly, false).then(function (ceweLayouts) {

            var usedLayouts = layoutService.getUsedLayouts(portraitImagesCount + landscapeImagesCount, textsCount, designAreaType, orientation);
            var returnedRandomLayouts = getReturnedRandomLayouts(portraitImagesCount + landscapeImagesCount, orientation);

            // get a random layouts from the array, filtered by page type
            //var filter = $filter('filter');
            //var filteredLayouts = filter(layouts, {designAreaType: designAreaType});

            var foundLayout = null;
            if (ceweLayouts.length > 0) {
              foundLayout = ceweLayouts[Utils.getRandomInt(0, ceweLayouts.length - 1)];
            }

            if (includingUsedLayouts) {
              var random = Math.random();

              // chance to get this way is configurable by the Constant USED_LAYOUT_BY_RANDOM_BUTTON_CHANCE
              if (usedLayouts.length > 0 && random < AppConstants.USED_LAYOUT_BY_RANDOM_BUTTON_CHANCE) {

                var usedLayout = usedLayouts[Utils.getRandomInt(0, usedLayouts.length - 1)];

                foundLayout = usedLayout;

                if (returnedRandomLayouts.length > 0) {

                  // we got already layouts in previouslyReturnedLayouts cache
                  var tries = 10 + 1;

                  // is the layouts already in the cache? so we don t want it
                  while (Utils.isInArray(returnedRandomLayouts, foundLayout) && tries > 0) {
                    usedLayout = usedLayouts[Utils.getRandomInt(0, usedLayouts.length - 1)];
                    foundLayout = usedLayout;
                    tries--;
                    // ok jonnyBoy, 10 times but all layouts are already cached?, we will give u a cewe standard layouts ;)
                    if (tries === 1 && ceweLayouts.length > 0) {
                      var ceweLayout = ceweLayouts[Utils.getRandomInt(0, ceweLayouts.length - 1)];
                      cacheReturnedRandomLayout(ceweLayout, portraitImagesCount + landscapeImagesCount, orientation);
                      foundLayout = ceweLayout;
                      break;
                    }
                  }

                }

              }

            }


            if (foundLayout) {
              cacheReturnedRandomLayout(foundLayout, portraitImagesCount + landscapeImagesCount, orientation);
              return foundLayout;
            }

          });
        }

      };


      return layoutService;
    }
  ])
  ;
})
();
/**
 *
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('LayoutFactory', [
    '$log', '$filter', 'AppConstants', 'Utils', 'LayoutBoxFactory', 'ImageItemFactory',
    function ($log, $filter, AppConstants, Utils, LayoutBoxFactory, ImageItemFactory) {

      var filter = $filter('filter');

      var subtractBleedMargin = function(itemBox, designArea, pageHalf) {
        var result = angular.copy(itemBox);

        if (result.getRotation() % 90 !== 0) {
          return result;
        }
        var switchDimensions = result.getRotation() === 90 || result.getRotation() === 270;
        var maxDelta = 0.1;

        // check top bleed margin
        if (Math.abs(result.getCenterY() - (switchDimensions ? result.getWidth() : result.getHeight()) / 2 + designArea.getBleedMarginVertical()) <= maxDelta) {
          if (switchDimensions) {
            result.setWidth(result.getWidth() - designArea.getBleedMarginVertical());
            result.setCenterY(result.getWidth() / 2);
          } else {
            result.setHeight(result.getHeight() - designArea.getBleedMarginVertical());
            result.setCenterY(result.getHeight() / 2);
          }
        }

        // check bottom bleed margin
        if (Math.abs(result.getCenterY() + (switchDimensions ? result.getWidth() : result.getHeight()) / 2 - designArea.getHeight() - designArea.getBleedMarginVertical()) <= maxDelta) {
          if (switchDimensions) {
            result.setWidth(result.getWidth() - designArea.getBleedMarginVertical());
            result.setCenterY(designArea.getHeight() - (result.getWidth() / 2));
          } else {
            result.setHeight(result.getHeight() - designArea.getBleedMarginVertical());
            result.setCenterY(designArea.getHeight() - (result.getHeight() / 2));
          }
        }

        if (pageHalf === 'left') {
          // check left bleed margin
          if (Math.abs(result.getCenterX() - (switchDimensions ? result.getHeight() : result.getWidth()) / 2 + designArea.getBleedMarginHorizontal()) <= maxDelta) {
            if (switchDimensions) {
              result.setHeight(result.getHeight() - designArea.getBleedMarginHorizontal());
              result.setCenterX(result.getHeight() / 2);
            } else {
              result.setWidth(result.getWidth() - designArea.getBleedMarginHorizontal());
              result.setCenterX(result.getWidth() / 2);
            }
          }
        }

        if (pageHalf === 'right') {
          // check right bleed margin
          if (Math.abs(result.getCenterX() + (switchDimensions ? result.getHeight() : result.getWidth()) / 2 - designArea.getWidth() - designArea.getBleedMarginHorizontal()) <= maxDelta) {
            if (switchDimensions) {
              result.setHeight(result.getHeight() - designArea.getBleedMarginHorizontal());
              result.setCenterX(designArea.getHeight() - (result.getWidth() / 2));
            } else {
              result.setWidth(result.getWidth() - designArea.getBleedMarginHorizontal());
              result.setCenterX(designArea.getWidth() - (result.getWidth() / 2));
            }
          }
        }
        return result;
      };

      function Layout() {
        this.id = 0;
        this.width = 0;
        this.height = 0;
        this.mirrored = false;
        this.designAreaType = 'inbook';
        this.layoutBoxes = [];
      }

      Layout.prototype.setId = function (id) {
        this.id = id;
      };

      Layout.prototype.getId = function () {
        return this.id;
      };

      Layout.prototype.getIdAsString = function () {
        return this.id.toString();
      };

      Layout.prototype.setWidth = function (width) {
        this.width = width;
      };

      Layout.prototype.getWidth = function () {
        return this.width;
      };

      Layout.prototype.setHeight = function (height) {
        this.height = height;
      };

      Layout.prototype.getHeight = function () {
        return this.height;
      };

      Layout.prototype.getDesignAreaType = function () {
        return this.designAreaType;
      };

      Layout.prototype.setDesignAreaType = function (pageType) {
        this.designAreaType = pageType;
      };

      Layout.prototype.getMirrored = function () {
        return this.mirrored;
      };

      Layout.prototype.setMirrored = function (mirrored) {
        this.mirrored = mirrored;
      };

      Layout.prototype.isCoverLayout = function () {
        return this.getDesignAreaType() === 'cover';
      };

      /**
       * @returns {Array} the layout's boxes
       */
      Layout.prototype.getBoxes = function () {
        return this.layoutBoxes;
      };

      /**
       * @returns {Array} the layout's image boxes
       */
      Layout.prototype.getImageBoxes = function () {
        return filter(this.layoutBoxes, {boxType: 'image'});
      };

      /**
       * @returns {Array} the layout's text boxes
       */
      Layout.prototype.getTextBoxes = function () {
        return filter(this.layoutBoxes, {boxType: 'text'});
      };

      Layout.prototype.addBox = function (layoutBox) {
        this.layoutBoxes.push(layoutBox);
      };

      Layout.prototype.isCustomLayout = function() {
        return this.id.toString().indexOf('custom-layouts') === 0;
      };

      var layoutFactory = {

        getClass: function() {
          return Layout;
        },

        getPrototype: function () {
          return new Layout();
        },

        createLayout: function (id, width, height) {

          if (width === null || width <= 0 || height === null || height <= 0) {
            throw new Error('Can\'t create a Layout with insufficiently defined width (' + width + ') or height (' + height + ')');
          }

          var layout = new Layout();
          layout.setId(id);
          layout.setWidth(width);
          layout.setHeight(height);

          return layout;
        },

        /**
         * Create a mirrored version of the specified layouts
         * @param layout the Layout to mirror
         * @param mirrorX mirror along x-axis?
         * @param mirrorY mirror along y-axis?
         */
        createMirroredLayout: function (layout, mirrorX, mirrorY) {

          if (layout === null || mirrorX === null || mirrorY === null) {
            throw new Error('Can\'t create a mirrored Layout. One or more parameters a missing or invalid.');
          }

          var mirroredLayout = angular.extend(layoutFactory.getPrototype(), angular.copy(layout));

          mirroredLayout.setId(mirroredLayout.getId() + '-' + (mirrorX ? 'x' : '') + (mirrorY ? 'y' : ''));


          // calculate mirrored item boxes
          mirroredLayout.getBoxes().forEach(function (layoutItemBox) {

            if (mirrorX) {
              var y = mirroredLayout.getHeight() - layoutItemBox.getCenterY();
              layoutItemBox.setCenterY(y);
            }

            if (mirrorY) {
              var x = mirroredLayout.getWidth() - layoutItemBox.getCenterX();
              layoutItemBox.setCenterX(x);
            }

            if (mirrorX !== mirrorY) {
              layoutItemBox.setRotation(360 - layoutItemBox.getRotation());
            }

          });

          return mirroredLayout;

        },

        /**
         * Creates a Layout object from the contents of the specified DesignArea.
         * @param layoutIdPrefix the prefix for the layouts id for the Layout to create (a calculated suffix will be appended to that)
         * @param designArea the DesignArea to create the Layout from
         * @param pageHalf the DesignArea's page half to consider for the Layout content
         * @param pagesCount the number of pages of the current Project
         * @param product the Product the Project is currently based on
         * @return {Layout} a Layout object if the DesignArea actually had content on the specified page half
         */
        createLayoutFromDesignAreaContent: function (layoutIdPrefix, designArea, pageHalf) {

          var imageAndTextItems = designArea.getImageAndTextItems(pageHalf);

          if (imageAndTextItems.length <= 0) {
            return; // no content --> no layouts
          }

          var doublePageWidth = Math.round(designArea.getWidth());
          var doublePageHeight = Math.round(designArea.getHeight());
          var spineWidth = designArea.isCover() ? designArea.getSpineWidth() * AppConstants.MM_TO_PX : 0;
          var rightPageOffset = 0;
          if (pageHalf === 'right') {
            rightPageOffset = doublePageWidth / 2 + spineWidth / 2;
          }

          var layout = layoutFactory.createLayout(layoutIdPrefix, (doublePageWidth  - spineWidth) / 2, doublePageHeight);
          layout.setDesignAreaType(designArea.getType());

          var id = '';
          // fetch all boxes attributes, and put them to the new layouts
          imageAndTextItems.forEach(function iterItemBoxes(itemBox) {
            if (!itemBox.isPositionEditable()) {
              return;
            }

            var checkedItemBox = subtractBleedMargin(itemBox, designArea, pageHalf);

            var centerX = Math.round(checkedItemBox.getCenterX() - rightPageOffset);
            var centerY = Math.round(checkedItemBox.getCenterY());
            var width = Math.round(checkedItemBox.getWidth());
            var height = Math.round(checkedItemBox.getHeight());
            var rotation = Math.round(checkedItemBox.getRotation());

            var boxType = checkedItemBox instanceof ImageItemFactory.getClass() ? 'image' : 'text';
            var layoutBox = LayoutBoxFactory.createLayoutBox(boxType, centerX, centerY, width, height, rotation);
            id = id + centerX.toString() + centerY.toString() + width.toString() + height.toString() + rotation.toString();
            layout.addBox(layoutBox);
          });
          layout.setId(layoutIdPrefix + '-' + id);

          return layout;
        }
      };

      return layoutFactory;
    }
  ]);
})();/**
 *
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('LayoutBoxFactory', [
    '$log',
    function ($log) {

      function LayoutBox() {

        this.boxType = null;
        this.centerX = 0;
        this.centerY = 0;
        this.width = 0;
        this.height = 0;
        this.rotation = 0;
        this.defaultText = null;

      }

      LayoutBox.prototype.getBoxType = function() {
        return this.boxType;
      };

      LayoutBox.prototype.setBoxType = function(boxType) {
        this.boxType = boxType;
      };

      LayoutBox.prototype.getCenterX = function () {
        return this.centerX;
      };

      LayoutBox.prototype.setCenterX = function (centerX) {
        this.centerX = centerX;
      };

      LayoutBox.prototype.getCenterY = function () {
        return this.centerY;
      };

      LayoutBox.prototype.setCenterY = function (centerY) {
        this.centerY = centerY;
      };

      LayoutBox.prototype.getWidth = function () {
        return this.width;
      };

      LayoutBox.prototype.setWidth = function (width) {
        this.width = width;
      };

      LayoutBox.prototype.getHeight = function () {
        return this.height;
      };

      LayoutBox.prototype.setHeight = function (height) {
        this.height = height;
      };

      LayoutBox.prototype.getRotation = function () {
        return this.rotation;
      };

      LayoutBox.prototype.setRotation = function (rotation) {
        this.rotation = (rotation + 360) % 360;
      };

      LayoutBox.prototype.getDefaultText = function() {
        return this.defaultText;
      };

      LayoutBox.prototype.setDefaultText = function(defaultText) {
        this.defaultText = defaultText;
      };

      LayoutBox.prototype.isImageBox = function() {
        return this.getBoxType() === 'image';
      };

      LayoutBox.prototype.isTextBox = function() {
        return this.getBoxType() === 'text';
      };


      return {

        getClass: function() {
          return LayoutBox;
        },

        getPrototype: function () {
          return new LayoutBox();
        },

        createLayoutBox: function (boxType, centerX, centerY, width, height, rotation, defaultText) {

          if ((boxType !== 'image' && boxType !== 'text' ) || centerX === null || centerY === null ||
            width === null || width <= 0 || height === null || height <= 0 || rotation === null) {
            throw new Error('Can\'t create LayoutBox. One or more parameters a missing or invalid.');
          }

          var layoutBox = new LayoutBox();

          layoutBox.setBoxType(boxType);
          layoutBox.setCenterX(centerX);
          layoutBox.setCenterY(centerY);
          layoutBox.setWidth(width);
          layoutBox.setHeight(height);
          layoutBox.setRotation(rotation);
          if (defaultText) {
            layoutBox.setDefaultText(defaultText);
          }

          return layoutBox;
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive represents a text item template for use in the text selection area.
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwTextItemTemplate', [
    '$log',
    function ($log) {
      return {
        replace: true,
        scope: {
          templateModel: '=templateModel', // put a TextItemTemplate instance in here
          width: '&width',
          height: '&height',
          dragAllowed: '=dragAllowed'
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/designelements/texts/cwTextItemTemplate.html.jsf',
        link: function (scope, element, attrs) {
          scope.boxStyle = {
            'width': scope.width(),
            'height': scope.height(),
            'background-color': scope.templateModel.getBackgroundColor()
          };

          scope.textStyle = {
            'color': scope.templateModel.getTextColor(),
            'font-family': scope.templateModel.getFont().getFamily(),
            'font-size': scope.templateModel.getFontSize()
          };


          scope.$on('$destroy', function destroy() {
            // TODO clean up directive on destruction
          });

        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This factory creates TextItemTemplates that can hold information about potential predefined settings for TextItems.
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('TextItemTemplateFactory', [
    '$log',
    function ($log) {

      function TextItemTemplate() {
        this.text = null;
        this.placeholderText = null;
        this.textAnchor = null;
        this.textColor = null;
        this.backgroundColor = null;
        this.font = null;
        this.fontSize = null;
        this.fontStyle = null;
        this.textDecoration =null;
        this.fontWeight = null;
        this.padding = null;
        this.verticalAlign = null;
      }

      TextItemTemplate.prototype.getText = function () {
        return this.text;
      };

      TextItemTemplate.prototype.$$setText = function (text) {
        this.text = text;
      };

      /**
       * Returns the text that is meant to be shown in a TextItem if there is no real text content available yet.
       * The placeholder text will not get produced.
       * @return {null|*} the TextItemTemplate's placeholder text
       */
      TextItemTemplate.prototype.getPlaceholderText = function () {
        return this.placeholderText;
      };

      /**
       * Sets a placeholder text that will be shown in a TextItem if there is no real text content available yet.
       * The placeholder text will not get produced.
       * @param text the TextItemTemplate's placeholder text
       */
      TextItemTemplate.prototype.$$setPlaceholderText = function (text) {
        this.placeholderText = text;
      };

      TextItemTemplate.prototype.getTextAnchor = function () {
        return this.textAnchor;
      };

      TextItemTemplate.prototype.$$setTextAnchor = function (textAnchor) {
        this.textAnchor = textAnchor;
      };

      TextItemTemplate.prototype.getTextColor = function () {
        return this.textColor;
      };

      TextItemTemplate.prototype.$$setTextColor = function (textColor) {
        this.textColor = textColor;
      };

      TextItemTemplate.prototype.getBackgroundColor = function () {
        return this.backgroundColor;
      };

      TextItemTemplate.prototype.$$setBackgroundColor = function (bgColor) {
        this.backgroundColor = bgColor;
      };

      TextItemTemplate.prototype.getPadding = function () {
        return this.padding;
      };

      TextItemTemplate.prototype.$$setPadding = function (padding) {
        this.padding = padding;
      };

      TextItemTemplate.prototype.$$setVerticalAlign = function (verticalAlign) {
        this.verticalAlign = verticalAlign;
      };

      TextItemTemplate.prototype.getVerticalAlign = function () {
        return this.verticalAlign;
      };

      /**
       * @return {Font}
       */
      TextItemTemplate.prototype.getFont = function () {
        return this.font;
      };

      /**
       *
       * @param {Font} font
       */
      TextItemTemplate.prototype.$$setFont = function (font) {
        this.font = font;
      };

      TextItemTemplate.prototype.getFontSize = function () {
        return this.fontSize;
      };

      TextItemTemplate.prototype.$$setFontSize = function (fontSize) {
        this.fontSize = fontSize;
      };


      TextItemTemplate.prototype.getFontWeight = function () {
        return this.fontWeight;
      };

      TextItemTemplate.prototype.$$setFontWeight = function (fontWeight) {
        this.fontWeight = fontWeight;
      };

      TextItemTemplate.prototype.getFontStyle = function () {
        return this.fontStyle;
      };

      TextItemTemplate.prototype.$$setFontStyle = function (fontStyle) {
        this.fontStyle = fontStyle;
      };

      TextItemTemplate.prototype.getTextDecoration = function () {
        return this.textDecoration;
      };

      TextItemTemplate.prototype.$$setTextDecoration = function (textDecoration) {
        this.textDecoration = textDecoration;
      };

      return {

        createTextItemTemplate: function (text, placeholderText, textAnchor, textColor, bgColor, font, fontSize, fontStyle, fontWeight,
                                          textDecoration, padding, verticalAlign) {

          if (text === undefined || placeholderText === undefined || textAnchor === undefined || textColor === undefined ||
            bgColor === undefined || font === undefined || padding === undefined || verticalAlign === undefined) {
            throw new Error('Can\'t create a TextItemTemplate. One or more parameters are missing or invalid.');
          }

          var textItemTemplate = new TextItemTemplate();
          textItemTemplate.$$setText(text);
          textItemTemplate.$$setPlaceholderText(placeholderText);
          textItemTemplate.$$setTextAnchor(textAnchor);
          textItemTemplate.$$setTextColor(textColor);
          textItemTemplate.$$setBackgroundColor(bgColor);
          textItemTemplate.$$setFont(font);
          textItemTemplate.$$setFontSize(fontSize);
          textItemTemplate.$$setFontStyle(fontStyle);
          textItemTemplate.$$setFontWeight(fontWeight);
          textItemTemplate.$$setTextDecoration(textDecoration);
          textItemTemplate.$$setPadding(padding);
          textItemTemplate.$$setVerticalAlign(verticalAlign);


          return textItemTemplate;
        },

        getClass: function() {
          return TextItemTemplate;
        },

        getPrototype: function () {
          return new TextItemTemplate();
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */


/**
 * @author Sascha to the F Friedrich
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('ClipartService', [
    '$log', '$http', '$resource', '$q', 'MessageService', 'ClipartItemTemplateFactory',
    function ($log, $http, $resource, $q, MessageService, ClipartItemTemplateFactory) {

      var endpointUrl = 'designElements/clipart.rest';
      var clipartItemTemplatesCache;

      var loadCliparts = function () {
        if (clipartItemTemplatesCache) {
          return $q.when(clipartItemTemplatesCache);
        }
        return $http({
          method: 'GET',
          url: endpointUrl
        }).then(
          function ok(response) {
            clipartItemTemplatesCache = {};
            angular.forEach(response.data, function (value, key) {
              var cliparts = [];
              value.forEach(function (clipart) {
                if (clipart.designElementId && clipart.categories) {
                  cliparts.push(ClipartItemTemplateFactory.createClipartItemTemplate(clipart.designElementId, clipart.categories[0]));
                }
              });
              clipartItemTemplatesCache[key] = cliparts;
            });

            return clipartItemTemplatesCache;
          },
          function error(response) {
            // TODO: we need some global error handling
            $log.error('ERROR: Can\'t get the clipart data: ', response);
          });
      };

      // definition of the public service functions
      var clipartTemplateService = {

        /**
         * @param {String} categoryId
         * @returns the possible cliparts
         */

        getClipartTemplatesByCategory: function (categoryId) {
          return loadCliparts().then(function ok(clipartCategoryMap) {
            return clipartCategoryMap[categoryId];
          });
        },

        getClipartCategoryMap: function () {
          return loadCliparts().then(function ok(clipartCategoryMap) {
            return clipartCategoryMap;
          });
        }

      };

      return clipartTemplateService;

    }
  ]);
})();
/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('ClipartItemTemplateFactory', [
    '$log', 'DesignElementItemTemplatePrototypeFactory',
    function ($log, DesignElementItemTemplatePrototypeFactory) {

      function ClipartItemTemplate() {
        // call super class constructor to instantiate its variables
        DesignElementItemTemplatePrototypeFactory.getClass().call(this);
      }

      ClipartItemTemplate.prototype = Object.create(DesignElementItemTemplatePrototypeFactory.getClass().prototype);
      ClipartItemTemplate.prototype.constructor = ClipartItemTemplate;

      return {

        /**
         *
         * @param {Number} designElementId
         * @param {String} categoryKey (optional)
         * @return {ClipartItemTemplate}
         */
        createClipartItemTemplate: function (designElementId, categoryKey) {

          if (!designElementId) {
            throw new Error('Can\'t create the ClipartItemTemplate. One or more parameters are missing or invalid.');
          }

          if (!categoryKey) {
            categoryKey = '';
          }

          var clipartItemTemplate = new ClipartItemTemplate();
          clipartItemTemplate.setDesignElementId(designElementId);
          clipartItemTemplate.setCategoryKey(categoryKey);

          return clipartItemTemplate;
        },

        getClass: function() {
          return ClipartItemTemplate;
        },

        getPrototype: function () {
          return new ClipartItemTemplate();
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive represents a ClipartItemTemplate for use in the Cliparts selection area.
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwClipartItemTemplate', [
    '$log',
    function ($log) {
      return {
        replace: true,
        scope: {
          templateModel: '=templateModel', // put a ClipartItemTemplate instance in here
          width: '&width',
          height: '&height',
          dragAllowed: '=dragAllowed'
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/designelements/cliparts/cwClipartItemTemplate.html.jsf',
        link: function (scope, element, attrs) {

          var clipartThumbUrl = 'designElements/designElementImage.rest?imageSize=thumb&elementId=';

          var boxStyle = {
            width: scope.width,
            height: scope.height
          };

          scope.getBoxStyle = function() {
            if (scope.templateModel.isInitialized()) {
              boxStyle.backgroundImage = 'url(' + clipartThumbUrl + scope.templateModel.getDesignElementId() + ')';
            }
            return boxStyle;
          };
        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This factory can be used to create CanvasDesignArea instances. A CanvasDesignArea is the visual representation of a double page data model.
 * @author Frank Bruns (frank.bruns@openknowledge.de)
 * @author Silvia Peter (silvia.peter@cewe.de)
 * @author Holger Cremer
 */
(function () {
  'use strict';
  /* global createjs */

  angular.module('tatooine').factory('CanvasDesignAreaFactory', [
    '$log', '$q', '$timeout', '$window', 'AppConstants', 'EventConstants', 'AppValues', 'SafeApply', 'Utils', 'MessageService', 'FileHandleService', 'UndoRedoService', 'OperatorService', 'ProjectService', 'DesignAreaService', 'CanvasImageItemFactory', 'CanvasTextItemFactory', 'CanvasBackgroundItemFactory', 'CanvasClipartItemFactory', 'ImageItemFactory', 'TextItemFactory', 'TemplateBackgroundItemFactory', 'ClipartItemFactory',
    function ($log, $q, $timeout, $window, AppConstants, EventConstants, AppValues, SafeApply, Utils, MessageService, FileHandleService, UndoRedoService, OperatorService, ProjectService, DesignAreaService, CanvasImageItemFactory, CanvasTextItemFactory, CanvasBackgroundItemFactory, CanvasClipartItemFactory, ImageItemFactory, TextItemFactory, TemplateBackgroundItemFactory, ClipartItemFactory) {

      // TODO Frank Bruns 01.04.2014: Maybe make an injectable constant from this (see designAreaService, too)
      var EDITOR_IMAGE_TARGET_SIZE_PX = 800;

      var calculateExtrema = function (values) {
        var maximum = Number.MIN_VALUE;
        var minimum = Number.MAX_VALUE;
        for (var i = 0; i < values.length; i++) {
          maximum = Math.max(maximum, values[i]);
          minimum = Math.min(minimum, values[i]);
        }
        return {
          max: maximum,
          min: minimum
        };
      };

      /**
       * A CanvasDesignArea is meant as the component where visual editing of products takes place, e.g. in photo book context
       * this could be the editable interactive double page.
       * A CanvasDesignArea is the visual representation of a design area data model and wraps an
       * EaselJS stage (which is an abstraction of the HTML5 canvas) to minimize the need to access
       * the EaselJS stage directly and to offer some more high level and common methods.
       * Please add only functionality to the CanvasDesignArea that is not specific to an context like CFO, but is tailored towards
       * any other potential product editor that might be implemented in the future.
       *
       * @param scope the Angular scope the design area data model is bound to
       * @param designAreaModel the data model to visually represent with this CanvasDesignArea
       * @Class CanvasDesignArea
       * @constructor
       */
      function CanvasDesignArea(scope, designAreaModel, cwDesignAreaDomElement) {

        var self = this;

        this.touchDevice = createjs.Touch.isSupported();

        this.model = designAreaModel;
        this.scope = scope;

        this.canvasItemBoxes = [];
        this.runningThumbKeyCreations = {};

        this.mouseWheelTimeout = null;
        this.mouseWheelScrolling = null;

        // will hold references to watches to be able to easily unregister them later on
        this.watches = [];
        this.eventListenerTargets = [];

        //Create a stage by getting a reference to the canvas and set its initial size
        this.stage = new createjs.Stage(this.model.getId());

        // while selected the design area will be automatically drawn relying on the frequency of the requestAnimationFrame (RAF)
        createjs.Ticker.timingMode = createjs.Ticker.RAF;
        createjs.Ticker.addEventListener('tick', function onRafTick(event) {
          if (!event.paused && self.model.isSelected()) {
            //$log.debug('updating design area stage on RAF tick', self.getId());
            self.update();
          }
        });

        this.printArea = new createjs.Container();
        this.printArea.x = designAreaModel.getPaddingHorizontal();
        this.printArea.y = designAreaModel.getPaddingVertical();
        this.printAreaMask = new createjs.Shape();
        this.printAreaMask.graphics.beginFill('#000000').drawRect(designAreaModel.getPaddingHorizontal(), designAreaModel.getPaddingVertical(),
          this.model.getWidth(), this.model.getHeight());
        this.printArea.mask = this.printAreaMask;
        this.stage.addChild(this.printArea);

        this.toolFrameContainer = new createjs.Container();
        this.toolFrameContainer.x = designAreaModel.getPaddingHorizontal();
        this.toolFrameContainer.y = designAreaModel.getPaddingVertical();
        this.stage.addChild(this.toolFrameContainer);

        this.stage.name = this.model.getId();
        if (designAreaModel.isDetailInteractionMode()) {
          this.stage.canvas.width = designAreaModel.getCanvasWidth();
          this.stage.canvas.height = designAreaModel.getCanvasHeight();
        } else {
          this.stage.canvas.width = designAreaModel.getCanvasWidth() * AppConstants.CANVAS_STORYBOARD_SCALE_FACTOR;
          this.stage.canvas.height = designAreaModel.getCanvasHeight() * AppConstants.CANVAS_STORYBOARD_SCALE_FACTOR;
          this.stage.scaleX = AppConstants.CANVAS_STORYBOARD_SCALE_FACTOR;
          this.stage.scaleY = AppConstants.CANVAS_STORYBOARD_SCALE_FACTOR;
        }


        this.magneticLineContainer = new createjs.Container();
        this.magneticLineContainer.name = 'magneticLineContainer';
        this.getPrintArea().addChild(this.magneticLineContainer);


        this.BUTTON_BAR_MARGIN = 10;
        this.MINIMUM_SPINE_LOGO_HEIGHT = 30 * AppConstants.MM_TO_PX;
        this.SPINE_ELEMENT_GAP = 50 * AppConstants.MM_TO_PX;
        this.mouseXY = {}; // holds mouse coordinates for the different pointers

        this.zoomStartViewPort = null;
        this.zoomedCanvasImageItem = null;

        if (this.model.isCover()) {
          // only create a spine shape if the designArea is the cover
          this.spine = new createjs.Shape();
          this.spine.name = 'spine';
          this.spine.graphics.setStrokeStyle(2).beginStroke('rgba(150,150,150,0.7)').drawRect(designAreaModel.getWidth() / 2 - designAreaModel.getSpineWidth() / 2 * AppConstants.MM_TO_PX, -10, designAreaModel.getSpineWidth() * AppConstants.MM_TO_PX, designAreaModel.getHeight() * 1.1);
          self.getPrintArea().addChild(this.spine);

          if (this.model.isSpineLogoEnabled()) {
            this.logoImage = new Image();
            this.logoImage.src = 'designElements/designElementImage.rest?imageSize=thumb&elementId=' + designAreaModel.getSpineLogoElementId();
            this.logo = new createjs.Bitmap(this.logoImage);
            this.logo.name = 'logo';
            this.logoImage.onload = function () {
              self.getPrintArea().addChild(self.logo);
              self.$$recalculateLogoSize();
              self.logo.rotation = self.model.getSpineContentRotation();

              var spineText = self.model.getSpineTextItem();
              if (spineText) {
                var logoAspectRatio = self.logo.image.width / self.logo.image.height;
                var maxSpineWidth = self.model.getSpineMaxWidth();
                var maxPagesLogoHeight = Math.max(maxSpineWidth * 0.5 * AppConstants.MM_TO_PX, self.MINIMUM_SPINE_LOGO_HEIGHT);
                var maxPagesLogoWidth = Math.round(maxPagesLogoHeight * logoAspectRatio);

                spineText.setWidth(self.model.getHeight() - maxPagesLogoWidth - 2 * self.SPINE_ELEMENT_GAP - self.model.getSafetyMargin());
                spineText.setCenterY(self.model.getSafetyMargin() + spineText.getWidth() / 2);
              }

            };

          }

          this.dummyBarCodeImage = new Image();
          this.dummyBarCodeImage.src = '/web/javax.faces.resource/app/tatooine/images/designArea/dummy-barcode.png.jsf';
          var dummyBarCode = new createjs.Bitmap(this.dummyBarCodeImage);
          dummyBarCode.name = 'dummyBarCode';
          this.dummyBarCodeImage.onload = function () {
            var scaleX = designAreaModel.getBarCode().width * AppConstants.MM_TO_PX / dummyBarCode.image.width;
            var scaleY = designAreaModel.getBarCode().height * AppConstants.MM_TO_PX / dummyBarCode.image.height;
            dummyBarCode.x = designAreaModel.getBarCode().left * AppConstants.MM_TO_PX - designAreaModel.getBleedMarginHorizontal();
            dummyBarCode.y = (designAreaModel.getBarCode().bottom - designAreaModel.getBarCode().height) * AppConstants.MM_TO_PX - designAreaModel.getBleedMarginVertical();
            dummyBarCode.scaleX = scaleX;
            dummyBarCode.scaleY = scaleY;
            self.getPrintArea().addChild(dummyBarCode);
          };

        }

        if (!this.model.isCover()) {
          this.centerFold = new createjs.Shape();
          this.centerFold.graphics.setStrokeStyle(3).beginStroke('rgba(150,150,150,0.3)').moveTo(designAreaModel.getWidth() / 2, 0).lineTo(designAreaModel.getWidth() / 2, designAreaModel.getHeight());
          self.getPrintArea().addChild(this.centerFold);
        }

        var blockedPageContainerOffset = this.model.isLeftPageBlocked() ? 0 : this.model.isRightPageBlocked() ? this.model.getWidth() / 2 : 0;
        this.blockedPageContainer = new createjs.Container();
        this.blockedPageContainer.visible = false;
        this.blockedPageContainer.name = 'blockedPageContainer';

        this.blockedPageContainer.x = blockedPageContainerOffset;
        this.blockedPageContainer.width = this.model.getWidth() / 2;
        this.blockedPageContainer.height = this.model.getHeight();


        var whiteBlockedArea = new createjs.Shape();
        whiteBlockedArea.graphics.beginFill('#FFFFFF').drawRect(0, 0, this.model.getWidth() / 2, this.model.getHeight());
        this.blockedPageContainer.addChild(whiteBlockedArea);

        this.warningImage = new Image();
        this.warningImage.src = '/web/javax.faces.resource/app/tatooine/images/designArea/ico_warndreieck_leere_seite.png.jsf';
        var blockedInfo = new createjs.Bitmap(this.warningImage);
        this.warningImage.onload = function () {
          blockedInfo.width = blockedInfo.image.width;
          blockedInfo.height = blockedInfo.image.height;
          blockedInfo.x = self.model.getWidth() / 4 - blockedInfo.width / 2;
          blockedInfo.y = self.model.getHeight() * 0.75 - blockedInfo.height;
        };
        this.blockedPageContainer.addChild(blockedInfo);


        // TODO Frank Bruns 25.07.2014: Maybe put the text message into the DesignArea data model (in ng variable) to get rid of the
        // undesired MessageService dependency in this factory class

        var blockedPageText = new createjs.Text();
        blockedPageText.font = 'bold 14px Myriad Pro';
        blockedPageText.color = 'rgba(150,150,150,0.7)';
        blockedPageText.text = MessageService.getMessage('designArea.notEditable');
        var textBounds = blockedPageText.getBounds();
        blockedPageText.y = designAreaModel.getHeight() * 0.8;
        blockedPageText.x = this.blockedPageContainer.width / 2 - textBounds.width / 2;
        this.blockedPageContainer.addChild(blockedPageText);

        self.getPrintArea().addChild(this.blockedPageContainer);

        // draw the design area once after it has been initialized
        self.update();

        this.eventListenerTargets.push(this.stage);

        this.$$initializeButtonBar = function () {
          if (this.buttonBar) {
            return $q.when();
          } else if (self.model.isButtonBarInitialized()) {
            self.buttonBar = new createjs.DOMElement('buttonBar-' + self.model.getId());
            self.stage.addChild(self.buttonBar);
            return $q.when();
          }
          var deferred = $q.defer();
          $timeout(function delay() {
            if (self.model.isButtonBarInitialized()) {
              self.buttonBar = new createjs.DOMElement('buttonBar-' + self.model.getId());
              self.stage.addChild(self.buttonBar);
              deferred.resolve();
            } else {
              deferred.reject();
            }
          }, 500);
          return deferred.promise;
        };


        this.$$canvasClicked = function (e) {

          // we don't want clicks on the canvas DOM element to bubble upwards through DOM hierarchy (e.g. the outer DIVs the design area is embedded in)
          e.cancelBubble = true;
          e.stopPropagation();

          // recalculate whether the potentially used layouts on the left and right page half were manipulated by the user
          self.model.updateLayoutModified('left');
          self.model.updateLayoutModified('right');

          if (self.model.isDetailInteractionMode()) {
            return;
          }
          // tell interested listeners that this canvas design area was clicked an provide the design area model as
          // the event data

          SafeApply.do(function applyClickOnDesignAreaEvent() {
            if (Math.abs(cwDesignAreaDomElement[0].offsetLeft) < 60 && Math.abs(cwDesignAreaDomElement[0].offsetTop) < 60) {
              DesignAreaService.removeDesignAreaToDrop();
              self.scope.$emit(EventConstants.DESIGN_AREA_CLICKED, self.model);
            }
          });
        };


        if (this.touchDevice) {
          createjs.Touch.enable(this.stage);
          this.stage.canvas.addEventListener('touchend', this.$$canvasClicked);
        } else {
          this.stage.canvas.addEventListener('click', this.$$canvasClicked);
        }


        /**
         * Reacts on window resize event
         */
        this.$$onResizeHandler = function () {
          var allCanvasItemBoxes = self.$$getAllCanvasItemBoxes(false);
          allCanvasItemBoxes.forEach(function iteration(canvasItemBox) {
            if (canvasItemBox.getModel().isSelected()) {
              canvasItemBox.getToolFrame().$$drawToolFrame();
              self.$$setAttachedDomElementsPositionToItemBox(canvasItemBox);
            }
          });

        };


        this.$$stageMouseDownHandler = function (e) {
          if (self.model.isDetailInteractionMode()) {
            self.$$storeMouseXY(e);
            var selectedCanvasItemBox = self.$$getSelectedCanvasItemBox(); // currently selected canvas item box
            var touchedCanvasItemBox = self.getCanvasItemBoxAt(self.mouseXY[0].x, self.mouseXY[0].y, true); // now touched canvas item box


            if (touchedCanvasItemBox && selectedCanvasItemBox) { // if there are a touched and a selected canvas item box...
              // ... deselect the selected one and select the touched one if the selected one is not in an ongoing toolframe operation
              if (!selectedCanvasItemBox.getToolFrame().isBusy() && (selectedCanvasItemBox !== touchedCanvasItemBox)) {
                self.$$setAttachedDomElementsPositionToItemBox(touchedCanvasItemBox);
                selectedCanvasItemBox.getModel().setSelected(false);
                touchedCanvasItemBox.getModel().setSelected(true);

                if (self.$$isCanvasImageItem(touchedCanvasItemBox)) {
                  // had to set the visibility directly to allow for immediate dragging of viewport(invisible toolframe doesn't react to events)
                  touchedCanvasItemBox.getToolFrame().setVisible(true);
                }
              }


            } else if (touchedCanvasItemBox && !selectedCanvasItemBox) { // if there is only a touched item box, but no selected one, select it
              self.$$setAttachedDomElementsPositionToItemBox(touchedCanvasItemBox);
              touchedCanvasItemBox.getModel().setSelected(true);

              if (self.$$isCanvasImageItem(touchedCanvasItemBox)) {
                // had to set the visibility directly to allow for immediate dragging of viewport(invisible toolframe doesn't react to events)
                touchedCanvasItemBox.getToolFrame().setVisible(true);
              }

            } else {
              if (selectedCanvasItemBox) { // no item box was touched --> deselect item box
                selectedCanvasItemBox.getModel().setSelected(false);
              }
            }


            var pointerCount = Object.keys(self.mouseXY).length;
            if (pointerCount > 1) {

              if (touchedCanvasItemBox && self.$$isCanvasImageItem(touchedCanvasItemBox)) { // activate image item for zoom gesture
                touchedCanvasItemBox.getToolFrame().setPinchZooming(true);
                touchedCanvasItemBox.getContentSilhouette().setVisible(true);
                self.zoomedCanvasImageItem = touchedCanvasItemBox;
                self.zoomStartViewPort = touchedCanvasItemBox.getViewPort(); // set the current canvas item viewport

                // set the toolframe's current position and the canvasItemsBox' viewport position to the item box model, because we need it as the new starting point right now,
                // usually during toolframe operations the values would have been transferred to the data model in the subsequent watch logic
                // after an mouse up event
                self.zoomedCanvasImageItem.model.setCenterX(touchedCanvasItemBox.getToolFrame().getCenterX());
                self.zoomedCanvasImageItem.model.setCenterY(touchedCanvasItemBox.getToolFrame().getCenterY());

              }
            }

          }
        };


        this.$$stageMouseMoveHandler = function (e) {
          self.$$storeMouseXY(e);
          if (self.imageItemContentMoveInProgress) {
            var itemBoxUnderMouse = self.getCanvasItemBoxAt(self.mouseXY[0].x, self.mouseXY[0].y, true);
            if (itemBoxUnderMouse && !itemBoxUnderMouse.getModel().isSelected() && itemBoxUnderMouse instanceof CanvasImageItemFactory.getClass()) {
              if (self.swapTargetItemBox !== itemBoxUnderMouse) {
                if (self.swapTargetItemBox) {
                  self.swapTargetItemBox.showSwapTargetMarker(false);
                }
                self.swapTargetItemBox = itemBoxUnderMouse;
                itemBoxUnderMouse.showSwapTargetMarker(true);
              }
            } else if (self.swapTargetItemBox) {
              self.swapTargetItemBox.showSwapTargetMarker(false);
              self.swapTargetItemBox = undefined;
            }
          }
        };


        this.$$stageMouseUpHandler = function (e) {

          if (e.primary) {
            delete self.mouseXY[0];
          } else {
            delete self.mouseXY[1];
          }

          var pointerCount = Object.keys(self.mouseXY).length;

          if (pointerCount === 0) {
            // $timeout executes the following code at the end of the event queue, so this will be executed after all other places have processed
            // the event (currently this prevents undesired switching between viewport mode and normal mode after pinchZoom ends)
            $timeout(function () {
              if (self.zoomedCanvasImageItem) {

                self.zoomedCanvasImageItem.getToolFrame().setPinchZooming(false);
                self.zoomedCanvasImageItem.getContentSilhouette().showTemporarily(50);
              }

              self.zoomedCanvasImageItem = null;
              self.zoomStartViewPort = null;
            });
          }

          if (self.swapTargetItemBox) {
            var selectedItemBox = self.$$getSelectedCanvasItemBox();
            self.swapImageItems(selectedItemBox, self.swapTargetItemBox);
          }

        };


        $log.debug('Bind stage mouse events for canvas', this.getId());
        // capture mouse movement on the stage to be able to access the last recognized mouse position
        this.stage.on('stagemousedown', this.$$stageMouseDownHandler);
        this.stage.on('stagemousemove', this.$$stageMouseMoveHandler);
        this.stage.on('stagemouseup', this.$$stageMouseUpHandler);


        this.$$addOnMouseWheelHandler(function mouseWheel(e) {

          if (!self.model.isDetailInteractionMode() || !self.mouseXY[0]) {
            return;
          }

          e.preventDefault(); // don't scroll the page if reached this point

          // TODO Frank Bruns 17.10.2014: This method makes the whole mouse scrolling thing pretty slow, because it is fired on ever mouse wheel event.
          // Find a more speedy solution.
          var canvasItemBox = self.getCanvasItemBoxAt(self.mouseXY[0].x, self.mouseXY[0].y, true);

          if (!self.$$isCanvasImageItem(canvasItemBox)) {
            return;
          }

          // Only zoom CanvasImageItems, if we are in detail view and if it was selected.
          if (self.model.isDetailInteractionMode() && canvasItemBox.getModel().isSelected()) {
            SafeApply.do(function applyMouseWheelHandler() {

              // if first mouse wheel event in this scrolling sequence
              if (!self.mouseWheelScrolling) {
                $log.debug('Mouse wheel action started. Pushing current state to undo/redo stack.');
                UndoRedoService.pushModelData(self.model).resolve();
                canvasItemBox.getToolFrame().setMouseZooming(true);
              }

              // cancel old timeout function, because it will be replaced with a new one.
              $timeout.cancel(self.mouseWheelTimeout);

              // consider mouse wheel scrolling sequence over as soon as a certain amount of time has passed
              self.mouseWheelTimeout = $timeout(function mouseWheelFinish() {
                self.mouseWheelScrolling = false;
                canvasItemBox.getToolFrame().setMouseZooming(false);
              }, 400);

              self.mouseWheelScrolling = true;

              canvasItemBox.getContentSilhouette().showTemporarily(300);

              var mouseWheelDelta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
              var viewport = canvasItemBox.$$calculateViewPort('mouseZoom', canvasItemBox.getModel().getViewPort(), -mouseWheelDelta);
              canvasItemBox.getModel().setViewPort(viewport);

            }, self.scope);
          }

        });


        function addWatchCollection(watchExpression, listener) {
          var unregisterWatch = self.scope.$watchCollection(watchExpression, listener);
          self.watches.push(unregisterWatch);
        }


        /**
         * Watches the data model attributes, which are used for the angular view display and not sent to the server.
         * @type {*}
         */
        addWatchCollection(function watchDesignAreaNgChanges() {
          return self.model.ng;
        }, function onDesignAreaNgChanged(newValue, oldValue) {
          if (newValue) {

            if (newValue.textItemEditBoxInitialized) {
              self.textItemEditBox = new createjs.DOMElement('textItemEditBox-' + self.model.getId());
              self.stage.addChild(self.textItemEditBox);
            }


            if (newValue.detailInteractionMode === true) {
              self.stage.mouseMoveOutside = true;
              if (!self.imageItemContentMoveStartListener) {
                self.imageItemContentMoveStartListener = scope.$on(EventConstants.IMAGE_ITEM_CONTENT_MOVE_START, function onImageItemContentMoveStart() {
                  self.imageItemContentMoveInProgress = true;
                });
              }

              if (!self.imageItemContentMoveEndListener) {
                self.imageItemContentMoveEndListener = scope.$on(EventConstants.IMAGE_ITEM_CONTENT_MOVE_END, function onImageItemContentMoveEnd() {
                  self.imageItemContentMoveInProgress = false;
                  if (self.swapTargetItemBox) {
                    self.swapTargetItemBox.showSwapTargetMarker(false);
                    self.swapTargetItemBox = undefined;
                  }
                });
              }

              if (newValue.zIndex !== oldValue.zIndex) {
                var selectedItemBox = self.$$getSelectedCanvasItemBox();
                if (selectedItemBox) {
                  self.$$setAttachedDomElementsPositionToItemBox(selectedItemBox);
                }
              }

            } else {
              self.stage.mouseMoveOutside = false;
              if (self.imageItemContentMoveStartListener) {
                self.imageItemContentMoveStartListener();
                self.imageItemContentMoveStartListener = undefined;
              }
              if (self.imageItemContentMoveEndListener) {
                self.imageItemContentMoveEndListener();
                self.imageItemContentMoveEndListener = undefined;
              }
            }

            // if the mode actually changed we would like to toggle event bindings and stuff
            if (newValue.detailInteractionMode === true && newValue.detailInteractionMode !== (oldValue && oldValue.detailInteractionMode)) {

              // only enable mouse over events on non-touch devices
              if (!self.touchDevice) {
                self.getStage().enableMouseOver(5); // for example needed to show different cursor pointers on mouse over
              }

              self.getStage().scaleX = 1;
              self.getStage().scaleY = 1;
              self.getStage().canvas.width = designAreaModel.getCanvasWidth();
              self.getStage().canvas.height = designAreaModel.getCanvasHeight();

              $log.debug('Bind resize events for canvas', self.getId());
              angular.element($window).on('resize', self.$$onResizeHandler);
              self.eventListenerTargets.push($window);

            } else if (newValue.detailInteractionMode === false && newValue.detailInteractionMode !== (oldValue && oldValue.detailInteractionMode)) {

              if (!self.touchDevice) {
                self.getStage().enableMouseOver(0);
              }

              self.getStage().scaleX = AppConstants.CANVAS_STORYBOARD_SCALE_FACTOR;
              self.getStage().scaleY = AppConstants.CANVAS_STORYBOARD_SCALE_FACTOR;
              self.getStage().canvas.width = Math.round(designAreaModel.getCanvasWidth() * AppConstants.CANVAS_STORYBOARD_SCALE_FACTOR);
              self.getStage().canvas.height = Math.round(designAreaModel.getCanvasHeight() * AppConstants.CANVAS_STORYBOARD_SCALE_FACTOR);

              // Deselect all itemboxes, if the detail view was left or another designArea was selected.
              if ((oldValue && oldValue.detailInteractionMode && !newValue.detailInteractionMode) || (oldValue.selected && !newValue.selected)) {
                var allCanvasItemBoxes = self.$$getAllCanvasItemBoxes(false);
                allCanvasItemBoxes.forEach(function deselectCanvasItemBoxes(canvasItemBox) {
                  canvasItemBox.model.setSelected(false);
                });
              }


              $log.debug('Unbind resize events for canvas', self.getId());
              angular.element($window).off('resize', self.$$onResizeHandler);
            }

            if (self.model.isLeftPageBlocked() || self.model.isRightPageBlocked()) {
              var blockedPageContainerOffset = self.model.isLeftPageBlocked() ? 0 : self.model.isRightPageBlocked() ? self.model.getWidth() / 2 : 0;
              self.blockedPageContainer.x = blockedPageContainerOffset;
            }
            self.blockedPageContainer.visible = self.model.isLeftPageBlocked() || self.model.isRightPageBlocked();

            if (newValue.modelStateVersion !== oldValue.modelStateVersion) {
              self.deleteAllCanvasItemBoxes();

              self.model.getAllItems(true).forEach(function (itemBoxModel) {
                self.addCanvasItemBoxToDesignArea(scope, itemBoxModel);
              });
            }

            if (newValue.triggerCanvasUpdate) {
              $timeout(function delay() {
                $log.debug('Apply manually triggered canvas update once for design area', self.getId());
                newValue.triggerCanvasUpdate = false;
                self.update();
              }, 250);
            }
          }

        });


        if (this.model.getType() === 'cover') {

          /**
           * Watches the data model spine attributes, which are used for the angular view display and not sent to the server.
           * @type {*}
           */
          addWatchCollection(function watchSpineWidthChanges() {
            return self.model.getSpineWidth();
          }, function onSpineWidthChanged(newValue, oldValue) {
            if (newValue) {
              if (self.model.isCover()) {
                var printArea = self.getPrintArea();
                printArea.x = self.model.getPaddingHorizontal();
                printArea.y = self.model.getPaddingVertical();
                self.printAreaMask.graphics.clear();
                self.printAreaMask.graphics.beginFill('#000000').drawRect(self.model.getPaddingHorizontal(), self.model.getPaddingVertical(),
                  self.model.getWidth(), self.model.getHeight());

                var spine = printArea.getChildByName('spine');
                var remindOldIndex = printArea.getChildIndex(spine);
                printArea.removeChild(spine);

                self.spine = new createjs.Shape();
                self.spine.name = 'spine';
                self.spine.graphics.setStrokeStyle(1).beginStroke('rgba(150,150,150,0.7)').drawRect(self.model.getWidth() / 2 - newValue / 2 * AppConstants.MM_TO_PX, -10, newValue * AppConstants.MM_TO_PX, self.model.getHeight() * 1.1);
                printArea.addChildAt(self.spine, remindOldIndex);
                if (self.model.isSpineLogoEnabled()) {
                  self.$$recalculateLogoSize();
                }
                self.update();
              }
            }

          });
        }

        addWatchCollection(function watchCanvasDimensionChanges() {
            return [self.model.getCanvasWidth(), self.model.getCanvasHeight()];
          },
          function onCanvasDimensionChanged(newValue, oldValue) {
            if (newValue) {
              if (self.model.isDetailInteractionMode()) {
                self.stage.canvas.width = newValue[0];
                self.stage.canvas.height = newValue[1];
              } else {
                self.stage.canvas.width = newValue[0] * AppConstants.CANVAS_STORYBOARD_SCALE_FACTOR;
                self.stage.canvas.height = newValue[1] * AppConstants.CANVAS_STORYBOARD_SCALE_FACTOR;
              }
            }
          }
        );

        self.model.getAllItems(true).forEach(function (itemBoxModel) {
          self.addCanvasItemBoxToDesignArea(scope, itemBoxModel);
        });

      }


      /**
       * @param canvasItemBox
       * @return {boolean} is the given CanvasItemBox among the CanvasDesignArea's CanvasTemplateBackgroundItems?
       */
      CanvasDesignArea.prototype.$$isCanvasTemplateBackgroundItem = function (canvasItemBox) {
        return canvasItemBox instanceof CanvasBackgroundItemFactory.getClass();
      };

      /**
       * @param canvasItemBox
       * @return {boolean} is the given CanvasItemBox among the CanvasDesignArea's CanvasImageItems?
       */
      CanvasDesignArea.prototype.$$isCanvasImageItem = function (canvasItemBox) {
        return canvasItemBox instanceof CanvasImageItemFactory.getClass();
      };

      /**
       * @param canvasItemBox
       * @return {boolean} is the given CanvasItemBox among the CanvasDesignArea's CanvasImageItems?
       */
      CanvasDesignArea.prototype.$$isCanvasTextItem = function (canvasItemBox) {
        return canvasItemBox instanceof CanvasTextItemFactory.getClass();
      };

      /**
       * Returns a concatenated array of all canvas item boxes.
       * @return {Array} an array of all canvas item boxes concatenated
       */
      CanvasDesignArea.prototype.$$getAllCanvasItemBoxes = function (sorted) {
        return sorted ? this.canvasItemBoxes.sort(Utils.layerIndexComparator) : this.canvasItemBoxes;
      };

      /**
       * Returns the CanvasBackgroundItems on the CanvasDesignArea.
       * @return {Array} the CanvasBackgroundItems on the CanvasDesignArea
       */
      CanvasDesignArea.prototype.$$getCanvasTemplateBackgroundItemBoxes = function () {
        return this.canvasItemBoxes.filter(function filter(itemBox) {
          return itemBox instanceof CanvasBackgroundItemFactory.getClass();
        });
      };


      /**
       * Returns the CanvasImageItems used as background images on the CanvasDesignArea.
       * @return {Array} the CanvasImageItems on the CanvasDesignArea
       */
      CanvasDesignArea.prototype.$$getCanvasImageBackgroundItemBoxes = function () {
        return this.canvasItemBoxes.filter(function filter(itemBox) {
          return itemBox instanceof CanvasImageItemFactory.getClass() && itemBox.getModel().isUsedAsBackgroundImage();
        });
      };

      /**
       * Returns the CanvasImageItems on the CanvasDesignArea.
       * @return {Array} the CanvasImageItems on the CanvasDesignArea
       */
      CanvasDesignArea.prototype.$$getCanvasImageItemBoxes = function () {
        return this.canvasItemBoxes.filter(function filter(itemBox) {
          return itemBox instanceof CanvasImageItemFactory.getClass();
        });
      };

      /**
       * Returns the CanvasTextItems on the CanvasDesignArea.
       * @return {Array} the CanvasTextItems on the CanvasDesignArea
       */
      CanvasDesignArea.prototype.$$getCanvasTextItemBoxes = function () {
        return this.canvasItemBoxes.filter(function filter(itemBox) {
          return itemBox instanceof CanvasTextItemFactory.getClass();
        });
      };


      CanvasDesignArea.prototype.$$getSelectedCanvasItemBox = function () {
        var selectedCanvasItemBox = null;
        var allCanvasItemBoxes = this.$$getAllCanvasItemBoxes(false);
        allCanvasItemBoxes.forEach(function iterCanvasItemBoxes(canvasItemBox) {
          if (canvasItemBox.getModel().isSelected()) {
            selectedCanvasItemBox = canvasItemBox;
          }
        });

        return selectedCanvasItemBox;
      };


      CanvasDesignArea.prototype.$$storeMouseXY = function (mouseEvent) {

        var pointer = mouseEvent.primary ? 0 : 1;

        if (!this.mouseXY[pointer]) {
          this.mouseXY[pointer] = {
            x: mouseEvent.rawX,
            y: mouseEvent.rawY
          }; // create a new object
        } else {
          this.mouseXY[pointer].x = mouseEvent.rawX; // reuse existing object (avoid object creations)
          this.mouseXY[pointer].y = mouseEvent.rawY;
        }
      };


      CanvasDesignArea.prototype.$$setAttachedDomElementsPositionToItemBox = function (canvasItemBox) {

        // find the bottom position for the button bar according to the currently lowest (rotated) toolframe corner
        var localBounds = canvasItemBox.getToolFrame().getRootContainer().getBounds();

        if (!localBounds) {
          return;
        }

        var globalTopLeft = canvasItemBox.getToolFrame().getRootContainer().localToGlobal(localBounds.x, localBounds.y);
        var globalTopRight = canvasItemBox.getToolFrame().getRootContainer().localToGlobal(localBounds.x + localBounds.width, localBounds.y);
        var globalBottomLeft = canvasItemBox.getToolFrame().getRootContainer().localToGlobal(localBounds.x, localBounds.y + localBounds.height);
        var globalBottomRight = canvasItemBox.getToolFrame().getRootContainer().localToGlobal(localBounds.x + localBounds.width, localBounds.y + localBounds.height);

        var globalYs = [globalTopLeft.y, globalTopRight.y, globalBottomLeft.y, globalBottomRight.y];
        var extrY = calculateExtrema(globalYs);

        var globalXs = [globalTopLeft.x, globalTopRight.x, globalBottomLeft.x, globalBottomRight.x];
        var extrX = calculateExtrema(globalXs);

        var paddingVerticalScaled = this.model.getPaddingVertical() / AppValues.designAreaScale;
        var positionEditable = canvasItemBox.getModel().isPositionEditable();
        var contextPadding = canvasItemBox.getModel().isContextView() ? 50 : 0;


        var buttonBarY = 0;
        var buttonBarYBelow = extrY.max / AppValues.designAreaScale + (positionEditable ? 0 : 50) + this.BUTTON_BAR_MARGIN - paddingVerticalScaled + contextPadding;
        var buttonBarYInside = extrY.max / AppValues.designAreaScale - 60 - (positionEditable ? 70 : 0) - this.BUTTON_BAR_MARGIN - paddingVerticalScaled + contextPadding;
        var buttonBarYAbove = extrY.min / AppValues.designAreaScale - 42 - this.BUTTON_BAR_MARGIN - paddingVerticalScaled + contextPadding;


        var isTextItem = this.$$isCanvasTextItem(canvasItemBox);

        if (buttonBarYBelow < (this.model.getHeight() / AppValues.designAreaScale)) {
          buttonBarY = buttonBarYBelow;
          canvasItemBox.getModel().setButtonBarOrientation('below');
        } else if (buttonBarYAbove > 0) {
          buttonBarY = buttonBarYAbove;
          canvasItemBox.getModel().setButtonBarOrientation('above');
        } else {
          // text items shall never use button bar 'inside' to avoid getting covered by the HTML text input area
          buttonBarY = isTextItem ? buttonBarYAbove : buttonBarYInside;
          canvasItemBox.getModel().setButtonBarOrientation(isTextItem ? 'above' : 'inside');
        }


        // adjust the button bar's position after a delay, because the DOM size might not be correctly calculated if the DOM nodes are not quite set up yet
        var self = this;

        self.$$initializeButtonBar().then(function ok() {
          // in case no item box is currently selected we don't want to show the movement animation for the button bar in order to make
          // the button bar appear directly at the target item box without any movement originating from a previously selected item box
          // we just hide the button bar by its alpha value and let it fade in at the target item box
          if (!self.model.getSelectedItemBox()) {
            self.buttonBar.alpha = 0;
          }

          $timeout(function delay() {

            var itemLeftX = (canvasItemBox.getToolFrame().getCenterX() - canvasItemBox.getToolFrame().getWidth() / 2) / AppValues.designAreaScale;
            var itemRightX = (canvasItemBox.getToolFrame().getCenterX() + canvasItemBox.getToolFrame().getWidth() / 2) / AppValues.designAreaScale;
            var daWidth = self.model.getWidth() / AppValues.designAreaScale;

            // center the button bar on the center of the item box's visible area on the design area.
            var buttonBarX = Math.max(0, itemLeftX) + ((Math.min(daWidth, itemRightX) - Math.max(0, itemLeftX)) / 2) - self.buttonBar.htmlElement.clientWidth / 2;

            var tweenTo = {
              x: buttonBarX,
              y: buttonBarY,
              alpha: 1
            };

            if (self.buttonBar.alpha === 0) { // skip the movement animation by just setting the target coordinates immediately
              self.buttonBar.x = tweenTo.x;
              self.buttonBar.y = tweenTo.y;
            }

            createjs.Tween.get(self.buttonBar, {override: true}).to(tweenTo, 275, createjs.Ease.sineInOut).call(function end() {
              $log.debug('--------------BUTTON BAR ATTACHED TO DOM ------------------', self.buttonBar.x, self.buttonBar.y);
            });

            // set the HTML text item input area overlay to the canvas item's position
            if (isTextItem) {
              self.textItemEditBox.regX = canvasItemBox.getToolFrame().getWidth() / 2 / AppValues.designAreaScale;
              self.textItemEditBox.regY = canvasItemBox.getToolFrame().getHeight() / 2 / AppValues.designAreaScale;
              self.textItemEditBox.x = canvasItemBox.getToolFrame().getCenterX() / AppValues.designAreaScale;
              self.textItemEditBox.y = canvasItemBox.getToolFrame().getCenterY() / AppValues.designAreaScale;

              var unrotatedUpperLeftX = (canvasItemBox.getToolFrame().getCenterX() - canvasItemBox.getToolFrame().getWidth() / 2) + self.model.getPaddingHorizontal();
              var unrotatedUpperLeftY = (canvasItemBox.getToolFrame().getCenterY() - canvasItemBox.getToolFrame().getHeight() / 2) + self.model.getPaddingVertical();


              var textItemSettingsContainer = angular.element('#textItemSettings-' + self.model.getId());
              var settingsLeft = canvasItemBox.getToolFrame().getCenterX() > self.model.getWidth() / 2;
              textItemSettingsContainer.css('right', settingsLeft ? Math.round((unrotatedUpperLeftX - extrX.min) / AppValues.designAreaScale) + 15 : '');
              textItemSettingsContainer.css('left', !settingsLeft ? Math.round((extrX.max - unrotatedUpperLeftX) / AppValues.designAreaScale) + 15 : '');

              var textItemSettingsContainerHeight = (5 * 42) * AppValues.designAreaScale; // based on the current number of 5 buttons with a height of 42px each

              var top = (canvasItemBox.getToolFrame().getCenterY() + self.model.getPaddingVertical()) - unrotatedUpperLeftY - textItemSettingsContainerHeight / 2;
              textItemSettingsContainer.css('top', Math.round(top / AppValues.designAreaScale));

              textItemSettingsContainer.css('display', 'block');
            }

          }, 175);
        }, function error() {
          $log.error('initialization of button bar failed');
        });


      };

      /**
       * Moves the specified CanvasItemBox to be within the bounds of the specified CanvasDesignArea
       * @param canvasItemBox
       * @param canvasDesignArea
       */
      CanvasDesignArea.prototype.$$moveToWithinBounds = function (canvasItemBox) {
        var areaBoundsUpperLeft = {
          x: 0,
          y: 0
        };
        var areaBoundsLowerRight = {
          x: this.model.width,
          y: this.model.height
        };

        var boxUpperLeft = canvasItemBox.getRootContainer().localToGlobal(0, 0);
        var boxUpperRight = canvasItemBox.getRootContainer().localToGlobal(canvasItemBox.getModel().getWidth(), 0);
        var boxLowerLeft = canvasItemBox.getRootContainer().localToGlobal(0, canvasItemBox.getModel().getHeight());
        var boxLowerRight = canvasItemBox.getRootContainer().localToGlobal(canvasItemBox.getModel().getWidth(), canvasItemBox.getModel().getHeight());

        var boxVertices = [boxUpperLeft, boxUpperRight, boxLowerLeft, boxLowerRight];

        for (var i = 0; i < 4; i++) {

          var boxVertex = boxVertices[i];

          if (boxVertex.x < areaBoundsUpperLeft.x) {
            canvasItemBox.getModel().setCenterX(areaBoundsUpperLeft.x + canvasItemBox.getModel().getWidth() / 2);
          }

          if (boxVertex.x > areaBoundsLowerRight.x) {
            canvasItemBox.getModel().setCenterX(areaBoundsLowerRight.x - canvasItemBox.getModel().getWidth() / 2);
          }

          if (boxVertex.y < areaBoundsUpperLeft.y) {
            canvasItemBox.getModel().setCenterY(areaBoundsUpperLeft.y + canvasItemBox.getModel().getHeight() / 2);
          }

          if (boxVertex.y > areaBoundsLowerRight.y) {
            canvasItemBox.getModel().setCenterY(areaBoundsLowerRight.y - canvasItemBox.getModel().getHeight() / 2);
          }

        }
      };


      /**
       * Adds the specified function as a handler for mouse wheel events.
       * @param fnMouseWheelHandler the function to be called in case of an mouse wheel event on the CanvasDesignArea
       */
      CanvasDesignArea.prototype.$$addOnMouseWheelHandler = function (fnMouseWheelHandler) {

        // for the Firefox...
        this.getStage().canvas.addEventListener('DOMMouseScroll', function (e) {
          fnMouseWheelHandler(e);
        });

        //... for all other browsers
        this.getStage().canvas.addEventListener('mousewheel', function (e) {
          fnMouseWheelHandler(e);
        });
      };

      CanvasDesignArea.prototype.$$recalculateLogoSize = function () {
        var logoAspectRatio = this.logo.image.width / this.logo.image.height;

        var logoHeight = Math.max(this.model.getSpineWidth() * 0.5 * AppConstants.MM_TO_PX, this.MINIMUM_SPINE_LOGO_HEIGHT);
        var logoWidth = Math.round(logoHeight * logoAspectRatio);

        this.logo.scaleX = logoWidth / this.logo.image.width;
        this.logo.scaleY = logoHeight / this.logo.image.height;

        this.logo.regX = 0;
        this.logo.regY = this.logo.image.height / 2;

        this.logo.x = this.model.getWidth() / 2;
        this.logo.y = this.model.getSpineContentRotation() === 270 ? this.model.getHeight() - this.SPINE_ELEMENT_GAP : this.model.getHeight() - this.SPINE_ELEMENT_GAP - logoWidth;
      };


      /**
       *
       * @returns {*} the id of the CanvasDesignArea
       */
      CanvasDesignArea.prototype.getId = function () {
        return this.model.getId();
      };

      /**
       * Gives access to the underlying EaselJS Stage (an abstraction of the HTML5 canvas).
       * If possible, don't operate on the stage directly but try to use the functions of the CanvasDesignArea class instead.
       * @returns {Stage} the underlying EaselJS stage
       */
      CanvasDesignArea.prototype.getStage = function () {
        return this.stage;
      };

      CanvasDesignArea.prototype.getPrintArea = function () {
        return this.printArea;
      };

      CanvasDesignArea.prototype.getToolFrameContainer = function () {
        return this.toolFrameContainer;
      };

      /**
       * Call this method to visually update the CanvasDesignArea when something has changed. If you don't call
       * this method, changes will take place internally, but they will not be displayed
       */
      CanvasDesignArea.prototype.update = function () {
        this.getStage().update();
      };


      CanvasDesignArea.prototype.getMouseX = function () {
        return this.mouseXY[0] && this.mouseXY[0].x || this.getStage().mouseX;
      };

      CanvasDesignArea.prototype.getMouseY = function () {
        return this.mouseXY[0] && this.mouseXY[0].y || this.getStage().mouseY;
      };


      /**
       * Adds the specified item box model (as a CanvasItemBox) to the CanvasDesignArea.
       * @param scope the Angular scope the item box model is bound to
       * @param itemBoxModel the item box model to add to this CanvasDesignArea
       */
      CanvasDesignArea.prototype.addCanvasItemBoxToDesignArea = function (scope, itemBoxModel) {

        var self = this;

        var canvasItemBox = null;

        var isTemplateBackgroundItem = itemBoxModel instanceof TemplateBackgroundItemFactory.getClass();
        var isTextItem = itemBoxModel instanceof TextItemFactory.getClass();
        var isImageItem = itemBoxModel instanceof ImageItemFactory.getClass();
        var isClipartItem = itemBoxModel instanceof ClipartItemFactory.getClass();

        if (isTemplateBackgroundItem) {

          canvasItemBox = CanvasBackgroundItemFactory.createCanvasBackgroundItem(scope, itemBoxModel);

        } else if (isTextItem) {

          canvasItemBox = CanvasTextItemFactory.createCanvasTextItem(scope, itemBoxModel);

          canvasItemBox.addMouseDraggedListener(function toolFrameMouseDragged(e) {
            // scale and move the HTML text input area overlay along with the canvas text item
            self.textItemEditBox.regX = canvasItemBox.getToolFrame().getWidth() / 2 / AppValues.designAreaScale;
            self.textItemEditBox.regY = canvasItemBox.getToolFrame().getHeight() / 2 / AppValues.designAreaScale;
            self.textItemEditBox.x = (canvasItemBox.getToolFrame().getCenterX()) / AppValues.designAreaScale;
            self.textItemEditBox.y = (canvasItemBox.getToolFrame().getCenterY()) / AppValues.designAreaScale;
            var textItemBoxElement = angular.element(self.textItemEditBox.htmlElement);
            var textAreas = angular.element(textItemBoxElement).find('textarea');

            var textAreaContent = textAreas[0].value;
            var firstTextAreaElement = angular.element(textAreas[0]);

            var fontSize = parseFloat(firstTextAreaElement.css('font-size'));
            var fontFamily = firstTextAreaElement.css('font-family');

            var offset = Utils.calculatedOffsetForVerticalAlign(itemBoxModel.getVerticalAlign(), parseFloat(firstTextAreaElement.css('width')), parseFloat(firstTextAreaElement.css('height')), parseFloat(firstTextAreaElement.css('padding-left')), textAreaContent, fontFamily, fontSize);

            if (itemBoxModel.getVerticalAlign() === 'bottom') {
              angular.forEach(textAreas, function (textArea) {
                textArea.scrollTop = textArea.scrollHeight;
              });
            }

            if (itemBoxModel.getVerticalAlign() === 'middle' && offset < 0) {
              angular.forEach(textAreas, function (textArea) {
                textArea.scrollTop = -offset;
              });
            }

            if (itemBoxModel.getVerticalAlign() === 'top') {
              angular.forEach(textAreas, function (textArea) {
                textArea.scrollTop = 0;
              });
            }

            textAreas.css('padding-top', Math.max(0, offset));
            textAreas.css('width', canvasItemBox.getToolFrame().getWidth() / AppValues.designAreaScale);
            textAreas.css('height', canvasItemBox.getToolFrame().getHeight() / AppValues.designAreaScale);
            textAreas.css('transform', 'rotate(' + canvasItemBox.getToolFrame().getRotation() + 'deg)');
            var textItemSettings = angular.element('#textItemSettings-' + self.model.getId());
            textItemSettings.css('display', 'none');
          });

        } else if (isImageItem) {
          canvasItemBox = CanvasImageItemFactory.createCanvasImageItem(scope, itemBoxModel);

          // add thumbKey if not available, but is associated to a file handle
          if (!itemBoxModel.getThumbKey() && itemBoxModel.getFileHandleId()) {

            // if a thumbkey creation is already running for the current item box --> do nothing
            if (this.runningThumbKeyCreations[itemBoxModel.getId()]) {
              return;
            }

            this.runningThumbKeyCreations[itemBoxModel.getId()] = 'running'; // the value actually doesn't matter at all, it just need to be there

            FileHandleService.createFileHandleThumbKey(itemBoxModel.getFileHandleId(), EDITOR_IMAGE_TARGET_SIZE_PX).then(function ok(thumbKey) {
              $log.debug('set newly calculated thumbkey for itembox with id ' + itemBoxModel.getId(), thumbKey);
              delete self.runningThumbKeyCreations[itemBoxModel.getId()];
              itemBoxModel.setThumbKey(thumbKey, false);
            });

          }

          // if the item box has a thumb key already, we set it to be unloaded since the box is freshly added to the canvas and needs to reload
          // its image content
          if (itemBoxModel.getThumbKey()) {
            itemBoxModel.setThumbKeyLoaded(false);
          }


        } else if (isClipartItem) {

          canvasItemBox = CanvasClipartItemFactory.createCanvasClipartItem(scope, itemBoxModel);

        }


        canvasItemBox.addMouseDraggedListener(function mouseDragged(e) {

          if (ProjectService.getProject().isMagneticLinesActive()) {

            var scaleButtons = ['scaleBottomLeft', 'scaleTopLeft', 'scaleBottomRight', 'scaleTopRight'];
            var cropButtons = ['cropTop', 'cropBottom', 'cropLeft', 'cropRight'];
            var deltaCenterX, deltaLeft, deltaRight;
            var deltaCenterY, deltaTop, deltaBottom;

            AppValues.nearestPoi = {
              x: undefined,
              y: undefined,
              nearestNeighborX: undefined,
              nearestNeighborY: undefined,
              deltaX: undefined,
              deltaY: undefined
            };

            var deltaMinX, deltaMinY;
            //get Points of interest
            var poisX, poisY;

            poisX = self.model.getPointsOfInterest('x');
            poisY = self.model.getPointsOfInterest('y');

            var centerY = canvasItemBox.getCenterY();
            var centerX = canvasItemBox.getCenterX();
            var left, right, top, bottom;

            if (canvasItemBox.getRotation() !== 90 && canvasItemBox.getRotation() !== 270) {
              left = canvasItemBox.getCenterX() - canvasItemBox.getWidth() / 2;
              right = canvasItemBox.getCenterX() + canvasItemBox.getWidth() / 2;
              top = canvasItemBox.getCenterY() - canvasItemBox.getHeight() / 2;
              bottom = canvasItemBox.getCenterY() + canvasItemBox.getHeight() / 2;
            } else {
              left = canvasItemBox.getCenterX() - canvasItemBox.getHeight() / 2;
              right = canvasItemBox.getCenterX() + canvasItemBox.getHeight() / 2;
              top = canvasItemBox.getCenterY() - canvasItemBox.getWidth() / 2;
              bottom = canvasItemBox.getCenterY() + canvasItemBox.getWidth() / 2;
            }


            // get the nearest x value
            var longestPoiListLength = Math.max(poisX.length, poisY.length);

            for (var i = 0; i < longestPoiListLength; i++) {
              if (poisX[i]) {
                deltaCenterX = Math.max(poisX[i], centerX) - Math.min(poisX[i], centerX);
                deltaLeft = Math.max(poisX[i], left) - Math.min(poisX[i], left);
                deltaRight = Math.max(poisX[i], right) - Math.min(poisX[i], right);
              }
              if (poisY[i]) {
                deltaCenterY = Math.max(poisY[i], centerY) - Math.min(poisY[i], centerY);
                deltaTop = Math.max(poisY[i], top) - Math.min(poisY[i], top);
                deltaBottom = Math.max(poisY[i], bottom) - Math.min(poisY[i], bottom);
              }
              if (poisX[i]) {
                if (scaleButtons.indexOf(e.target.name) < 0 && cropButtons.indexOf(e.target.name) < 0) {
                  deltaMinX = (canvasItemBox.getRotation() === 0 || canvasItemBox.getRotation() === 90 || canvasItemBox.getRotation() === 180 || canvasItemBox.getRotation() === 270) ? Math.min(deltaCenterX, deltaLeft, deltaRight) : deltaCenterX;
                } else {
                  deltaMinX = Math.min(deltaLeft, deltaRight);
                }
                if (deltaMinX <= AppConstants.MAGNETIC_SNAP_DISTANCE && (deltaMinX <= AppValues.nearestPoi.deltaX || !AppValues.nearestPoi.deltaX)) {
                  AppValues.nearestPoi.x = poisX[i];
                  AppValues.nearestPoi.deltaX = deltaMinX;
                  AppValues.nearestPoi.nearestNeighborX = deltaMinX === deltaRight ? 'right' : deltaMinX === deltaLeft ? 'left' : 'centerX';
                }
              }
              if (poisY[i]) {
                if (scaleButtons.indexOf(e.target.name) < 0 && cropButtons.indexOf(e.target.name) < 0) {
                  deltaMinY = (canvasItemBox.getRotation() === 0 || canvasItemBox.getRotation() === 90 || canvasItemBox.getRotation() === 180 || canvasItemBox.getRotation() === 270) ? Math.min(deltaCenterY, deltaTop, deltaBottom) : deltaCenterY;
                } else {
                  deltaMinY = Math.min(deltaTop, deltaBottom);
                }
                if (deltaMinY <= AppConstants.MAGNETIC_SNAP_DISTANCE && (deltaMinY <= AppValues.nearestPoi.deltaY || !AppValues.nearestPoi.deltaY)) {
                  AppValues.nearestPoi.y = poisY[i];
                  AppValues.nearestPoi.deltaY = deltaMinY;
                  AppValues.nearestPoi.nearestNeighborY = deltaMinY === deltaTop ? 'top' : deltaMinY === deltaBottom ? 'bottom' : 'centerY';
                }
              }
            }
            self.magneticLineContainer.removeAllChildren();

            for (var j = 0; j < longestPoiListLength; j++) {
              if (poisX[j]) {
                deltaCenterX = Math.max(poisX[j], centerX) - Math.min(poisX[j], centerX);
                deltaLeft = Math.max(poisX[j], left) - Math.min(poisX[j], left);
                deltaRight = Math.max(poisX[j], right) - Math.min(poisX[j], right);
              }
              if (poisY[j]) {
                deltaCenterY = Math.max(poisY[j], centerY) - Math.min(poisY[j], centerY);
                deltaTop = Math.max(poisY[j], top) - Math.min(poisY[j], top);
                deltaBottom = Math.max(poisY[j], bottom) - Math.min(poisY[j], bottom);
              }

              if (poisX[j] && (deltaCenterX <= AppConstants.MAGNETIC_SNAP_DISTANCE && deltaCenterX <= AppValues.nearestPoi.deltaX)) {
                if (!self.magneticLineContainer.getChildByName('lineCenterX' + j)) {
                  var lineCenterX = new createjs.Shape();
                  lineCenterX.name = 'lineCenterX' + j;
                  lineCenterX.graphics.setStrokeStyle(AppConstants.MAGNETIC_LINE_WIDTH).beginStroke(AppConstants.MAGNETIC_LINE_COLOR).moveTo(poisX[j], 0).lineTo(poisX[j], self.model.getHeight());
                  self.magneticLineContainer.addChild(lineCenterX);
                }
              }

              if (poisY[j] && deltaCenterY <= AppConstants.MAGNETIC_SNAP_DISTANCE && deltaCenterY <= AppValues.nearestPoi.deltaY) {
                if (!self.magneticLineContainer.getChildByName('lineCenterY' + j)) {
                  var lineCenterY = new createjs.Shape();
                  lineCenterY.name = 'lineCenterY' + j;
                  lineCenterY.graphics.setStrokeStyle(AppConstants.MAGNETIC_LINE_WIDTH).beginStroke(AppConstants.MAGNETIC_LINE_COLOR).moveTo(0, poisY[j]).lineTo(self.model.getWidth(), poisY[j]);
                  self.magneticLineContainer.addChild(lineCenterY);
                }
              }
              if (canvasItemBox.getRotation() === 0 || canvasItemBox.getRotation() === 90 || canvasItemBox.getRotation() === 180 || canvasItemBox.getRotation() === 270) {
                if (poisX[j] && deltaLeft <= AppConstants.MAGNETIC_SNAP_DISTANCE && deltaLeft <= AppValues.nearestPoi.deltaX) {
                  if (!self.magneticLineContainer.getChildByName('lineLeftX' + j)) {
                    var lineLeftX = new createjs.Shape();
                    lineLeftX.name = 'lineLeftX' + j;
                    lineLeftX.graphics.setStrokeStyle(AppConstants.MAGNETIC_LINE_WIDTH).beginStroke(AppConstants.MAGNETIC_LINE_COLOR).moveTo(poisX[j], 0).lineTo(poisX[j], self.model.getHeight());
                    self.magneticLineContainer.addChild(lineLeftX);
                  }
                }
                if (poisX[j] && deltaRight <= AppConstants.MAGNETIC_SNAP_DISTANCE && deltaRight <= AppValues.nearestPoi.deltaX) {
                  if (!self.magneticLineContainer.getChildByName('lineRightX' + j)) {
                    var lineRightX = new createjs.Shape();
                    lineRightX.name = 'lineRightX' + j;
                    lineRightX.graphics.setStrokeStyle(AppConstants.MAGNETIC_LINE_WIDTH).beginStroke(AppConstants.MAGNETIC_LINE_COLOR).moveTo(poisX[j], 0).lineTo(poisX[j], self.model.getHeight());
                    self.magneticLineContainer.addChild(lineRightX);
                  }
                }
                if (poisY[j] && deltaTop <= AppConstants.MAGNETIC_SNAP_DISTANCE && deltaTop <= AppValues.nearestPoi.deltaY) {
                  if (!self.magneticLineContainer.getChildByName('lineTopY' + j)) {
                    var lineTopY = new createjs.Shape();
                    lineTopY.name = 'lineTopY' + j;
                    lineTopY.graphics.setStrokeStyle(AppConstants.MAGNETIC_LINE_WIDTH).beginStroke(AppConstants.MAGNETIC_LINE_COLOR).moveTo(0, poisY[j]).lineTo(self.model.getWidth(), poisY[j]);
                    self.magneticLineContainer.addChild(lineTopY);
                  }
                }
                if (poisY[j] && deltaBottom <= AppConstants.MAGNETIC_SNAP_DISTANCE && deltaBottom <= AppValues.nearestPoi.deltaY) {
                  if (!self.magneticLineContainer.getChildByName('lineBottomY' + j)) {
                    var lineBottomY = new createjs.Shape();
                    lineBottomY.name = 'lineBottomY' + j;
                    lineBottomY.graphics.setStrokeStyle(AppConstants.MAGNETIC_LINE_WIDTH).beginStroke(AppConstants.MAGNETIC_LINE_COLOR).moveTo(0, poisY[j]).lineTo(self.model.getWidth(), poisY[j]);
                    self.magneticLineContainer.addChild(lineBottomY);
                  }
                }
              }
            }


            if ((AppValues.nearestPoi.deltaX <= AppConstants.MAGNETIC_SNAP_DISTANCE || AppValues.nearestPoi.deltaY <= AppConstants.MAGNETIC_SNAP_DISTANCE) && scaleButtons.indexOf(e.target.name) < 0 && cropButtons.indexOf(e.target.name) < 0) {
              if (AppValues.nearestPoi.nearestNeighborX === 'centerX') {
                canvasItemBox.setCenterX(AppValues.nearestPoi.x);
              }
              if (AppValues.nearestPoi.nearestNeighborY === 'centerY') {
                canvasItemBox.setCenterY(AppValues.nearestPoi.y);
              }
              if (canvasItemBox.getRotation() === 0 || canvasItemBox.getRotation() === 180) {
                if (AppValues.nearestPoi.nearestNeighborX === 'left') {
                  canvasItemBox.setCenterX(AppValues.nearestPoi.x + canvasItemBox.getWidth() / 2);
                }
                if (AppValues.nearestPoi.nearestNeighborX === 'right') {
                  canvasItemBox.setCenterX(AppValues.nearestPoi.x - canvasItemBox.getWidth() / 2);
                }
                if (AppValues.nearestPoi.nearestNeighborY === 'top') {
                  canvasItemBox.setCenterY(AppValues.nearestPoi.y + canvasItemBox.getHeight() / 2);
                }
                if (AppValues.nearestPoi.nearestNeighborY === 'bottom') {
                  canvasItemBox.setCenterY(AppValues.nearestPoi.y - canvasItemBox.getHeight() / 2);
                }
              } else if (canvasItemBox.getRotation() === 90 || canvasItemBox.getRotation() === 270) {
                if (AppValues.nearestPoi.nearestNeighborX === 'left') {
                  canvasItemBox.setCenterX(AppValues.nearestPoi.x + canvasItemBox.getHeight() / 2);
                }
                if (AppValues.nearestPoi.nearestNeighborX === 'right') {
                  canvasItemBox.setCenterX(AppValues.nearestPoi.x - canvasItemBox.getHeight() / 2);
                }
                if (AppValues.nearestPoi.nearestNeighborY === 'top') {
                  canvasItemBox.setCenterY(AppValues.nearestPoi.y + canvasItemBox.getWidth() / 2);
                }
                if (AppValues.nearestPoi.nearestNeighborY === 'bottom') {
                  canvasItemBox.setCenterY(AppValues.nearestPoi.y - canvasItemBox.getWidth() / 2);
                }
              }
            }


            // ROTATION HERE
            var poisRotation = self.model.getPointsOfInterest('rot');
            var roundedRotation = Math.round(canvasItemBox.getRotation());
            poisRotation.forEach(function (poiRot) {
              if (roundedRotation > poiRot - AppConstants.MAGNETIC_SNAP_DISTANCE / 2 && roundedRotation < poiRot + AppConstants.MAGNETIC_SNAP_DISTANCE / 2) {
                canvasItemBox.setRotation(poiRot);
              }
            });


            self.getPrintArea().setChildIndex(self.magneticLineContainer, self.getPrintArea().getNumChildren() - 1);
          }
        });


        self.$$getAllCanvasItemBoxes(false).push(canvasItemBox);
        var dummyBarCodeImage;

        if (self.model.isCover()) {
          dummyBarCodeImage = self.getPrintArea().getChildByName('dummyBarCode');
          self.getPrintArea().removeChild(this.logo);
          self.getPrintArea().removeChild(dummyBarCodeImage);
        }
        var tempContainer = self.getPrintArea().getChildByName('blockedPageContainer');
        self.getPrintArea().removeChild(tempContainer);
        self.getPrintArea().addChild(canvasItemBox.getRootContainer());
        if (isImageItem) {
          self.getPrintArea().addChild(canvasItemBox.getContentSilhouette().getRootContainer());
        }

        self.getPrintArea().addChild(tempContainer);
        if (self.model.isCover()) {
          self.getPrintArea().addChild(dummyBarCodeImage);
          self.getPrintArea().addChild(this.logo);
        }

        var lastChildIndex = self.getPrintArea().getNumChildren() - 1;
        self.getPrintArea().setChildIndex(this.spine ? this.spine : this.centerFold, lastChildIndex);


        self.getToolFrameContainer().addChild(canvasItemBox.getToolFrame().getRootContainer());


        canvasItemBox.getToolFrame().initialize().then(function toolFrameInitialized() {
          if (canvasItemBox.getModel() && canvasItemBox.getModel().isSelected()) {
            self.$$setAttachedDomElementsPositionToItemBox(canvasItemBox);
          }
        });


        // Safe the states before the move, rotate scale functions
        // of the itemboxes for undo/redo
        canvasItemBox.addMouseDownListener(function toolFrameMouseDown(e) {

          // refill the point of intereset
          self.model.clearAllPointsOfInterest();
          AppValues.nearestPoi = {
            x: undefined,
            y: undefined,
            nearestNeighborX: undefined,
            nearestNeighborY: undefined,
            deltaX: undefined,
            deltaY: undefined
          };

          if (ProjectService.getProject().isMagneticLinesActive()) {
            var tolerance = 50;
            /** fill points of interests (x) for the move button if pressed**/

            if (e.target.name === 'move') {
              self.model.getImageAndTextAndClipartItems().forEach(function (item) {
                if (!item.isSelected()) {
                  self.model.setPointOfInterest('x', item.getCenterX());
                  self.model.setPointOfInterest('y', item.getCenterY());
                  if (item.getRotation() === 0 || item.getRotation() === 180) {
                    self.model.setPointOfInterest('x', item.getCenterX() - item.getWidth() / 2);
                    self.model.setPointOfInterest('x', item.getCenterX() + item.getWidth() / 2);
                    self.model.setPointOfInterest('y', item.getCenterY() - item.getHeight() / 2);
                    self.model.setPointOfInterest('y', item.getCenterY() + item.getHeight() / 2);
                  } else if (item.getRotation() === 90 || item.getRotation() === 270) {
                    self.model.setPointOfInterest('x', item.getCenterX() - item.getHeight() / 2);
                    self.model.setPointOfInterest('x', item.getCenterX() + item.getHeight() / 2);
                    self.model.setPointOfInterest('y', item.getCenterY() - item.getWidth() / 2);
                    self.model.setPointOfInterest('y', item.getCenterY() + item.getWidth() / 2);
                  }
                }
              });
              self.model.setPointOfInterest('x', self.model.getWidth() / 2);
              self.model.setPointOfInterest('x', self.model.getWidth() / 4);
              self.model.setPointOfInterest('x', self.model.getWidth() / 4 * 3);
              self.model.setPointOfInterest('y', self.model.getHeight() / 2);
            }
            /** fill points of interests (x) for the scaleTopLeft cropLeft or scaleBottomLeft button if pressed **/
            if (((e.target.name === 'scaleTopLeft' || e.target.name === 'cropLeft' || e.target.name === 'scaleBottomLeft') && canvasItemBox.getRotation() === 0) ||
              (e.target.name === 'scaleTopRight' || e.target.name === 'cropRight' || e.target.name === 'scaleBottomRight') && canvasItemBox.getRotation() === 180) {
              self.model.getImageAndTextAndClipartItems().forEach(function (item) {
                if (!item.isSelected() && item.getRotation() === 0) {
                  var selectedRight = (canvasItemBox.getCenterX() + canvasItemBox.getWidth() / 2) - tolerance;
                  if (selectedRight > (item.getCenterX() + item.getWidth() / 2)) {
                    self.model.setPointOfInterest('x', item.getCenterX() + item.getWidth() / 2);
                  }
                  if (selectedRight > item.getCenterX()) {
                    self.model.setPointOfInterest('x', item.getCenterX());
                  }
                  if (selectedRight > (item.getCenterX() - item.getWidth() / 2)) {
                    self.model.setPointOfInterest('x', item.getCenterX() - item.getWidth() / 2);
                  }
                  if (selectedRight > (self.model.getWidth() / 2)) {
                    self.model.setPointOfInterest('x', self.model.getWidth() / 2);
                  }
                  if (selectedRight > (self.model.getWidth() / 4 * 3)) {
                    self.model.setPointOfInterest('x', self.model.getWidth() / 4 * 3);
                  }
                  if (selectedRight > (self.model.getWidth() / 4)) {
                    self.model.setPointOfInterest('x', self.model.getWidth() / 4);
                  }
                }
              });
            }
            if (((e.target.name === 'scaleTopRight' || e.target.name === 'cropRight' || e.target.name === 'scaleBottomRight') && canvasItemBox.getRotation() === 0) ||
              (e.target.name === 'scaleTopLeft' || e.target.name === 'cropLeft' || e.target.name === 'scaleBottomLeft') && canvasItemBox.getRotation() === 180) {
              self.model.getImageAndTextAndClipartItems().forEach(function (item) {
                if (!item.isSelected() && item.getRotation() === 0) {
                  var selectedLeft = (canvasItemBox.getCenterX() - canvasItemBox.getWidth() / 2) + tolerance;
                  if (selectedLeft < (item.getCenterX() - item.getWidth() / 2)) {
                    self.model.setPointOfInterest('x', item.getCenterX() - item.getWidth() / 2);
                  }
                  if (selectedLeft < item.getCenterX()) {
                    self.model.setPointOfInterest('x', item.getCenterX());
                  }
                  if (selectedLeft < (item.getCenterX() + item.getWidth() / 2)) {
                    self.model.setPointOfInterest('x', item.getCenterX() + item.getWidth() / 2);
                  }
                  if (selectedLeft < (self.model.getWidth() / 2)) {
                    self.model.setPointOfInterest('x', self.model.getWidth() / 2);
                  }
                  if (selectedLeft < (self.model.getWidth() / 4 * 3)) {
                    self.model.setPointOfInterest('x', self.model.getWidth() / 4 * 3);
                  }
                  if (selectedLeft < (self.model.getWidth() / 4)) {
                    self.model.setPointOfInterest('x', self.model.getWidth() / 4);
                  }
                }
              });
            }
            if (((e.target.name === 'scaleTopLeft' || e.target.name === 'cropTop' || e.target.name === 'scaleTopRight') && canvasItemBox.getRotation() === 0) ||
              (e.target.name === 'scaleBottomLeft' || e.target.name === 'cropBottom' || e.target.name === 'scaleBottomRight') && canvasItemBox.getRotation() === 180) {
              self.model.getImageAndTextAndClipartItems().forEach(function (item) {
                if (!item.isSelected() && item.getRotation() === 0) {
                  var selectedBottom = (canvasItemBox.getCenterY() + canvasItemBox.getHeight() / 2) - tolerance;
                  if (selectedBottom > (item.getCenterY() - item.getHeight() / 2)) {
                    self.model.setPointOfInterest('y', item.getCenterY() - item.getHeight() / 2);
                  }
                  if (selectedBottom > item.getCenterY()) {
                    self.model.setPointOfInterest('y', item.getCenterY());
                  }
                  if (selectedBottom > (item.getCenterY() + item.getHeight() / 2)) {
                    self.model.setPointOfInterest('y', item.getCenterY() + item.getHeight() / 2);
                  }
                  if (selectedBottom > (self.model.getHeight() / 2)) {
                    self.model.setPointOfInterest('y', self.model.getHeight() / 2);
                  }
                }

              });
            }
            if (((e.target.name === 'scaleBottomLeft' || e.target.name === 'cropBottom' || e.target.name === 'scaleBottomRight') && canvasItemBox.getRotation() === 0) ||
              (e.target.name === 'scaleTopLeft' || e.target.name === 'cropTop' || e.target.name === 'scaleTopRight') && canvasItemBox.getRotation() === 180) {
              self.model.getImageAndTextAndClipartItems().forEach(function (item) {
                if (!item.isSelected() && item.getRotation() === 0) {
                  var selectedTop = (canvasItemBox.getCenterY() - canvasItemBox.getHeight() / 2) + tolerance;
                  if (selectedTop < (item.getCenterY() - item.getHeight() / 2)) {
                    self.model.setPointOfInterest('y', item.getCenterY() - item.getHeight() / 2);
                  }
                  if (selectedTop < item.getCenterY()) {
                    self.model.setPointOfInterest('y', item.getCenterY());
                  }
                  if (selectedTop < (item.getCenterY() + item.getHeight() / 2)) {
                    self.model.setPointOfInterest('y', item.getCenterY() + item.getHeight() / 2);
                  }
                  if (selectedTop < (self.model.getHeight() / 2)) {
                    self.model.setPointOfInterest('y', self.model.getHeight() / 2);
                  }
                }
              });
            }

            if (e.target.name !== 'scaleBottomLeft' && e.target.name !== 'scaleTopLeft' && e.target.name !== 'scaleBottomRight' && e.target.name !== 'scaleTopRight') {
              self.model.getImageAndTextAndClipartItems().forEach(function (item) {
                if (canvasItemBox.getRotation() === 90 || canvasItemBox.getRotation() === 270) {
                  if (!item.isSelected() && item.getRotation() === 0) {
                    self.model.setPointOfInterest('x', item.getCenterX() - item.getWidth() / 2);
                    self.model.setPointOfInterest('x', item.getCenterX() + item.getWidth() / 2);
                    self.model.setPointOfInterest('x', item.getCenterX());
                    self.model.setPointOfInterest('y', item.getCenterY());
                    self.model.setPointOfInterest('y', item.getCenterY() - item.getHeight() / 2);
                    self.model.setPointOfInterest('y', item.getCenterY() + item.getHeight() / 2);
                  }
                }
                if (canvasItemBox.getRotation() === 0 || canvasItemBox.getRotation() === 180) {
                  if (item.getRotation() === 90 || item.getRotation() === 270) {
                    self.model.setPointOfInterest('x', item.getCenterX());
                    self.model.setPointOfInterest('y', item.getCenterY());
                    self.model.setPointOfInterest('x', item.getCenterX() - item.getHeight() / 2);
                    self.model.setPointOfInterest('x', item.getCenterX() + item.getHeight() / 2);
                    self.model.setPointOfInterest('y', item.getCenterY() - item.getWidth() / 2);
                    self.model.setPointOfInterest('y', item.getCenterY() + item.getWidth() / 2);
                  }
                }
              });
            }

            if (e.target.name === 'rotateTopLeft' || e.target.name === 'rotateTopRight' || e.target.name === 'rotateBottomLeft' || e.target.name === 'rotateBottomRight') {
              self.model.getImageAndTextAndClipartItems().forEach(function (item) {
                if (!item.isSelected() && item.getRotation() % 90 !== 0) {
                  self.model.setPointOfInterest('rot', item.getRotation());
                }
              });
            }
          }

          var handle = UndoRedoService.pushModelData(self.model);
          if (canvasItemBox.model.isContextView() && canvasItemBox.model.isSelected()) {

            var allImageItemsOnArea = self.$$getCanvasImageItemBoxes();
            allImageItemsOnArea.forEach(function (imageItem) {
              imageItem.getModel().setContextView(false);
            });
          }
          SafeApply.do(function applyToolFrameMouseDown() {
            handle.resolve();
            handle = null;
          }, self.scope);
        });

        canvasItemBox.addMouseUpListener(function toolFrameMouseUp(e) {
            if (canvasItemBox.getModel().isSelected()) {
              self.$$setAttachedDomElementsPositionToItemBox(canvasItemBox);
            }
            if (self.magneticLineContainer && self.getPrintArea().getChildByName('magneticLineContainer')) {
              self.magneticLineContainer.removeAllChildren();
            }

            // remove the last model data entry from the undo/redo stack, if the operation was just toggling between toolframe modes. It was not
            // worth storing it on the stack, but we could not know which operation was intended until release of the mouse button (i.e. mouse up)
            if (canvasItemBox.getToolFrame().isTogglingModes()) {
              var handle = UndoRedoService.popModelData();
              SafeApply.do(function applyToolFrameMouseUp() {
                handle.resolve();
                handle = null;
              }, self.scope);
            }
          }
        )
        ;
      };

      /**
       * Returns the CanvasItemBox found at the specified coordinates.
       * @param x
       * @param y
       * @param {Boolean} topMostOnly consider the top most canvas element only for return
       * @returns {CanvasItemBox} the found CanvasItemBox
       */
      CanvasDesignArea.prototype.getCanvasItemBoxAt = function (x, y, topMostOnly) {

        var self = this;

        var allCanvasItems = this.$$getAllCanvasItemBoxes(true);

        if (topMostOnly) {
          var topMostCanvasElement = this.getStage().getObjectUnderPoint(x, y);

          allCanvasItems.forEach(function iterCanvasItems(canvasItem) {
            if (canvasItem.getToolFrame().getRootContainer().contains(topMostCanvasElement) ||
              (self.$$isCanvasImageItem(canvasItem) && canvasItem.getContentSilhouette().getRootContainer().contains(topMostCanvasElement))) {
              // within toolframe bounds? (e.g. click on the contentSilhouette oftentimes is not)
              var localPoint = canvasItem.getToolFrame().getRootContainer().globalToLocal(x, y);
              if (canvasItem.getToolFrame().getRootContainer().hitTest(localPoint.x, localPoint.y)) {
                return canvasItem;
              }
            }
          });
        }


        var displayObjects = this.getStage().getObjectsUnderPoint(x, y);

        if (displayObjects && displayObjects.length > 0) {

          var contentNodes = [];

          for (var i = 0; i < displayObjects.length; i++) {
            if (displayObjects[i].name && displayObjects[i].name === 'itemBoxContent') {
              contentNodes.push(displayObjects[i]);
            }
          }

          // find out whether the user clicked within the bounds of the toolframe of the currently selected canvasItemBox
          var clickedOnSelectedItemBoxToolFrame = false;
          var selectedCanvasItemBox = this.$$getSelectedCanvasItemBox();

          if (selectedCanvasItemBox && selectedCanvasItemBox.getToolFrame().getRootContainer().contains(displayObjects[0]) ||
            this.$$isCanvasImageItem(selectedCanvasItemBox) && selectedCanvasItemBox.getContentSilhouette().getRootContainer().contains(displayObjects[0])) {

            // within toolframe bounds? (e.g. click on the contentSilhouette oftentimes is not)
            var localPoint = selectedCanvasItemBox.getToolFrame().getRootContainer().globalToLocal(x, y);
            if (selectedCanvasItemBox.getToolFrame().getRootContainer().hitTest(localPoint.x, localPoint.y) && !selectedCanvasItemBox.getToolFrame().btnItemContent.hitArea.hitTest(localPoint.x, localPoint.y)) {
              clickedOnSelectedItemBoxToolFrame = true;
            }
          }


          var canvasItemBoxUnderMouse;
          allCanvasItems.forEach(function iterateAllCanvasItems(canvasItemBox) {

            if (canvasItemBox.getContent() === contentNodes[0]) {
              // currently we don't want to return a CanvasBackgroundItem as the clicked upon item
              if (!self.$$isCanvasTemplateBackgroundItem(canvasItemBox)) {
                canvasItemBoxUnderMouse = canvasItemBox;
              }
            }
          });

          if (clickedOnSelectedItemBoxToolFrame) {
            canvasItemBoxUnderMouse = selectedCanvasItemBox;

          }
          return canvasItemBoxUnderMouse;
        }
      };

      /**
       * Deletes all CanvasItemBoxes from the CanvasDesignArea.
       * @param canvasItemBox the CanvasItemBox to delete
       */
      CanvasDesignArea.prototype.deleteAllCanvasItemBoxes = function () {
        var self = this;
        this.canvasItemBoxes.forEach(function iterateItemBoxes(canvasItemBox) {
          if (self.$$isCanvasImageItem(canvasItemBox)) {
            self.getPrintArea().removeChild(canvasItemBox.getContentSilhouette().getRootContainer());
          }
          self.getPrintArea().removeChild(canvasItemBox.getRootContainer());
          self.getToolFrameContainer().removeChild(canvasItemBox.getToolFrame().getRootContainer());
          canvasItemBox.cleanUp();
        });
        this.canvasItemBoxes = [];
      };

      /**
       * Removes all watches and all eventListeners from the specifc objects (also for the resize event on the $window)
       */

      CanvasDesignArea.prototype.cleanUp = function () {
        var self = this;
        // remove all watches
        for (var i = 0; i < this.watches; i++) {
          this.watches[i]();
        }
        self.eventListenerTargets.forEach(function (eventListenerTarget) {
          if (eventListenerTarget && eventListenerTarget !== $window) {
            eventListenerTarget.removeAllEventListeners();
          }


          //this is more important for the window object here, the CanvasDesignArea itself (and all eventListenerTargets) will be destroyed, so no event
          //is able to fire after they are killed. The window object is still alive, so we have to unbind the events

          else if (eventListenerTarget && eventListenerTarget === $window) {
            angular.element($window).unbind('resize', self.onResizeHandler);
          }
        });


        var allCanvasItemBoxes = self.$$getAllCanvasItemBoxes(false);
        allCanvasItemBoxes.forEach(function (canvasItemBox) {
          canvasItemBox.cleanUp();
        });


        this.getStage().enableDOMEvents(false);
        this.getStage().removeAllChildren();
        this.getStage().removeAllEventListeners();

        this.stage.canvas.removeEventListener('touchend', this.$$canvasClicked);
        this.stage.canvas.removeEventListener('click', this.$$canvasClicked);
      };


      CanvasDesignArea.prototype.pinchZoom = function (hammerJsEvent) {

        var scale = hammerJsEvent.gesture.scale;

        // Only zoom the itembox, if we are in detail view and if it was selected.
        if (this.zoomedCanvasImageItem && this.model.isDetailInteractionMode() && this.zoomedCanvasImageItem.model.isSelected()) {

          var newViewPort = this.zoomedCanvasImageItem.$$calculateViewPort('pinchZoom', this.zoomStartViewPort, scale);
          this.zoomedCanvasImageItem.model.setViewPort(newViewPort);

        }
      };


      /**
       * Checks whether the given CanvasItemBox is within the bounds of the given CanvasDesignArea.
       * @param canvasItemBox
       * @param canvasDesignArea
       */
      CanvasDesignArea.prototype.isWithinDesignArea = function (canvasItemBox, canvasDesignArea) {

        var boundsUpperLeft = {
          x: 0,
          y: 0
        };
        var boundsLowerRight = {
          x: canvasDesignArea.model.width,
          y: canvasDesignArea.model.height
        };

        var upperLeft = canvasItemBox.getRootContainer().localToGlobal(0, 0);
        var upperRight = canvasItemBox.getRootContainer().localToGlobal(canvasItemBox.model.getWidth(), 0);
        var lowerLeft = canvasItemBox.getRootContainer().localToGlobal(0, canvasItemBox.model.getHeight());
        var lowerRight = canvasItemBox.getRootContainer().localToGlobal(canvasItemBox.model.getWidth(), canvasItemBox.model.getHeight());


        var itemBoxCorners = [upperLeft, upperRight, lowerLeft, lowerRight];

        for (var i = 0; i < itemBoxCorners.length; i++) {
          var itemBoxCorner = itemBoxCorners[i];

          if (itemBoxCorner.x < boundsUpperLeft.x ||
            itemBoxCorner.y < boundsUpperLeft.y ||
            itemBoxCorner.x > boundsLowerRight.x ||
            itemBoxCorner.y > boundsLowerRight.y) {

            return false;
          }

        }

        return true;

      };

      CanvasDesignArea.prototype.swapImageItems = function (imageItemOne, imageItemTwo) {
        var self = this;

        var tweenOneInterpolation = {
          centerX: imageItemOne.getModel().getCenterX(),
          centerY: imageItemOne.getModel().getCenterY(),
          width: imageItemOne.getModel().getWidth(),
          height: imageItemOne.getModel().getHeight(),
          rotation: imageItemOne.getModel().getRotation()
        };

        var tweenTwoInterpolation = {
          centerX: imageItemTwo.getModel().getCenterX(),
          centerY: imageItemTwo.getModel().getCenterY(),
          width: imageItemTwo.getModel().getWidth(),
          height: imageItemTwo.getModel().getHeight(),
          rotation: imageItemTwo.getModel().getRotation()
        };

        // create a tween timeline to be able to tween the item boxes to the new positions as a group
        var swapImagesTimeline = new createjs.Timeline();
        swapImagesTimeline.on('change', function change() {
          imageItemOne.setCenterX(tweenOneInterpolation.centerX);
          imageItemOne.setCenterY(tweenOneInterpolation.centerY);
          imageItemOne.setWidth(tweenOneInterpolation.width);
          imageItemOne.setHeight(tweenOneInterpolation.height);
          imageItemOne.setRotation(tweenOneInterpolation.rotation);
          imageItemOne.resetViewPortToFitIntelligently();

          imageItemTwo.setCenterX(tweenTwoInterpolation.centerX);
          imageItemTwo.setCenterY(tweenTwoInterpolation.centerY);
          imageItemTwo.setWidth(tweenTwoInterpolation.width);
          imageItemTwo.setHeight(tweenTwoInterpolation.height);
          imageItemTwo.setRotation(tweenTwoInterpolation.rotation);
          imageItemTwo.resetViewPortToFitIntelligently();
        });

        var tweenDuration = 400;

        var tweenOneTo = {
          centerX: imageItemTwo.getModel().getCenterX(),
          centerY: imageItemTwo.getModel().getCenterY(),
          width: imageItemTwo.getModel().getWidth(),
          height: imageItemTwo.getModel().getHeight(),
          rotation: imageItemTwo.getModel().getRotation()
        };

        var tweenTwoTo = {
          centerX: imageItemOne.getModel().getCenterX(),
          centerY: imageItemOne.getModel().getCenterY(),
          width: imageItemOne.getModel().getWidth(),
          height: imageItemOne.getModel().getHeight(),
          rotation: imageItemOne.getModel().getRotation()
        };

        var numberOfTweensCompleted = 0;
        var onTweenCompleted = function () {
          numberOfTweensCompleted++;
          if (numberOfTweensCompleted >= 2) {
            SafeApply.do(function doApply() {
              var itemModelOne = imageItemOne.getModel();
              itemModelOne.setCenterX(tweenOneTo.centerX);
              itemModelOne.setCenterY(tweenOneTo.centerY);
              itemModelOne.setWidth(tweenOneTo.width);
              itemModelOne.setHeight(tweenOneTo.height);
              itemModelOne.setRotation(tweenOneTo.rotation);
              itemModelOne.resetViewPortToFitIntelligently();

              var itemModelTwo = imageItemTwo.getModel();
              itemModelTwo.setCenterX(tweenTwoTo.centerX);
              itemModelTwo.setCenterY(tweenTwoTo.centerY);
              itemModelTwo.setWidth(tweenTwoTo.width);
              itemModelTwo.setHeight(tweenTwoTo.height);
              itemModelTwo.setRotation(tweenTwoTo.rotation);
              itemModelTwo.resetViewPortToFitIntelligently();

              self.model.swapLayers(itemModelOne, itemModelTwo);
            });
          }
        };

        var tweenOne = createjs.Tween.get(tweenOneInterpolation, {override: true}).to(tweenOneTo, tweenDuration, createjs.Ease.sineInOut).call(function tweenOneComplete() {
          onTweenCompleted();
        });
        swapImagesTimeline.addTween(tweenOne);

        var tweenTwo = createjs.Tween.get(tweenTwoInterpolation, {override: true}).to(tweenTwoTo, tweenDuration, createjs.Ease.sineInOut).call(function tweenTwoComplete() {
          onTweenCompleted();
        });
        swapImagesTimeline.addTween(tweenTwo);

        /*$timeout(function releaseTweenLock() {


         }, tweenDuration);*/

      };


      // definition of the public factory functions
      return {
        /**
         * Creates a CanvasDesignArea from the specified design area data model.
         * @param scope the Angular scope the design area data model is bound to
         * @param designAreaModel the design area data model to visually represent with the CanvasDesignArea
         * @returns {CanvasDesignArea} the created CanvasDesignArea
         */
        createCanvasDesignArea: function (scope, designAreaModel, cwDesignAreaDomElement) {
          return new CanvasDesignArea(scope, designAreaModel, cwDesignAreaDomElement);
        }
      };

    }

  ])
  ;

})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Creates CanvasItemPrototype instances with common attributes for all CanvasDesignArea relevant canvas item boxes that are considered to be
 * abstract and are only for subclasses to use with prototypical inheritance.
 *
 * Note: It's a contract for sublasses to call this class' $$initModel(itemBoxModel) method.
 *
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';
  /* global createjs */

  angular.module('tatooine').factory('CanvasItemPrototypeFactory', [
    '$log', 'SafeApply', 'AppConstants', 'AppValues', 'ToolFrameFactory',
    function ($log, SafeApply, AppConstants, AppValues, ToolFrameFactory) {

      function CanvasItemPrototype(scope, itemBoxModel) {

        this.touchDevice = createjs.Touch.isSupported();

        this.scope = scope;
        this.model = itemBoxModel;

        this.getModel().origWidth = this.getModel().getWidth();
        this.getModel().origHeight = this.getModel().getHeight();

        this.content = null;

        this.toolFrame = null;

        this.rootContainer = new createjs.Container();
        this.getRootContainer().id = this.getModel().getId();
        this.getRootContainer().name = 'itemBox-' + this.getModel().getId();
        this.getRootContainer().x = this.getModel().getCenterX();
        this.getRootContainer().y = this.getModel().getCenterY();
        this.getRootContainer().regX = this.getModel().getWidth() / 2;
        this.getRootContainer().regY = this.getModel().getHeight() / 2;


        this.getRootContainer().mouseEnabled = false; // deactivate mouse event listening (for the container and its children)

        this.itemBorder = new createjs.Shape();

        // every CanvasItemBox gets its own ToolFrame instance
        this.toolFrame = ToolFrameFactory.createToolFrame(this.getModel().getWidth(), this.getModel().getHeight(), this.getModel().isPositionEditable());
        this.getToolFrame().setCenterX(this.getModel().getCenterX());
        this.getToolFrame().setCenterY(this.getModel().getCenterY());


        var self = this;

        this.getToolFrame().addMouseDownListener(function (e) {
          self.$$onMouseDown(e);
        });


        // update the canvas representation of the item box on every drag operation on the ToolFrame, but the data model is not changed yet
        this.getToolFrame().addMouseDraggedListener(function mouseDraggedListener(e) {
          self.$$onMouseDragged(e);
        });


        // as soon as the toolframe is not pressed anymore, we transfer the canvas state into the (Angular) watched data model
        this.getToolFrame().addMouseUpListener(function mouseUpListener(e) {

          SafeApply.do(function applyMouseUpListener() {
            self.$$onMouseUp(e);
          }, self.scope);

        });


        // watch the item box data model for changes and adapt the canvas item accordingly
        this.deleteDataModelWatch = this.scope.$watch(function watchItemBoxModelStateVersion() {
          return self.getModel().getModelStateVersion();
        }, function onItemBoxModelStateVersionChanged(newValue, oldValue) {


          if (!self.getRootContainer().getStage()) {
            // If the root container has no stage anymore, this item box was removed from the stage. It means, we can skip here.
            return;
          }

          self.$$onModelChange(self.getModel());
        });


      }


      /**
       * Called whenever the underlying data model changed.
       * This is meant for subclasses to override, if interested in the model change.
       * @param model
       */
      CanvasItemPrototype.prototype.$$onModelChange = function (model) {
        var self = this;
        self.setCenterX(model.getCenterX());
        self.setCenterY(model.getCenterY());
        self.setHeight(model.getHeight());
        self.setWidth(model.getWidth());
        self.setRotation(model.getRotation());
        self.setSelected(model.isSelected());
        self.drawItemBorder();
      };


      /**
       * Called whenever the 'mouse up' event fired on the CanvasItem's ToolFrame.
       * This is meant for subclasses to override, if interested in the event. But if you do, don't forget to call this method
       * from your overridden method.
       * @param e
       */
      CanvasItemPrototype.prototype.$$onMouseUp = function (e) {
        var model = this.getModel();

        model.setCenterX(this.getToolFrame().getCenterX());
        model.setCenterY(this.getToolFrame().getCenterY());
        model.setWidth(this.getToolFrame().getWidth());
        model.setHeight(this.getToolFrame().getHeight());
        model.setRotation(Math.round(this.getToolFrame().getRotation()));
        model.setMouseDown(false);
      };

      /**
       * Called whenever the 'mouse down' event fired on the CanvasItem's ToolFrame.
       * This is meant for subclasses to override, if interested in the event. But if you do, don't forget to call this method
       * from your overridden method.
       * @param e
       */
      CanvasItemPrototype.prototype.$$onMouseDown = function (e) {
        this.getModel().setMouseDown(true);
      };


      /**
       * Called whenever the 'mouse dragged' event fired on the CanvasItem's ToolFrame.
       * This is meant for subclasses to override, if interested in the event. But if you do, don't forget to call this method
       * from your overridden method.
       * @param e
       */
      CanvasItemPrototype.prototype.$$onMouseDragged = function (e) {
        var toolFramePosition = {
          centerX: this.getToolFrame().getCenterX(),
          centerY: this.getToolFrame().getCenterY(),
          width: this.getToolFrame().getWidth(),
          height: this.getToolFrame().getHeight(),
          rotation: this.getToolFrame().getRotation()
        };

        var newPosition = this.getModel().checkRestrictionBox(toolFramePosition, e);

        this.setCenterX(newPosition.centerX);
        this.setCenterY(newPosition.centerY);
        this.setWidth(newPosition.width);
        this.setHeight(newPosition.height);
        this.setRotation(newPosition.rotation);
        this.getModel().setLayoutModified(true);
        this.drawItemBorder();
      };


      CanvasItemPrototype.prototype.getRootContainer = function () {
        return this.rootContainer;
      };

      CanvasItemPrototype.prototype.getModel = function () {
        return this.model;
      };

      /**
       * @return {ToolFrame}
       */
      CanvasItemPrototype.prototype.getToolFrame = function () {
        return this.toolFrame;
      };

      CanvasItemPrototype.prototype.getId = function () {
        return this.getModel().getId();
      };

      CanvasItemPrototype.prototype.setCenterX = function (x) {
        this.getRootContainer().x = x;
        this.getToolFrame().setCenterX(x);
      };

      CanvasItemPrototype.prototype.setCenterY = function (y) {
        this.getRootContainer().y = y;
        this.getToolFrame().setCenterY(y);
      };


      CanvasItemPrototype.prototype.getCenterX = function (x) {
        return this.getRootContainer().x;
      };

      CanvasItemPrototype.prototype.getCenterY = function (y) {
        return this.getRootContainer().y;
      };

      /**
       *
       * @param width the width of the CanvasItem in pixels
       */
      CanvasItemPrototype.prototype.setWidth = function (width) {
        this.getRootContainer().regX = width / 2;
        this.getToolFrame().setWidth(width);
      };

      CanvasItemPrototype.prototype.getWidth = function () {
        return this.getToolFrame().getWidth();
      };

      /**
       *
       * @param height the height of the CanvasItem in pixels
       */
      CanvasItemPrototype.prototype.setHeight = function (height) {
        this.getRootContainer().regY = height / 2;
        this.getToolFrame().setHeight(height);
      };


      CanvasItemPrototype.prototype.getHeight = function () {
        return this.getToolFrame().getHeight();
      };

      /**
       * Sets the rotation of the CanvasItem in degrees.
       * @param rotation
       */
      CanvasItemPrototype.prototype.setRotation = function (rotation) {
        this.getRootContainer().rotation = rotation;
        this.getToolFrame().setRotation(rotation);
      };

      CanvasItemPrototype.prototype.getRotation = function () {
        return this.getRootContainer().rotation;
      };

      CanvasItemPrototype.prototype.getLayerIndex = function () {
        return this.getModel().getLayerIndex();
      };

      CanvasItemPrototype.prototype.drawItemBorder = function () {
        this.itemBorder.graphics.clear();
        var borderWidth = this.getModel().getBorderWidth() * AppConstants.MM_TO_PX;
        if (this.getModel().isBorderAllowed() && borderWidth > 0) {
          this.getToolFrame().setGap(AppConstants.TOOLFRAME_DEFAULT_GAP + borderWidth);
          var borderColor = this.getModel().getBorderColor();
          this.itemBorder.graphics.setStrokeStyle(borderWidth).beginStroke(borderColor).drawRect(-borderWidth / 2, -borderWidth / 2, this.getToolFrame().getWidth() + borderWidth, this.getToolFrame().getHeight() + borderWidth);
        }
        else {
          this.getToolFrame().setGap(AppConstants.TOOLFRAME_DEFAULT_GAP);
        }
      };

      CanvasItemPrototype.prototype.getRotation = function () {
        return this.getRootContainer().rotation;
      };

      /**
       * Sets the selection status of the CanvasItem.
       * @param selected
       */
      CanvasItemPrototype.prototype.setSelected = function (selected) {
        this.getToolFrame().setVisible(selected);
        if (selected) {
          var stage = this.getRootContainer().getStage();
          var lastChildIndex = stage.getNumChildren() - 1;
          stage.setChildIndex(this.getToolFrame().rootContainer, lastChildIndex);
        }
      };


      /**
       *
       * @returns {DisplayObject} the EaselJS DisplayObject that is the visual content of the CanvasItemBox
       */
      CanvasItemPrototype.prototype.getContent = function () {
        return this.content;
      };


      /**
       * Sets the display object that is the visual content of this ItemBox.
       * @param displayObject the display object to use as content (e.g. an EaselJS Bitmap)
       */
      CanvasItemPrototype.prototype.setContent = function (displayObject) {

        this.content = displayObject;
        this.content.name = 'itemBoxContent';

        if (this.getRootContainer()) {
          this.getRootContainer().removeAllChildren();
          this.getRootContainer().addChild(this.content);

          if (this.getModel().isBorderAllowed()) {
            this.getRootContainer().addChild(this.itemBorder);
            this.drawItemBorder();
          }
        }
      };

      /**
       * Sets the visual representation for an empty CanvasItemBox using the specified color.
       */
      CanvasItemPrototype.prototype.setEmptyContent = function (hexColor) {
        // TODO: create a better default visualization
        var shape = new createjs.Shape();
        shape.graphics.beginFill(hexColor).drawRect(0, 0, this.getModel().getWidth(), this.getModel().getHeight());
        shape.setBounds(0, 0, this.getModel().getWidth(), this.getModel().getHeight());
        this.setContent(shape);
      };


      CanvasItemPrototype.prototype.fadeIn = function (durationInMillis) {
        this.getContent().alpha = 0.15;
        var self = this;
        var tween = createjs.Tween.get(this.getContent(), {override: true}).to({alpha: 1}, durationInMillis, createjs.Ease.sineInOut);
      };


      CanvasItemPrototype.prototype.addMouseDownListener = function (listener) {
        this.getToolFrame().addMouseDownListener(listener);
      };

      CanvasItemPrototype.prototype.addMouseUpListener = function (listener) {
        this.getToolFrame().addMouseUpListener(listener);
      };


      CanvasItemPrototype.prototype.addMouseDraggedListener = function (listener) {
        this.getToolFrame().addMouseDraggedListener(listener);
      };

      CanvasItemPrototype.prototype.setBounds = function (x, y, width, height) {
        this.getRootContainer.setBounds(x, y, width, height);
      };


      CanvasItemPrototype.prototype.cleanUp = function () {
        this.deleteDataModelWatch();
        this.getToolFrame().cleanUp();
        this.getRootContainer().removeAllEventListeners();
        this.rootContainer = null;
        this.scope = null;
        this.model = null;
        this.toolFrame = null;
        this.content = null;
      };


      // definition of the public factory functions
      return {

        getClass: function () {
          return CanvasItemPrototype;
        }
      };

    }
  ])
  ;

})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A factory for CanvasImageItem instances that inherits from CanvasItemPrototype.
 *
 * @author Frank Bruns (frank.bruns@cewe.de)
 * @author Silvia Peter (silvia.peter@cewe.de)
 * @author Holger Cremer
 * @author Sascha Friedrich
 */
(function () {
  'use strict';
  /* global createjs */

  angular.module('tatooine').factory('CanvasImageItemFactory', [
    '$log', '$q', '$timeout', '$resource', 'SafeApply', 'AppConstants', 'AppValues', 'FileHandleService', 'NotificationService', 'MessageService', 'CanvasItemPrototypeFactory', 'ViewPortFactory', 'ContentSilhouetteFactory',
    function ($log, $q, $timeout, $resource, SafeApply, AppConstants, AppValues, FileHandleService, NotificationService, MessageService, CanvasItemPrototypeFactory, ViewPortFactory, ContentSilhouetteFactory) {

      /**
       * A CanvasImageItem is the visual representation of an ImageItem data model and it wraps EaselJS functionality to
       * accomplish the task.
       * @param scope the Angular scope the ImageItem data model is bound to
       * @param imageItemModel the ImageItem data model to visually represent with this CanvasImageItem
       * @constructor
       */
      function CanvasImageItem(scope, imageItemModel) {

        // call super class constructor to instantiate its variables
        CanvasItemPrototypeFactory.getClass().call(this, scope, imageItemModel);

        var self = this;

        this.setEmptyContent('#DDDDDD');

        this.contentSilhouette = ContentSilhouetteFactory.createContentSilhouette(this.getModel().getCenterX(), this.getModel().getCenterY(),
          this.getModel().getWidth(), this.getModel().getHeight());

        this.quality = undefined;
        this.badQualityNote = undefined;

        var qualityImageRed = new Image();
        qualityImageRed.src = AppConstants.IMAGE_ITEM_QUALITY_RED_SRC;
        this.qualityIconRed = new createjs.Bitmap(qualityImageRed);
        this.qualityIconRed.name = 'qualityIconRed';
        this.getToolFrame().btnItemContent.cursor = '-webkit-grab';

        this.designElementId = imageItemModel.getAlphaMaskId() ? imageItemModel.getAlphaMaskId() : imageItemModel.getDecoFrameId();
        this.alphaMaskImage = undefined;
        this.decoFrameClipartImage = undefined;
        this.decoFrameMetadata = undefined;


        var unregisterContextPanelWatch = self.scope.$watch(function (watchContextPanel) {
          return imageItemModel.isContextView();
        }, function onChange(newValue, oldValue) {
          if (imageItemModel.isContextView() && self.getToolFrame()) {
            self.getToolFrame().setDashed(true);
            self.getToolFrame().setOpacity(AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY, AppConstants.TOOLFRAME_CONTEXT_MODE_FRAME_OPACITY);
            self.getToolFrame().setToolFrameLineColor(AppConstants.TOOLFRAME_CONTEXT_MODE_COLOR);
            self.getToolFrame().setToolFrameLineWidth(AppConstants.TOOLFRAME_CONTEXT_MODE_LINE_WIDTH);
            self.getToolFrame().setImageMargins(imageItemModel.getImageMargins());
          }
          else {
            if (self.getToolFrame()) {
              self.getToolFrame().setDashed(false);
              self.getToolFrame().setOpacity(AppConstants.TOOLFRAME_DEFAULT_OPACITY, AppConstants.TOOLFRAME_DEFAULT_OPACITY);
              self.getToolFrame().setToolFrameLineColor(AppConstants.TOOLFRAME_DEFAULT_COLOR);
              self.getToolFrame().setToolFrameLineWidth(AppConstants.TOOLFRAME_DEFAULT_LINE_WIDTH);
              self.getToolFrame().setImageMargins(AppConstants.TOOLFRAME_DEFAULT_IMAGE_MARGINS);
            }
          }

        });
      }


      CanvasImageItem.prototype = Object.create(CanvasItemPrototypeFactory.getClass().prototype);
      CanvasImageItem.prototype.constructor = CanvasImageItem;


      /**
       * This method is called when changes on the underlying data model have occured (observed by a watch in the super class)
       * @param {CanvasImageItem} model
       */
      CanvasImageItem.prototype.$$onModelChange = function (model) {

        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onModelChange.call(this, model);

        var self = this;
        self.setViewPort(model.getViewPort());
        if (model.getThumbKey()) { // only do something if a thumbkey is actually available
          self._loadThumbnail().then(function ok() {
            $log.debug('Thumbnail loaded for ImageItem with id ', model.getId());
            self.setViewPort(model.getViewPort());

            if (self.getRootContainer() && self.getRootContainer().getStage()) {
              self.$$updateQuality(true);

              if (model.isFadeIn()) {
                self.fadeIn(400);
                model.setFadeIn(false);
              }

              // this manual stage update for double pages is important when photos are placed by the wizard machanism, because
              // they are not automatically redrawn via requestAnimationFrame as defined in the CanvasDesignArea (RAF)
              $log.debug('Manual stage update on model change for image item', self.model.getId());
              self.getRootContainer().getStage().update();

            } else {
              $log.debug('No stage for ItemBox, no update needed. Itembox id: ', model.getId());
            }

          }).finally(function doFinally() {
            if (self.alphaMaskImage && !model.getAlphaMaskId() && !model.getDecoFrameId()) {
              self.removeAlphaMask();
              if (self.decoFrameClipartImage) {
                self.removeDecoFrameClipart();
              }
            } else {
              self.setAlphaMask(model.getAlphaMaskId());
              self.setDecoFrame(model.getDecoFrameId());
              self.$$updateAlphaMask();
            }
            if (!model.getDecoFrameId()) {
              self.getToolFrame().setImageMargins(model.getImageMargins());
            }
          });
        }

      };

      CanvasImageItem.prototype.$$onMouseUp = function (e) {

        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onMouseUp.call(this, e);

        var model = this.getModel();


        // INFO this code block is a temporary implementation to change the viewport with a right mouse click
        if (!this.getToolFrame().isPinchZooming()) {
          this.getContentSilhouette().setVisible(false);
        }

        var canvasViewPort = this.getContent().sourceRect;
        if (canvasViewPort) {
          var origViewPort = model.getViewPort();
          var newViewPort = ViewPortFactory.createViewPort(canvasViewPort.x, canvasViewPort.y, canvasViewPort.width, canvasViewPort.height, origViewPort.getFullWidth(), origViewPort.getFullHeight());
          model.setViewPort(newViewPort);
          model.setImageMargins(this.$$calculateImageMargins());
          this.$$checkSafetyArea();
        }

      };

      CanvasImageItem.prototype.$$checkSafetyArea = function () {
        var model = this.getModel();
        var oldPosition = {
          centerX: model.getCenterX(),
          centerY: model.getCenterY(),
          width: model.getWidth(),
          height: model.getHeight(),
          rotation: model.getRotation()
        };
        var oldBoundary = this.$$getRelativeBoundary(oldPosition);
        this.getToolFrame().dimensionOnMouseDown = {
          width: model.getWidth(),
          height: model.getHeight()
        };

        var newPosition = model.checkSafetyArea();

        this.getToolFrame().setWidth(newPosition.width);
        this.getToolFrame().setHeight(newPosition.height);
        this.getToolFrame().setCenterX(newPosition.centerX);
        this.getToolFrame().setCenterY(newPosition.centerY);

        var newBoundary = this.$$getRelativeBoundary(newPosition);

        if (newPosition.width !== oldPosition.width || newPosition.height !== oldPosition.height) {
          var currentViewPort = angular.copy(model.getViewPort());
          if (newBoundary.right !== oldBoundary.right) {
            currentViewPort = this.$$calculateViewPort('cropRight', currentViewPort, newBoundary.right - oldBoundary.right);
          }
          if (newBoundary.left !== oldBoundary.left) {
            currentViewPort = this.$$calculateViewPort('cropLeft', currentViewPort, newBoundary.left - oldBoundary.left);
          }
          if (newBoundary.top !== oldBoundary.top) {
            currentViewPort = this.$$calculateViewPort('cropTop', currentViewPort, oldBoundary.top - newBoundary.top);
          }
          if (newBoundary.bottom !== oldBoundary.bottom) {
            currentViewPort = this.$$calculateViewPort('cropBottom', currentViewPort, oldBoundary.bottom - newBoundary.bottom);
          }
          model.setViewPort(currentViewPort);
          this.setViewPort(currentViewPort);
        }
      };

      CanvasImageItem.prototype.$$getRelativeBoundary = function (position) {
        if (position.rotation === 0) {
          return {
            left: position.centerX - position.width / 2,
            right: position.centerX + position.width / 2,
            top: position.centerY - position.height / 2,
            bottom: position.centerY + position.height / 2
          };
        }
        if (position.rotation === 90) {
          return {
            left: position.centerY - position.width / 2,
            right: position.centerY + position.width / 2,
            top: position.centerX + position.height / 2,
            bottom: position.centerX - position.height / 2
          };
        }
        if (position.rotation === 180) {
          return {
            left: position.centerX + position.width / 2,
            right: position.centerX - position.width / 2,
            top: position.centerY - position.height / 2,
            bottom: position.centerY + position.height / 2
          };
        }
        if (position.rotation === 270) {
          return {
            left: position.centerY + position.width / 2,
            right: position.centerY - position.width / 2,
            top: position.centerX - position.height / 2,
            bottom: position.centerX + position.height / 2
          };
        }
      };


      CanvasImageItem.prototype.$$onMouseDown = function (e) {

        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onMouseDown.call(this, e);

        // save image scale factor before modifying the item box
        this.imageScaleOnMouseDown = {
          x: this.getContent().scaleX,
          y: this.getContent().scaleY
        };

        if (this.getToolFrame().isCropping()) {
          this.getContentSilhouette().setVisible(true);
        }
      };


      CanvasImageItem.prototype.$$onMouseDragged = function (e) {
        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onMouseDragged.call(this, e);
        if (e.nativeEvent.button === 0 || e.nativeEvent.buttons === 0 || e.nativeEvent.type === 'touchmove') {
          var viewPort = this.getModel().getViewPort();
          if (e.target.name === 'btnItemContent') {
            viewPort = this.$$calculateViewPort('viewPort', viewPort, e.dragDistance);

          } else {
            this.getModel().setLayoutModified(true);
            // only consider actions as dragging if the drag distance is at least a certain amount of pixels (this is meant
            // to make it easier to toggle the viewport mode, even if the mouse was slightly moved during the click)
            if (this.getToolFrame().isCropping()) {
              viewPort = this.$$calculateViewPort(e.target.name, viewPort, e.dragDistance);
            }
          }
          if (e.target.name !== 'rotateTopRight' && e.target.name !== 'rotateBottomRight' && e.target.name !== 'rotateTopLeft' && e.target.name !== 'rotateBottomLeft' && e.target.name !== 'move') {
            this.setViewPort(viewPort);
          } else {
            this.$$updateQuality(false);
          }
        }
      };

      CanvasImageItem.prototype.$$updateQuality = function (reCalculate) {
        if (reCalculate) {
          this.quality = this.getModel().calculateQuality(this.getWidth(), this.getHeight(), this.getViewPort());
        }
        if (this.quality === 'red') {
          if (!this.getModel().isBadQualiy()) {
            this.getModel().setBadQuality(true);
            if (this.getModel().isSelected()) {
              this.badQualityNote = NotificationService.addCustomIconNotification('toast-badQuality', MessageService.getMessage('notification.badQualityTitle'), MessageService.getMessage('notification.badQualityDescription'), 'warning', 10000);
            }
          }
          this.qualityIconRed.x = this.getWidth() - this.qualityIconRed.image.width;
          this.qualityIconRed.y = this.getHeight() - this.qualityIconRed.image.height;
          var newGlobalPosition = this.getRootContainer().localToGlobal(this.qualityIconRed.x, this.qualityIconRed.y);
          if (newGlobalPosition.x < 0 ||
            newGlobalPosition.x + this.qualityIconRed.image.width > this.getRootContainer().getStage().canvas.width ||
            newGlobalPosition.y < 0 ||
            newGlobalPosition.y + this.qualityIconRed.image.height > this.getRootContainer().getStage().canvas.height) {
            this.qualityIconRed.x = (this.getWidth() - this.qualityIconRed.image.width) / 2;
            this.qualityIconRed.y = (this.getHeight() - this.qualityIconRed.image.height) / 2;
          }
          this.getRootContainer().addChild(this.qualityIconRed);
        } else {
          this.getRootContainer().removeChild(this.qualityIconRed);
          this.getModel().setBadQuality(false);
          if (this.badQualityNote) {
            NotificationService.removeNotification(this.badQualityNote);
          }
        }
      };


      CanvasImageItem.prototype.$$calculateViewPort = function (operation, originalViewPort, specificDeltaValue) {

        if (!this.getContent() || !this.getContent().image) {
          return originalViewPort;
        }
        var imageWidth = this.getContent().image.width;
        var imageHeight = this.getContent().image.height;
        var toolFrame = this.getToolFrame();
        var imageScale = this.imageScaleOnMouseDown ? this.imageScaleOnMouseDown : {
          x: 1,
          y: 1
        };
        var deltaWidth = !toolFrame.dimensionOnMouseDown ? 0 : toolFrame.getWidth() - toolFrame.dimensionOnMouseDown.width;
        var deltaHeight = !toolFrame.dimensionOnMouseDown ? 0 : toolFrame.getHeight() - toolFrame.dimensionOnMouseDown.height;
        var scaledDeltaWidth = deltaWidth / imageScale.x;
        var scaledDeltaHeight = deltaHeight / imageScale.y;
        var scaledDelta = {
          width: scaledDeltaWidth,
          height: scaledDeltaHeight
        };

        var newViewPort = {};

        var calculatedViewPortWidth;
        var calculatedViewPortHeight;
        var deltaViewPortHeight;

        if (operation === 'cropLeft') {

          newViewPort.x = Math.min(imageWidth, Math.max(0, originalViewPort.getX() - scaledDelta.width));
          newViewPort.width = Math.min(imageWidth, originalViewPort.getWidth() + scaledDelta.width);
          if (deltaWidth <= 0) {
            newViewPort.height = originalViewPort.getHeight();
            newViewPort.y = originalViewPort.getY();
          } else {
            newViewPort.height = newViewPort.width * toolFrame.getHeight() / toolFrame.getWidth();
            newViewPort.y = Math.min(imageHeight, Math.max(0, originalViewPort.getY() - (newViewPort.height - originalViewPort.getHeight()) / 2));
          }

        } else if (operation === 'cropRight') {

          calculatedViewPortWidth = originalViewPort.getWidth() + scaledDelta.width;
          var deltaViewPortWidth = calculatedViewPortWidth + originalViewPort.getX() - imageWidth;
          newViewPort.width = Math.min(imageWidth, originalViewPort.getWidth() + scaledDelta.width);
          if (deltaViewPortWidth <= 0) {
            newViewPort.x = originalViewPort.getX();
            newViewPort.height = originalViewPort.getHeight();
            newViewPort.y = originalViewPort.getY();
          } else {
            newViewPort.x = Math.max(0, originalViewPort.getX() - deltaViewPortWidth);
            newViewPort.height = toolFrame.getHeight() / toolFrame.getWidth() * newViewPort.width;
            newViewPort.y = Math.min(imageHeight, Math.max(0, originalViewPort.getY() - (newViewPort.height - originalViewPort.getHeight()) / 2));
          }

        } else if (operation === 'cropTop') {

          newViewPort.y = Math.max(0, originalViewPort.getY() - scaledDelta.height);
          calculatedViewPortHeight = originalViewPort.getHeight() + scaledDelta.height;
          deltaViewPortHeight = calculatedViewPortHeight + originalViewPort.getY() - imageHeight;
          newViewPort.height = Math.min(imageHeight, calculatedViewPortHeight);
          if (deltaViewPortHeight <= 0) {
            newViewPort.width = originalViewPort.getWidth();
            newViewPort.x = originalViewPort.getX();
          } else {
            newViewPort.width = toolFrame.getWidth() * newViewPort.height / toolFrame.getHeight();
            newViewPort.x = Math.min(imageWidth, Math.max(0, originalViewPort.getX() - (newViewPort.width - originalViewPort.getWidth()) / 2));
          }

        } else if (operation === 'cropBottom') {

          calculatedViewPortHeight = originalViewPort.getHeight() + scaledDelta.height;
          deltaViewPortHeight = calculatedViewPortHeight + originalViewPort.getY() - imageHeight;
          newViewPort.height = Math.min(imageHeight, originalViewPort.getHeight() + scaledDelta.height);
          if (deltaViewPortHeight <= 0) {
            newViewPort.y = originalViewPort.getY();
            newViewPort.width = originalViewPort.getWidth();
            newViewPort.x = originalViewPort.getX();
          } else {
            newViewPort.y = Math.max(0, originalViewPort.getY() - deltaViewPortHeight);
            newViewPort.width = toolFrame.getWidth() / toolFrame.getHeight() * newViewPort.height;
            newViewPort.x = Math.min(imageWidth, Math.max(0, originalViewPort.getX() - (newViewPort.width - originalViewPort.getWidth()) / 2));
          }

        } else if (operation === 'viewPort') {
          // in case of 'move' the specificDeltaValue is the drag distance to apply
          newViewPort.width = originalViewPort.getWidth();
          newViewPort.height = originalViewPort.getHeight();
          newViewPort.x = Math.min(imageWidth - newViewPort.width, Math.max(0, originalViewPort.getX() - specificDeltaValue.x / imageScale.x));
          newViewPort.y = Math.min(imageHeight - newViewPort.height, Math.max(0, originalViewPort.getY() - specificDeltaValue.y / imageScale.y));

        } else if (operation === 'mouseZoom' || operation === 'pinchZoom') {

          var zoomFactor = null;

          if (operation === 'mouseZoom') {
            // in case of 'mouseZoom' the specificDeltaValue is a simple integer (-1 or +1) that indicates whether we should zoom in or out
            zoomFactor = specificDeltaValue > 0 ? 1.035 : 0.965;
            calculatedViewPortWidth = originalViewPort.getWidth() * zoomFactor;
            calculatedViewPortHeight = originalViewPort.getHeight() * zoomFactor;
          } else { // pinch zoom
            // in case of 'pinchZoom' the specificDeltaValue is the zoom factor to apply
            zoomFactor = specificDeltaValue;
            calculatedViewPortWidth = originalViewPort.getWidth() / zoomFactor;
            calculatedViewPortHeight = originalViewPort.getHeight() / zoomFactor;
          }


          newViewPort.width = calculatedViewPortWidth;
          newViewPort.height = calculatedViewPortHeight;

          if (newViewPort.width > imageWidth) {
            newViewPort.width = imageWidth;
            newViewPort.height = toolFrame.getHeight() / toolFrame.getWidth() * newViewPort.width;
          }

          if (newViewPort.height > imageHeight) {
            newViewPort.height = imageHeight;
            newViewPort.width = toolFrame.getWidth() / toolFrame.getHeight() * newViewPort.height;
          }

          deltaWidth = newViewPort.width - originalViewPort.getWidth();
          deltaHeight = newViewPort.height - originalViewPort.getHeight();
          newViewPort.x = Math.min(imageWidth - newViewPort.width, Math.max(0, originalViewPort.getX() - deltaWidth / 2));
          newViewPort.y = Math.min(imageHeight - newViewPort.height, Math.max(0, originalViewPort.getY() - deltaHeight / 2));

        } else {
          newViewPort = originalViewPort;
        }

        // make sure the new viewport is within valid dimension bounds
        newViewPort.x = Math.min(imageWidth, Math.max(0, newViewPort.x));
        newViewPort.y = Math.min(imageHeight, Math.max(0, newViewPort.y));
        newViewPort.width = Math.min(imageWidth, Math.max(0, newViewPort.width));
        newViewPort.height = Math.min(imageHeight, Math.max(0, newViewPort.height));

        if (this.alphaMaskImage) {
          this.$$updateAlphaMask();
        }

        this.getContentSilhouette().setVisible(true);
        return ViewPortFactory.createViewPort(newViewPort.x, newViewPort.y, newViewPort.width, newViewPort.height, imageWidth, imageHeight);
      };


      /**
       *
       * @returns {Promise} a promise that is resolved after the thumbnail is fully loaded. It has this item box as parameter or null if it has no parent stage anymore.
       * @private
       */
      CanvasImageItem.prototype._loadThumbnail = function () {


        var thumbKey = this.getModel().getThumbKey();

        if (!thumbKey || this.getModel().isThumbKeyLoaded()) {
          return $q.reject(this);
        }
        $log.debug('Loading thumb key for item box', this.getModel());

        var self = this;

        var maxSize = thumbKey.width >= thumbKey.height ? thumbKey.width : thumbKey.height;
        var fitTo = thumbKey.width >= thumbKey.height ? 'width' : 'height';
        // if an image source was specified, load it now
        return FileHandleService.getThumbnail(this.getModel().getFileHandleId(), maxSize, fitTo, thumbKey.multiStepDownScaling).then(
          function ok(imageObj) {

            if (!imageObj) {
              $log.warn('Could not find thumbnail!', self.getModel().getFileHandleId());
              return $q.reject(self);
            }
            var stage = self.getRootContainer() && self.getRootContainer().getStage();
            if (!stage) {
              // If the root container has no stage anymore, this item box was removed from the stage. It means, we can skip here.
              return null;
            }

            self.loadImageSource(imageObj.data);
            self.getModel().setThumbKeyLoaded(true);

            if (self.getModel().isResetViewPortAfterThumbLoaded()) {
              self.getModel().resetViewPort();
            }

            return self;
          });
      };


      CanvasImageItem.prototype.setCenterX = function (x) {
        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.setCenterX.call(this, x);
        this.getContentSilhouette().setCenterX(x);
      };

      CanvasImageItem.prototype.setCenterY = function (y) {
        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.setCenterY.call(this, y);
        this.getContentSilhouette().setCenterY(y);
      };


      CanvasImageItem.prototype.setWidth = function (width) {
        // call super method
        var needsRecalculateQuality = this.getWidth() !== width;
        CanvasItemPrototypeFactory.getClass().prototype.setWidth.call(this, width);
        this.getContentSilhouette().setWidth(width);
        if (needsRecalculateQuality) {
          this.$$updateQuality(true);
        }
      };


      CanvasImageItem.prototype.setHeight = function (height) {
        // call super method
        var needsRecalculateQuality = this.getHeight() !== height;
        CanvasItemPrototypeFactory.getClass().prototype.setHeight.call(this, height);
        this.getContentSilhouette().setHeight(height);
        if (needsRecalculateQuality) {
          this.$$updateQuality(true);
        }
      };


      CanvasImageItem.prototype.setRotation = function (rotation) {
        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.setRotation.call(this, rotation);
        this.getContentSilhouette().setRotation(rotation);
      };


      /**
       * Sets the selection status of the CanvasImageItem.
       * @param selected
       */
      CanvasImageItem.prototype.setSelected = function (selected) {

        if (selected) {
          var stage = this.getRootContainer().getStage();
          var lastChildIndex = stage.getNumChildren() - 1;
          stage.setChildIndex(this.getContentSilhouette().rootContainer, lastChildIndex);
        }

        // call super class method afterwards
        CanvasItemPrototypeFactory.getClass().prototype.setSelected.call(this, selected);
      };


      /**
       * Resets the ViewPort to fit into the item's boundings. The viewport gets centered in horizontal and vertical direction by default.
       */
      CanvasImageItem.prototype.resetViewPortToFitIntelligently = function () {

        var viewport = this.getViewPort();
        var aspectRatioItemBox = this.getWidth() / this.getHeight();
        var aspectRatioContent = viewport.getFullWidth() / viewport.getFullHeight();

        if (aspectRatioContent >= aspectRatioItemBox) {
          viewport.setWidth(viewport.getFullWidth() * (aspectRatioItemBox / aspectRatioContent));
          viewport.setHeight(viewport.getFullHeight());
        } else {
          viewport.setWidth(viewport.getFullWidth());
          viewport.setHeight(viewport.getFullHeight() * (aspectRatioContent / aspectRatioItemBox));
        }

        viewport.setX((viewport.getFullWidth() - viewport.getWidth()) / 2);

        if (aspectRatioContent > 1) {
          // landscape format content focuses its viewport more on the bottom
          viewport.setY((viewport.getFullHeight() - viewport.getHeight()) * 0.725);
        } else { // portrait format content
          // portrait format content focuses its viewport more on the top
          viewport.setY((viewport.getFullHeight() - viewport.getHeight()) * 0.275);
        }

        this.setViewPort(viewport);
      };


      CanvasImageItem.prototype.setViewPort = function (viewport) {
        if (!this.getContent() || !this.getContent().sourceRect) {
          return;
        }

        var scaleX = this.getToolFrame().getWidth() / viewport.getWidth();
        var scaleY = this.getToolFrame().getHeight() / viewport.getHeight();

        var needsRecalculateQuality = this.getContent().scaleX !== scaleX || this.getContent().scaleY !== scaleY;

        var rect = this.getContent().sourceRect;

        if (rect.x !== viewport.getX() || rect.y !== viewport.getY() || scaleX !== this.getContent().scaleX || scaleY !== this.getContent().scaleY) {
          this.getContent().scaleX = scaleX;
          this.getContent().scaleY = scaleY;
          this.getContentSilhouette().scaleContent(scaleX, scaleY);
          this.getContentSilhouette().setContentPosition(-scaleX * viewport.getX(), -scaleY * viewport.getY());
        }

        if (rect.x !== viewport.getX() || rect.y !== viewport.getY() || rect.width !== viewport.getWidth() || rect.height !== viewport.getHeight()) {
          this.getContent().sourceRect = new createjs.Rectangle(viewport.getX(), viewport.getY(), viewport.getWidth(), viewport.getHeight());
        }

        if (this.decoFrameClipartImage) {
          var margins = this.$$calculateImageMargins();
          this.decoFrameClipartImage.x = -margins.left;
          this.decoFrameClipartImage.y = -margins.top;
          this.decoFrameClipartImage.scaleX = (this.getToolFrame().getWidth() + margins.left + margins.right) / this.decoFrameClipartImage.image.width;
          this.decoFrameClipartImage.scaleY = (this.getToolFrame().getHeight() + margins.top + margins.bottom) / this.decoFrameClipartImage.image.height;
        }

        if (needsRecalculateQuality) {
          this.$$updateQuality(true);
        }
      };

      CanvasImageItem.prototype.getViewPort = function () {
        var rect = this.getContent().sourceRect;
        if (!rect) {
          return null;
        }
        return ViewPortFactory.createViewPort(rect.x, rect.y, rect.width, rect.height, this.getContent().image.width, this.getContent().image.height);
      };

      CanvasImageItem.prototype.removeAlphaMask = function () {
        // remove existing mask
        $log.debug('Removing mask from image item', this);
        this.alphaMaskImage = undefined;
        this.designElementId = undefined;
        this.getContent().uncache();
      };

      CanvasImageItem.prototype.removeDecoFrameClipart = function () {
        $log.debug('Removing deco frame clipart from image item', this);
        if (this.decoFrameClipartImage) {
          this.getRootContainer().removeChild(this.decoFrameClipartImage);
          this.decoFrameClipartImage = undefined;
        }
      };

      CanvasImageItem.prototype.setAlphaMask = function (designElementId) {

        if (!designElementId || !this.getContent() || !this.getContent().sourceRect ||
          (this.alphaMaskImage && this.designElementId === designElementId)) {
          return;
        }

        this.removeDecoFrameClipart();

        var self = this;
        this.$$loadAlphaMaskImageFromServer().then(function maskLoaded(alphaMaskImage) {
          var model = self.getModel();
          if (model.isKeepMaskAspectRatio()) {
            var newWidth = model.getWidth();
            var newHeight = model.getHeight();

            var oldAspectRatio = model.getHeight() / model.getWidth();
            var newAspectRatio = alphaMaskImage.height / alphaMaskImage.width;

            if (newAspectRatio > oldAspectRatio) {
              newWidth = model.getHeight() / newAspectRatio;
            } else {
              newHeight = model.getWidth() * newAspectRatio;
            }

            //keep the area of the item box
            var oldArea = model.getWidth() * model.getHeight();
            var newArea = newWidth * newHeight;
            var scale = oldArea / newArea;
            newWidth = newWidth * Math.sqrt(scale);
            newHeight = newHeight * Math.sqrt(scale);
            model.setWidth(newWidth);
            model.setHeight(newHeight);
            self.getToolFrame().setWidth(newWidth);
            self.getToolFrame().setHeight(newHeight);

            if (newAspectRatio !== oldAspectRatio) {
              self.getModel().resetViewPort();
            }
            model.setKeepMaskAspectRatio(false);
          }
          self.alphaMaskImage = alphaMaskImage;
          self.$$updateAlphaMask();
          self.designElementId = designElementId;
        });
      };

      CanvasImageItem.prototype.$$updateAlphaMask = function () {
        if (!this.alphaMaskImage) {
          return;
        }
        var maskCanvas = document.createElement('canvas');
        maskCanvas.width = this.alphaMaskImage.width;
        maskCanvas.height = this.alphaMaskImage.height;
        var context = maskCanvas.getContext('2d');
        context.drawImage(this.alphaMaskImage, 0, 0);

        this.getContent().cache(0, 0, this.getContent().image.width, this.getContent().image.height);

        var cacheContext = this.getContent().cacheCanvas.getContext('2d');
        cacheContext.save();
        cacheContext.globalCompositeOperation = 'destination-in';
        cacheContext.drawImage(maskCanvas, 0, 0, this.getToolFrame().getWidth() / this.getContent().scaleX, this.getToolFrame().getHeight() / this.getContent().scaleY);
        cacheContext.restore();
      };

      CanvasImageItem.prototype.$$calculateImageMargins = function () {
        if (!this.decoFrameClipartImage || !this.decoFrameMetadata) {
          return {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
          };
        }
        var clipartDimensions = {
          width: this.getToolFrame().getWidth() / this.decoFrameMetadata.fotoArea.width,
          height: this.getToolFrame().getHeight() / this.decoFrameMetadata.fotoArea.height
        };
        var imageMargins = {};
        imageMargins.left = clipartDimensions.width * this.decoFrameMetadata.fotoArea.x;
        imageMargins.top = clipartDimensions.height * this.decoFrameMetadata.fotoArea.y;
        imageMargins.right = clipartDimensions.width - this.getToolFrame().getWidth() - imageMargins.left;
        imageMargins.bottom = clipartDimensions.height - this.getToolFrame().getHeight() - imageMargins.top;

        return imageMargins;
      };

      CanvasImageItem.prototype.setDecoFrame = function (designElementId) {

        if (!designElementId || !this.getContent() || !this.getContent().sourceRect ||
          (this.alphaMaskImage && this.designElementId === designElementId)) {
          return;
        }

        var self = this;
        this.$$loadDecoFrameMetadataFromServer().then(function decoFrameMetadataLoaded(metadata) {
          $log.debug('loaded deco frame metadata', metadata);
          self.decoFrameMetadata = metadata;
        }).then(this.$$loadAlphaMaskImageFromServer.bind(this)).then(function maskLoaded(alphaMaskImage) {
          self.alphaMaskImage = alphaMaskImage;
          var margins = self.getModel().getImageMargins();
          var oldItemBoxBounds = {
            width: self.getToolFrame().getWidth() + margins.left + margins.right,
            height: self.getToolFrame().getHeight() + margins.top + margins.bottom
          };
          var oldItemBoxBoundsRatio = oldItemBoxBounds.height / oldItemBoxBounds.width;
          var oldItemBoxAspectRatio = self.getToolFrame().getHeight() / self.getToolFrame().getWidth();

          var newItemBoxBounds = {
            width: oldItemBoxBounds.width,
            height: oldItemBoxBounds.height
          };

          var newItemBoxDimension = {
            width: self.getToolFrame().getWidth(),
            height: self.getToolFrame().getHeight()
          };

          var fotoArea = self.decoFrameMetadata.fotoArea;
          var decoFrameAspectRatio = self.decoFrameMetadata.aspectRatio;
          if (self.designElementId !== designElementId) {
            if (self.decoFrameMetadata.keepAspectRatio) {
              newItemBoxBounds = {
                width: decoFrameAspectRatio > oldItemBoxBoundsRatio ? oldItemBoxBounds.height / decoFrameAspectRatio : oldItemBoxBounds.width,
                height: decoFrameAspectRatio > oldItemBoxBoundsRatio ? oldItemBoxBounds.height : oldItemBoxBounds.width * decoFrameAspectRatio
              };
              //keep the area of the item box bounds
              var oldArea = oldItemBoxBounds.width * oldItemBoxBounds.height;
              var newArea = newItemBoxBounds.width * newItemBoxBounds.height;
              var scale = oldArea / newArea;
              newItemBoxBounds.width = newItemBoxBounds.width * Math.sqrt(scale);
              newItemBoxBounds.height = newItemBoxBounds.height * Math.sqrt(scale);

              newItemBoxDimension = {
                width: newItemBoxBounds.width * fotoArea.width,
                height: newItemBoxBounds.height * fotoArea.height
              };

              var newItemBoxAspectRatio = newItemBoxDimension.height / newItemBoxDimension.width;
              $log.debug('calculated item box dimension for deco frame', newItemBoxDimension);

              self.getModel().setWidth(newItemBoxDimension.width);
              self.getModel().setHeight(newItemBoxDimension.height);
              if (oldItemBoxAspectRatio !== newItemBoxAspectRatio) {
                self.getModel().resetViewPort();
              }
            }
          }

          var newClipartDimension = {
            width: newItemBoxDimension.width / fotoArea.width,
            height: newItemBoxDimension.height / fotoArea.height
          };
          $log.debug('calculated clipart dimension for deco frame', newClipartDimension);

          var newImageMargins = {
            top: newClipartDimension.height * fotoArea.y,
            right: newClipartDimension.width - newItemBoxDimension.width - newClipartDimension.width * fotoArea.x,
            bottom: newClipartDimension.height - newItemBoxDimension.height - newClipartDimension.height * fotoArea.y,
            left: newClipartDimension.width * fotoArea.x
          };

          self.getModel().setImageMargins(newImageMargins);

          $timeout(function delayToNextApply() {
            self.$$updateAlphaMask();
          });
        }).then(this.$$loadDecoFrameClipartImageFromServer.bind(this)).then(function clipartLoaded(clipartImage) {
          self.removeDecoFrameClipart();

          var bitmap = new createjs.Bitmap(clipartImage);
          self.decoFrameClipartImage = bitmap;
          var model = self.getModel();
          var margins = model.getImageMargins();
          bitmap.x = -margins.left;
          bitmap.y = -margins.top;
          bitmap.scaleX = (model.getWidth() + margins.left + margins.right) / bitmap.image.width;
          bitmap.scaleY = (model.getHeight() + margins.top + margins.bottom) / bitmap.image.height;
          self.getRootContainer().addChild(bitmap);
          self.designElementId = designElementId;

          var toolFrameMargin = self.getModel().isContextView() ? model.getImageMargins() : AppConstants.TOOLFRAME_DEFAULT_IMAGE_MARGINS;
          self.getToolFrame().setImageMargins(toolFrameMargin);

        });
      };


      /**
       *
       * @returns {Promise} a promise that is resolved after the mask image is fully loaded.
       * @private
       */
      CanvasImageItem.prototype.$$loadAlphaMaskImageFromServer = function () {
        var deferred = $q.defer();

        var model = this.getModel();

        $log.debug('triggered loading of mask image from server');

        var maskImageUrl = 'designElements/designElementImage.rest?imageSize=medium&elementId=' +
          (model.getDecoFrameId() ? model.getDecoFrameId() + '&decoFrameComponentType=mask' : model.getAlphaMaskId());

        var maskImage = new Image();
        maskImage.src = maskImageUrl;

        var self = this;
        var onMaskImgLoaded = function onMaskImgLoaded() {
          $log.debug('Received mask image for item box', self.getModel());
          maskImage.removeEventListener('load', onMaskImgLoaded);
          deferred.resolve(maskImage);
        };
        maskImage.addEventListener('load', onMaskImgLoaded);
        return deferred.promise;
      };

      /**
       *
       * @returns {Promise} a promise that is resolved after the deco frame clipart image is fully loaded.
       * @private
       */
      CanvasImageItem.prototype.$$loadDecoFrameClipartImageFromServer = function () {
        var deferred = $q.defer();

        var model = this.getModel();

        $log.debug('triggered loading of mask image from server');

        var clipartImageUrl = 'designElements/designElementImage.rest?imageSize=medium&decoFrameComponentType=clipart&elementId=' + model.getDecoFrameId();

        var clipartImage = new Image();
        clipartImage.src = clipartImageUrl;

        var self = this;
        var onClipartImgLoaded = function onClipartImgLoaded() {
          $log.debug('Received deco frame clipart image for item box', self.getModel());
          clipartImage.removeEventListener('load', onClipartImgLoaded);
          deferred.resolve(clipartImage);
        };
        clipartImage.addEventListener('load', onClipartImgLoaded);
        return deferred.promise;
      };

      /**
       *
       * @returns {Promise} a promise that is resolved after the mask image is fully loaded.
       * @private
       */
      CanvasImageItem.prototype.$$loadDecoFrameMetadataFromServer = function () {
        var model = this.getModel();

        $log.debug('triggered loading of deco frame meta data from server');

        var decoFrameMetatdataUrl = 'designElements/decoFrameMetadata.rest';
        var loadMetadataParams = {
          elementId: model.getDecoFrameId()

        };
        var DecoFrameMetadataResource = $resource(decoFrameMetatdataUrl, loadMetadataParams);

        return DecoFrameMetadataResource.get(function metadataLoaded(metadata) {
          return metadata;
        }, function loadingMetadataFailed() {
          $log.error('Metadata of deco frame with ID ' + model.getDecoFrameId() + ' could not be loaded');
        }).$promise;
      };

      /**
       *
       * @returns {ContentSilhouette} the semi transparent silhouette of the original content
       */
      CanvasImageItem.prototype.getContentSilhouette = function () {
        return this.contentSilhouette;
      };


      CanvasImageItem.prototype.setContent = function (displayObject) {

        // explicitly call super method and after that do the code from this class
        CanvasItemPrototypeFactory.getClass().prototype.setContent.call(this, displayObject);

        if (this.getContent().image) { // is image content?
          this.getContent().sourceRect = new createjs.Rectangle(0, 0, displayObject.image.width, displayObject.image.height);
          this.getContentSilhouette().setContent(this.getContent().clone());
          this.$$updateQuality(true);
        }

        if (this.decoFrameClipartImage) {
          this.getRootContainer().addChild(this.decoFrameClipartImage);
        }

      };

      /**
       * Loads the given image source and set it as the content of this CanvasImageItem.
       * @param imgSrc the image source to load
       */
      CanvasImageItem.prototype.loadImageSource = function (imgSrc) {
        var self = this;
        var photo = new createjs.Bitmap(imgSrc);
        // awkward! there is no setWidth/Height on a bitmap, the size can only be manipulated by scaleX/Y
        photo.scaleX = this.getModel().getWidth() / photo.image.width;
        photo.scaleY = this.getModel().getHeight() / photo.image.height;

        this.setContent(photo);

        var viewPort = self.getModel().getViewPort();

        var thumbWidth = photo.image.width;
        var thumbHeight = photo.image.height;

        // if the view port data is uninitialized use the currents image dimensions as base data, else assume it
        // was a viewport based on server image dimensions and convert it into client thumbnail image dimensions
        if (viewPort.getWidth() <= 0 || viewPort.getHeight() <= 0) {

          viewPort.setX(0);
          viewPort.setY(0);
          viewPort.setWidth(thumbWidth);
          viewPort.setHeight(thumbHeight);

        } else {
          var serverImgWidth = viewPort.getFullWidth();
          var serverImgHeight = viewPort.getFullHeight();

          var scaleFactorX = thumbWidth / serverImgWidth;
          var scaleFactorY = thumbHeight / serverImgHeight;

          viewPort.setX(viewPort.getX() * scaleFactorX);
          viewPort.setY(viewPort.getY() * scaleFactorY);
          viewPort.setWidth(viewPort.getWidth() * scaleFactorX);
          viewPort.setHeight(viewPort.getHeight() * scaleFactorY);
        }

        viewPort.setFullWidth(thumbWidth);
        viewPort.setFullHeight(thumbHeight);

        self.getModel().setViewPort(viewPort);
      };

      CanvasImageItem.prototype.showSwapTargetMarker = function (trueOrFalse) {
        if (trueOrFalse) {
          this.getToolFrame().setOpacity(0, AppConstants.TOOLFRAME_DEFAULT_OPACITY);
          this.getToolFrame().setToolFrameLineColor(AppConstants.TOOLFRAME_SWAP_MARKER_COLOR);
          this.getToolFrame().setToolFrameLineWidth(AppConstants.TOOLFRAME_CONTEXT_MODE_LINE_WIDTH);
          this.getToolFrame().setVisible(true);
        } else {
          this.getToolFrame().setOpacity(AppConstants.TOOLFRAME_DEFAULT_OPACITY, AppConstants.TOOLFRAME_DEFAULT_OPACITY);
          this.getToolFrame().setToolFrameLineColor(AppConstants.TOOLFRAME_DEFAULT_COLOR);
          this.getToolFrame().setToolFrameLineWidth(AppConstants.TOOLFRAME_DEFAULT_LINE_WIDTH);
          this.getToolFrame().setVisible(false);
        }
      };

      CanvasImageItem.prototype.cleanUp = function () {

        // explicitly call super method and after that do the code from this class
        CanvasItemPrototypeFactory.getClass().prototype.cleanUp.call(this);

        this.getContentSilhouette().cleanUp();

      };


      // definition of the public factory functions
      return {

        getClass: function () {
          return CanvasImageItem;
        },

        /**
         * Creates an CanvasImageItem that acts as the visual representation of the specified ImageItem data model.
         * @param scope the scope the ImageItem data model is bound to
         * @param imageItemModel the ImageItem data model to visually represent with the CanvasImageItem.
         * @returns {CanvasImageItem} a CanvasImageItem
         */
        createCanvasImageItem: function (scope, imageItemModel) {
          return new CanvasImageItem(scope, imageItemModel);
        }
      };

    }
  ]);

})();
/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A factory for CanvasClipartItem instances that inherits from CanvasItemPrototype.
 *
 * @author Christoph Suhren
 * @author Sascha Friedrich
 */
(function () {
  'use strict';
  /* global createjs */

  angular.module('tatooine').factory('CanvasClipartItemFactory', [
    '$log', '$q', '$timeout', 'SafeApply', 'AppConstants', 'FileHandleService', 'NotificationService', 'MessageService', 'CanvasItemPrototypeFactory' ,
    function ($log, $q, $timeout, SafeApply, AppConstants, FileHandleService, NotificationService, MessageService, CanvasItemPrototypeFactory) {

      /**
       * A CanvasClipartItem is the visual representation of an ClipartItem data model and it wraps EaselJS functionality to
       * accomplish the task.
       * @param scope the Angular scope the ClipartItem data model is bound to
       * @param clipartItemModel the ClipartItem data model to visually represent with this CanvasClipartItem
       * @constructor
       */
      function CanvasClipartItem(scope, clipartItemModel) {

        // call super class constructor to instantiate its variables
        CanvasItemPrototypeFactory.getClass().call(this, scope, clipartItemModel);


        var self = this;

        this.setEmptyContent('#DDDDDD');
        this.$$loadClipartImageFromServer();
      }


      CanvasClipartItem.prototype = Object.create(CanvasItemPrototypeFactory.getClass().prototype);
      CanvasClipartItem.prototype.constructor = CanvasClipartItem;

      CanvasClipartItem.prototype.$$onMouseUp = function (e) {
        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onMouseUp.call(this, e);

        this.$$checkSafetyArea();
      };

      CanvasClipartItem.prototype.$$checkSafetyArea = function () {
        var model = this.getModel();
        this.getToolFrame().dimensionOnMouseDown = {width: model.getWidth(), height: model.getHeight()};

        var newPosition = model.checkSafetyArea();

        this.getToolFrame().setWidth(newPosition.width);
        this.getToolFrame().setHeight(newPosition.height);
        this.getToolFrame().setCenterX(newPosition.centerX);
        this.getToolFrame().setCenterY(newPosition.centerY);

      };

      CanvasClipartItem.prototype.$$onMouseDragged = function (e) {
        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onMouseDragged.call(this, e);

        if (e.nativeEvent.button === 0 || e.nativeEvent.buttons === 0 || e.nativeEvent.type === 'touchmove') {

          if (this.getToolFrame().isCropping() || this.getToolFrame().isScaling()) {
            var content = this.getContent();
            content.scaleX = this.getToolFrame().getWidth() / content.image.width;
            content.scaleY = this.getToolFrame().getHeight() / content.image.height;
          }
        }
      };

      /**
       * This method is called when changes on the underlying data model have occured (observed by a watch in the super class)
       * @param {CanvasClipartItem} model
       */
      CanvasClipartItem.prototype.$$onModelChange = function (model) {
        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onModelChange.call(this, model);

        var content = this.getContent();
        if (content && content.image) {
          content.scaleX = this.getModel().getWidth() / content.image.width;
          content.scaleY = this.getModel().getHeight() / content.image.height;
        }

      };


      /**
       *
       * @returns {Promise} a promise that is resolved after the thumbnail is fully loaded. It has this item box as parameter or null if it has no parent stage anymore.
       * @private
       */
      CanvasClipartItem.prototype.$$loadClipartImageFromServer = function () {

        var model = this.getModel();

        $log.debug('triggered loading of clipart image from server');

        var clipartImageUrl = 'designElements/designElementImage.rest?imageSize=medium&elementId=' + model.getDesignElementId();

        var bitmap = new createjs.Bitmap(clipartImageUrl);

        var onClipartImgLoaded = function onClipartImgLoaded() {

          $log.debug('Received server side clipart image for item box', self.getModel());
          self.setContent(bitmap);

          // scale the image down to fit
          if (model.getWidth() > 0 && model.getHeight() > 0) {
            bitmap.scaleX = model.getWidth() / bitmap.image.width;
            bitmap.scaleY = model.getHeight() / bitmap.image.height;
          } else {
            var scaleX = AppConstants.CLIPART_ITEM_BOX_DEFAULT_SIZE_PX / bitmap.image.width;
            var scaleY = AppConstants.CLIPART_ITEM_BOX_DEFAULT_SIZE_PX / bitmap.image.height;
            // take the smaller scale value
            SafeApply.do(function applyDimension() {
              if (scaleX <= scaleY) {
                model.setWidth(AppConstants.CLIPART_ITEM_BOX_DEFAULT_SIZE_PX);
                model.setHeight(bitmap.image.height * scaleX);
                scaleY = scaleX;
              } else if (scaleY < scaleX) {
                model.setWidth(bitmap.image.width * scaleY);
                model.setHeight(AppConstants.CLIPART_ITEM_BOX_DEFAULT_SIZE_PX);
                scaleX = scaleY;
              }
            });
          }

          var imgHitArea = new createjs.Shape();
          imgHitArea.graphics.beginFill('#000').rect(0, 0, model.getWidth() / bitmap.scaleX, model.getHeight() / bitmap.scaleY);

          bitmap.hitArea = imgHitArea;

          bitmap.image.removeEventListener('load', onClipartImgLoaded);

          if (model.isFadeIn()) {
            self.fadeIn(250);
            model.setFadeIn(false);
          }

        };

        var self = this;
        bitmap.image.addEventListener('load', onClipartImgLoaded);
      };

      // definition of the public factory functions
      return {

        getClass: function () {
          return CanvasClipartItem;
        },

        /**
         * Creates an CanvasClipartItem that acts as the visual representation of the specified ClipartItem data model.
         * @param scope the scope the ClipartItem data model is bound to
         * @param clipartItemModel the ClipartItem data model to visually represent with the CanvasClipartItem.
         * @returns {CanvasClipartItem} a CanvasClipartItem
         */
        createCanvasClipartItem: function (scope, clipartItemModel) {
          return new CanvasClipartItem(scope, clipartItemModel);
        }
      };

    }
  ]);

})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A factory for CanvasTextItem instances that inherits from CanvasItemPrototype.
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';
  /* global createjs */

  angular.module('tatooine').factory('CanvasTextItemFactory', [
    '$log', '$q', '$http', '$timeout', 'AppConstants', 'SafeApply', 'Utils', 'CanvasItemPrototypeFactory' ,
    function ($log, $q, $http, $timeout, AppConstants, SafeApply, Utils, CanvasItemPrototypeFactory) {

      /**
       * A CanvasTextItem is the visual representation of an TextItem data model and it wraps EaselJS functionality to
       * accomplish the task.
       * @param scope the Angular scope the TextItem data model is bound to
       * @param {TextItem} textItemModel the TextItem data model to visually represent with this CanvasTextItem
       * @constructor
       */
      function CanvasTextItem(scope, textItemModel) {

        // call super class constructor to instantiate its variables
        CanvasItemPrototypeFactory.getClass().call(this, scope, textItemModel);

        this.setEmptyContent(textItemModel.getBackgroundColor());
        this.getModel().setImageRenderingNeeded(true);

      }


      CanvasTextItem.prototype = Object.create(CanvasItemPrototypeFactory.getClass().prototype);
      CanvasTextItem.prototype.constructor = CanvasTextItem;


      /**
       * This method is called when changes on the underlying data model have occured (observed by a watch in the super class)
       * @param {TextItem} model
       */
      CanvasTextItem.prototype.$$onModelChange = function (model) {

        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onModelChange.call(this, model);

        if (model.isImageRenderingNeeded()) {
          this.$$loadTextImageFromServer();
          model.setImageRenderingNeeded(false);
        }

        if (this.getContent().image) {
          this.getContent().scaleX = (this.getToolFrame().getWidth() / this.getContent().image.width);
          this.getContent().scaleY = (this.getToolFrame().getHeight() / this.getContent().image.height);
        }

        // Hide/show the content and toolframe according to whether the TextItem is selected or not.
        // This is basically important for text boxes with transparent backgrounds, because the HTML text input area would be transparent, too,
        // and would otherwise show the CanvasTextItem underneath, which is pretty irritating.
        this.getRootContainer().visible = !model.isSelected();
        this.getToolFrame().setVisible(model.isSelected());
      };


      /*
       CanvasTextItem.prototype.$$onMouseUp = function (e) {

       // call super method
       CanvasItemPrototypeFactory.getClass().prototype.$$onMouseUp.call(this, e);

       var self = this;
       SafeApply.do(function applyModelChangeOnMouseUp() {
       self.getModel().setEditMode(self.getModel().isSelected() && !self.getModel().isEditMode() && self.getToolFrame().isTogglingModes());
       self.getModel().setImageRenderingNeeded(true);
       });

       };
       */


      CanvasTextItem.prototype.$$onMouseDown = function (e) {

        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onMouseDown.call(this, e);

        // TODO Frank Bruns 24.07.2014: do special CanvasTextItem stuff when the event fires

      };


      CanvasTextItem.prototype.$$onMouseDragged = function (e) {

        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onMouseDragged.call(this, e);

      };


      CanvasTextItem.prototype.$$loadTextImageFromServer = function () {

        var model = this.getModel();

        $log.debug('triggered server side text rendering');

        var isEmptyContent = model.isBlank();

        var width = model.getWidth() / AppConstants.MM_TO_PX;
        var height = model.getHeight() / AppConstants.MM_TO_PX;

        // use placeholder text if no real text content is available yet
        var textContent = isEmptyContent ? model.getPlaceholderText() : model.getText();
        var fontWeight = isEmptyContent ? 'normal' : model.getFontWeight();
        var fontStyle = isEmptyContent ? 'normal' : model.getFontStyle();
        var textAnchor = model.getTextAnchor();
        var textColor = model.getTextColor();
        var padding = model.getPadding();
        var verticalAlign = model.getVerticalAlign();
        var backgroundColor = isEmptyContent && model.getBackgroundColor() === 'none' ? '#DFDFDF' : model.getBackgroundColor();
        var fontSize = isEmptyContent ? Math.round(Math.min(width * 0.03, height * 0.15)) : model.getFontSize();
        var fontFamily = model.getFont().getFamily() ? model.getFont().getFamily() : 'Arezzo';
        var style = 'word-wrap:wrap;overflow:hidden;fill:' + textColor + ';background-color:' + backgroundColor + ';font-family:' + fontFamily +
          ';font-weight:' + fontWeight + ';font-style:' + fontStyle + ';font-size:' + fontSize + 'pt' + ';padding:' + padding +
          ';text-anchor:' + (isEmptyContent ? 'middle' : textAnchor) + ';vertical-align:' + (isEmptyContent ? 'middle' : verticalAlign);

        // encode the strings in order to be able attach it to the text rendering URL as a parameter and replace spaces (%20) with '+' signs.
        var encodedText = encodeURIComponent(textContent).replace(/%20/g, '+');
        var encodedStyle = encodeURIComponent(style).replace(/%20/g, '+');

        var textRenderingUrl = 'textrender/textimage.rest?targetWidth=' + Math.round(this.getWidth() * 2) + '&targetHeight=' + Math.round(this.getHeight() * 2) +
          '&width=' + width + '&height=' + height + '&text=' + encodedText + '&style=' + encodedStyle;

        var bitmap = new createjs.Bitmap(textRenderingUrl);

        var onImgLoaded = function imgLoaded() {

          $log.debug('Received server side text image for item box', self.getModel());
          self.setContent(bitmap);

          // if the received image is bigger than requested (e.g. in case of Flash text rendering backend), scale the image down to fit
          var scale = self.getModel().getWidth() / bitmap.image.width;
          bitmap.scaleX = scale;
          bitmap.scaleY = scale;
          var imgHitArea = new createjs.Shape();
          imgHitArea.graphics.beginFill('#000').rect(0, 0, self.getModel().getWidth() / bitmap.scaleX, self.getModel().getHeight() / bitmap.scaleY);

          bitmap.hitArea = imgHitArea;

          bitmap.image.removeEventListener('load', onImgLoaded);

          if (model.isFadeIn()) {
            self.fadeIn(400);
            model.setFadeIn(false);
          }
        };

        var self = this;
        bitmap.image.addEventListener('load', onImgLoaded);
      };


      // definition of the public factory functions
      return {

        getClass: function () {
          return CanvasTextItem;
        },

        /**
         * Creates an CanvasTextItem that acts as the visual representation of the specified TextItem data model.
         * @param scope the scope the TextItem data model is bound to
         * @param textItemModel the TextItem data model to visually represent with the CanvasTextItem.
         * @returns {CanvasTextItem} a CanvasTextItem
         */
        createCanvasTextItem: function (scope, textItemModel) {
          return new CanvasTextItem(scope, textItemModel);
        }
      };

    }
  ])
  ;

})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A factory for CanvasBackgroundItem instances that inherits from CanvasItemPrototype.
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';
  /* global createjs */

  angular.module('tatooine').factory('CanvasBackgroundItemFactory', [
    '$log', '$q', '$http', '$timeout', 'SafeApply', 'Utils', 'CanvasItemPrototypeFactory' ,
    function ($log, $q, $http, $timeout, SafeApply, Utils, CanvasItemPrototypeFactory) {

      /**
       * A CanvasBackgroundItem is the visual representation of an BackgroundItem data model and it wraps EaselJS functionality to
       * accomplish the task.
       * @param scope the Angular scope the BackgroundItem data model is bound to
       * @param {BackgroundItem} backgroundItemModel the BackgroundItem data model to visually represent with this CanvasBackgroundItem
       * @constructor
       */
      function CanvasBackgroundItem(scope, backgroundItemModel) {

        // call super class constructor to instantiate its variables
        CanvasItemPrototypeFactory.getClass().call(this, scope, backgroundItemModel);
        this.oldDesignElementId = backgroundItemModel.getDesignElementId();
        this.oldImageSection = backgroundItemModel.getImageSection();
        this.oldWidth = backgroundItemModel.getWidth();

        this.setEmptyContent('#FFFFFF');
        this.$$loadBackgroundTemplateImageFromServer();
      }


      CanvasBackgroundItem.prototype = Object.create(CanvasItemPrototypeFactory.getClass().prototype);
      CanvasBackgroundItem.prototype.constructor = CanvasBackgroundItem;


      /**
       * This method is called when changes on the underlying data model have occurred (observed by a watch in the super class)
       * @param {BackgroundItem} model
       */
      CanvasBackgroundItem.prototype.$$onModelChange = function (model) {

        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onModelChange.call(this, model);

        if (this.oldDesignElementId !== model.getDesignElementId() || this.oldImageSection !== model.getImageSection() ||
          this.oldWidth !== model.getWidth()) {
          this.$$loadBackgroundTemplateImageFromServer();
          this.oldDesignElementId = model.getDesignElementId();
          this.oldImageSection = model.getImageSection();
        }
      };


      CanvasBackgroundItem.prototype.$$onMouseUp = function (e) {

        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onMouseUp.call(this, e);

      };


      CanvasBackgroundItem.prototype.$$onMouseDown = function (e) {

        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onMouseDown.call(this, e);

        // TODO Frank Bruns 24.07.2014: do special CanvasTextItem stuff when the event fires

      };


      CanvasBackgroundItem.prototype.$$onMouseDragged = function (e) {

        // call super method
        CanvasItemPrototypeFactory.getClass().prototype.$$onMouseDragged.call(this, e);

      };

      /**
       * Sets the display object that is the visual content of this ItemBox.
       * @param displayObject the display object to use as content (e.g. an EaselJS Bitmap)
       */
      CanvasBackgroundItem.prototype.setContent = function (displayObject) {
        if (this.getContent()) {
          this.getContent().uncache();
        }

        if (displayObject.image) {
          $log.debug('Put canvasBackgroundItem into canvas cache', displayObject);
          displayObject.cache(0, 0, displayObject.image.width, displayObject.image.height);
        }
        // explicitly call super method and after that do the code from this class
        CanvasItemPrototypeFactory.getClass().prototype.setContent.call(this, displayObject);


      };


      CanvasBackgroundItem.prototype.$$loadBackgroundTemplateImageFromServer = function () {

        var model = this.getModel();

        $log.debug('triggered loading of design area background template image from server');

        var bgTemplateUrl = 'designElements/designElementImage.rest?imageSize=medium&elementId=' + model.getDesignElementId();

        var bitmap = new createjs.Bitmap(bgTemplateUrl);

        var onBgImgLoaded = function bgImgLoaded() {

          $log.debug('Received server side background template image for item box', self.getModel());


          // scale the image down to fit
          var scaleX;
          if (model.getImageSection() !== 4) {
            scaleX = model.getWidth() * 2 / bitmap.image.width;
          } else {
            scaleX = model.getWidth() / bitmap.image.width;
          }
          var scaleY = model.getHeight() / bitmap.image.height;
          var aspectRatioViewPort = model.getWidth() / model.getHeight();

          bitmap.scaleX = Math.max(scaleX, scaleY);
          bitmap.scaleY = bitmap.scaleX;

          var viewPortX;
          var viewPortY;
          var viewPortWidth;
          var viewPortHeight;
          if (scaleX > scaleY) {
            viewPortWidth = model.getImageSection() === 4 ? bitmap.image.width : bitmap.image.width / 2;
            viewPortHeight = viewPortWidth / aspectRatioViewPort;
            if (model.getImageSection() === 1 || model.getImageSection() === 4) {
              viewPortX = 0;
            } else if (model.getImageSection() === 2) {
              viewPortX = bitmap.image.width / 4;
            } else if (model.getImageSection() === 3) {
              viewPortX = bitmap.image.width / 2;
            }
            viewPortY = (bitmap.image.height - viewPortHeight) / 2;
            bitmap.sourceRect = new createjs.Rectangle(viewPortX, viewPortY, viewPortWidth, viewPortHeight);
          } else {
            viewPortHeight = bitmap.image.height;
            viewPortWidth = viewPortHeight * aspectRatioViewPort;
            if (model.getImageSection() === 1) {
              viewPortX = (bitmap.image.width - viewPortWidth * 2) / 2;
            } else if (model.getImageSection() === 2 || model.getImageSection() === 4) {
              viewPortX = (bitmap.image.width - viewPortWidth) / 2;
            } else if (model.getImageSection() === 3) {
              viewPortX = bitmap.image.width / 2;
            }
            viewPortY = 0;
            bitmap.sourceRect = new createjs.Rectangle(viewPortX, viewPortY, viewPortWidth, viewPortHeight);
          }

          self.setContent(bitmap);

          bitmap.image.removeEventListener('load', onBgImgLoaded);

          if (model.isFadeIn()) {
            self.fadeIn(250);
            model.setFadeIn(false);
          }

        };

        var self = this;
        bitmap.image.addEventListener('load', onBgImgLoaded);
      };


      // definition of the public factory functions
      return {

        getClass: function () {
          return CanvasBackgroundItem;
        },

        /**
         * Creates an CanvasBackgroundItem that acts as the visual representation of the specified TextItem data model.
         * @param scope the scope the BackgroundItem data model is bound to
         * @param backgroundItemModel the BackgroundItem data model to visually represent with the CanvasBackgroundItem.
         * @returns {CanvasBackgroundItem} a CanvasBackgroundItem
         */
        createCanvasBackgroundItem: function (scope, backgroundItemModel) {
          return new CanvasBackgroundItem(scope, backgroundItemModel);
        }
      };

    }
  ])
  ;

})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A factory for ToolFrame instances. Tool frames contain the manipulation handles for ItemBox instances.
 * @author Frank Bruns (frank.bruns@cewe.de)
 * @author Sascha Friedrich (sascha.friedrich@cewe.de)
 * @author Christoph Suhren (christoph.suhren@cewe.de)
 */
(function () {
  'use strict';
  /* global createjs */

  angular.module('tatooine').factory('ToolFrameFactory', [
    '$rootScope', '$log', '$q', 'AppValues', 'AppConstants', 'EventConstants',
    function ($rootScope, $log, $q, AppValues, AppConstants, EventConstants) {
      function ToolFrame(width, height, positionEditable) {
        var self = this;
        this.touchDevice = createjs.Touch.isSupported();

        // will hold references to event listener target objects to be able to easily unregister event listeners from them later on
        this.eventListenerTargets = [];

        this.BUTTON_ROTATE_SIZE = 50;
        this.BUTTON_RECT_SIZE = 27;
        this.BUTTON_CROP_HIT_SCALE = 1;
        this.BUTTON_CIRCLE_HIT_SCALE = 1;

        this.toolFrameGap = AppConstants.TOOLFRAME_DEFAULT_GAP;
        if (this.touchDevice) {
          // we are on a touch device here (iPad, iPhone etc.)
          //this.toolframeLineWidth = 8;
          //this.toolFrameGap = 9;
          this.BUTTON_CROP_HIT_SCALE = 1.5;
          this.BUTTON_CIRCLE_HIT_SCALE = 1.75;
        }
        this.CIRCLE_RADIUS = 15;
        this.RAD_TO_DEG = 180 / Math.PI;
        this.MIN_SIZE = 20;
        this.MIN_BUTTON_MARGIN = 5;
        this.MIN_BUTTONAREA_SIDE = 2 * this.CIRCLE_RADIUS + this.BUTTON_RECT_SIZE + 2 * this.MIN_BUTTON_MARGIN;
        this.MAX_BUTTONAREA_MARGIN = 60;


        this.rotateArrow = new Image();

        this.cropping = false; // indicates an ongoing cropping operation
        this.scaling = false;
        this.dragging = false;
        this.rotating = false;
        this.togglingModes = false;
        this.pinchZooming = false;
        this.mouseZooming = false;
        this.toolframeLineWidth = AppConstants.TOOLFRAME_DEFAULT_LINE_WIDTH;
        this.toolFrameLineColor = AppConstants.TOOLFRAME_DEFAULT_COLOR;
        this.dashed = false;
        this.imageMargins = AppConstants.TOOLFRAME_DEFAULT_IMAGE_MARGINS;

        this.rootContainer = new createjs.Container();
        this.rootContainer.name = 'toolframe';
        this.rootContainer.regX = width / 2;
        this.rootContainer.regY = height / 2;
        this.rootContainer.alpha = 1;
        this.positionEditable = positionEditable;

        //container for tool frame components
        this.containerScaleBottomLeft = new createjs.Container();
        this.containerScaleBottomLeft.name = 'containerScaleBottomLeft';

        this.containerScaleTopLeft = new createjs.Container();
        this.containerScaleTopLeft.name = 'containerScaleTopLeft';

        this.containerScaleBottomRight = new createjs.Container();
        this.containerScaleBottomRight.name = 'containerScaleBottomRight';

        this.containerScaleTopRight = new createjs.Container();
        this.containerScaleTopRight.name = 'containerScaleTopRight';

        this.containerCropTop = new createjs.Container();
        this.containerCropTop.name = 'containerCropTop';

        this.containerCropBottom = new createjs.Container();
        this.containerCropBottom.name = 'containerCropBottom';

        this.containerCropLeft = new createjs.Container();
        this.containerCropLeft.name = 'containerCropLeft';

        this.containerCropRight = new createjs.Container();
        this.containerCropRight.name = 'containerCropRight';

        this.btnMove = new createjs.Shape();
        this.btnMove.name = 'move';
        if (positionEditable) {
          this.btnMove.cursor = 'move';
        }
        this.rootContainer.addChild(this.btnMove);

        this.btnItemContent = new createjs.Shape();
        this.btnItemContent.name = 'btnItemContent';
        this.btnItemContent.setBounds(0, 0, width, height);
        this.rootContainer.addChild(this.btnItemContent);

        this.btnMoveHit = new createjs.Shape();
        this.btnMove.hitArea = this.btnMoveHit;

        this.btnItemContentHit = new createjs.Shape();
        this.btnItemContent.hitArea = this.btnItemContentHit;

        this.btnRotatetHit = new createjs.Shape();
        this.btnRotatetHit.graphics.beginFill('#000').rect(0, 0, this.BUTTON_ROTATE_SIZE, this.BUTTON_ROTATE_SIZE);

        this.btnScaleTopLeftHit = new createjs.Shape();
        this.btnScaleTopRightHit = new createjs.Shape();
        this.btnScaleBottomLeftHit = new createjs.Shape();
        this.btnScaleBottomRightHit = new createjs.Shape();
        var btnScaleHitAreaSize = this.BUTTON_RECT_SIZE * this.BUTTON_CIRCLE_HIT_SCALE;
        var deltaScaleHitXY = btnScaleHitAreaSize / 2;

        this.btnScaleTopLeftHit.graphics.beginFill('#000').rect(-this.CIRCLE_RADIUS, -this.CIRCLE_RADIUS, btnScaleHitAreaSize, btnScaleHitAreaSize);
        this.btnScaleTopRightHit.graphics.beginFill('#000').rect(this.CIRCLE_RADIUS - btnScaleHitAreaSize, -this.CIRCLE_RADIUS, btnScaleHitAreaSize, btnScaleHitAreaSize);
        this.btnScaleBottomLeftHit.graphics.beginFill('#000').rect(-this.CIRCLE_RADIUS, this.CIRCLE_RADIUS - btnScaleHitAreaSize, btnScaleHitAreaSize, btnScaleHitAreaSize);
        this.btnScaleBottomRightHit.graphics.beginFill('#000').rect(this.CIRCLE_RADIUS - btnScaleHitAreaSize, this.CIRCLE_RADIUS - btnScaleHitAreaSize, btnScaleHitAreaSize, btnScaleHitAreaSize);

        this.btnCropHit = new createjs.Shape();
        var btnCropHitAreaSize = this.BUTTON_RECT_SIZE * this.BUTTON_CROP_HIT_SCALE;
        var deltaCropHitXY = (btnCropHitAreaSize - this.BUTTON_RECT_SIZE) / 2;
        this.btnCropHit.graphics.beginFill('#000').rect(-deltaCropHitXY, -deltaCropHitXY, btnCropHitAreaSize, btnCropHitAreaSize);

        this.btnRotateTopRight = new createjs.Bitmap(this.rotateArrow);
        this.btnRotateTopRight.name = 'rotateTopRight';
        this.btnRotateTopRight.hitArea = this.btnRotatetHit;
        this.btnRotateTopRight.regX = this.BUTTON_ROTATE_SIZE / 2;
        this.btnRotateTopRight.regY = this.BUTTON_ROTATE_SIZE / 2;
        this.rootContainer.addChild(this.btnRotateTopRight);

        this.btnRotateBottomRight = new createjs.Bitmap(this.rotateArrow);
        this.btnRotateBottomRight.name = 'rotateBottomRight';
        this.btnRotateBottomRight.hitArea = this.btnRotatetHit;
        this.btnRotateBottomRight.regX = this.BUTTON_ROTATE_SIZE / 2;
        this.btnRotateBottomRight.regY = this.BUTTON_ROTATE_SIZE / 2;
        this.btnRotateBottomRight.scaleY = -1;
        this.rootContainer.addChild(this.btnRotateBottomRight);

        this.btnRotateTopLeft = new createjs.Bitmap(this.rotateArrow);
        this.btnRotateTopLeft.name = 'rotateTopLeft';
        this.btnRotateTopLeft.hitArea = this.btnRotatetHit;
        this.btnRotateTopLeft.regX = this.BUTTON_ROTATE_SIZE / 2;
        this.btnRotateTopLeft.regY = this.BUTTON_ROTATE_SIZE / 2;
        this.btnRotateTopLeft.scaleX = -1;
        this.rootContainer.addChild(this.btnRotateTopLeft);

        this.btnRotateBottomLeft = new createjs.Bitmap(this.rotateArrow);
        this.btnRotateBottomLeft.name = 'rotateBottomLeft';
        this.btnRotateBottomLeft.hitArea = this.btnRotatetHit;
        this.btnRotateBottomLeft.regX = this.BUTTON_ROTATE_SIZE / 2;
        this.btnRotateBottomLeft.regY = this.BUTTON_ROTATE_SIZE / 2;
        this.btnRotateBottomLeft.scaleX = -1;
        this.btnRotateBottomLeft.scaleY = -1;
        this.rootContainer.addChild(this.btnRotateBottomLeft);

        // create white arrows for scale and crop buttons
        this.arrowScaleBottomLeftShapeFirst = new createjs.Shape();
        this.arrowScaleBottomLeftShapeFirst.graphics.setStrokeStyle(0.5).beginStroke('grey').beginFill('#FFFFFF').drawPolyStar(-4, +2, 6, 3, 0, -90);
        this.arrowScaleBottomLeftShapeFirst.visible = true;
        this.arrowScaleBottomLeftShapeFirst.rotation = 340;
        this.arrowScaleBottomLeftShapeFirst.mouseEnabled = false;
        this.rootContainer.addChild(this.arrowScaleBottomLeftShapeFirst);

        this.arrowScaleBottomLeftShapeSecond = new createjs.Shape();
        this.arrowScaleBottomLeftShapeSecond.graphics.setStrokeStyle(0.5).beginStroke('grey').beginFill('#FFFFFF').drawPolyStar(-4, +2, 6, 3, 0, -90);
        this.arrowScaleBottomLeftShapeSecond.visible = true;
        this.arrowScaleBottomLeftShapeSecond.rotation = 160;
        this.arrowScaleBottomLeftShapeSecond.mouseEnabled = false;
        this.rootContainer.addChild(this.arrowScaleBottomLeftShapeSecond);

        this.arrowCropTopShapeFirst = new createjs.Shape();
        this.arrowCropTopShapeFirst.graphics.setStrokeStyle(0.5).beginStroke('grey').beginFill('#FFFFFF').drawPolyStar(0, 0, 6, 3, 0, -90);
        this.arrowCropTopShapeFirst.visible = true;
        this.arrowCropTopShapeFirst.rotation = 0;
        this.arrowCropTopShapeFirst.x = 0;
        this.arrowCropTopShapeFirst.y = -5;
        this.arrowCropTopShapeFirst.mouseEnabled = false;
        this.rootContainer.addChild(this.arrowCropTopShapeFirst);

        this.arrowCropTopShapeSecond = new createjs.Shape();
        this.arrowCropTopShapeSecond.graphics.setStrokeStyle(0.5).beginStroke('grey').beginFill('#FFFFFF').drawPolyStar(0, 0, 6, 3, 0, -90);
        this.arrowCropTopShapeSecond.visible = true;
        this.arrowCropTopShapeSecond.rotation = 180;
        this.arrowCropTopShapeSecond.x = 0;
        this.arrowCropTopShapeSecond.y = 5;
        this.arrowCropTopShapeSecond.mouseEnabled = false;
        this.rootContainer.addChild(this.arrowCropTopShapeSecond);

        //clone shape for scale and crop buttons
        var scaleTopLeftCloneArrowFirst = this.arrowScaleBottomLeftShapeFirst.clone();
        scaleTopLeftCloneArrowFirst.rotation = 80;

        var scaleTopLeftCloneArrowSecond = this.arrowScaleBottomLeftShapeSecond.clone();
        scaleTopLeftCloneArrowSecond.rotation = 260;

        var scaleBottomRightCloneArrowFirst = this.arrowScaleBottomLeftShapeFirst.clone();
        scaleBottomRightCloneArrowFirst.rotation = 80;

        var scaleBottomRightCloneArrowSecond = this.arrowScaleBottomLeftShapeSecond.clone();
        scaleBottomRightCloneArrowSecond.rotation = 260;

        var scaleTopRightCloneArrowFirst = this.arrowScaleBottomLeftShapeFirst.clone();
        var scaleTopRightCloneArrowSecond = this.arrowScaleBottomLeftShapeSecond.clone();

        var cropBottomCloneArrowFirst = this.arrowCropTopShapeFirst.clone();
        var cropBottomCloneArrowSecond = this.arrowCropTopShapeSecond.clone();

        var cropLeftCloneArrowFirst = this.arrowCropTopShapeFirst.clone();
        cropLeftCloneArrowFirst.rotation = 270;
        cropLeftCloneArrowFirst.x = -5;
        cropLeftCloneArrowFirst.y = 0;

        var cropLeftCloneArrowSecond = this.arrowCropTopShapeSecond.clone();
        cropLeftCloneArrowSecond.rotation = 85;
        cropLeftCloneArrowSecond.x = 5;
        cropLeftCloneArrowSecond.y = 0;

        var cropRightCloneArrowFirst = this.arrowCropTopShapeFirst.clone();
        cropRightCloneArrowFirst.rotation = 270;
        cropRightCloneArrowFirst.x = -5;
        cropRightCloneArrowFirst.y = 0;

        var cropRightCloneArrowSecond = this.arrowCropTopShapeSecond.clone();
        cropRightCloneArrowSecond.rotation = 90;
        cropRightCloneArrowSecond.x = 5;
        cropRightCloneArrowSecond.y = 0;

        // Low Left Scale Button

        this.btnScaleBottomLeft = new createjs.Shape();
        this.btnScaleBottomLeft.name = 'scaleBottomLeft';
        this.btnScaleBottomLeft.graphics.setStrokeStyle(2).beginStroke('white').beginFill('rgba(192,0,16,1)').drawCircle(0, 0, this.CIRCLE_RADIUS);
        this.containerScaleBottomLeft.addChild(this.btnScaleBottomLeft, this.arrowScaleBottomLeftShapeFirst, this.arrowScaleBottomLeftShapeSecond);
        this.rootContainer.addChild(this.containerScaleBottomLeft);
        this.btnScaleBottomLeft.hitArea = this.btnScaleBottomLeftHit;

        // Top Left Scale Button

        this.btnScaleTopLeft = new createjs.Shape();
        this.btnScaleTopLeft.name = 'scaleTopLeft';
        this.btnScaleTopLeft.graphics.setStrokeStyle(2).beginStroke('white').beginFill('rgba(192,0,16,1)').drawCircle(0, 0, this.CIRCLE_RADIUS);
        this.containerScaleTopLeft.addChild(this.btnScaleTopLeft, scaleTopLeftCloneArrowFirst, scaleTopLeftCloneArrowSecond);
        this.rootContainer.addChild(this.containerScaleTopLeft);
        this.btnScaleTopLeft.hitArea = this.btnScaleTopLeftHit;

        // Low Right Scale Button

        this.btnScaleBottomRight = new createjs.Shape();
        this.btnScaleBottomRight.name = 'scaleBottomRight';
        this.btnScaleBottomRight.graphics.setStrokeStyle(2).beginStroke('white').beginFill('rgba(192,0,16,1)').drawCircle(0, 0, this.CIRCLE_RADIUS);
        this.containerScaleBottomRight.addChild(this.btnScaleBottomRight, scaleBottomRightCloneArrowFirst, scaleBottomRightCloneArrowSecond);
        this.rootContainer.addChild(this.containerScaleBottomRight);
        this.btnScaleBottomRight.hitArea = this.btnScaleBottomRightHit;

        // Top Right Scale Button

        this.btnScaleTopRight = new createjs.Shape();
        this.btnScaleTopRight.name = 'scaleTopRight';
        this.btnScaleTopRight.graphics.setStrokeStyle(2).beginStroke('white').beginFill('rgba(192,0,16,1)').drawCircle(0, 0, this.CIRCLE_RADIUS);
        this.containerScaleTopRight.addChild(this.btnScaleTopRight, scaleTopRightCloneArrowFirst, scaleTopRightCloneArrowSecond);
        this.rootContainer.addChild(this.containerScaleTopRight);
        this.btnScaleTopRight.hitArea = this.btnScaleTopRightHit;

        this.btnCropTop = new createjs.Shape();
        this.btnCropTop.name = 'cropTop';
        this.btnCropTop.graphics.setStrokeStyle(2).beginStroke('white').beginFill('rgba(192,0,16,1)').drawRect(0, 0, this.BUTTON_RECT_SIZE, this.BUTTON_RECT_SIZE);
        this.btnCropTop.regX = this.BUTTON_RECT_SIZE / 2;
        this.btnCropTop.regY = this.BUTTON_RECT_SIZE / 2;
        this.containerCropTop.addChild(this.btnCropTop, this.arrowCropTopShapeFirst, this.arrowCropTopShapeSecond);
        this.rootContainer.addChild(this.containerCropTop);
        this.btnCropTop.hitArea = this.btnCropHit;

        this.btnCropBottom = new createjs.Shape();
        this.btnCropBottom.name = 'cropBottom';
        this.btnCropBottom.graphics.setStrokeStyle(2).beginStroke('white').beginFill('rgba(192,0,16,1)').drawRect(0, 0, this.BUTTON_RECT_SIZE, this.BUTTON_RECT_SIZE);
        this.btnCropBottom.regX = this.BUTTON_RECT_SIZE / 2;
        this.btnCropBottom.regY = this.BUTTON_RECT_SIZE / 2;
        this.containerCropBottom.addChild(this.btnCropBottom, cropBottomCloneArrowFirst, cropBottomCloneArrowSecond);
        this.rootContainer.addChild(this.containerCropBottom);
        this.btnCropBottom.hitArea = this.btnCropHit;

        this.btnCropLeft = new createjs.Shape();
        this.btnCropLeft.name = 'cropLeft';
        this.btnCropLeft.graphics.setStrokeStyle(2).beginStroke('white').beginFill('rgba(192,0,16,1)').drawRect(0, 0, this.BUTTON_RECT_SIZE, this.BUTTON_RECT_SIZE);
        this.btnCropLeft.regX = this.BUTTON_RECT_SIZE / 2;
        this.btnCropLeft.regY = this.BUTTON_RECT_SIZE / 2;
        this.containerCropLeft.addChild(this.btnCropLeft, cropLeftCloneArrowFirst, cropLeftCloneArrowSecond);
        this.rootContainer.addChild(this.containerCropLeft);
        this.btnCropLeft.hitArea = this.btnCropHit;

        this.btnCropRight = new createjs.Shape();
        this.btnCropRight.name = 'cropRight';
        this.btnCropRight.graphics.setStrokeStyle(2).beginStroke('white').beginFill('rgba(192,0,16,1)').drawRect(0, 0, this.BUTTON_RECT_SIZE, this.BUTTON_RECT_SIZE);
        this.btnCropRight.regX = this.BUTTON_RECT_SIZE / 2;
        this.btnCropRight.regY = this.BUTTON_RECT_SIZE / 2;
        this.containerCropRight.addChild(this.btnCropRight, cropRightCloneArrowFirst, cropRightCloneArrowSecond);
        this.rootContainer.addChild(this.containerCropRight);
        this.btnCropRight.hitArea = this.btnCropHit;

        this.antennaLength = 0;

        // this array needs to contain every component of the tool frame that needs to be
        this.toolFrameComponents = [
          this.btnRotateTopLeft,
          this.btnRotateBottomLeft,
          this.btnRotateTopRight,
          this.btnRotateBottomRight,
          this.btnScaleBottomLeft,
          this.btnScaleBottomRight,
          this.btnScaleTopLeft,
          this.btnScaleTopRight,
          this.btnCropTop,
          this.btnCropBottom,
          this.btnCropLeft,
          this.btnCropRight,
          this.arrowScaleBottomLeftShapeFirst,
          this.arrowScaleBottomLeftShapeSecond,
          this.arrowCropTopShapeFirst,
          this.arrowCropTopShapeSecond,
          scaleTopLeftCloneArrowFirst,
          scaleTopLeftCloneArrowSecond,
          scaleTopRightCloneArrowFirst,
          scaleTopRightCloneArrowSecond,
          scaleBottomRightCloneArrowFirst,
          scaleBottomRightCloneArrowSecond,
          cropBottomCloneArrowSecond,
          cropBottomCloneArrowFirst,
          cropRightCloneArrowSecond,
          cropRightCloneArrowFirst,
          cropLeftCloneArrowSecond,
          cropLeftCloneArrowFirst
        ];

        this.activeComponent = null;
        // add mouse up/down listeners to tool frame components in order to fade them in/out.
        this.toolFrameComponents.forEach(function (component) {
          self.addMouseDownListenerTo(component, function onToolFrameComponentMouseDown(e) {
            self.activeComponent = component;
            if (self.activeComponent === self.btnCropTop || self.activeComponent === self.btnCropRight ||
              self.activeComponent === self.btnCropBottom || self.activeComponent === self.btnCropLeft) {
              self.cropping = true;
            }
            if (self.activeComponent === self.btnScaleTopLeft || self.activeComponent === self.btnScaleTopRight ||
              self.activeComponent === self.btnScaleBottomLeft || self.activeComponent === self.btnScaleBottomRight) {
              self.scaling = true;
            }
            if (self.activeComponent === self.btnRotateTopLeft || self.activeComponent === self.btnRotateTopRight ||
              self.activeComponent === self.btnRotateBottomLeft || self.activeComponent === self.btnRotateBottomRight) {
              self.rotating = true;
            }
            self.$$drawToolFrame();
            self.$$fadeToolFrameComponents(self.toolFrameComponents, 0, false, component);
          });

          self.addMouseUpListenerTo(component, function onToolFrameComponentMouseUp(e) {
            self.activeComponent = null;
            self.$$drawToolFrame();
            self.$$fadeToolFrameComponents(self.toolFrameComponents, 1, true, component);
          });

        });

        //add mouse over/out listeners to rotate buttons to add a hover effect

        this.addMouseOverListenerTo(this.btnRotateTopLeft, function (event) {
          self.btnRotateTopLeft.cursor = 'pointer';
          self.btnRotateTopLeft.alpha = self.btnRotateTopLeft.alpha === AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY ? AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY : 0.7;
          $log.debug(self.btnRotateTopLeft);
        });

        this.addMouseOutListenerTo(this.btnRotateTopLeft, function (event) {
          self.btnRotateTopLeft.alpha = self.btnRotateTopLeft.alpha === AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY ? AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY : AppConstants.TOOLFRAME_DEFAULT_OPACITY;
        });


        this.addMouseOverListenerTo(this.btnRotateBottomLeft, function (event) {
          self.btnRotateBottomLeft.cursor = 'pointer';
          self.btnRotateBottomLeft.alpha = self.btnRotateBottomLeft.alpha === AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY ? AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY : 0.7;
        });

        this.addMouseOutListenerTo(this.btnRotateBottomLeft, function (event) {
          self.btnRotateBottomLeft.alpha = self.btnRotateBottomLeft.alpha === AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY ? AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY : AppConstants.TOOLFRAME_DEFAULT_OPACITY;
        });

        this.addMouseOverListenerTo(this.btnRotateTopRight, function (event) {
          self.btnRotateTopRight.cursor = 'pointer';
          self.btnRotateTopRight.alpha = self.btnRotateTopRight.alpha === AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY ? AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY : 0.7;
        });

        this.addMouseOutListenerTo(this.btnRotateTopRight, function (event) {
          self.btnRotateTopRight.alpha = self.btnRotateTopRight.alpha === AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY ? AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY : AppConstants.TOOLFRAME_DEFAULT_OPACITY;
        });

        this.addMouseOverListenerTo(this.btnRotateBottomRight, function (event) {
          self.btnRotateBottomRight.cursor = 'pointer';
          self.btnRotateBottomRight.alpha = self.btnRotateBottomRight.alpha === AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY ? AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY : 0.7;
        });

        this.addMouseOutListenerTo(this.btnRotateBottomRight, function (event) {
          self.btnRotateBottomRight.alpha = self.btnRotateBottomRight.alpha === AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY ? AppConstants.TOOLFRAME_CONTEXT_MODE_BUTTONS_OPACITY : AppConstants.TOOLFRAME_DEFAULT_OPACITY;
        });

        //add mouse over/out listeners to scale and crop buttons to draw arrows
        this.addMouseOverListenerTo(this.containerCropTop, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(self.arrowCropTopShapeFirst, {override: true});
          tweenArrowFirst.to({
            y: self.arrowCropTopShapeFirst.y - 15,
            x: self.btnCropTop.x
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(self.arrowCropTopShapeSecond, {override: true});
          tweenArrowSecond.to({
            y: self.arrowCropTopShapeSecond.y + 15,
            x: self.btnCropTop.x
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });

        this.addMouseOutListenerTo(this.containerCropTop, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(self.arrowCropTopShapeFirst, {override: true});
          tweenArrowFirst.to({
            y: self.arrowCropTopShapeFirst.y + 15,
            x: self.btnCropTop.x
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(self.arrowCropTopShapeSecond, {override: true});
          tweenArrowSecond.to({
            y: self.arrowCropTopShapeSecond.y - 15,
            x: self.btnCropTop.x
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });


        this.addMouseOverListenerTo(this.containerCropBottom, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(cropBottomCloneArrowFirst, {override: true});
          tweenArrowFirst.to({
            y: cropBottomCloneArrowFirst.y - 15,
            x: self.btnCropBottom.x
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(cropBottomCloneArrowSecond, {override: true});
          tweenArrowSecond.to({
            y: cropBottomCloneArrowSecond.y + 15,
            x: self.btnCropBottom.x
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });

        this.addMouseOutListenerTo(this.containerCropBottom, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(cropBottomCloneArrowFirst, {override: true});
          tweenArrowFirst.to({
            y: cropBottomCloneArrowFirst.y + 15,
            x: self.btnCropBottom.x
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(cropBottomCloneArrowSecond, {override: true});
          tweenArrowSecond.to({
            y: cropBottomCloneArrowSecond.y - 15,
            x: self.btnCropBottom.x
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });

        this.addMouseOverListenerTo(this.containerCropLeft, function (event) {

          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(cropLeftCloneArrowFirst, {override: true});
          tweenArrowFirst.to({x: cropLeftCloneArrowFirst.x - 15}, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(cropLeftCloneArrowSecond, {override: true});
          tweenArrowSecond.to({x: cropLeftCloneArrowSecond.x + 15}, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);

        });

        this.addMouseOutListenerTo(this.containerCropLeft, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(cropLeftCloneArrowFirst, {override: true});
          tweenArrowFirst.to({x: cropLeftCloneArrowFirst.x + 15}, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(cropLeftCloneArrowSecond, {override: true});
          tweenArrowSecond.to({x: cropLeftCloneArrowSecond.x - 15}, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });


        this.addMouseOverListenerTo(this.containerCropRight, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(cropRightCloneArrowFirst, {override: true});
          tweenArrowFirst.to({x: cropRightCloneArrowFirst.x - 15}, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(cropRightCloneArrowSecond, {override: true});
          tweenArrowSecond.to({x: cropRightCloneArrowSecond.x + 15}, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });

        this.addMouseOutListenerTo(this.containerCropRight, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(cropRightCloneArrowFirst, {override: true});
          tweenArrowFirst.to({x: cropRightCloneArrowFirst.x + 15}, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(cropRightCloneArrowSecond, {override: true});
          tweenArrowSecond.to({x: cropRightCloneArrowSecond.x - 15}, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });


        this.addMouseOverListenerTo(this.containerScaleTopLeft, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(scaleTopLeftCloneArrowFirst, {override: true});
          tweenArrowFirst.to({
            x: scaleTopLeftCloneArrowFirst.x - 12,
            y: scaleTopLeftCloneArrowFirst.y - 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(scaleTopLeftCloneArrowSecond, {override: true});
          tweenArrowSecond.to({
            x: scaleTopLeftCloneArrowSecond.x + 12,
            y: scaleTopLeftCloneArrowSecond.y + 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });

        this.addMouseOutListenerTo(this.containerScaleTopLeft, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(scaleTopLeftCloneArrowFirst, {override: true});
          tweenArrowFirst.to({
            x: scaleTopLeftCloneArrowFirst.x + 12,
            y: scaleTopLeftCloneArrowFirst.y + 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(scaleTopLeftCloneArrowSecond, {override: true});
          tweenArrowSecond.to({
            x: scaleTopLeftCloneArrowSecond.x - 12,
            y: scaleTopLeftCloneArrowSecond.y - 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });

        this.addMouseOverListenerTo(this.containerScaleTopRight, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(scaleTopRightCloneArrowFirst, {override: true});
          tweenArrowFirst.to({
            x: scaleTopRightCloneArrowFirst.x - 12,
            y: scaleTopRightCloneArrowFirst.y + 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(scaleTopRightCloneArrowSecond, {override: true});
          tweenArrowSecond.to({
            x: scaleTopRightCloneArrowSecond.x + 12,
            y: scaleTopRightCloneArrowSecond.y - 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });

        this.addMouseOutListenerTo(this.containerScaleTopRight, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(scaleTopRightCloneArrowFirst, {override: true});
          tweenArrowFirst.to({
            x: scaleTopRightCloneArrowFirst.x + 12,
            y: scaleTopRightCloneArrowFirst.y - 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(scaleTopRightCloneArrowSecond, {override: true});
          tweenArrowSecond.to({
            x: scaleTopRightCloneArrowSecond.x - 12,
            y: scaleTopRightCloneArrowSecond.y + 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });

        this.addMouseOverListenerTo(this.containerScaleBottomLeft, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(self.arrowScaleBottomLeftShapeFirst, {override: true});
          tweenArrowFirst.to({
            x: self.arrowScaleBottomLeftShapeFirst.x - 12,
            y: self.arrowScaleBottomLeftShapeFirst.y + 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(self.arrowScaleBottomLeftShapeSecond, {override: true});
          tweenArrowSecond.to({
            x: self.arrowScaleBottomLeftShapeSecond.x + 12,
            y: self.arrowScaleBottomLeftShapeSecond.y - 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });

        this.addMouseOutListenerTo(this.containerScaleBottomLeft, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(self.arrowScaleBottomLeftShapeFirst, {override: true});
          tweenArrowFirst.to({
            x: self.arrowScaleBottomLeftShapeFirst.x + 12,
            y: self.arrowScaleBottomLeftShapeFirst.y - 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(self.arrowScaleBottomLeftShapeSecond, {override: true});
          tweenArrowSecond.to({
            x: self.arrowScaleBottomLeftShapeSecond.x - 12,
            y: self.arrowScaleBottomLeftShapeSecond.y + 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });

        this.addMouseOverListenerTo(this.containerScaleBottomRight, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(scaleBottomRightCloneArrowFirst, {override: true});
          tweenArrowFirst.to({
            x: scaleBottomRightCloneArrowFirst.x - 12,
            y: scaleBottomRightCloneArrowFirst.y - 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(scaleBottomRightCloneArrowSecond, {override: true});
          tweenArrowSecond.to({
            x: scaleBottomRightCloneArrowSecond.x + 12,
            y: scaleBottomRightCloneArrowSecond.y + 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);

        });

        this.addMouseOutListenerTo(this.containerScaleBottomRight, function (event) {
          var timeLine = new createjs.Timeline();
          var duration = 75;

          var tweenArrowFirst = createjs.Tween.get(scaleBottomRightCloneArrowFirst, {override: true});
          tweenArrowFirst.to({
            x: scaleBottomRightCloneArrowFirst.x + 12,
            y: scaleBottomRightCloneArrowFirst.y + 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowFirst);

          var tweenArrowSecond = createjs.Tween.get(scaleBottomRightCloneArrowSecond, {override: true});
          tweenArrowSecond.to({
            x: scaleBottomRightCloneArrowSecond.x - 12,
            y: scaleBottomRightCloneArrowSecond.y - 12
          }, duration, createjs.Ease.sineInOut);
          timeLine.addTween(tweenArrowSecond);
        });

        this.addMouseDownListenerTo(this.rootContainer, function (e) {
          self.globalPositionOnMouseDown = {
            x: e.rawX,
            y: e.rawY
          };
          self.centerOnMouseDown = {
            x: self.getCenterX(),
            y: self.getCenterY()
          };
          self.dimensionOnMouseDown = {
            width: self.getWidth(),
            height: self.getHeight()
          };
          self.rotationOnMouseDown = self.getRotation();
          self.togglingModes = false;
        });

        this.addMouseUpListenerTo(this.rootContainer, function (e) {
          if (!self.isVisible() || self.isPinchZooming()) {
            e.stopPropagation();
            return;
          }

          // reset some variables that have been set on mouse down
          self.globalPositionOnMouseDown = null;
          self.centerOnMouseDown = null;
          self.dimensionOnMouseDown = null;
          self.rotationOnMouseDown = null;
          self.activeComponent = null;

          var alphaFadeIn = 1.0;
          self.$$fadeToolFrameComponents(self.toolFrameComponents, alphaFadeIn, true);

          if (!self.dragging && e.target.name === 'btnItemContent') {
            // indicate toggling of the toolframe mode
            self.togglingModes = true;
          }

          self.dragging = false;
          self.cropping = false;
          self.scaling = false;
          self.rotating = false;

          $rootScope.$broadcast(EventConstants.IMAGE_ITEM_CONTENT_MOVE_END);

          self.$$drawToolFrame();
        });

        if (this.positionEditable) {
          this.addMouseDraggedListenerTo(this.btnMove, function (e) {
            if (!self.isVisible() || self.isPinchZooming()) {
              e.stopPropagation();
              return;
            }

            if (!self.dragging) {
              self.activeComponent = self.btnMove;
              self.$$fadeToolFrameComponents(self.toolFrameComponents, 0, false);
            }

            // only consider actions as dragging if the drag distance is at least a certain amount of pixels (this is meant
            // to make it easier to toggle the viewport mode, even if the mouse was slightly moved during the click)
            var dragDistance = self.$$getDragDistance(self, e);
            if (self.dragging || Math.abs(dragDistance.x) > 0 || Math.abs(dragDistance.y) > 0) {
              var localCenterOnMouseDown = self.rootContainer.globalToLocal(self.centerOnMouseDown.x, self.centerOnMouseDown.y);
              var newLocalCenter = {
                x: localCenterOnMouseDown.x + dragDistance.x,
                y: localCenterOnMouseDown.y + dragDistance.y
              };
              var newGlobalCenter = self.rootContainer.localToGlobal(newLocalCenter.x, newLocalCenter.y);
              self.setPosition(newGlobalCenter.x, newGlobalCenter.y);
              self.dragging = true;
            }
          });
        }

        this.addMouseDraggedListenerTo(this.btnItemContent, function (e) {

          var dragDistance = self.$$getDragDistance(self, e);

          if (!self.isVisible() || self.isPinchZooming()) {
            e.stopPropagation();
            return;
          }
          if (!self.dragging) {
            self.activeComponent = self.btnItemContent;
            self.$$fadeToolFrameComponents(self.toolFrameComponents, 0, false);
          }
          // just if the left mouse button is clicked
          if (e.nativeEvent.button === 0 || e.nativeEvent.buttons === 0 || e.nativeEvent.type === 'touchmove') {
            // only consider actions as dragging if the drag distance is at least a certain amount of pixels (this is meant
            // to make it easier to toggle the viewport mode, even if the mouse was slightly moved during the click)
            if (self.dragging || Math.abs(dragDistance.x) > 0 || Math.abs(dragDistance.y) > 0) {
              if (!self.dragging) {
                $rootScope.$broadcast(EventConstants.IMAGE_ITEM_CONTENT_MOVE_START);
              }
              self.dragging = true;
            }
          }
          // otherwise we will move the item
          else {
            if (self.dragging || Math.abs(dragDistance.x) > 0 || Math.abs(dragDistance.y) > 0) {
              var localCenterOnMouseDown = self.rootContainer.globalToLocal(self.centerOnMouseDown.x, self.centerOnMouseDown.y);
              var newLocalCenter = {
                x: localCenterOnMouseDown.x + dragDistance.x,
                y: localCenterOnMouseDown.y + dragDistance.y
              };
              var newGlobalCenter = self.rootContainer.localToGlobal(newLocalCenter.x, newLocalCenter.y);
              self.setGlobalPosition(newGlobalCenter.x, newGlobalCenter.y);
              self.dragging = true;
            }
          }

        });

        this.addMouseDraggedListenerTo(this.btnRotateTopRight, function (e) {
          self.$$rotateToolFrame(e);
        });

        this.addMouseDraggedListenerTo(this.btnRotateBottomRight, function (e) {
          self.$$rotateToolFrame(e);
        });

        this.addMouseDraggedListenerTo(this.btnRotateTopLeft, function (e) {
          self.$$rotateToolFrame(e);
        });

        this.addMouseDraggedListenerTo(this.btnRotateBottomLeft, function (e) {
          self.$$rotateToolFrame(e);
        });

        this.addMouseDraggedListenerTo(this.btnScaleBottomRight, function (e) {

          var dragDistance = self.$$getDragDistance(self, e);

          var aspectRatio = self.dimensionOnMouseDown.width / self.dimensionOnMouseDown.height;

          var totalDeltaWidth = (dragDistance.x * aspectRatio + dragDistance.y) / 2;
          var newWidth = self.dimensionOnMouseDown.width + totalDeltaWidth;

          var newPoiWidth;
          if (self.getRotation() === 0 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiWidth = AppValues.nearestPoi.x - (self.centerOnMouseDown.x - self.dimensionOnMouseDown.width / 2);
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          if (self.getRotation() === 180 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiWidth = Math.abs(AppValues.nearestPoi.x - (self.centerOnMouseDown.x + self.dimensionOnMouseDown.width / 2));
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          var newPoiHeight;
          var newHeight = newWidth / aspectRatio;
          if (self.getRotation() === 0 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiHeight = AppValues.nearestPoi.y - (self.centerOnMouseDown.y - self.dimensionOnMouseDown.height / 2);
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
              newWidth = newHeight * aspectRatio;
            }
          }

          if (self.getRotation() === 180 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiHeight = Math.abs(AppValues.nearestPoi.y - (self.centerOnMouseDown.y + self.dimensionOnMouseDown.height / 2));
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
              newWidth = newHeight * aspectRatio;
            }
          }


          if (newWidth < self.MIN_SIZE || newHeight < self.MIN_SIZE) {
            return;
          }

          var deltaWidth = newWidth - self.getWidth();
          var deltaHeight = newHeight - self.getHeight();

          // Scale it!
          self.setDimension(newWidth, newHeight);

          // Position it!
          var newGlobalCenter = self.rootContainer.localToGlobal(self.getLocalCenter().x + deltaWidth / 2, self.getLocalCenter().y + deltaHeight / 2);
          self.setGlobalPosition(newGlobalCenter.x, newGlobalCenter.y);

          self.$$drawToolFrame();
        });


        this.addMouseDraggedListenerTo(this.btnScaleTopRight, function (e) {

          var dragDistance = self.$$getDragDistance(self, e);
          var aspectRatio = self.dimensionOnMouseDown.width / self.dimensionOnMouseDown.height;

          var totalDeltaWidth = (dragDistance.x * aspectRatio - dragDistance.y) / 2;
          var newWidth = self.dimensionOnMouseDown.width + totalDeltaWidth;
          var newPoiWidth;
          if (self.getRotation() === 0 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiWidth = AppValues.nearestPoi.x - (self.centerOnMouseDown.x - self.dimensionOnMouseDown.width / 2);
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          if (self.getRotation() === 180 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiWidth = Math.abs(AppValues.nearestPoi.x - (self.centerOnMouseDown.x + self.dimensionOnMouseDown.width / 2));
            $log.debug(newPoiWidth, newWidth);
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          var newHeight = newWidth / aspectRatio;
          var newPoiHeight;
          if (self.getRotation() === 0 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiHeight = self.centerOnMouseDown.y + self.dimensionOnMouseDown.height / 2 - AppValues.nearestPoi.y;
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
              newWidth = newHeight * aspectRatio;
            }
          }

          if (self.getRotation() === 180 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiHeight = Math.abs(self.centerOnMouseDown.y - self.dimensionOnMouseDown.height / 2 - AppValues.nearestPoi.y);
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
              newWidth = newHeight * aspectRatio;
            }
          }

          if (newWidth < self.MIN_SIZE || newHeight < self.MIN_SIZE) {
            return;
          }

          var deltaWidth = newWidth - self.getWidth();
          var deltaHeight = newHeight - self.getHeight();

          // Scale it!
          self.setDimension(newWidth, newHeight);

          // Position it!
          var newGlobalCenter = self.rootContainer.localToGlobal(self.getLocalCenter().x + deltaWidth / 2, self.getLocalCenter().y - deltaHeight / 2);
          self.setGlobalPosition(newGlobalCenter.x, newGlobalCenter.y);

          self.$$drawToolFrame();
        });


        this.addMouseDraggedListenerTo(this.btnScaleBottomLeft, function (e) {

          var dragDistance = self.$$getDragDistance(self, e);
          var aspectRatio = self.dimensionOnMouseDown.width / self.dimensionOnMouseDown.height;

          var totalDeltaWidth = (-dragDistance.x * aspectRatio + dragDistance.y) / 2;
          var newWidth = self.dimensionOnMouseDown.width + totalDeltaWidth;


          var newPoiWidth = newWidth;
          if (self.getRotation() === 0 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiWidth = self.centerOnMouseDown.x + self.dimensionOnMouseDown.width / 2 - AppValues.nearestPoi.x;
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          if (self.getRotation() === 180 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiWidth = Math.abs(self.centerOnMouseDown.x - self.dimensionOnMouseDown.width / 2 - AppValues.nearestPoi.x);
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          var newHeight = newWidth / aspectRatio;
          var newPoiHeight;
          if (self.getRotation() === 0 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiHeight = AppValues.nearestPoi.y - (self.centerOnMouseDown.y - self.dimensionOnMouseDown.height / 2);
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
              newWidth = newHeight * aspectRatio;
            }
          }

          if (self.getRotation() === 180 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiHeight = Math.abs(AppValues.nearestPoi.y - (self.centerOnMouseDown.y + self.dimensionOnMouseDown.height / 2));
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
              newWidth = newHeight * aspectRatio;
            }
          }

          if (newWidth < self.MIN_SIZE || newHeight < self.MIN_SIZE) {
            return;
          }

          var deltaWidth = newWidth - self.getWidth();
          var deltaHeight = newHeight - self.getHeight();

          // Scale it!
          self.setDimension(newWidth, newHeight);

          // Position it!
          var newGlobalCenter = self.rootContainer.localToGlobal(self.getLocalCenter().x - deltaWidth / 2, self.getLocalCenter().y + deltaHeight / 2);
          self.setGlobalPosition(newGlobalCenter.x, newGlobalCenter.y);

          self.$$drawToolFrame();
        });


        this.addMouseDraggedListenerTo(this.btnScaleTopLeft, function (e) {

          var aspectRatio = self.dimensionOnMouseDown.width / self.dimensionOnMouseDown.height;

          var dragDistance = self.$$getDragDistance(self, e);
          var totalDeltaWidth = (-1 * dragDistance.x * aspectRatio - dragDistance.y) / 2;
          var newWidth = self.dimensionOnMouseDown.width + totalDeltaWidth;
          var newPoiWidth = newWidth;
          if (self.getRotation() === 0 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiWidth = self.centerOnMouseDown.x + self.dimensionOnMouseDown.width / 2 - AppValues.nearestPoi.x;
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }
          if (self.getRotation() === 180 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiWidth = Math.abs(self.centerOnMouseDown.x - self.dimensionOnMouseDown.width / 2 - AppValues.nearestPoi.x);
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          var newHeight = newWidth / aspectRatio;
          var newPoiHeight;

          if (self.getRotation() === 0 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiHeight = self.centerOnMouseDown.y + self.dimensionOnMouseDown.height / 2 - AppValues.nearestPoi.y;
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
              newWidth = newHeight * aspectRatio;
            }
          }

          if (self.getRotation() === 180 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiHeight = Math.abs(self.centerOnMouseDown.y - self.dimensionOnMouseDown.height / 2 - AppValues.nearestPoi.y);
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
              newWidth = newHeight * aspectRatio;
            }
          }

          if (newWidth < self.MIN_SIZE || newHeight < self.MIN_SIZE) {
            return;
          }

          var deltaWidth = newWidth - self.getWidth();
          var deltaHeight = newHeight - self.getHeight();

          // Scale it!
          self.setDimension(newWidth, newHeight);

          // Position it!
          var newGlobalCenter = self.rootContainer.localToGlobal(self.getLocalCenter().x - deltaWidth / 2, self.getLocalCenter().y - deltaHeight / 2);
          self.setGlobalPosition(newGlobalCenter.x, newGlobalCenter.y);

          self.$$drawToolFrame();
        });


        this.addMouseDraggedListenerTo(this.btnCropLeft, function (e) {

          var dragDistance = self.$$getDragDistance(self, e);

          var newWidth = self.dimensionOnMouseDown.width - dragDistance.x;
          var newPoiWidth;
          if (self.getRotation() === 0 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiWidth = self.centerOnMouseDown.x + self.dimensionOnMouseDown.width / 2 - AppValues.nearestPoi.x;
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          if (self.getRotation() === 90 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiWidth = Math.abs(AppValues.nearestPoi.y - self.centerOnMouseDown.y - self.dimensionOnMouseDown.width / 2);
            $log.debug(newPoiWidth, newWidth);
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          if (self.getRotation() === 180 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiWidth = Math.abs(self.centerOnMouseDown.x - self.dimensionOnMouseDown.width / 2 - AppValues.nearestPoi.x);
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          if (self.getRotation() === 270 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiWidth = AppValues.nearestPoi.y - self.centerOnMouseDown.y + self.dimensionOnMouseDown.width / 2;
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }


          if (newWidth < self.MIN_SIZE) {
            return;
          }

          var deltaWidth = newWidth - self.getWidth();

          // Scale it!
          self.setDimension(newWidth, self.getHeight());

          // Position it!
          var newGlobalCenter = self.rootContainer.localToGlobal(self.getLocalCenter().x - deltaWidth / 2, self.getLocalCenter().y);
          self.setGlobalPosition(newGlobalCenter.x, newGlobalCenter.y);

          self.$$drawToolFrame();

        });

        this.addMouseDraggedListenerTo(this.btnCropRight, function (e) {

          if (!e.primary) {
            return;
          }

          var dragDistance = self.$$getDragDistance(self, e);

          var newWidth = self.dimensionOnMouseDown.width + dragDistance.x;
          var newPoiWidth;

          if (self.getRotation() === 0 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiWidth = AppValues.nearestPoi.x - (self.centerOnMouseDown.x - self.dimensionOnMouseDown.width / 2);
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          if (self.getRotation() === 90 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiWidth = AppValues.nearestPoi.y - self.centerOnMouseDown.y + self.dimensionOnMouseDown.width / 2;
            $log.debug(newPoiWidth, newWidth);
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          if (self.getRotation() === 180 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiWidth = Math.abs(AppValues.nearestPoi.x - (self.centerOnMouseDown.x + self.dimensionOnMouseDown.width / 2));
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          if (self.getRotation() === 270 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiWidth = Math.abs(AppValues.nearestPoi.y - self.centerOnMouseDown.y - self.dimensionOnMouseDown.width / 2);
            if (Math.abs(newPoiWidth - newWidth) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newWidth = newPoiWidth;
            }
          }

          var newGlobalCenter;
          if (newWidth < self.MIN_SIZE) {
            return;
          }
          var deltaWidth = newWidth - self.getWidth();
          // Scale it!
          self.setDimension(newWidth, self.getHeight());
          // Position it!
          newGlobalCenter = self.rootContainer.localToGlobal(self.getLocalCenter().x + deltaWidth / 2, self.getLocalCenter().y);
          self.setGlobalPosition(newGlobalCenter.x, newGlobalCenter.y);

          self.$$drawToolFrame();
        });


        this.addMouseDraggedListenerTo(this.btnCropTop, function (e) {

          if (!e.primary) {
            return;
          }

          var dragDistance = self.$$getDragDistance(self, e);
          var newHeight = self.dimensionOnMouseDown.height - dragDistance.y;
          var newPoiHeight;
          if (self.getRotation() === 0 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiHeight = self.centerOnMouseDown.y + self.dimensionOnMouseDown.height / 2 - AppValues.nearestPoi.y;
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
            }
          }

          if (self.getRotation() === 90 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiHeight = AppValues.nearestPoi.x - (self.centerOnMouseDown.x - self.dimensionOnMouseDown.height / 2);
            $log.debug(newPoiHeight, newHeight);
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
            }
          }

          if (self.getRotation() === 180 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiHeight = Math.abs(self.centerOnMouseDown.y - self.dimensionOnMouseDown.height / 2 - AppValues.nearestPoi.y);
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
            }
          }

          if (self.getRotation() === 270 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiHeight = Math.abs(AppValues.nearestPoi.x - (self.centerOnMouseDown.x + self.dimensionOnMouseDown.height / 2));
            $log.debug(newPoiHeight, newHeight);
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
            }
          }

          if (newHeight < self.MIN_SIZE) {
            return;
          }

          var deltaHeight = newHeight - self.getHeight();

          // Scale it!
          self.setDimension(self.getWidth(), newHeight);

          // Position it!
          var newGlobalCenter = self.rootContainer.localToGlobal(self.getLocalCenter().x, self.getLocalCenter().y - deltaHeight / 2);
          self.setGlobalPosition(newGlobalCenter.x, newGlobalCenter.y);

          self.$$drawToolFrame();
        });


        this.addMouseDraggedListenerTo(this.btnCropBottom, function (e) {

          if (!e.primary) {
            return;
          }

          var dragDistance = self.$$getDragDistance(self, e);

          var newHeight = self.dimensionOnMouseDown.height + dragDistance.y;
          var newPoiHeight;
          if (self.getRotation() === 0 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiHeight = AppValues.nearestPoi.y - self.centerOnMouseDown.y + self.dimensionOnMouseDown.height / 2;
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
            }
          }

          if (self.getRotation() === 90 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiHeight = Math.abs(AppValues.nearestPoi.x - (self.centerOnMouseDown.x + self.dimensionOnMouseDown.height / 2));
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
            }
          }

          if (self.getRotation() === 180 && AppValues.nearestPoi.y && AppValues.nearestPoi.nearestNeighborY !== 'centerY') {
            newPoiHeight = Math.abs(AppValues.nearestPoi.y - self.centerOnMouseDown.y - self.dimensionOnMouseDown.height / 2);
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
            }
          }

          if (self.getRotation() === 270 && AppValues.nearestPoi.x && AppValues.nearestPoi.nearestNeighborX !== 'centerX') {
            newPoiHeight = AppValues.nearestPoi.x - (self.centerOnMouseDown.x - self.dimensionOnMouseDown.height / 2);
            if (Math.abs(newPoiHeight - newHeight) <= AppConstants.MAGNETIC_SNAP_DISTANCE) {
              newHeight = newPoiHeight;
            }
          }

          if (newHeight < self.MIN_SIZE) {
            return;
          }

          var deltaHeight = newHeight - self.getHeight();

          // Scale it!
          self.setDimension(self.getWidth(), newHeight);

          // Position it!
          var newGlobalCenter = self.rootContainer.localToGlobal(self.getLocalCenter().x, self.getLocalCenter().y + deltaHeight / 2);
          self.setGlobalPosition(newGlobalCenter.x, newGlobalCenter.y);

          self.$$drawToolFrame();
        });
      }


      ToolFrame.prototype.initialize = function () {

        this.rotateArrow.src = '/web/javax.faces.resource/app/tatooine/images/toolframe/rotate_Arrow_test3.png.jsf';

        var defer = $q.defer();
        var self = this;

        var onLoadImage = function () {
          if (self.rotateArrow) {
            self.rotateArrow.removeEventListener('load', onLoadImage);
          }
          defer.resolve();
          defer = null;
        };

        this.rotateArrow.addEventListener('load', onLoadImage);

        return defer.promise;
      };

      ToolFrame.prototype.getRootContainer = function () {
        return this.rootContainer;
      };

      ToolFrame.prototype.cleanUp = function () {
        this.removeEventListeners();
        this.getRootContainer().removeAllEventListeners();
        this.rootContainer.removeAllChildren();
        this.rootContainer = null;
        this.rotateArrow = null;
      };

      /**
       * Removes all event listeners that are associated to this ToolFrame. It's good practice to call this as soon as you
       * don't need the ToolFrame instance anymore.
       */
      ToolFrame.prototype.removeEventListeners = function () {
        this.eventListenerTargets.forEach(function (eventListenerTarget) {
          eventListenerTarget.removeAllEventListeners();
        });
        this.getRootContainer().removeAllEventListeners();
      };

      /**
       * Adds a event handler to the specified display object that calls the specified action function in case
       * the mouse is dragged across the canvas (pressed + moved)
       * @param displayObject the display object to register the event listener for
       * @param fnCallback the function to be called in case the event is fired
       */
      ToolFrame.prototype.addMouseDraggedListenerTo = function (displayObject, fnCallback) {
        var self = this;

        // store for unregistering later
        this.eventListenerTargets.push(displayObject);
        displayObject.on('pressmove', function pressMoved(e) {
          if (!e.primary) {
            return;
          }
          fnCallback(e);
        });
      };

      ToolFrame.prototype.addMouseClickedListenerTo = function (displayObject, fnCallback) {
        var self = this;

        // store for unregistering later
        this.eventListenerTargets.push(displayObject);
        displayObject.on('click', function clicked(e) {
          if (!e.primary) {
            return;
          }
          fnCallback(e);
        });
      };

      ToolFrame.prototype.addMouseDownListenerTo = function (displayObject, fnCallback) {
        var self = this;

        this.eventListenerTargets.push(displayObject);
        displayObject.on('mousedown', function mouseDown(e) {
          if (!e.primary) {
            return;
          }
          fnCallback(e);
        });
      };

      ToolFrame.prototype.addMouseUpListenerTo = function (displayObject, fnCallback) {
        var self = this;

        this.eventListenerTargets.push(displayObject);
        displayObject.on('pressup', function pressUp(e) {
          if (!e.primary) {
            return;
          }
          fnCallback(e);
        });
      };

      ToolFrame.prototype.addMouseOverListenerTo = function (displayObject, fnCallback) {
        var self = this;

        this.eventListenerTargets.push(displayObject);
        displayObject.on('mouseover', function pressUp(e) {
          if (!e.primary) {
            return;
          }
          fnCallback(e);
        });
      };

      ToolFrame.prototype.addMouseOutListenerTo = function (displayObject, fnCallback) {
        var self = this;

        this.eventListenerTargets.push(displayObject);
        displayObject.on('mouseout', function pressUp(e) {
          if (!e.primary) {
            return;
          }
          fnCallback(e);
        });
      };

      ToolFrame.prototype.addBtnMoveMouseDownListener = function (fnCallback) {
        this.addMouseDownListenerTo(this.btnMove, fnCallback);
      };

      /**
       *
       * @param fnCallback a function that gets called when the mouse is down somewhere on the ToolFrame
       */
      ToolFrame.prototype.addMouseDownListener = function (fnCallback) {
        this.addMouseDownListenerTo(this.rootContainer, fnCallback);
      };

      /**
       *
       * @param fnCallback a function that gets called when the mouse was released somewhere on the ToolFrame
       */
      ToolFrame.prototype.addMouseUpListener = function (fnCallback) {
        this.addMouseUpListenerTo(this.rootContainer, fnCallback);
      };

      /**
       *
       * @param fnCallback a function that gets called when the mouse is dragged somewhere on the ToolFrame
       */
      ToolFrame.prototype.addMouseDraggedListener = function (fnCallback) {
        this.addMouseDraggedListenerTo(this.rootContainer, fnCallback);
      };

      /**
       *
       * @param toolFrame
       * @param dragEvent
       * @returns {{x: number, y: number}}
       */
      ToolFrame.prototype.$$getDragDistance = function (toolFrame, dragEvent) {
        var globalMouse = {
          x: dragEvent.rawX,
          y: dragEvent.rawY
        };
        var localMouse = toolFrame.rootContainer.globalToLocal(globalMouse.x, globalMouse.y);
        var localPositionOnMouseDown = toolFrame.rootContainer.globalToLocal(toolFrame.globalPositionOnMouseDown.x, toolFrame.globalPositionOnMouseDown.y);
        var dragDistance = {
          x: localMouse.x - localPositionOnMouseDown.x,
          y: localMouse.y - localPositionOnMouseDown.y
        };


        dragEvent.dragDistance = dragDistance;
        return dragDistance;
      };


      /**
       * Fades the specified toolframe components to the given alpha
       * @param components the toolframe components to fade
       * @param alpha the alpha value to fade to, a value from interval [0.0, 1.0]
       * @param doPulseEffect show pulse effect
       * @param notFadingComponent this toolframe component will be left out of the fading operation (optional)
       */
      ToolFrame.prototype.$$fadeToolFrameComponents = function (components, alpha, doPulseEffect, notFadingComponent) {

        if (this.isDashed()) {
          return;
        }
        var duration = 150;
        var timeLine = new createjs.Timeline();

        components.forEach(function iterateComponents(component) {

          var tween = createjs.Tween.get(component, {override: true});

          if (notFadingComponent !== component) {

            //tween.to({alpha: alpha}, duration, createjs.Ease.linear);
            component.alpha = alpha;
            component.visible = alpha !== 0;

          } else if (doPulseEffect) { // the not fading component is pulsating

            var scaleUp = {
              x: component.scaleX * 1.1,
              y: component.scaleY * 1.1
            };

            var scaleDown = {
              x: component.scaleX * 0.9,
              y: component.scaleY * 0.9
            };

            // rotate buttons need the design area scale factor applied (not sure why :-( )
            var isRotateButton = component.name.indexOf('rotate') === 0;
            var scaleFactor = isRotateButton ? AppValues.designAreaScale : 1;

            var scaleNormal = {
              x: component.scaleX / Math.abs(component.scaleX) * scaleFactor, // will be 1 or -1 (times design area scale) according to the scale factor's original sign
              y: component.scaleY / Math.abs(component.scaleY) * scaleFactor// will be 1 or -1 (times design area scale) according to the scale factor's original sign
            };

            for (var pulseCount = 0; pulseCount < 2; pulseCount++) {
              tween.to({
                scaleX: scaleUp.x,
                scaleY: scaleUp.y
              }, duration, createjs.Ease.linear).to({
                scaleX: scaleDown.x,
                scaleY: scaleDown.y
              }, duration, createjs.Ease.linear);
            }

            tween.to({
              scaleX: scaleNormal.x,
              scaleY: scaleNormal.y
            }, duration, createjs.Ease.linear);
          }

          timeLine.addTween(tween);

        });

        var self = this;
      };

      ToolFrame.prototype.$$updateStage = function () {
        if (this.rootContainer.getStage()) {
          this.rootContainer.getStage().update();
        }
      };

      ToolFrame.prototype.$$rotateToolFrame = function (e) {

        if (!e.primary) {
          return;
        }

        var currentMousePos = {
          x: e.rawX,
          y: e.rawY
        };

        var globalCenter = this.getGlobalPosition();

        // find the direction from the tool frame's center to the mouse pointer
        var currentMouseDirectionX = currentMousePos.x - globalCenter.x;
        var currentMouseDirectionY = currentMousePos.y - globalCenter.y;

        // Calculate the angle to rotate the tool frame considering the mouse position.
        // A very nice convenience method to accomplish the task is Math.atan2().
        var currentMouseAngleRadians = Math.atan2(currentMouseDirectionY, currentMouseDirectionX);
        var currentMouseAngleDegrees = currentMouseAngleRadians * this.RAD_TO_DEG;

        // calculate an offset to the angle to take start position on mouse down event into account
        var mouseDownDirectionX = this.globalPositionOnMouseDown.x - globalCenter.x;
        var mouseDownDirectionY = this.globalPositionOnMouseDown.y - globalCenter.y;
        var mouseDownAngleDegrees = Math.atan2(mouseDownDirectionY, mouseDownDirectionX) * this.RAD_TO_DEG;

        var rotDegrees = this.rotationOnMouseDown + currentMouseAngleDegrees - mouseDownAngleDegrees;

        // make the rotation value positive
        rotDegrees = (rotDegrees + 360) % 360;

        var snapRange = 3;

        if (rotDegrees >= 90 - snapRange && rotDegrees <= 90 + snapRange) {
          rotDegrees = 90;
        } else if (rotDegrees >= 180 - snapRange && rotDegrees <= 180 + snapRange) {
          rotDegrees = 180;
        } else if (rotDegrees >= 270 - snapRange && rotDegrees <= 270 + snapRange) {
          rotDegrees = 270;
        } else if (rotDegrees >= 360 - snapRange || rotDegrees <= 0 + snapRange) {
          rotDegrees = 0;
        }

        this.setRotation(rotDegrees);
      };


      ToolFrame.prototype.$$drawToolFrame = function () {

        var toolFrameGap = this.getGap();

        var toolFrameWidth = this.getWidth();
        var toolFrameHeight = this.getHeight();

        this.btnItemContent.x = this.getWidth() / 2;
        this.btnItemContent.y = this.getHeight() / 2;

        this.btnItemContent.graphics.clear();
        this.btnItemContent.graphics.drawRect(0 - this.toolframeLineWidth - toolFrameGap, 0 - this.toolframeLineWidth - toolFrameGap, this.getWidth() + 4 * this.toolframeLineWidth + toolFrameGap, this.getHeight() + 4 * this.toolframeLineWidth + toolFrameGap);
        this.btnItemContent.regX = this.getWidth() / 2;
        this.btnItemContent.regY = this.getHeight() / 2;
        this.btnItemContent.setBounds(0, 0, this.getWidth(), this.getHeight());

        this.btnItemContentHit.graphics.clear();
        this.btnItemContentHit.graphics.beginFill('#000').rect(0, 0, this.getWidth(), this.getHeight());

        // draw the frame with some color always in viewport or in pinchZoom mode, but not when currently dragging or rotating in other modes
        this.btnMove.x = this.getWidth() / 2;
        this.btnMove.y = this.getHeight() / 2;

        this.btnMove.graphics.clear();

        this.btnRotateTopLeft.visible = !this.isDashed();
        this.btnRotateTopRight.visible = !this.isDashed();
        this.btnRotateBottomLeft.visible = !this.isDashed();
        this.btnRotateBottomRight.visible = !this.isDashed();

        if (this.isDashed()) {
          this.btnMove.graphics.setStrokeDash([8, 8]);
        }
        this.btnMove.graphics.setStrokeStyle(this.toolframeLineWidth * AppValues.designAreaScale).beginStroke(this.toolFrameLineColor).drawRect(0 - toolFrameGap - this.imageMargins.left, 0 - toolFrameGap - this.imageMargins.top, this.getWidth() + 2 * toolFrameGap + this.imageMargins.left + this.imageMargins.right, this.getHeight() + 2 * toolFrameGap + this.imageMargins.top + this.imageMargins.bottom);
        this.btnMove.regX = this.getWidth() / 2;
        this.btnMove.regY = this.getHeight() / 2;

        this.btnMoveHit.graphics.clear();
        this.btnMoveHit.graphics.setStrokeStyle(this.toolframeLineWidth * AppValues.designAreaScale + toolFrameGap).beginStroke('rgba(0, 0, 0, 1)').drawRect(0 - toolFrameGap, 0 - toolFrameGap, this.getWidth() + 2 * toolFrameGap, this.getHeight() + 2 * toolFrameGap);

        var buttonAreaWidth = toolFrameWidth;
        var buttonAreaHeight = toolFrameHeight;

        // check if the picture is smaller than the minimum toolframe size
        if (toolFrameWidth < this.MIN_BUTTONAREA_SIDE || toolFrameHeight < this.MIN_BUTTONAREA_SIDE) {
          if (toolFrameWidth > toolFrameHeight) {
            buttonAreaHeight = this.MIN_BUTTONAREA_SIDE;
            buttonAreaWidth = Math.min(toolFrameWidth + this.MAX_BUTTONAREA_MARGIN, toolFrameWidth / toolFrameHeight * buttonAreaHeight);
          } else {
            buttonAreaWidth = this.MIN_BUTTONAREA_SIDE;
            buttonAreaHeight = Math.min(toolFrameHeight + this.MAX_BUTTONAREA_MARGIN, toolFrameHeight / toolFrameWidth * buttonAreaWidth);
          }
        }

        var rotationButtonOffset = this.BUTTON_ROTATE_SIZE / 2 * AppValues.designAreaScale;

        this.containerScaleTopRight.x = toolFrameWidth / 2 + buttonAreaWidth / 2 + toolFrameGap;
        this.containerScaleTopRight.y = toolFrameHeight / 2 - buttonAreaHeight / 2 - toolFrameGap;
        this.containerScaleTopRight.scaleX = AppValues.designAreaScale;
        this.containerScaleTopRight.scaleY = AppValues.designAreaScale;

        this.btnRotateTopRight.x = this.containerScaleTopRight.x + rotationButtonOffset;
        this.btnRotateTopRight.y = this.containerScaleTopRight.y - rotationButtonOffset;
        this.btnRotateTopRight.scaleX = AppValues.designAreaScale;
        this.btnRotateTopRight.scaleY = AppValues.designAreaScale;
        //this.btnRotateTopRight.x = this.getWidth() / 2;
        //this.btnRotateTopRight.y = -this.BUTTON_ROTATE_SIZE;

        this.containerScaleBottomRight.x = this.containerScaleTopRight.x;
        this.containerScaleBottomRight.y = toolFrameHeight / 2 + buttonAreaHeight / 2 + toolFrameGap;
        this.containerScaleBottomRight.scaleX = AppValues.designAreaScale;
        this.containerScaleBottomRight.scaleY = AppValues.designAreaScale;

        this.btnRotateBottomRight.x = this.containerScaleBottomRight.x + rotationButtonOffset;
        this.btnRotateBottomRight.y = this.containerScaleBottomRight.y + rotationButtonOffset;
        this.btnRotateBottomRight.scaleX = AppValues.designAreaScale;
        this.btnRotateBottomRight.scaleY = -AppValues.designAreaScale;
        //this.btnRotateBottomRight.x = this.getWidth() / 2;
        //this.btnRotateBottomRight.y = toolFrameHeight + this.BUTTON_ROTATE_SIZE;

        this.containerScaleTopLeft.x = toolFrameWidth / 2 - buttonAreaWidth / 2 - toolFrameGap;
        this.containerScaleTopLeft.y = toolFrameHeight / 2 - buttonAreaHeight / 2 - toolFrameGap;
        this.containerScaleTopLeft.scaleX = AppValues.designAreaScale;
        this.containerScaleTopLeft.scaleY = AppValues.designAreaScale;

        this.btnRotateTopLeft.x = this.containerScaleTopLeft.x - rotationButtonOffset;
        this.btnRotateTopLeft.y = this.containerScaleTopLeft.y - rotationButtonOffset;
        this.btnRotateTopLeft.scaleX = -AppValues.designAreaScale;
        this.btnRotateTopLeft.scaleY = AppValues.designAreaScale;

        //this.btnRotateTopLeft.x = -this.BUTTON_ROTATE_SIZE;
        //this.btnRotateTopLeft.y = this.getHeight() / 2;


        this.containerScaleBottomLeft.x = this.containerScaleTopLeft.x;
        this.containerScaleBottomLeft.y = this.containerScaleBottomRight.y;
        this.containerScaleBottomLeft.scaleX = AppValues.designAreaScale;
        this.containerScaleBottomLeft.scaleY = AppValues.designAreaScale;

        this.btnRotateBottomLeft.x = this.containerScaleBottomLeft.x - rotationButtonOffset;
        this.btnRotateBottomLeft.y = this.containerScaleBottomLeft.y + rotationButtonOffset;
        this.btnRotateBottomLeft.scaleX = -AppValues.designAreaScale;
        this.btnRotateBottomLeft.scaleY = -AppValues.designAreaScale;

        //this.btnRotateBottomLeft.x = this.getWidth() + this.BUTTON_ROTATE_SIZE;
        //this.btnRotateBottomLeft.y = this.getHeight() / 2;

        this.containerCropTop.x = this.getWidth() / 2;
        this.containerCropTop.y = this.containerScaleTopRight.y;
        this.containerCropTop.scaleX = AppValues.designAreaScale;
        this.containerCropTop.scaleY = AppValues.designAreaScale;

        this.containerCropBottom.x = toolFrameWidth / 2;
        this.containerCropBottom.y = this.containerScaleBottomRight.y;
        this.containerCropBottom.scaleX = AppValues.designAreaScale;
        this.containerCropBottom.scaleY = AppValues.designAreaScale;

        this.containerCropLeft.x = this.containerScaleTopLeft.x;
        this.containerCropLeft.y = toolFrameHeight / 2;
        this.containerCropLeft.scaleX = AppValues.designAreaScale;
        this.containerCropLeft.scaleY = AppValues.designAreaScale;

        this.containerCropRight.x = this.containerScaleTopRight.x;
        this.containerCropRight.y = toolFrameHeight / 2;
        this.containerCropRight.scaleX = AppValues.designAreaScale;
        this.containerCropRight.scaleY = AppValues.designAreaScale;
        // draw 'antennas'
        if (this.positionEditable) {
          if (!this.isDashed()) {
            if (!this.activeComponent || this.activeComponent === this.btnScaleTopRight) {
              this.btnMove.graphics.moveTo(toolFrameWidth + toolFrameGap, -toolFrameGap).lineTo(this.containerScaleTopRight.x, this.containerScaleTopRight.y);
              this.antennaLength = this.containerScaleTopRight.y;
            }
            if (!this.activeComponent || this.activeComponent === this.btnScaleBottomRight) {
              this.btnMove.graphics.moveTo(toolFrameWidth + toolFrameGap, toolFrameHeight + toolFrameGap).lineTo(this.containerScaleBottomRight.x, this.containerScaleBottomRight.y);
              this.antennaLength = this.containerScaleBottomRight.y - toolFrameHeight;
            }
            if (!this.activeComponent || this.activeComponent === this.btnScaleTopLeft) {
              this.btnMove.graphics.moveTo(0 - toolFrameGap, 0 - toolFrameGap).lineTo(this.containerScaleTopLeft.x, this.containerScaleTopLeft.y);
              this.antennaLength = this.containerScaleTopLeft.y;
            }
            if (!this.activeComponent || this.activeComponent === this.btnScaleBottomLeft) {
              this.btnMove.graphics.moveTo(0 - toolFrameGap, toolFrameHeight + toolFrameGap).lineTo(this.containerScaleBottomLeft.x, this.containerScaleBottomLeft.y);
              this.antennaLength = this.containerScaleBottomLeft.y - toolFrameHeight;
            }
            if (!this.activeComponent || this.activeComponent === this.btnCropTop) {
              this.btnMove.graphics.moveTo(toolFrameWidth / 2, -toolFrameGap).lineTo(this.containerCropTop.x, this.containerCropTop.y);
              this.antennaLength = this.containerCropTop.y;
            }
            if (!this.activeComponent || this.activeComponent === this.btnCropBottom) {
              this.btnMove.graphics.moveTo(toolFrameWidth / 2, toolFrameHeight + toolFrameGap).lineTo(this.containerCropBottom.x, this.containerCropBottom.y);
              this.antennaLength = this.containerCropBottom.y - toolFrameHeight;
            }
            if (!this.activeComponent || this.activeComponent === this.btnCropLeft) {
              this.btnMove.graphics.moveTo(-toolFrameGap, toolFrameHeight / 2).lineTo(this.containerCropLeft.x, this.containerCropLeft.y);
              this.antennaLength = this.btnCropLeft.x;
            }
            if (!this.activeComponent || this.activeComponent === this.btnCropRight) {
              this.btnMove.graphics.moveTo(toolFrameWidth + toolFrameGap, toolFrameHeight / 2).lineTo(this.containerCropRight.x, this.containerCropRight.y);
              this.antennaLength = this.containerCropRight.x - toolFrameWidth;
            }
          }
        } else {
          // position is not editable, remove buttons
          this.rootContainer.removeChild(this.containerCropTop);
          this.rootContainer.removeChild(this.containerCropBottom);
          this.rootContainer.removeChild(this.containerCropLeft);
          this.rootContainer.removeChild(this.containerCropRight);
          this.rootContainer.removeChild(this.containerScaleTopLeft);
          this.rootContainer.removeChild(this.containerScaleBottomLeft);
          this.rootContainer.removeChild(this.containerScaleBottomRight);
          this.rootContainer.removeChild(this.containerScaleTopRight);
          this.rootContainer.removeChild(this.btnRotateTopLeft);
          this.rootContainer.removeChild(this.btnRotateBottomLeft);
          this.rootContainer.removeChild(this.btnRotateTopRight);
          this.rootContainer.removeChild(this.btnRotateBottomRight);
        }
      };

      /**
       * @returns {boolean} Last action was scaling the toolframe?
       */
      ToolFrame.prototype.isScaling = function () {
        return this.scaling;
      };


      /**
       * @returns {boolean} Last action was cropping the toolframe?
       */
      ToolFrame.prototype.isCropping = function () {
        return this.cropping;
      };

      /**
       * @returns {boolean} Last action was dragging the toolframe?
       */
      ToolFrame.prototype.isDragging = function () {
        return this.dragging;
      };

      /**
       * @returns {boolean} Last action was rotating the toolframe?
       */
      ToolFrame.prototype.isRotating = function () {
        return this.rotating;
      };

      /**
       * @returns {boolean} Last action was toggling between toolframe modes?
       */
      ToolFrame.prototype.isTogglingModes = function () {
        return this.togglingModes;
      };

      ToolFrame.prototype.setPinchZooming = function (trueOrFalse) {
        this.pinchZooming = trueOrFalse;
        if (trueOrFalse) { // fade out components when entering pinch to zoom mode
          this.$$fadeToolFrameComponents(this.toolFrameComponents, 0, false);
        } else {
          this.dragging = false;
          this.$$fadeToolFrameComponents(this.toolFrameComponents, 1, false);
        }
      };

      ToolFrame.prototype.isPinchZooming = function () {
        return this.pinchZooming;
      };


      ToolFrame.prototype.setMouseZooming = function (trueOrFalse) {
        this.mouseZooming = trueOrFalse;
        if (trueOrFalse) {
          this.$$fadeToolFrameComponents(this.toolFrameComponents, 0, false);
        } else {
          this.$$fadeToolFrameComponents(this.toolFrameComponents, 1, false);
        }
      };

      ToolFrame.prototype.isMouseZooming = function () {
        return this.mouseZooming;
      };


      /**
       *
       * @returns {boolean} Indicates whether there is an ongoing operation on the toolframe
       */
      ToolFrame.prototype.isBusy = function () {
        return this.isScaling() || this.isCropping() || this.isDragging() || this.isRotating() || this.isPinchZooming();
      };

      ToolFrame.prototype.setVisible = function (visible) {
        if (visible && !this.rootContainer.visible) {
          this.newlyVisible = true;
        }

        this.rootContainer.visible = visible;
      };

      ToolFrame.prototype.isVisible = function () {
        return this.rootContainer.visible;
      };

      ToolFrame.prototype.getAntennaLength = function () {
        return Math.ceil(Math.abs(this.antennaLength));
      };

      ToolFrame.prototype.setItemBox = function (itemBox) {
        this.itemBox = itemBox;
      };


      ToolFrame.prototype.getCenterX = function () {
        return this.rootContainer.x;
      };

      ToolFrame.prototype.getCenterY = function () {

        return this.rootContainer.y;
      };

      /**
       * Moves the ToolFrame to the specified x position in the coordinate system of the parent (global).
       * @param x
       */
      ToolFrame.prototype.setCenterX = function (x) {
        this.rootContainer.x = x;
      };

      /**
       * Moves the ToolFrame to the specified y position in the coordinate system of the parent (global).
       * @param y
       */
      ToolFrame.prototype.setCenterY = function (y) {
        this.rootContainer.y = y;
      };


      ToolFrame.prototype.getPosition = function () {
        return {
          x: this.getCenterX(),
          y: this.getCenterY()
        };
      };

      /**
       * Moves the ToolFrame to the specified position (global).
       * @param centerX
       * @param centerY
       */
      ToolFrame.prototype.setPosition = function (centerX, centerY) {
        this.setCenterX(centerX);
        this.setCenterY(centerY);
      };

      /**
       * Moves the ToolFrame to the specified position (global).
       * @param centerX
       * @param centerY
       */
      ToolFrame.prototype.setGlobalPosition = function (globalX, globalY) {
        var newPosition = this.rootContainer.parent.globalToLocal(globalX, globalY);
        this.setCenterX(newPosition.x);
        this.setCenterY(newPosition.y);
      };

      ToolFrame.prototype.getGlobalPosition = function () {
        return this.rootContainer.parent.localToGlobal(this.getCenterX(), this.getCenterY());
      };

      /**
       * Returns the center in its own coordinate system.
       * @returns {{x: *, y: *}}
       */
      ToolFrame.prototype.getLocalCenter = function () {
        return {
          x: this.rootContainer.regX,
          y: this.rootContainer.regY
        };
      };

      /**
       *
       * @returns {Number} the width of the ToolFrame in pixels
       */
      ToolFrame.prototype.getWidth = function () {
        return this.rootContainer.regX * 2;
      };

      /**
       *
       * @returns {Number} the height of the ToolFrame in pixels
       */
      ToolFrame.prototype.getHeight = function () {
        return this.rootContainer.regY * 2;
      };

      /**
       * Changes the width and redraws the ToolFrame.
       * @param width - the width of the ToolFrame in pixels
       */
      ToolFrame.prototype.setWidth = function (width) {
        this.rootContainer.regX = width / 2;

        this.$$drawToolFrame();

      };

      /**
       * Changes the height and redraws the ToolFrame.
       * @param height - the height of the ToolFrame in pixels
       */
      ToolFrame.prototype.setHeight = function (height) {
        this.rootContainer.regY = height / 2;

        this.$$drawToolFrame();
      };

      /**
       * Changes width and height and redraws the ToolFrame.
       * @param width
       * @param height
       */
      ToolFrame.prototype.setDimension = function (width, height) {
        this.rootContainer.regX = width / 2;
        this.rootContainer.regY = height / 2;

        this.$$drawToolFrame();
      };

      ToolFrame.prototype.getGap = function () {
        return this.toolFrameGap;
      };

      ToolFrame.prototype.setGap = function (gap) {
        this.toolFrameGap = gap;
        this.$$drawToolFrame();
      };
      /**
       * Sets the rotation of the ToolFrame in degrees.
       * @param rotation
       */
      ToolFrame.prototype.setRotation = function (rotation) {
        this.rootContainer.rotation = rotation;
      };

      /**
       *
       * @returns {Number} the current rotation of the ToolFrame in degrees
       */
      ToolFrame.prototype.getRotation = function () {
        return this.rootContainer.rotation;
      };

      ToolFrame.prototype.setOpacity = function (opacityButtons, opacityFrame) {
        var rootContainerChildren = this.rootContainer.children;
        rootContainerChildren.forEach(function (child) {
          if (child.name !== 'move') {
            child.alpha = opacityButtons;
          }
          else {
            child.alpha = opacityFrame;
          }
        });
        this.$$drawToolFrame();
      };

      ToolFrame.prototype.getButtonOpacity = function () {
        return this.rootContainer.alpha;
      };


      ToolFrame.prototype.setToolFrameLineWidth = function (width) {
        this.toolframeLineWidth = width;
        this.$$drawToolFrame();
      };

      ToolFrame.prototype.getToolFrameLineWidth = function () {
        return this.toolframeLineWidth;
      };

      ToolFrame.prototype.setToolFrameLineColor = function (color) {
        this.toolFrameLineColor = color;
      };

      ToolFrame.prototype.isDashed = function () {
        return this.dashed;
      };

      ToolFrame.prototype.setDashed = function (trueOrFalse) {
        this.dashed = trueOrFalse;
      };

      ToolFrame.prototype.getImageMargins = function () {
        return this.imageMargins;
      };

      ToolFrame.prototype.setImageMargins = function (width) {
        this.imageMargins = width;
        this.$$drawToolFrame();
      };

      // definition of the public factory functions
      return {
        createToolFrame: function (width, height, positionEditable) {
          return new ToolFrame(width, height, positionEditable);
        }
      };

    }

  ])
  ;

})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A factory for ContentSilhouette instances.
 * @author Christoph Suhren
 */
(function () {
  'use strict';
  /* global createjs */

  angular.module('tatooine').factory('ContentSilhouetteFactory', [
    '$log',
    function ($log) {

      function ContentSilhouette(x, y, width, height) {
        $log.debug('create content silhouette at position ' + x + ', ' + y + ' with dimension ' + width + 'x' + height);

        var self = this;

        this.CONTENT_SILHOUETTE_ALPHA = 0.4;
        this.FADE_OUT_DURATION = 100;

        this.rootContainer = new createjs.Container();
        this.rootContainer.name = 'contentSilhouette';
        this.rootContainer.x = x;
        this.rootContainer.y = y;
        this.rootContainer.regX = width / 2;
        this.rootContainer.regY = height / 2;
        this.rootContainer.mouseEnabled = false; // deactivate mouse event listening
      }

      ContentSilhouette.prototype.$$updateStage = function() {
        if (this.rootContainer.getStage()) {
          this.rootContainer.getStage().update();
        }
      };

      ContentSilhouette.prototype.getRootContainer = function () {
        return this.rootContainer;
      };

      ContentSilhouette.prototype.setContent = function (content) {
        content.name = 'silhouetteContent';
        this.getRootContainer().removeAllChildren();
        this.getRootContainer().addChild(content);
        this.getRootContainer().visible = false;
        this.getRootContainer().alpha = 0;
      };

      ContentSilhouette.prototype.scaleContent = function (scaleX, scaleY) {
        this.getRootContainer().getChildAt(0).scaleX = scaleX;
        this.getRootContainer().getChildAt(0).scaleY = scaleY;
      };

      ContentSilhouette.prototype.setContentPosition = function (x, y) {
        this.getRootContainer().getChildAt(0).x = x;
        this.getRootContainer().getChildAt(0).y = y;
      };

      ContentSilhouette.prototype.setVisible = function (visible) {
        if (visible) {
          this.getRootContainer().visible = visible;
          this.getRootContainer().alpha = this.CONTENT_SILHOUETTE_ALPHA;
        } else {
          var self = this;
          createjs.Tween.get(this.getRootContainer(), {override: true}).to({alpha: 0, visible: false}, this.FADE_OUT_DURATION, createjs.Ease.linear);
        }
      };

      ContentSilhouette.prototype.isVisible = function () {
        return this.getRootContainer().visible;
      };

      /**
       * Shows the content silhouette for the specified duration of miliseconds and then fades out softly.
       * @param duration time in miliseconds the content silhouette is shown before fading out
       */
      ContentSilhouette.prototype.showTemporarily = function (duration) {
        var self = this;
        this.getRootContainer().visible = true;
        this.getRootContainer().alpha = this.CONTENT_SILHOUETTE_ALPHA;

        createjs.Tween.get(this.getRootContainer(), {override: true}).wait(duration)
          .to({alpha: 0, visible: false}, this.FADE_OUT_DURATION, createjs.Ease.linear);
      };

      ContentSilhouette.prototype.getCenterX = function () {
        return this.getRootContainer().x;
      };

      ContentSilhouette.prototype.getCenterY = function () {
        return this.getRootContainer().y;
      };

      /**
       * Moves the ContentSilhouette to the specified x position in the coordinate system of the parent (global).
       */
      ContentSilhouette.prototype.setCenterX = function (x) {
        this.getRootContainer().x = x;
      };

      /**
       * Moves the ContentSilhouette to the specified y position in the coordinate system of the parent (global).
       */
      ContentSilhouette.prototype.setCenterY = function (y) {
        this.getRootContainer().y = y;
      };

      /**
       * Moves the ContentSilhouette to the specified position (global).
       */
      ContentSilhouette.prototype.setPosition = function (centerX, centerY) {
        this.setCenterX(centerX);
        this.setCenterY(centerY);
      };

      /**
       * @returns {Number} the width of the ContentSilhouette in pixels
       */
      ContentSilhouette.prototype.getWidth = function () {
        return this.getRootContainer().regX * 2;
      };

      /**
       *
       * @returns {Number} the height of the v in pixels
       */
      ContentSilhouette.prototype.getHeight = function () {
        return this.getRootContainer().regY * 2;
      };

      /**
       * Changes the width and redraws the ContentSilhouette.
       * @param width - the width of the ContentSilhouette in pixels
       */
      ContentSilhouette.prototype.setWidth = function (width) {
        this.getRootContainer().regX = width / 2;
      };

      /**
       * Changes the height and redraws the ContentSilhouette.
       * @param height - the height of the ContentSilhouette in pixels
       */
      ContentSilhouette.prototype.setHeight = function (height) {
        this.getRootContainer().regY = height / 2;
      };

      /**
       * Changes width and height and redraws the v.
       */
      ContentSilhouette.prototype.setDimension = function (width, height) {
        this.getRootContainer().regX = width / 2;
        this.getRootContainer().regY = height / 2;
      };

      /**
       * Sets the rotation of the ToolFrame in degrees.
       */
      ContentSilhouette.prototype.setRotation = function (rotation) {
        this.getRootContainer().rotation = rotation;
      };

      /**
       * @returns {Number} the current rotation of the ToolFrame in degrees
       */
      ContentSilhouette.prototype.getRotation = function () {
        return this.getRootContainer().rotation;
      };


      ContentSilhouette.prototype.cleanUp = function () {
        this.getRootContainer().removeAllEventListeners();
        this.getRootContainer().removeAllChildren();
        this.rootContainer = null;
      };


      // definition of the public factory functions
      return {
        createContentSilhouette: function (x, y, width, height) {
          return new ContentSilhouette(x, y, width, height);
        }
      };
    }

  ])
  ;

})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';
  /* global Kinetic */
  /* global createjs */

  angular.module('tatooine').directive('cwDesignArea', [
    '$log', '$timeout', '$window', 'SafeApply', 'AppConstants', 'AppValues', 'EventConstants', 'DesignAreaService', 'FileHandleService', 'ProjectService',
    'IndexedDBService', 'LayoutService', 'UndoRedoService', 'MessageService', 'NotificationService', 'CanvasDesignAreaFactory', 'FileHandleFactory',
    'TextItemTemplateFactory', 'BackgroundItemTemplateFactory', 'ClipartItemTemplateFactory', 'DesignAreaFactory', 'Utils', 'DeviceDetectionService', 'PhotoSourcesService', 'IpsAlbumService',
    function ($log, $timeout, $window, SafeApply, AppConstants, AppValues, EventConstants, DesignAreaService, FileHandleService, ProjectService, IndexedDBService, LayoutService, UndoRedoService, MessageService, NotificationService, CanvasDesignAreaFactory, FileHandleFactory, TextItemTemplateFactory, BackgroundItemTemplateFactory, ClipartItemTemplateFactory, DesignAreaFactory, Utils, DeviceDetectionService, PhotoSourcesService, IpsAlbumService) {
      return {
        restrict: 'A',
        scope: {
          designArea: '=cwDesignArea'
        },
        replace: true,
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/editorstage/cwDesignArea.html.jsf',

        link: function (scope, element, attrs) {

          var project = ProjectService.getProject();

          element.find('canvas').attr('id', scope.designArea.getId());
          var designAreaModel = scope.designArea;

          scope.getPaddingHorizontal = function () {
            return designAreaModel.getPaddingHorizontal() / AppValues.designAreaScale;
          };

          scope.getPaddingVertical = function () {
            return designAreaModel.getPaddingVertical() / AppValues.designAreaScale;
          };

          scope.getPrintAreaDimension = function () {
            return {
              width: (designAreaModel.getCssWidth() - 2 * scope.getPaddingHorizontal()),
              height: (designAreaModel.getCssHeight() - 2 * scope.getPaddingVertical())
            };
          };


          // we use a timeout here, because the canvas dom node from the template is not available (by id) in the link function.
          $timeout(function () {
            var canvasDesignArea = CanvasDesignAreaFactory.createCanvasDesignArea(scope, designAreaModel, element);

            scope.isDesignAreaDragNDropAllowed = function () {
              return (!DeviceDetectionService.isMobileDevice() && project.isStoryBoardView() && !designAreaModel.isCover() && !designAreaModel.isLeftPageBlocked() && !designAreaModel.isRightPageBlocked());
            };

            scope.onDesignAreaDragStop = function (e, helper) {
              // this is not nice here, but this is the last chance to remove the draggedObject from the service when no drop will appear
            };

            scope.onDesignAreaDrop = function (e, helper) {
              var areaToDrop = DesignAreaService.getDesignAreaToDrop();
              if (areaToDrop) {
                var designAreas = project.getDesignAreas();
                if (designAreas.indexOf(areaToDrop) >= 0 && designAreas.indexOf(designAreaModel) >= 0) {
                  var undoHandle = UndoRedoService.pushProject();
                  var areaToDropIndex = designAreas.indexOf(areaToDrop);
                  var targetAreaIndex = designAreas.indexOf(designAreaModel);
                  Utils.swapArrayPositions(designAreas, areaToDropIndex, targetAreaIndex);
                  ProjectService.setProject(project, false, false);
                  undoHandle.resolve();
                  NotificationService.addNotification(MessageService.getMessage('notification.interchangeSites.end.header'), MessageService.getMessage('notification.interchangeSites.end.text', [(areaToDropIndex * 2 - 2), (areaToDropIndex * 2 + 1 - 2), (targetAreaIndex * 2 - 2), (targetAreaIndex * 2 + 1 - 2)]), 'info', 5000);
                }
                DesignAreaService.removeDesignAreaToDrop();
              }
            };

            scope.onDesignAreaDragStart = function (e, helper) {
              DesignAreaService.setDesignAreaInDragProcess(designAreaModel);
              if (!DeviceDetectionService.isMobileDevice()) {
                NotificationService.addNotification(MessageService.getMessage('notification.interchangeSites.start.header'), MessageService.getMessage('notification.interchangeSites.start.text'), 'info', 10000);
              } else {
                NotificationService.addNotification(MessageService.getMessage('notification.interchangeSites.start.header'), MessageService.getMessage('notification.interchangeSites.start.textMobile'), 'info', 10000);
              }
            };

            scope.onDesignAreaDrag = function (e, helper) {
              //element.css('transform', 'translateY(' + storyBoardContainer[0].scrollTop + 'px)');
            };


            scope.isDropAllowed = function () {
              return designAreaModel.isSelected() || project.isStoryBoardView();
            };

            scope.onDropComplete = function (droppedObject, e) {
              if (!droppedObject || !scope.isDropAllowed() || e.y <= (AppConstants.HEAD_AREA_HEIGHT + AppConstants.TOGGLE_HEAD_AREA_HEIGHT)) {
                return;
              }
              // 30.04.2014 Frank Bruns: This is currently a hack that simulates a touch event at the drop position, since EaselJS didn't
              // update its internal touch coordinates while dragging over the stage on mobile devices during the drag&drop operation
              if (canvasDesignArea.touchDevice) {
                var pointerId = e.nativeEvent.changedTouches[e.nativeEvent.which].identifier;
                canvasDesignArea.getStage()._handlePointerDown(pointerId, e.nativeEvent, e.x, e.y, canvasDesignArea.getStage());
                canvasDesignArea.getStage()._handlePointerUp(pointerId, e.nativeEvent, true, canvasDesignArea.getStage());
              }

              var mouseX, mouseY;
              if (designAreaModel.isDetailInteractionMode()) {
                mouseX = canvasDesignArea.getMouseX() - designAreaModel.getPaddingHorizontal();
                mouseY = canvasDesignArea.getMouseY() - designAreaModel.getPaddingVertical();
              } else {
                mouseX = canvasDesignArea.getMouseX() / AppConstants.CANVAS_STORYBOARD_SCALE_FACTOR - designAreaModel.getPaddingHorizontal();
                mouseY = canvasDesignArea.getMouseY() / AppConstants.CANVAS_STORYBOARD_SCALE_FACTOR - designAreaModel.getPaddingVertical();
              }
              var pageHalf = mouseX <= designAreaModel.getWidth() / 2 ? 'left' : 'right';
              if (pageHalf === 'left' && designAreaModel.isLeftPageBlocked() || pageHalf === 'right' && designAreaModel.isRightPageBlocked()) {
                NotificationService.addNotification('', MessageService.getMessage('notification.designAreaNotEditable'), 'info', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
                return; // do nothing if dropped on blocked page half
              }


              // handle the correct type of dropped object

              var undoHandle = UndoRedoService.pushModelData(designAreaModel);

              if (droppedObject instanceof FileHandleFactory.getClass()) { // dropped a FileHandle instance?

                var fileHandle = droppedObject;

                if (fileHandle.getMyPhotosPictureId() && fileHandle.getRefCountId() === -1) {
                  PhotoSourcesService.makeAlbumItemFromCloudPicture(fileHandle.getMyPhotosEventId(), fileHandle.getMyPhotosPictureId()).then(function (data) {
                    if (data.refCountId) {
                      var fileHandles = FileHandleService.getFileHandles();
                      var serverFileHandle = FileHandleService.createServerFileHandle(data.refCountId, fileHandle.getFileName(), null, null, fileHandles.indexOf(fileHandle));
                      IpsAlbumService.createExifDataForRefCountId(data.refCountId).then(function (data) {
                        serverFileHandle.setExif(data.exif);
                        serverFileHandle.setMyPhotosPictureId(fileHandle.getMyPhotosPictureId());
                        serverFileHandle.setMyPhotosEventName(data.myPhotosEventName);
                        serverFileHandle.setMyPhotosEventId(fileHandle.getMyPhotosEventId());
                        fileHandle = serverFileHandle;
                        // adding a photo makes the specified design area the new selected one
                        ProjectService.getSelectedDesignArea().setSelected(false);
                        designAreaModel.setSelected(true);
                        FileHandleService.setActiveFilter(FileHandleService.getActiveFilter());

                        DesignAreaService.addImageItemOrReplaceImage(fileHandle, designAreaModel, canvasDesignArea, mouseX, mouseY).then(function ok() {
                          if (project.isStoryBoardView()) {
                            DesignAreaService.applyRandomLayout(designAreaModel, pageHalf);
                          }
                        }).then(undoHandle.resolve);
                      });
                    } else {
                      NotificationService.addNotification('', MessageService.getMessage('notification.photoSources.myPhotos.error', [fileHandle.getFileName()]), 'danger', 5000);
                    }
                  }, function error(data) {
                    $log.error('Cant make AlbumItem from CloudPciture, something went wrong: ', data);
                  });
                } else {
                  // adding a photo makes the specified design area the new selected one
                  ProjectService.getSelectedDesignArea().setSelected(false);
                  designAreaModel.setSelected(true);

                  DesignAreaService.addImageItemOrReplaceImage(fileHandle, designAreaModel, canvasDesignArea, mouseX, mouseY).then(function ok() {

                    if (project.isStoryBoardView()) {
                      DesignAreaService.applyRandomLayout(designAreaModel, pageHalf);
                    }

                  }).then(undoHandle.resolve);
                }

              } else if (droppedObject instanceof TextItemTemplateFactory.getClass()) { // dropped TextItemTemplate instance?

                var textItemTemplate = droppedObject;
                DesignAreaService.addTextItem(textItemTemplate, designAreaModel, mouseX, mouseY, true);

                // apply a random layouts to the design area page half if in storyboard view
                if (project.isStoryBoardView()) {
                  DesignAreaService.applyRandomLayout(designAreaModel, pageHalf);
                } else {
                  undoHandle.resolve();
                }

              } else if (droppedObject instanceof BackgroundItemTemplateFactory.getClass()) {

                DesignAreaService.addTemplateBackgroundItem(droppedObject, designAreaModel, pageHalf);
                undoHandle.resolve();
              }
              else if (droppedObject instanceof ClipartItemTemplateFactory.getClass()) {
                DesignAreaService.addClipartItem(droppedObject, designAreaModel, canvasDesignArea, mouseX, mouseY);
                undoHandle.resolve();
              }

              scope.$emit(EventConstants.DROPPED_ON_DESIGN_AREA, designAreaModel);
            };


            scope.pinch = function ($event) {
              canvasDesignArea.pinchZoom($event);
            };

            scope.addPagePackage = function () {
              // Use the transaction-like mechanism of the undoRedoService to make this action undoable.
              var undoHandle = UndoRedoService.pushProject();
              ProjectService.addPagePackage();

              undoHandle.resolve();
            };

            scope.$on(EventConstants.IMAGE_UPLOAD_FAILED, function uploadFailed(event, fileHandleId) {
              designAreaModel.removeImageItemsByFileHandleId(fileHandleId);
              IndexedDBService.removeImageFile(ProjectService.getProject().getId(), FileHandleService.getFileHandleById(fileHandleId).getFile());
            });

            // We want to remove the watches, if the designArea gets deleted (e.g. project model changed).
            scope.$on('$destroy', function destroy(e) {
              $log.debug('Design Area removed from DOM -> cleaning up', canvasDesignArea);
              canvasDesignArea.cleanUp();
            });

          }); // end $timeout

        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';
  /* global Kinetic */
  /* global createjs */

  angular.module('tatooine').directive('cwButtonBar', [
    '$log', '$timeout', 'AppConstants', 'BaseConfigService', 'ProjectService', 'UndoRedoService', 'DesignAreaService', 'FileHandleService', 'ContextPanelAreaService', 'ImageItemFactory', 'TextItemFactory',
    function ($log, $timeout, AppConstants, BaseConfigService, ProjectService, UndoRedoService, DesignAreaService, FileHandleService, ContextPanelAreaService, ImageItemFactory, TextItemFactory) {
      return {
        scope: {
          designArea: '=designArea'
        },
        restrict: 'A',
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/editorstage/cwButtonBar.html.jsf',
        link: function (scope, element, attrs) {

          // no itemBox ist selected at the start, so we use the watch to get notified when an itembox is selected
          scope.buttonBarActive = false;
          scope.itemBox = null;

          $timeout(function delay() {
            scope.designArea.setButtonBarInitialized(true);
          });

          var deleteWatch = scope.$watch(function watchSelectedItemBoxChange() {
            return scope.designArea.getSelectedItemBox();
          }, function onSelectedItemBoxChanged(newValue, oldValue) {
            scope.itemBox = newValue;
            scope.buttonBarActive = newValue && !newValue.isMouseDown();
            element.css('z-index', scope.buttonBarActive ? '1035' : '-1');

          }, true);


          scope.$on('$destroy', function destroy() {
            deleteWatch();
          });

          scope.getButtonBarOrientation = function () {
            if (scope.itemBox) {
              return scope.itemBox.getButtonBarOrientation();
            }
          };

          scope.getButtonBarArrowPositionCssClass = function () {
            if (!scope.buttonBarActive) {
              return '';
            }

            if (scope.itemBox.getButtonBarOrientation() === 'below') {
              return 'cewe-button-bar-arrow-top';
            }

            if (scope.itemBox.getButtonBarOrientation() === 'above' || scope.itemBox.getButtonBarOrientation() === 'inside') {
              return 'cewe-button-bar-arrow-bottom';
            }
          };

          scope.isAttachedToImageBackgroundItem = function () {
            return scope.designArea.hasImageBackgroundItem(scope.itemBox);
          };

          scope.isAttachedToImageItem = function () {
            return scope.itemBox instanceof ImageItemFactory.getClass(); // true for normal ImageItems and the ones used as backgrounds
          };

          scope.isAttachedToTextItem = function () {
            return scope.itemBox instanceof TextItemFactory.getClass();
          };


          scope.toggleContextPanelArea = function (){
            ContextPanelAreaService.setContextPanelAreaVisible(!ContextPanelAreaService.isContextPanelAreaVisible());
          };

          scope.isPhotoContextPanelAreaAvailable = function () {
            return ContextPanelAreaService.getContextPanelAreaConfigByName('photo-settings').available;
          };

          scope.isTextContextPanelAreaAvailable = function () {
            return ContextPanelAreaService.getContextPanelAreaConfigByName('text-settings').available;
          };

          scope.hasLayerDown = function () {
            if (scope.buttonBarActive) {
              var allItems = scope.designArea.getAllItems(false);
              for (var i = 0; i < allItems.length; i++) {
                if (allItems[i].getLayerIndex() < scope.itemBox.getLayerIndex() && allItems[i].getLayerIndex() >= AppConstants.MIN_UNRESERVED_LAYER_INDEX) {
                  return true;
                }
              }
              return false;
            }
          };

          scope.hasLayerUp = function () {
            if (scope.buttonBarActive) {
              var allItems = scope.designArea.getAllItems(false);
              for (var i = 0; i < allItems.length; i++) {
                if (allItems[i].getLayerIndex() > scope.itemBox.getLayerIndex()) {
                  return true;
                }
              }
              return false;
            }
          };

          scope.decreaseItemBoxLayer = function () {
            UndoRedoService.pushModelData(scope.designArea).resolve();
            scope.designArea.moveLayerDown(scope.itemBox);
            if (scope.itemBox instanceof TextItemFactory.getClass()) {
              scope.itemBox.setSelected(false);
            }
          };

          scope.moveToBottomLayer = function () {
            UndoRedoService.pushModelData(scope.designArea).resolve();
            scope.designArea.moveToBottomLayer(scope.itemBox);
            if (scope.itemBox instanceof TextItemFactory.getClass()) {
              scope.itemBox.setSelected(false);
            }
          };

          scope.increaseItemBoxLayer = function () {
            UndoRedoService.pushModelData(scope.designArea).resolve();
            scope.designArea.moveLayerUp(scope.itemBox);
            if (scope.itemBox instanceof TextItemFactory.getClass()) {
              scope.itemBox.setSelected(false);
            }
          };

          scope.moveToTopLayer = function () {
            UndoRedoService.pushModelData(scope.designArea).resolve();
            scope.designArea.moveToTopLayer(scope.itemBox);
            if (scope.itemBox instanceof TextItemFactory.getClass()) {
              scope.itemBox.setSelected(false);
            }
          };

          scope.deleteItemBox = function () {
            var undoHandle = UndoRedoService.pushModelData(scope.designArea);
            scope.designArea.removeItemBox(scope.itemBox);
            undoHandle.resolve();
          };


          /**
           *
           * @param pageHalf
           */
          scope.setAsBackgroundImage = function (pageHalf) {

            if (!scope.isAttachedToImageItem()) {
              $log.info('Cannot set item box as background since it is not an ImageItem');
              return;
            }
            var fileHandle = FileHandleService.getFileHandleById(scope.itemBox.getFileHandleId());

            var undoHandle = UndoRedoService.pushModelData(scope.designArea);
            DesignAreaService.addImageBackgroundItem(fileHandle, scope.designArea, pageHalf);
            scope.designArea.removeItemBox(scope.itemBox);
            undoHandle.resolve();

          };

          scope.toggleBackgroundDropDownState = function() {
            scope.backgroundDropDownActive = !scope.backgroundDropDownActive;
            if (scope.backgroundDropDownActive) {
              scope.layerDropDownActive = false;
            }
          };

          scope.toggleLayerDropDownState = function() {
            scope.layerDropDownActive = !scope.layerDropDownActive;
            if (scope.layerDropDownActive) {
              scope.backgroundDropDownActive = false;
            }
          };

        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';
  /* global Kinetic */
  /* global createjs */

  angular.module('tatooine').directive('cwTextItemEditBox', [
    '$log', '$timeout', 'Utils', 'AppConstants', 'AppValues', 'DeviceDetectionService', 'ProjectService', 'ProductService', 'FontService', 'MessageService', 'TextItemTemplateFactory',
    function ($log, $timeout, Utils, AppConstants, AppValues, DeviceDetectionService, ProjectService, ProductService, FontService, MessageService, TextItemTemplateFactory) {
      return {
        scope: {
          designArea: '=designArea'
        },
        restrict: 'A',
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/editorstage/cwTextItemEditBox.html.jsf',
        link: function (scope, element, attrs) {

          $timeout(function delay() {
            scope.designArea.setTextItemEditBoxInitialized(true);
          });
          // no TextItem ist selected at the start, so we use the watch to get notified when an TextItem is selected
          scope.textItem = null;
          scope.showEditBox = false;

          element.css('z-index', 1032);
          scope.textAreaContent = null;
          scope.textAreaStyle = null;
          scope.textAreaSettingsStyle = null;
          FontService.getFontColors().then(function (resp) {
            scope.colors = resp;
          });

          scope.$watch(function watchSelectedTextItemChange() {
            var itemBox = scope.designArea.getSelectedItemBox();
            if (scope.designArea.hasTextItem(itemBox)) {  // is it actually a TextItem?
              return itemBox;
            }
          }, function onSelectedTextItemChanged(newValue, oldValue) {
            scope.textItem = newValue;
            if (!newValue) {
              scope.textEditDone(oldValue);
              scope.showEditBox = false;
              return;
            }
            if (oldValue && oldValue.getId() !== newValue.getId()) {
              scope.textEditDone(oldValue);
            }


            scope.textAreaContent = newValue.getText();
            var padding = 10.581 * AppConstants.MM_TO_PX / AppValues.designAreaScale; // 1.0581 mm = 3 pt
            var fontSize = newValue.getFontSize() * 3.527 * AppConstants.MM_TO_PX / AppValues.designAreaScale;
            var verticalAlign = newValue.getVerticalAlign();
            var textAreaWidth = newValue.getWidth() / AppValues.designAreaScale;
            var lineHeight = 1.3;
            var textAreaHeight = newValue.getHeight() / AppValues.designAreaScale;
            var offset = Utils.calculatedOffsetForVerticalAlign(verticalAlign, textAreaWidth, textAreaHeight, padding, newValue.getText(), newValue.getFont().getFamily(), fontSize);

            // we need to find the textarea by tag name, because the id is not yet set in the dom node at this time
            var textAreas = angular.element(element).find('textarea');

            if (newValue.getVerticalAlign() === 'bottom') {
              angular.forEach(textAreas, function (textArea) {
                textArea.scrollTop = textArea.scrollHeight;
              });
            }

            if (newValue.getVerticalAlign() === 'middle' && offset < 0) {
              angular.forEach(textAreas, function (textArea) {
                textArea.scrollTop = -offset;
              });
            }

            if (newValue.getVerticalAlign() === 'top') {
              angular.forEach(textAreas, function (textArea) {
                textArea.scrollTop = 0;
              });
            }

            var textAreaBackgroundColor = newValue.getBackgroundColor();
            if (newValue.getBackgroundColor() === 'none') {
              if (newValue.getText().length === 0) {
                textAreaBackgroundColor = 'rgba(255, 255, 255, .6)';
              } else {
                textAreaBackgroundColor = 'transparent';
              }
            }
            scope.textAreaStyle = {
              'width': textAreaWidth + 'px',
              'height': textAreaHeight + 'px',
              'text-align': newValue.getTextAlign(),
              'color': newValue.getTextColor(),
              'font-weight': newValue.getFontWeight(),
              'font-style': newValue.getFontStyle(),
              'text-decoration': newValue.getTextDecoration(),
              'background-color': textAreaBackgroundColor,
              'font-family': newValue.getFont().getFamily(),
              'font-size': fontSize + 'px',
              'padding-top': Math.max(0, offset) + 'px',
              'line-height': lineHeight,
              'margin': '0',
              'padding-left': padding + 'px',
              'padding-right': padding + 'px',
              'padding-bottom': padding + 'px',
              'overflow': 'hidden',
              'resize': 'none',
              'word-wrap': 'normal',
              'float': 'left',
              'transform': 'rotate(' + newValue.getRotation() + 'deg)'
            };

            if (!oldValue || newValue.getId() !== oldValue.getId()) {
              $timeout(function delay() {
                scope.showEditBox = true;

                $timeout(function delayFocus() {
                  var focusTextarea = element.find('textarea');
                  // can't focus via code on iOS --> needs user interaction for that and calling focus() on iOS results in strange behaviour
                  if (focusTextarea && !DeviceDetectionService.isIosDevice()) {
                    angular.forEach(focusTextarea, function iterateTextareas(textarea) {
                        if (textarea.clientWidth) {
                          textarea.focus();
                        }
                      }
                    );
                  }
                });
              }, 250);
            }

          }, true);


          scope.onWindowResize = function (width, height) {
            if (!scope.textItem) {
              return;
            }
            scope.textAreaStyle.width = scope.textItem.getWidth() / AppValues.designAreaScale + 'px';
            scope.textAreaStyle.height = scope.textItem.getHeight() / AppValues.designAreaScale + 'px';
            scope.textAreaStyle['font-size'] = (scope.textItem.getFontSize() / 1.15 / AppValues.designAreaScale) + 'px';
          };

          scope.onTextAreaContentChanged = function () {
            if (scope.textItem) {
              scope.textItem.setText(scope.textAreaContent);
            }
          };

          scope.textEditDone = function (textItem /*optional*/) {
            var deselectedTextItem = textItem || scope.textItem;
            if (deselectedTextItem) {
              deselectedTextItem.setSelected(false);
              var textArea = angular.element('textInput-itemBox-' + deselectedTextItem.getId());
              if (textArea && !DeviceDetectionService.isIosDevice()) {
                textArea.blur();
              }
              var placeholderText = MessageService.getMessage('project.textItem.placeholderText');
              var deselectedTextItemTemplate = TextItemTemplateFactory.createTextItemTemplate('', placeholderText, deselectedTextItem.getTextAnchor(), deselectedTextItem.getTextColor(), deselectedTextItem.getBackgroundColor(), deselectedTextItem.getFont(), deselectedTextItem.getFontSize(),
                deselectedTextItem.getFontStyle(), deselectedTextItem.getFontWeight(), deselectedTextItem.getTextDecoration(), deselectedTextItem.getPadding(), deselectedTextItem.getVerticalAlign());
              ProjectService.getProject().addUserTextItemTemplate(deselectedTextItemTemplate);
            }
          };
        }
      };
    }
  ])
  ;
})
();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This component visualizes a preview of the book
 *
 * @since 08.12.14
 * @author Sascha Friedrich
 */
(function () {
  'use strict';
  /* global createjs */
  angular.module('tatooine').directive('cwBookPreview', [
    '$log', '$window', '$timeout', '$location', 'AppConstants', 'AppValues', 'BaseConfigService', 'BookPreviewService', 'ProductService', 'MessageService', 'NotificationService', 'UploadService', 'ProjectService', 'AuthenticationService', 'LeaveEditorService',
    function ($log, $window, $timeout, $location, AppConstants, AppValues, BaseConfigService, BookPreviewService, ProductService, MessageService, NotificationService, UploadService, ProjectService, AuthenticationService, LeaveEditorService) {
      return {
        restrict: 'A',
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/bookPreview/cwBookPreview.html.jsf',
        replace: false,
        scope: {},
        link: function preCompile(scope, iElement, iAttrs, controller) {
          var notUploadedNote, confirmDesignNote;

          scope.buttonEnabled = true;

          var previewActiveWatch = scope.$watch(function () {
            return BookPreviewService.isPreviewActive();
          }, function (newValue) {
            scope.previewActive = newValue;
            scope.forShoppingCart = BookPreviewService.isShoppingCartPreview();
            scope.checkBookText = BookPreviewService.isShoppingCartPreview() ? MessageService.getMessage('preview.checkDesign') : '';
            scope.checkBookCaption = MessageService.getMessage('preview.productPreview');
          });


          scope.getPreviewStyling = function () {
            if (!BookPreviewService.isPreviewActive()) {
              return;
            }
            var windowElement = angular.element($window);
            return {
              'height': windowElement.height() + 'px',
              'width': windowElement.width() + 'px',
              'top': -(AppValues.headAreaHeight + 15) + 'px'
            };
          };


          scope.closePreview = function () {
            var pageflipContext = angular.element('#pageflip').pageflip();
            pageflipContext.closePageflip();
            if (notUploadedNote) {
              NotificationService.removeNotification(notUploadedNote);
            }
            if (confirmDesignNote) {
              NotificationService.removeNotification(confirmDesignNote);
            }
            BookPreviewService.setPreviewActive(false);
          };


          scope.previewClicked = function () {
            scope.buttonEnabled = false;

            ProjectService.saveProject(true).then(function () {
                if (ProjectService.getProject().isUserRelated()) {
                  AuthenticationService.ensureUserLoggedIn('loginRegister.session.timeout', null, null, true).then(function loggedIn() {
                    BookPreviewService.setPreviewActive(true, false);
                  }, function notLoggedIn(result) {
                    if (BaseConfigService.isSSOSession() && result === 'sso') {
                      ProjectService.saveCurrentProjectModal('saveStatus.finished.sso.redirectToLogin').then(function () {
                        LeaveEditorService.handleSsoLogin(null, null);
                      });
                    }
                  });
                } else {
                  BookPreviewService.setPreviewActive(true, false);
                }
              }, function saveFailed(failedData) {
                NotificationService.addNotification('', MessageService.getMessage('notification.preview.error'), 'danger', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
              }
            ).finally(function doFinally() {
                scope.buttonEnabled = true;
              });
          };


          scope.$on('$destroy', function destroy() {
            previewActiveWatch();
          });

        }




      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This component visualizes a preview of the book
 *
 * @since 08.12.14
 * @author Sascha Friedrich
 */
(function () {
  'use strict';
  /* global createjs */
  angular.module('tatooine').directive('cwBookPreviewViewer', [
    '$log', '$timeout', '$window', '$interval', 'AppConstants', 'AppValues', 'SafeApply', 'Utils', 'UndoRedoService', 'ProjectService', 'BaseConfigService', 'FileHandleService', 'MessageService', 'ProductService', 'BookPreviewService',
    function ($log, $timeout, $window, $interval, AppConstants, AppValues, SafeApply, Utils, UndoRedoService, ProjectService, BaseConfigService, FileHandleService, MessageService, ProductService, BookPreviewService) {
      return {
        restrict: 'A',
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/bookPreview/cwBookPreviewViewer.html.jsf',
        replace: false,
        scope: {},
        link: function preCompile(scope, iElement, iAttrs, controller) {
          var project = ProjectService.getProject();
          var product = ProductService.getProductById(project.getProductId());

          scope.allUsedImagesUploaded = ProjectService.allUsedImagesUploaded();
          var windowElement = angular.element($window);

          var designAreas = project.getDesignAreas();
          var selectedDesignArea = project.getSelectedDesignArea();
          var daIndex = designAreas.indexOf(selectedDesignArea);
          var coverWidth, coverHeight, pageWidth, pageHeight, marginTop, marginSide;
          coverWidth = Math.round(designAreas[0].getWidth() / 2 + (designAreas[0].getSpineWidth() / 2) * AppConstants.MM_TO_PX);
          coverHeight = Math.round(designAreas[0].getHeight());
          pageWidth = Math.round(designAreas[1].getWidth() / 2);
          pageHeight = Math.round(designAreas[1].getHeight());
          var maxCoverWidth, maxCoverHeight, maxPageWidth, maxPageHeight, coverRatio, pageRatio;
          if (pageWidth > pageHeight) {
            maxCoverWidth = parseInt((windowElement.width() - 200) / 2, 10);
            maxPageWidth = maxCoverWidth;
            coverRatio = coverWidth / coverHeight;
            pageRatio = pageWidth / pageHeight;
            maxCoverHeight = maxCoverWidth / coverRatio;
            maxPageHeight = maxPageWidth / pageRatio;
            marginTop = parseInt(((windowElement.height() - maxCoverHeight) / 2), 10);
            marginSide = parseInt((windowElement.width() - maxCoverWidth * 2) / 2, 10);
          } else {
            var maxHeightGap = pageWidth === pageHeight ? 280 : 140;
            maxCoverHeight = parseInt((windowElement.height() - maxHeightGap), 10);
            maxPageHeight = maxCoverHeight;
            coverRatio = coverHeight / coverWidth;
            pageRatio = pageHeight / pageWidth;
            maxCoverWidth = maxCoverHeight / coverRatio;
            maxPageWidth = maxPageHeight / pageRatio;
            marginTop = 20;
            marginSide = parseInt((windowElement.width() - maxCoverWidth * 2) / 2, 10);
          }

          maxCoverWidth = parseInt(maxCoverWidth, 10);
          maxCoverHeight = parseInt(maxCoverHeight, 10);
          maxPageWidth = parseInt(maxPageWidth, 10);
          maxPageHeight = parseInt(maxPageHeight, 10);

          var getNotYetUploadedPageUrl = function (forCover) {
            var canvas = document.createElement('canvas');
            canvas.width = forCover ? coverWidth : pageWidth;
            canvas.height = forCover ? coverHeight : pageHeight;
            var stage = new createjs.Stage(canvas);

            var whiteBackground = new createjs.Shape();
            whiteBackground.graphics.beginFill('#FFFFFF').drawRect(0, 0, forCover ? maxCoverWidth : maxPageWidth, forCover ? maxCoverHeight : maxPageHeight);
            stage.addChild(whiteBackground);

            var text = new createjs.Text(MessageService.getMessage('preview.notUploadedYet'), 'bold 12px Arial', '#ff7700');
            var textBounds = text.getBounds();
            text.y = canvas.height / 2;
            text.x = canvas.width / 2 - textBounds.width / 2;

            stage.addChild(text);
            stage.update();
            return stage.toDataURL();
          };

          var halfPageDesignAreasWithoutCover = [];
          var randomInt = Utils.getRandomInt(0, 9999);
          var accessCode = ProjectService.getProject().getAccessCode();

          var notYetUploadedInBookPlaceHolder = getNotYetUploadedPageUrl();
          var notYetUploadedCoverPlaceHolder = getNotYetUploadedPageUrl('cover');

          var createHalfDesignAreaPagesWithoutCover = function () {
            halfPageDesignAreasWithoutCover = [];
            for (var i = 1; i < designAreas.length; i++) {
              var allLeftImagesUploaded = ProjectService.allUsedImagesOnDesignAreaUploaded(designAreas[i], 'left');
              var allRightImagesUploaded = ProjectService.allUsedImagesOnDesignAreaUploaded(designAreas[i], 'right');
              halfPageDesignAreasWithoutCover.push({url: allLeftImagesUploaded ? 'photoBookRequest.do?operation=retrieveDoublePagePreview&photoBookId=' + project.getId() + '&doublePageIndex=' + i + '&previewWidth=' + maxPageWidth + '&previewPageHalf=left&accessCode=' + accessCode + '&src=tatooine&rnd=' + randomInt : notYetUploadedInBookPlaceHolder, id: designAreas[i].getId() + 'left', afterUploadUrl: 'photoBookRequest.do?operation=retrieveDoublePagePreview&photoBookId=' + project.getId() + '&doublePageIndex=' + i + '&previewWidth=' + maxPageWidth + '&previewPageHalf=left&accessCode=' + accessCode + '&src=tatooine&rnd=' + randomInt});
              halfPageDesignAreasWithoutCover.push({url: allRightImagesUploaded ? 'photoBookRequest.do?operation=retrieveDoublePagePreview&photoBookId=' + project.getId() + '&doublePageIndex=' + i + '&previewWidth=' + maxPageWidth + '&previewPageHalf=right&accessCode=' + accessCode + '&src=tatooine&rnd=' + randomInt : notYetUploadedInBookPlaceHolder, id: designAreas[i].getId() + 'right', afterUploadUrl: 'photoBookRequest.do?operation=retrieveDoublePagePreview&photoBookId=' + project.getId() + '&doublePageIndex=' + i + '&previewWidth=' + maxPageWidth + '&previewPageHalf=right&accessCode=' + accessCode + '&src=tatooine&rnd=' + randomInt});
            }
          };

          createHalfDesignAreaPagesWithoutCover();

          scope.getFrontCoverUrl = function () {
            if (!ProjectService.allUsedImagesOnDesignAreaUploaded(designAreas[0], 'right')) {
              return notYetUploadedCoverPlaceHolder;
            }
            return 'photoBookRequest.do?operation=retrieveDoublePagePreview&photoBookId=' + project.getId() + '&doublePageIndex=0&previewWidth=' + maxCoverWidth + '&previewPageHalf=right&accessCode=' + accessCode + '&src=tatooine&rnd=' + randomInt;
          };

          scope.getBackCoverUrl = function () {
            if (!ProjectService.allUsedImagesOnDesignAreaUploaded(designAreas[0], 'left')) {
              return notYetUploadedCoverPlaceHolder;
            }
            return 'photoBookRequest.do?operation=retrieveDoublePagePreview&photoBookId=' + project.getId() + '&doublePageIndex=0&previewWidth=' + maxCoverWidth + '&previewPageHalf=left&accessCode=' + accessCode + '&src=tatooine&rnd=' + randomInt;
          };


          var pageflip = angular.element('#pageflip');
          $timeout(function () {
            pageflip.pageflipInit({
              Copyright: AppConstants.PAGEFLIP_COPYRIGHT,
              Key: AppConstants.PAGEFLIP_KEY,
              PageWidth: maxPageWidth,
              PageHeight: maxPageHeight,
              CoverWidth: maxCoverWidth,
              CoverHeight: maxCoverHeight,
              PagerSkip: false,
              ZoomEnabled: false,
              PinchZoom: true,
              Transparency: true,
              MarginTop: marginTop,
              MarginRight: marginSide,
              MarginLeft: marginSide,
              MarginBottom: 60,
              AlwaysOpened: false,
              StartPage: 1,
              AutoFlipLoop: -1,
              CenterSinglePage: true,
              Thumbnails: false,
              ThumbnailsToFront: true,
              ThumbnailsAutoHide: 3000,
              ThumbnailAlwaysCentered: true,
              ThumbnailWidth: 84,
              ThumbnailHeight: 84,
              PreflipArea: 128,
              FullScreenEnabled: false,
              ControlbarFile: '/web/javax.faces.resource/app/tatooine/lib/pageflip/pageflip5_v1.3/common/controlbar_svg.html.jsf',
              AutoFlipInterval: 5000
            });

          });

          var CustomPFEventHandler = {
              onLoad: function (PN) {
                // dont touch this
                var inbook, preFetchBefore, preFetchAfter, preFetchFirstPage;
                if (PN === 1) {
                  inbook = angular.element('#page_' + (PN - 1));
                  inbook.css('background-image', 'url(' + scope.getFrontCoverUrl() + ')');

                  preFetchFirstPage = new Image();
                  preFetchFirstPage.src = ProjectService.allUsedImagesUploaded() ? halfPageDesignAreasWithoutCover[0].afterUploadUrl : halfPageDesignAreasWithoutCover[0].url;
                  // needed for IE:
                  inbook.css('width', maxCoverWidth + 'px');
                  inbook.css('height', maxCoverHeight + 'px');
                }
                else if (PN < halfPageDesignAreasWithoutCover.length + 2) {
                  inbook = angular.element('#page_' + (PN - 1));
                  inbook.css('background-image', ProjectService.allUsedImagesUploaded() ? 'url(' + halfPageDesignAreasWithoutCover[(PN - 2)].afterUploadUrl + ')' : 'url(' + halfPageDesignAreasWithoutCover[(PN - 2)].url + ')');
                  if (halfPageDesignAreasWithoutCover[(PN - 1)]) {
                    preFetchBefore = new Image();
                    preFetchBefore.src = ProjectService.allUsedImagesUploaded() ? halfPageDesignAreasWithoutCover[(PN - 1)].afterUploadUrl : halfPageDesignAreasWithoutCover[(PN - 1)].url;
                  }
                  if (halfPageDesignAreasWithoutCover[(PN)]) {
                    preFetchAfter = new Image();
                    preFetchAfter.src = ProjectService.allUsedImagesUploaded() ? halfPageDesignAreasWithoutCover[(PN)].afterUploadUrl : halfPageDesignAreasWithoutCover[(PN)].url;
                  }
                  // needed for IE:
                  inbook.css('width', maxPageWidth + 'px');
                  inbook.css('height', maxPageHeight + 'px');
                } else {
                  inbook = angular.element('#page_' + (PN - 1));
                  inbook.css('background-image', 'url(' + scope.getBackCoverUrl() + ')');
                  // needed for IE:
                  inbook.css('width', maxCoverWidth + 'px');
                  inbook.css('height', maxCoverHeight + 'px');
                }
              }
            },
            pageflipContext = pageflip.pageflip();
          pageflipContext.setPFEventCallBack(CustomPFEventHandler);

          $timeout(function () {
            var pagerin = angular.element('#pagerin');
            pagerin.attr('disabled', 'disabled');
            if (project.isDetailView() && !BookPreviewService.isShoppingCartPreview()) {
              pageflipContext.gotoPageNumber(daIndex * 2, true);
            }
          }, 1000);

          var watchUploads = scope.$watch(function () {
            return ProjectService.allUsedImagesUploaded();
          }, function (newValue, oldValue) {
            if (newValue === true && oldValue === false) {
              ProjectService.saveProject(true).then(function () {
                scope.allUsedImagesUploaded = true;
                var coverFront = angular.element('#page_0');
                coverFront.css('background-image', 'url(' + scope.getFrontCoverUrl() + ')');
                // needed for IE:
                coverFront.css('width', maxCoverWidth + 'px');
                coverFront.css('height', maxCoverHeight + 'px');
                var coverBack = angular.element('#page_' + (scope.getHalfPageDesignAreas().length + 1));
                coverBack.css('background-image', 'url(' + scope.getBackCoverUrl() + ')');
                // needed for IE:
                coverBack.css('width', maxCoverWidth + 'px');
                coverBack.css('height', maxCoverHeight + 'px');

                for (var i = 0; i < halfPageDesignAreasWithoutCover.length; i++) {
                  var inbook = angular.element('#page_' + (i + 1));
                  inbook.css('background-image', 'url(' + halfPageDesignAreasWithoutCover[i].afterUploadUrl + ')');
                  // needed for IE:
                  inbook.css('width', maxPageWidth + 'px');
                  inbook.css('height', maxPageHeight + 'px');
                }
              });
            }
          });


          scope.getHalfPageDesignAreas = function () {
            return halfPageDesignAreasWithoutCover;
          };

          scope.getDesignAreas = function () {
            var project = ProjectService.getProject();
            return project.getDesignAreas();
          };

          scope.getPageName = function (index) {
            if (index !== 0 && index !== halfPageDesignAreasWithoutCover.length - 1) {
              return MessageService.getMessage('preview.siteParam', [index]);
            }
            return ' ';
          };


          scope.getProjectId = function () {
            var project = ProjectService.getProject();
            return project.getId();
          };

          scope.$on('$destroy', function destroy() {
            watchUploads();
          });

        }




      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Service for bookPreview
 * @author Sascha Friedrich
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('BookPreviewService', [
    '$log', 'ProjectService',
    function ($log, ProjectService) {

      var previewActive = false;
      var shoppingCartPreview = false;

      // definition of the public service functions
      return {

        /**
         * @param {Boolean} previewActiveParameter
         * @param {Boolean} forShoppingCart (optional)
         */
        setPreviewActive: function (previewActiveParameter, forShoppingCart) {
          previewActive = previewActiveParameter;
          if (!previewActiveParameter) {
            shoppingCartPreview = false;
          } else {
            shoppingCartPreview = forShoppingCart;
          }

          // deselect the potentially currently selected item box
          var selectedDesignArea = ProjectService.getProject().getSelectedDesignArea();
          if (selectedDesignArea) {
            selectedDesignArea.deselectAllItems();
          }
        },

        isPreviewActive: function () {
          return previewActive;
        },

        isShoppingCartPreview: function () {
          return shoppingCartPreview;
        }

      };

    }

  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive represents a button to apply certain filter settings on the FileHandles in the photo selection area.
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwFileHandleFilterButton', [
    '$log', 'FileHandleService', 'PhotoSourcesService',
    function ($log, FileHandleService, PhotoSourcesService) {
      return {
        replace: false,
        scope: {
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/files/cwFileHandleFilterButton.html.jsf',
        link: function (scope, element, attrs) {
          scope.flyoutVisible = false;
          scope.toggleFlyout = function () {
            scope.flyoutVisible = !scope.flyoutVisible;
          };

          scope.filterData = {
            filterUsedFileHandles: false,
            filterByFileName: true,
            filterFileName: '',
            filterMyPhotosGeneral: false,
            filterNonCloudPhotos: false,
            filterMyPhotosEvent: {}
          };

          var fileNameWatch = scope.$watch(function watchFileNameChange() {
            return scope.filterData.filterFileName;
          }, function onFileNameChanged(newValue, oldValue) {
            FileHandleService.getFilterCriteria().fileName = scope.filterData.filterByFileName ? scope.filterData.filterFileName : '';
          });

          scope.setFilterUsedFileHandles = function (trueOrFalse) {
            scope.filterData.filterUsedFileHandles = trueOrFalse;
            FileHandleService.getFilterCriteria().maxUsageCount = scope.filterData.filterUsedFileHandles ? 0 : 9999;
          };


          scope.clearFilterFileName = function () {
            scope.filterData.filterFileName = '';
          };


          scope.$on('$destroy', function destroy() {
            fileNameWatch();
          });

        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2016, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive represents a dropDown to apply certain filter settings on the FileHandles in the photo selection area.
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwFileHandleFilterDropDown', [
    '$log', 'FileHandleService', 'PhotoSourcesService', 'MessageService',
    function ($log, FileHandleService, PhotoSourcesService, MessageService) {
      return {
        replace: false,
        scope: {
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/files/cwFileHandleFilterDropDown.html.jsf',
        link: function (scope, element, attrs) {

          scope.dropDownFilterData = {};
          scope.dropDownFilterData.selectedFilterText = '';
          scope.dropDownFilterData.allPhotosText = MessageService.getMessage('photoSources.filter.allPhotos.selection');
          scope.dropDownFilterData.allmyPhotosPhotosText = MessageService.getMessage('photoSources.filter.myPhotos.selection');
          scope.dropDownFilterData.onlyLocalPhotos = MessageService.getMessage('photoSources.filter.myComputerPhotos.selection');
          scope.dropDownFilterData.iconClass = 'cewe-editor-iconset-background-both-brand';
          scope.usedEvents = PhotoSourcesService.getUsedMyPhotosEvents();

          scope.toggleFileHandleFilterDropDownState = function () {
            scope.fileHandleFilterDropDownActive = !scope.fileHandleFilterDropDownActive;
          };

          scope.showAllFileHandles = function () {
            FileHandleService.setActiveFilter('allPhotos');
          };

          scope.showAllMyPhotosFileHandles = function () {
            FileHandleService.setActiveFilter('myPhotos');
          };

          scope.showOnlyLocalPhotos = function () {
            FileHandleService.setActiveFilter('localPhotos');
          };

          scope.setFilterMyPhotosEvent = function (event) {
            FileHandleService.setActiveFilter(event);
          };

          scope.clearFilterFileName = function () {
            scope.filterData.filterFileName = '';
          };


          var usedEventsWatch = scope.$watch(function watchFileNameChange() {
            return PhotoSourcesService.getUsedMyPhotosEvents().length;
          }, function onUsedEventsChanged(newValue, oldValue) {
            scope.usedEvents = PhotoSourcesService.getUsedMyPhotosEvents();
          });


          var filterWatch = scope.$watch(function watchFileNameChange() {
            return FileHandleService.getActiveFilter();
          }, function onUsedEventsChanged(newValue, oldValue) {
            if (newValue && newValue.displayName) {
              scope.dropDownFilterData.selectedFilterText = newValue.displayName;
              scope.dropDownFilterData.iconClass = 'cewe-editor-iconset-cewe-my-photos';
            }
            if (newValue === 'myPhotos') {
              scope.dropDownFilterData.selectedFilterText = MessageService.getMessage('photoSources.filter.myPhotos.selected');
              scope.dropDownFilterData.iconClass = 'cewe-editor-iconset-cewe-my-photos';
            }
            if (newValue === 'localPhotos') {
              scope.dropDownFilterData.selectedFilterText = MessageService.getMessage('photoSources.filter.myComputerPhotos.selected');
              scope.dropDownFilterData.iconClass = 'cewe-editor-iconset-my-computer-brand';
            }
            if (newValue === 'allPhotos') {
              scope.dropDownFilterData.selectedFilterText = MessageService.getMessage('photoSources.filter.allPhotos.selected');
              scope.dropDownFilterData.iconClass = 'cewe-editor-iconset-all-photos-brand';
            }
          });


          scope.$on('$destroy', function destroy() {
          });

        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 *
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwFileHandleThumb', [
    '$log', 'FileHandleService', 'PhotoEffectService', '$compile',
    function ($log, FileHandleService, PhotoEffectService, $compile) {
      return {
        replace: true,
        scope: {
          fileHandle: '=fileHandle',
          maxSize: '@maxSize',
          fitTo: '@fitTo', // 'width' or 'height'
          multiStepDownScaling: '@multiStepDownScaling', // (optional) apply multistep downscaling on thumbnail? --> true of false
          cssMaxHeight: '@cssMaxHeight', // (optional) the thumbnail is created with a max height as specified in the @maxHeight parameter, but if you need to display it at a different size in you frontend you can modify the css height with this parameter
          cssMinWidth: '@cssMinWidth', // (optional)
          cssMinHeight: '@cssMinHeight', // (optional)
          centerImage: '@centerImage', // (optional)
          effect: '=addEffect', // (optional)
          showWaitingIndicator: '@showWaitingIndicator', // (optional) display a waiting indicator while thumbnail is being in creation? default is 'true'
          useAsBackground: '@useAsBackground'
        },
        link: function (scope, element, attrs) {

          var imageInserted = false;

          var watchFileHandleValidity = scope.$watch(function watchValidity() {
            return scope.fileHandle.isValid();
          }, function onValidityChanged(newValue, oldValue) {
            if (newValue === true) {
              element.css('opacity', 1);
            } else {
              element.css('opacity', 0.35);
            }
          });


          function insertImage(imageObj) {

            // we need to clone the content of the provided image data, because in case of a canvas
            // there needs to be a dedicated canvas DOM element for every place the image is meant to be displayed
            var image = document.createElement('canvas');
            image.width = imageObj.data.width;
            image.height = imageObj.data.height;
            image.getContext('2d').drawImage(imageObj.data, 0, 0);


            if (scope.useAsBackground) {
              //this is still under development, might be useful for a better lazyloading experience
              element.attr('data-afkl-lazy-image', image.toDataURL('image/jpg'));
              element.attr('afkl-lazy-image-options', '{\'background\': true}');
              $compile(element.contents())(scope);
              element.removeAttr('data-cw-file-handle-thumb');
              element = $compile(element)(scope);
              element.css('background-size', 'cover');
              element.css('height', scope.cssMaxHeight + 'px');
              element.css('width', imageObj.width * (parseInt(scope.cssMaxHeight, 10) / imageObj.height) + 'px');
              element.css('background-repeat', 'no-repeat');

            } else {
              angular.element(element).html('').append(image);
              var imageElement = angular.element(image);
              if (scope.cssMaxHeight) {
                imageElement.css('max-height', parseInt(scope.cssMaxHeight, 10) + 'px');
                imageElement.css('max-width', (imageObj.width * (parseInt(scope.cssMaxHeight, 10) / imageObj.height)) + 'px');
              }

              if (scope.cssMinWidth) {
                imageElement.css('min-width', scope.cssMinWidth);
              }
              if (scope.cssMinHeight) {
                imageElement.css('min-height', scope.cssMinHeight);
              }
              if (scope.centerImage === 'true') {
                var left = (angular.element(element).width() - imageElement.width()) / 2;
                var top = (angular.element(element).height() - imageElement.height()) / 2;
                imageElement.css('position', 'relative');
                imageElement.css('left', left);
                imageElement.css('top', top);
                element.addClass('cewe-img-rounded');
              } else {
                imageElement.addClass('cewe-img-rounded');
              }
              if (!scope.fileHandle.getFile()) { // in case of a server image we need to set dimensions explicitly
                imageElement.css('width', imageObj.width + 'px');
                imageElement.css('height', imageObj.height + 'px');
                imageElement.css('vertical-align', 'inherit');
              }

              if (scope.effect && scope.effect.effectName !== 'none') {
                PhotoEffectService.addEffectToCanvas(image, scope.effect.effectName);
              }

            }
          }

          // data-ng-drag-data="fileHandle.getId()"
          function insertError(error) {
            imageInserted = false;
            angular.element(element).html('<b>thumb error:(</b>');
          }

          if (imageInserted) {
            return;
          }

          if (!scope.useAsBackground && (!scope.showWaitingIndicator || scope.showWaitingIndicator.toLowerCase() !== 'false')) {
            angular.element(element).html('<div class="cewe-spinner"></div>');
          }

          var applyMultiStepDownScaling = false;
          if (scope.multiStepDownScaling && scope.multiStepDownScaling.toLowerCase() === 'true') {
            applyMultiStepDownScaling = true;
          }
          FileHandleService.getThumbnail(scope.fileHandle.getId(), parseInt(scope.maxSize, 10), scope.fitTo, applyMultiStepDownScaling).then(insertImage, insertError);

          scope.$on('$destroy', function destroy() {
            // TODO clean up directive on destruction
            watchFileHandleValidity();
          });

        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Enables an input[type=file] element for angular.
 */

(function () {
  'use strict';

  angular.module('tatooine').directive('cwFiles', [
    '$log',
    function ($log) {
      return {
        scope: {
          files: '=cwFiles'
        },
        link: function (scope, el, attrs) {
          el.bind('change', function (event) {
            if (!event.target.files.length) {
              return;
            }
            scope.files = event.target.files;
            scope.$apply();
          });
        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 *
 */
var de = de || {};
de.cewecolor = de.cewecolor || {};
(function () {
  'use strict';
  angular.module('tatooine').directive('cwUploader', [
    '$rootScope', '$log', '$http', '$window', '$q', 'SafeApply', 'AppConstants', 'UploadService', 'FileHandleService', 'NotificationService', 'MessageService', 'ProjectService', 'IndexedDBService', 'AuthenticationService', 'OperatorService', 'TrackingService', 'LeaveEditorService',
    function ($rootScope, $log, $http, $window, $q, SafeApply, AppConstants, UploadService, FileHandleService, NotificationService, MessageService, ProjectService, IndexedDBService, AuthenticationService, OperatorService, TrackingService, LeaveEditorService) {

      return {
        scope: {
          auto: '&',
          fromDialog: '=fromDialog'
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/files/cwUploader.html.jsf',

        link: function (scope, el, attrs) {

          if (!scope.auto()) {
            $log.debug('on demand upload enabled');
          } else {
            $log.debug('auto upload enabled');
          }

          if (!scope.fromDialog) {
            TrackingService.trackByContextData(TrackingService.TRACKING_KEY_BUTTONS, 'button.noPhotoSources.local', 'button.noExternalSources.local');
          } else {
            TrackingService.trackByContextData(TrackingService.TRACKING_KEY_BUTTONS, 'button.photoSources.local', 'button.photoSources.local');
          }

          function initHtmlUpload(uploadUrl) {
            var options = {
              url: uploadUrl + '&rcId=true', // we request the refcount id for the uploaded imageItems
              dataType: 'json',
              mimeType: 'application/json', // avoids not well-formed errors in firefox
              acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
              limitMultiFileUploads: 1,
              // Our backend doesn't support this
              // limitConcurrentUploads: 2,
              sequentialUploads: true,
              done: onJqFileUploadDone,
              add: onJqFileUploadAdd,
              progress: uploadProgress,
              //progressall: uploadProgressall,
              fail: onJqFileUploadFail
            };
            var jqInput = el.find('#uploaderInput');
            jqInput.fileupload(options);

            IndexedDBService.resolveJqFileUploadInitialized();
          }

          var numberOfParsedFiles = 0;
          var numberOfUnsupportedFiles = 0;
          var numberOfNewPhotos = 0;

          function onJqFileUploadAdd(e, data) {

            var isUnsupportedFile = false;

            if (data.files[0].type === 'image/tiff') {
              numberOfUnsupportedFiles++;
              isUnsupportedFile = true;
              NotificationService.addNotification(data.files[0].name, MessageService.getMessage('notification.noTiff'), 'danger', AppConstants.NOTIFICATION_UNLIMITED_TIMEOUT);
            }
            if (data.originalFiles.length + FileHandleService.getFileHandles().length >= OperatorService.getDesktopRecommendationLimit() && data.files[0] === data.originalFiles[0] && FileHandleService.getUsedFileHandles() < 10) {
              NotificationService.addTooManyPhotosNotification();
            }

            var parseOptions = {
              // avoid problems with greyscale images
              disableImageHead: true,
              disableExifThumbnail: true
            };


            // is the current image file the last one and does it already exist in the FileHandle repository?
            var isLastFile = (data.files[0] === data.originalFiles[data.originalFiles.length - 1]);
            var fileAlreadyExists = FileHandleService.getFileHandleByHtmlFile(data.files[0]);

            if (isLastFile) {
              if (data.originalFiles.length >= 1 && data.originalFiles.length < OperatorService.getDesktopRecommendationLimit()) {
                var alreadyExistsCounter = 0;
                data.originalFiles.forEach(function (file) {
                  if (FileHandleService.getFileHandleByHtmlFile(file)) {
                    alreadyExistsCounter++;
                    $log.debug('FileHandle already exists.', file.name);
                  }
                });

                numberOfNewPhotos = data.originalFiles.length - alreadyExistsCounter - numberOfUnsupportedFiles;

                // display a notification with the number of newly selected files, if photos weren't from indexedDB
                if (!data.files[0].loadedFromIndexedDB) {
                  var message;
                  if (numberOfNewPhotos <= 0) {
                    message = MessageService.getMessage('notification.noNewPhotosAdded');
                  } else if (numberOfNewPhotos === 1) {
                    message = MessageService.getMessage('notification.oneNewPhotoAdded');
                  } else if (numberOfNewPhotos > 1) {
                    message = MessageService.getMessage('notification.severalNewPhotosAdded', [numberOfNewPhotos]);
                  }

                  NotificationService.addNotification('', message, 'info', 5000);
                }
              }

            }

            if (isLastFile) {
              numberOfUnsupportedFiles = 0;
            }

            if (fileAlreadyExists || isUnsupportedFile) {
              return;
            }

            $window.loadImage.parseMetaData(data.files[0], function (imageData) {
              numberOfParsedFiles++;
              var fileHandle = FileHandleService.createLocalFileHandle(data.files[0], imageData.exif, data.submit.bind(data));
              /*
               Shipt it Day stuff
               var fileUploadData = {
               response: data.response,
               state: data.state,
               submit: data.submit,
               originalFiles: data.originalFiles,
               files: data.files
               };
               fileHandle.setFileUploadData(fileUploadData);*/

              if (isLastFile && numberOfParsedFiles === numberOfNewPhotos) {
                FileHandleService.setActiveFilter('localPhotos');
              }

              if (isLastFile) {
                numberOfParsedFiles = 0;
              }


              if (!fileHandle) {
                return;
              }

              var exifMap = fileHandle.getExifMap();
              if (exifMap) {
                exifMap.processExifDimension = true;
                data.formData = [
                  {
                    name: 'exif',
                    value: JSON.stringify(exifMap)
                  }
                ];
              }

              var promise;
              if (IndexedDBService.isActive() && !data.files[0].loadedFromIndexedDB && ProjectService.getProject() && ProjectService.getProject().getId() > 0) {
                promise = IndexedDBService.putImageFile(ProjectService.getProject().getId(), AuthenticationService.isLoggedIn(), data.files[0]);
              } else {
                promise = $q.when();
              }

              // we have to wait, until the (potential) operation on the indexedDB has finished
              promise.finally(function doFinally() {
                SafeApply.do(function applyAddFileForUpload() {
                  var startUpload = scope.auto() || (OperatorService.isUploadUnusedImagesEnabled() && !IndexedDBService.isActive());
                  UploadService.addFile(fileHandle, data.submit.bind(data), startUpload);
                });
              });

            }, parseOptions);
          }

          function onJqFileUploadDone(e, data) {
            SafeApply.do(function applyFileUploadFinished() {
              var refCountId = data.response().result.IDs[0].rcId;
              UploadService.finishFile(data.files[0], refCountId);
              if (IndexedDBService.isActive() && ProjectService.getProject() && ProjectService.getProject().getId() > 0) {
                IndexedDBService.removeImageFile(ProjectService.getProject().getId(), data.files[0]);
              }
            });
          }

          function uploadProgress(e, data) {
            var fileHandleToUpload = FileHandleService.getFileHandleByHtmlFile(data.files[0]);
            if (fileHandleToUpload) {
              SafeApply.do(function applyUploadedSize() {
                fileHandleToUpload.setUploadedSize(data.loaded);
              });
            }
          }


          function onJqFileUploadFail(e, data) {

            SafeApply.do(function applyFileUploadFailed() {
              var file = data.files[0];
              var successfulRetry = UploadService.retryFile(file);

              if (!successfulRetry) {

                // try to get the error code (this may fail also!)
                var errorObj;
                try {
                  errorObj = angular.fromJson(data.jqXHR.responseText);
                } catch (excp) {
                  errorObj = (data && data.jqXHR && data.jqXHR.responseText) || '-';
                }
                var errorThrown = (data && data.errorThrown) || data;
                var errorMsg = (errorObj && errorObj.message) || errorObj;

                // TODO: IPS-11544: maybe map the error code to an message? (mk)
                var errorCode = errorObj.code || -100;

                // fail because of upload abortion?
                if (errorThrown === 'abort') {
                  return;
                }

                $log.error('Upload error', errorThrown, errorMsg);
              }
            });
          }

          (function requestUploadUrl() {
            var PREPARE_URL = 'do.prepareIpsUpload';
            $http({
              url: PREPARE_URL + '?ut=utrost',
              method: 'GET',
              responseType: 'text'
            }).success(function (data, status, headers, config) {
              $log.debug('Upload url: ' + data);
              initHtmlUpload(data);
            }).error(function (data, status, headers, config) {
              throw new Error('CanT fetch the upload url: ' + data);
            });
          })();
        }
      };
    }
  ]);


})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A factory for FileHandle instances. FileHandles contain the reference to an HTML5 file object along with some other data.
 * @author Frank Bruns (frank.bruns@cewe.de)
 * @author Mart Köhler (mart.koehler@openknowledge.de)
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('FileHandleFactory', [
    '$log', 'AppConstants',
    function ($log, AppConstants) {

      var reDatetime = /^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2}).*$/;

      function exifDegreeToDecimal(degrees, minutes, seconds, direction) {
        var dd = degrees + minutes / 60 + seconds / (60 * 60);

        if (direction === 'S' || direction === 'W') {
          dd = dd * -1;
        } // Don't do anything for N or E
        return dd;
      }

      function FileHandle() {
        // needed because of some ios specific things and so on....
        this.id = null;
        this.refCountId = -1;
        this.usageCount = 0;
        this.rotation = 0;
        this.rating = 0;
        this.file = null;
        this.fileName = '';
        this.width = null;
        this.height = null;
        this.valid = false;
        this.failedTransferAttempts = 0;
        this.transferred = false;
        this.transferToServerFunction = null;
        this.thumnailReady = false;
        this.exifMap = null;
        this.exif = {};
        this.uploadedSize = 0;
        this.fileUploadData = null;
      }


      FileHandle.prototype.getId = function () {
        return this.id.toString();
      };

      FileHandle.prototype.setId = function (id) {
        this.id = id.toString();
      };

      FileHandle.prototype.getRefCountId = function () {
        return this.refCountId;
      };

      FileHandle.prototype.setRefCountId = function (refCountId) {
        this.refCountId = refCountId;
      };

      FileHandle.prototype.setUploadedSize = function (size) {
        this.uploadedSize = parseInt(size, 10);
      };

      FileHandle.prototype.getUploadedSize = function () {
        return this.uploadedSize;
      };

      FileHandle.prototype.executeTransfer = function () {
        this.transferToServerFunction();
      };

      /**
       *
       * @returns {Number} the current rotation of the ToolFrame in degrees
       */
      FileHandle.prototype.getFile = function () {
        return this.file;
      };

      FileHandle.prototype.setFile = function (file) {
        this.file = file;
      };

      FileHandle.prototype.getFileName = function () {
        if (this.fileName === '' && this.getFile()) {
          return this.getFile().name;
        }

        return this.fileName;
      };

      /**
       *
       * @param fileName {String} set the FileHandle's file name
       */
      FileHandle.prototype.setFileName = function (fileName) {
        this.fileName = fileName;
      };

      FileHandle.prototype.getUsageCount = function () {
        return this.usageCount;
      };

      FileHandle.prototype.setUsageCount = function (usageCount) {
        this.usageCount = usageCount;
      };

      FileHandle.prototype.getRotation = function () {
        return this.rotation;
      };

      FileHandle.prototype.setRotation = function (rotation) {
        this.rotation = rotation;
      };

      FileHandle.prototype.getRating = function () {
        return this.rating;
      };

      FileHandle.prototype.setRating = function (rating) {
        this.rating = rating;
      };

      FileHandle.prototype.increaseUsageCount = function () {
        this.usageCount++;
      };

      FileHandle.prototype.decreaseUsageCount = function () {
        this.usageCount--;
        this.usageCount = Math.max(0, this.usageCount);
      };

      FileHandle.prototype.isValid = function () {
        return this.valid && !this.isUploadFailed();
      };

      FileHandle.prototype.setValid = function (valid) {
        this.valid = valid;
      };

      FileHandle.prototype.getFailedTransferAttempts = function () {
        return this.failedTransferAttempts;
      };

      FileHandle.prototype.increaseFailedTransferAttempts = function () {
        this.failedTransferAttempts++;
      };

      FileHandle.prototype.isTransferred = function () {
        return this.transferred;
      };

      FileHandle.prototype.setTransferred = function () {
        this.transferred = true;
      };

      FileHandle.prototype.isUploadFailed = function() {
        return this.failedTransferAttempts >= AppConstants.MAX_UPLOAD_ATTEMPTS;
      };

      FileHandle.prototype.isThumbnailReady = function () {
        return this.thumnailReady;
      };

      FileHandle.prototype.setThumbnailReady = function (trueOrFalse) {
        this.thumnailReady = trueOrFalse;
      };

      FileHandle.prototype.getWidth = function () {
        return this.width || this.getExifWidth();
      };

      FileHandle.prototype.setWidth = function (width) {
        this.width = width;
      };

      FileHandle.prototype.getHeight = function () {
        return this.height || this.getExifHeight();
      };

      FileHandle.prototype.setHeight = function (height) {
        this.height = height;
      };

      FileHandle.prototype.setExif = function (exif) {
        $log.debug(exif);
        this.exif = exif;
        if (this.exif.DateTimeOriginal && !(this.exif.DateTimeOriginal instanceof Date)) {
          this.exif.DateTimeOriginal = new Date(this.exif.DateTimeOriginal);
        }
      };

      FileHandle.prototype.getExifMap = function () {
        return this.exifMap;
      };

      FileHandle.prototype.setExifMap = function (exifMap) {
        this.exifMap = exifMap;
        this.exif = {};

        if (!exifMap) {
          return;
        }

        if (exifMap.get('DateTimeOriginal')) {
          this.exif.DateTimeOriginal = new Date(exifMap.get('DateTimeOriginal').replace(reDatetime, '$2/$3/$1 $4:$5'));
        } else if (exifMap.get('DateTimeDigitized')) {
          this.exif.DateTimeOriginal = new Date(exifMap.get('DateTimeDigitized').replace(reDatetime, '$2/$3/$1 $4:$5'));
        } else if (exifMap.get('DateTime')) {
          this.exif.DateTimeOriginal = new Date(exifMap.get('DateTime').replace(reDatetime, '$2/$3/$1 $4:$5'));
        } else if (this.getFile()) {
          this.exif.DateTimeOriginal = this.getFile().lastModifiedDate;
        } else {
          $log.debug('cant read DateTimeOriginal, DateTimeDigitized or DateTime from exif and found no info in lastModifiedDate', this);
        }

        var exifLatitude = exifMap.get('GPSLatitude');
        if (exifLatitude && Array.isArray(exifLatitude) && exifMap.get('GPSLatitudeRef')) {
          this.exif.GPSLatitude = exifDegreeToDecimal(exifLatitude[0], exifLatitude[1], exifLatitude[2], exifMap.get('GPSLatitudeRef'));
        } else {
          this.exif.GPSLatitude = exifLatitude;
        }

        var exifLongitude = exifMap.get('GPSLongitude');
        if (exifLongitude && Array.isArray(exifLongitude) && exifMap.get('GPSLongitudeRef')) {
          this.exif.GPSLongitude = exifDegreeToDecimal(exifLongitude[0], exifLongitude[1], exifLongitude[2], exifMap.get('GPSLongitudeRef'));
        } else {
          this.exif.GPSLongitude = exifLongitude;
        }

        this.exif.Model = exifMap.get('Model');
        this.exif.Make = exifMap.get('Make');
        this.exif.Orientation = exifMap.get('Orientation');
        this.exif.Width = exifMap.get('PixelXDimension') || exifMap.get('ImageWidth');
        this.exif.Height = exifMap.get('PixelYDimension') || exifMap.get('ImageHeight');
      };


      FileHandle.prototype.getExifWidth = function () {
        return this.exif.Width || 0;
      };

      FileHandle.prototype.getExifHeight = function () {
        return this.exif.Height || 0;
      };

      FileHandle.prototype.getDateTimeOriginal = function () {
        return this.exif.DateTimeOriginal ? this.exif.DateTimeOriginal : undefined;
      };

      FileHandle.prototype.getLatitude = function () {
        return this.exif.GPSLatitude ? this.exif.GPSLatitude : undefined;
      };

      FileHandle.prototype.getLongitude = function () {
        return this.exif.GPSLongitude ? this.exif.GPSLongitude : undefined;
      };

      FileHandle.prototype.getModel = function () {
        return this.exif.Model ? this.exif.Model : undefined;
      };

      FileHandle.prototype.getMake = function () {
        return this.exif.Make ? this.exif.Make : undefined;
      };

      FileHandle.prototype.getExif = function () {
        return this.exif;
      };

      FileHandle.prototype.getExifOrientation = function () {
        return this.exif.Orientation ? this.exif.Orientation : 1;
      };

      FileHandle.prototype.setFileUploadData = function (uploadData) {
        this.fileUploadData = uploadData;
      };

      FileHandle.prototype.getFileUploadData = function () {
        return this.fileUploadData;
      };

      FileHandle.prototype.setMyPhotosPictureId = function (pictureId) {
        this.myPhotosPictureId = pictureId;
      };

      FileHandle.prototype.getMyPhotosPictureId = function () {
        return this.myPhotosPictureId;
      };

      FileHandle.prototype.setMyPhotosEventId = function (cloudEventId) {
        this.myPhotosEventId = cloudEventId;
      };

      FileHandle.prototype.getMyPhotosEventId = function () {
        return this.myPhotosEventId;
      };

      FileHandle.prototype.setMyPhotosEventName = function (cloudEventName) {
        this.myPhotosEventName = cloudEventName;
      };

      FileHandle.prototype.getMyPhotosEventName = function () {
        return this.myPhotosEventName;
      };

      FileHandle.prototype.getFileUploadData = function () {
        return this.fileUploadData;
      };

      FileHandle.prototype.isCloudFileHandle = function () {
        return this.myPhotosPictureId && this.refCountId === -1;
      };


      // definition of the public factory functions
      return {
        createLocalFileHandle: function (file, exifMap, transferToServerFunction) {

          // Safari doesn't support the lastModifiedDate attribute anymore (probably a bug), so check for its existence
          var lastModifiedDate = file.lastModifiedDate ? file.lastModifiedDate.getTime() : '';

          var fileHandle = new FileHandle();
          fileHandle.setId(file.name + lastModifiedDate + file.size);
          fileHandle.setFile(file);
          fileHandle.setExifMap(exifMap);
          fileHandle.transferToServerFunction = transferToServerFunction;

          return fileHandle;
        },

        /**
         *
         * @param {Number} refCountId
         * @param {String} fileName the file name to set for the server FileHandle
         * @param {Number} width the original image width
         * @param {Number} height the original image height
         * @return {FileHandle}
         */
        createServerFileHandle: function (refCountId, fileName, width, height) {

          var fileHandle = new FileHandle();
          fileHandle.setId(refCountId);
          fileHandle.setRefCountId(refCountId);
          fileHandle.setFileName(fileName);
          fileHandle.setWidth(width);
          fileHandle.setHeight(height);
          fileHandle.setTransferred();

          return fileHandle;
        },

        createCloudFileHandle: function (cloudPhoto, eventId) {
          var fileHandle = new FileHandle();
          fileHandle.setMyPhotosPictureId(cloudPhoto.id);
          fileHandle.setId(cloudPhoto.id);
          fileHandle.setFileName(cloudPhoto.name);
          fileHandle.setMyPhotosEventId(eventId);
          return fileHandle;
        },

        getClass: function () {
          return FileHandle;
        },

        getPrototype: function () {
          return new FileHandle();
        }

      };

    }
  ])
  ;


})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';

  angular.module('tatooine').factory('FileHandleRepository', [
    '$log',
    function ($log) {
      var fileHandles = [];


      /**
       * {
       *   <fileHandleId1>: {
       *      <thumbKey1>: thumbnail1,
       *      <thumbKey2>: thumbnail2,
       *      ...
       *    },
       *    <fileHandleId2>: {
       *      ...
       *    }
       */
      var fileHandleThumbs = {};

      /**
       * @type fileHandleId -> {width, height}
       */
      var fileHandleImageDimension = {};

      function createThumbnailKey(maxSize, fitTo, useMultiStepDownSacle) {
        return maxSize + '/' + fitTo + '/' + useMultiStepDownSacle;
      }

      var fileHandleReposity = {

        /**
         *
         * @return {Array} file handles array
         */
        getFileHandles: function () {
          return fileHandles;
        },

        /**
         *
         * @param fileHandleId
         * @return {FileHandle}
         */
        getFileHandle: function (fileHandleId) {
          return fileHandleReposity.getFileHandleById(fileHandleId);
        },

        getFileHandleById: function (id) {
          if (id) {
            for (var i = 0; i < fileHandles.length; i++) {
              if (fileHandles[i].getId() === id.toString()) {
                return fileHandles[i];
              }
            }
          }
        },

        getFileHandleByMyPhotosPictureId: function (id) {
          for (var i = 0; i < fileHandles.length; i++) {
            if (fileHandles[i].getMyPhotosPictureId() && fileHandles[i].getMyPhotosPictureId() === id.toString()) {
              return fileHandles[i];
            }
          }
        },

        getFileHandleByHtmlFile: function (file) {
          for (var i = 0; i < fileHandles.length; i++) {
            var tmpFile = fileHandles[i].getFile();
            if (tmpFile && tmpFile.name === file.name && tmpFile.size === file.size && tmpFile.type === file.type) {
              return fileHandles[i];
            }
          }

        },

        /**
         * Stores the specified FileHandle in the repository.
         * @param fileHandle
         * @returns {boolean}
         */
        putFileHandle: function (fileHandle, index) {
          // TODO IPS-11691: Does it really matter if the fileHandle is already in the repository? Why not just replace it?
          if (fileHandles.indexOf(fileHandle) < 0) {
            if (index || index === 0) {
              fileHandles[index] = fileHandle;
            } else {
              fileHandles.push(fileHandle);
            }
            return true;
          }
          return false;
        },

        /**
         * Removes the corresponding file handle and all its thumbnails.
         *
         * @param fileHandleId
         */
        removeFileHandle: function (fileHandle) {

          if (!fileHandle) {
            return;
          }
          var index = fileHandles.indexOf(fileHandle);
          fileHandles.splice(index, 1);

          var fileHandleIdAsString = fileHandle.getId().toString();
          delete fileHandleThumbs[fileHandleIdAsString];
          delete fileHandleImageDimension[fileHandleIdAsString];
          return index;
        },


        /**
         *
         * @param fileHandleId
         * @param maxSize
         * @param fitTo fit size to 'width' or 'height'
         * @param useMultiStepDownScale
         * @returns {*} the thumbnail or undefined
         */
        getThumbnailForFileHandle: function (fileHandleId, maxSize, fitTo, useMultiStepDownScale) {
          var thumbMap = fileHandleThumbs[fileHandleId.toString()];
          if (!thumbMap) {
            return;
          }

          var key = createThumbnailKey(maxSize, fitTo, useMultiStepDownScale);
          return thumbMap[key];
        },


        /**
         *
         * @param fileHandleId
         * @param maxSize
         * @param fitTo fit size to 'width' or 'height'
         * @param useMultiStepDownScale
         * @param thumbnail
         */
        putThumbnailForFileHandle: function (fileHandleId, maxSize, fitTo, useMultiStepDownScale, thumbnail) {

          if (fileHandles.indexOf(fileHandleReposity.getFileHandleById(fileHandleId)) < 0) {
            throw new Error('Unknown fileHandleId ' + fileHandleId);
          }

          var fileHandleIdAsString = fileHandleId.toString();

          var thumbMap = fileHandleThumbs[fileHandleIdAsString];
          if (!thumbMap) {
            thumbMap = fileHandleThumbs[fileHandleIdAsString] = {};
          }

          var key = createThumbnailKey(maxSize, fitTo, useMultiStepDownScale);
          thumbMap[key] = thumbnail;
        },

        /**
         *
         * @param fileHandleId
         * @returns {Object} the dimension {width, height} or undefined.
         */
        getDimensionForFileHandle: function (fileHandleId) {
          return fileHandleImageDimension[fileHandleId.toString()];
        },

        putDimensionForFileHandle: function (fileHandleId, dimension) {

          var fileHandle = fileHandleReposity.getFileHandleById(fileHandleId);
          if (fileHandles.indexOf(fileHandle) < 0) {
            throw new Error('Unknown fileHandleId ' + fileHandleId);
          }

          // update original image dimensions in the file handle, if they were not set yet
          if (!fileHandle.getWidth() && !fileHandle.getHeight()) {
            fileHandle.setWidth(dimension.width);
            fileHandle.setHeight(dimension.height);
          }

          var fileHandleIdAsString = fileHandleId.toString();
          fileHandleImageDimension[fileHandleIdAsString] = dimension;
        }

      };

      // definition of the public repository functions
      return fileHandleReposity;

    }
  ]);

})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Provides a service for common DesignArea tasks.
 */

(function () {
  'use strict';
  angular.module('tatooine').factory('FileHandleService', [
    '$window', '$log', '$q', '$resource', '$filter', 'AppConstants', 'SafeApply', 'BaseConfigService', 'NotificationService', 'ImagingService', 'MessageService', 'FileHandleFactory', 'FileHandleRepository',
    function ($window, $log, $q, $resource, $filter, AppConstants, SafeApply, BaseConfigService, NotificationService, ImagingService, MessageService, FileHandleFactory, FileHandleRepository) {

      var filter = $filter('filter');

      var activeFilter = 'localPhotos';
      var filterCriteria = {
        maxUsageCount: 9999,
        fileName: '',
        allFileHandles: FileHandleRepository.getFileHandles(),
        localFileHandles: [],
        fileHandlesWithAnyMyPhotosEvent: [],
        fileHandlesWithoutCloudContext: [],
        fileHandlesWithSpecificEventId: []
      };

      // definition of the public service functions
      var fileHandleService = {

        /**
         * @return {Object} the filter criteria object that can be used to changed the filter settings
         */
        getFilterCriteria: function () {
          return filterCriteria;
        },
        /**
         *
         * @param {Array} fileHandles an array of FileHandles to filter
         * @return {Array} an array with filtered FileHandles
         */
        filterFileHandles: function (fileHandles) {
          var filteredFileHandles = filter(fileHandles, function predicateFunction(fileHandle) {
            return fileHandle.getUsageCount() <= fileHandleService.getFilterCriteria().maxUsageCount &&
              (fileHandleService.getFilterCriteria().allFileHandles.indexOf(fileHandle) >= 0 ||
                fileHandleService.getFilterCriteria().fileHandlesWithAnyMyPhotosEvent.indexOf(fileHandle) >= 0 ||
                fileHandleService.getFilterCriteria().localFileHandles.indexOf(fileHandle) >= 0 ||
                fileHandleService.getFilterCriteria().fileHandlesWithSpecificEventId.indexOf(fileHandle) >= 0);
            //fileHandle.getFileName().indexOf(fileHandleService.getFilterCriteria().fileName) >= 0; // &&
          });
          return filteredFileHandles;
        },

        setActiveFilter: function (filterNameOrEvent) {
          activeFilter = filterNameOrEvent;
          $log.debug('here comes the filter or event', filterNameOrEvent);
          if (filterNameOrEvent.id) {
            fileHandleService.getFilterCriteria().allFileHandles = [];
            fileHandleService.getFilterCriteria().fileHandlesWithAnyMyPhotosEvent = [];
            fileHandleService.getFilterCriteria().localFileHandles = [];
            fileHandleService.getFilterCriteria().fileHandlesWithSpecificEventId = fileHandleService.getFileHandlesWithSpecificMyPhotosEventId(filterNameOrEvent.id);
          } else if (filterNameOrEvent === 'myPhotos') {
            fileHandleService.getFilterCriteria().allFileHandles = [];
            fileHandleService.getFilterCriteria().fileHandlesWithAnyMyPhotosEvent = fileHandleService.getFileHandlesWithCloudBackground();
            fileHandleService.getFilterCriteria().localFileHandles = [];
            fileHandleService.getFilterCriteria().fileHandlesWithSpecificEventId = [];
          } else if (filterNameOrEvent === 'localPhotos') {
            fileHandleService.getFilterCriteria().allFileHandles = [];
            fileHandleService.getFilterCriteria().fileHandlesWithAnyMyPhotosEvent = [];
            fileHandleService.getFilterCriteria().localFileHandles = fileHandleService.getLocalFileHandles().concat(fileHandleService.getServerFileHandlesWithoutCloudContext());
            fileHandleService.getFilterCriteria().fileHandlesWithSpecificEventId = [];
          } else if (filterNameOrEvent === 'allPhotos') {
            fileHandleService.getFilterCriteria().allFileHandles = fileHandleService.getFileHandles();
            fileHandleService.getFilterCriteria().fileHandlesWithAnyMyPhotosEvent = [];
            fileHandleService.getFilterCriteria().localFileHandles = [];
            fileHandleService.getFilterCriteria().fileHandlesWithSpecificEventId = [];
          }

        },

        getActiveFilter: function () {
          return activeFilter;
        },

        /**
         *
         * @return {Array} the array of FileHandles
         */
        getFileHandles: function () {
          return FileHandleRepository.getFileHandles();
        },

        getCloudFileHandles: function () {
          var cloudFileHandles = [];
          var fileHandles = FileHandleRepository.getFileHandles();
          fileHandles.forEach(function (fileHandle) {
            if (fileHandle.isCloudFileHandle()) {
              cloudFileHandles.push(fileHandle);
            }
          });
          return cloudFileHandles;
        },

        getServerFileHandlesWithoutCloudContext: function () {
          var serverFileHandles = [];
          var fileHandles = FileHandleRepository.getFileHandles();
          fileHandles.forEach(function (fileHandle) {
            if (fileHandle.getRefCountId() > -1 && !fileHandle.getMyPhotosPictureId()) {
              serverFileHandles.push(fileHandle);
            }
          });
          return serverFileHandles;
        },

        getFileHandlesWithCloudBackground: function () {
          var cloudFileHandles = [];
          var fileHandles = FileHandleRepository.getFileHandles();
          fileHandles.forEach(function (fileHandle) {
            if (fileHandle.getMyPhotosPictureId()) {
              cloudFileHandles.push(fileHandle);
            }
          });
          return cloudFileHandles;
        },

        getLocalFileHandles: function () {
          var localFileHandles = [];
          var fileHandles = FileHandleRepository.getFileHandles();
          fileHandles.forEach(function (fileHandle) {
            if (fileHandle.getFile()) {
              localFileHandles.push(fileHandle);
            }
          });
          return localFileHandles;
        },

        getFileHandlesWithSpecificMyPhotosEventId: function (specificEventId) {
          var fileHandlesWithSpecificMyPhotosEventId = [];
          var fileHandles = FileHandleRepository.getFileHandles();
          fileHandles.forEach(function (fileHandle) {
            if (fileHandle.getMyPhotosEventId() === specificEventId) {
              if (fileHandlesWithSpecificMyPhotosEventId.indexOf(fileHandle) === -1) {
                fileHandlesWithSpecificMyPhotosEventId.push(fileHandle);
              }
            }
          });
          return fileHandlesWithSpecificMyPhotosEventId;
        },

        /**
         *
         * @return {Array} the array of FileHandles
         */
        removeFileHandle: function (fileHandle) {
          return FileHandleRepository.removeFileHandle(fileHandle);
        },


        /**
         * Returns a FileHandle from the underlying repository by the specified id.
         * @param fileHandleId
         * @returns {*FileHandle}
         */
        getFileHandle: function (fileHandleId) {
          return FileHandleRepository.getFileHandle(fileHandleId);
        },

        /**
         * Get the file handle that is considered next to the specified file handle id
         * @param fileHandleId the current FileHandle id
         * @returns {FileHandle} a fileHandle
         */
        getNextFileHandle: function (fileHandleId) {

          var fileHandles = fileHandleService.getFileHandles();

          var currentFileHandle = fileHandleService.getFileHandle(fileHandleId);
          var nextIndex = fileHandles.indexOf(currentFileHandle) + 1;
          if (nextIndex === fileHandles.length) {
            nextIndex = 0;
          }
          return fileHandles[nextIndex];

        },

        /**
         * Get the file handle that is considered previous to the specified file handle id
         * @param fileHandleId
         * @returns {FileHandle} a fileHandle
         */
        getPreviousFileHandle: function (fileHandleId) {
          var fileHandles = fileHandleService.getFileHandles();

          var currentFileHandle = fileHandleService.getFileHandle(fileHandleId);
          var previousIndex = fileHandles.indexOf(currentFileHandle) - 1;
          if (previousIndex === -1) {
            previousIndex = fileHandles.length - 1;
          }
          return fileHandles[previousIndex];
        },

        getFileHandleByHtmlFile: function (file) {
          return FileHandleRepository.getFileHandleByHtmlFile(file);
        },

        getFileNameForId: function (id) {
          var fileHandle = fileHandleService.getFileHandleById(id);

          if (fileHandle.getId() === id && fileHandle.getFile()) {
            return fileHandle.getFile().name;
          }

          return '';
        },

        getFileHandleById: function (refCountId) {
          return FileHandleRepository.getFileHandleById(refCountId);
        },

        /**
         * Returns all FileHandles currently in use (i.e. usage count > 0)
         * @return {Array} all FileHandles currently in use (i.e. usage count > 0)
         */
        getUsedFileHandles: function () {
          var fileHandles = [];

          this.getFileHandles().forEach(function iterateFileHandles(fileHandle) {
            if (fileHandle.getUsageCount() > 0) {
              fileHandles.push(fileHandle);
            }
          });

          return fileHandles;
        },

        getUnusedFileHandles: function () {
          var fileHandles = [];

          this.getFileHandles().forEach(function iterateFileHandles(fileHandle) {
            if (fileHandle.getUsageCount() === 0) {
              fileHandles.push(fileHandle);
            }
          });

          return fileHandles;
        },

        getTransferredClientFileHandles: function () {
          var transferredClientFiles = [];
          fileHandleService.getUsedClientFileHandles().forEach(function iterateUsedClientFiles(fileHandle) {
            if (fileHandle.getFile() && fileHandle.isTransferred()) {
              transferredClientFiles.push(fileHandle);
            }
          });
          return transferredClientFiles;
        },

        getUsedClientFileHandles: function () {
          var usedClientFiles = [];
          fileHandleService.getUsedFileHandles().forEach(function iterateUsedFileHandles(fileHandle) {
            if (fileHandle.getFile()) {
              usedClientFiles.push(fileHandle);
            }
          });
          return usedClientFiles;
        },

        getNumberOfTransferredFilesHandles: function () {
          var result = 0;

          fileHandleService.getUsedFileHandles().forEach(function iterateUsedFileHandles(fileHandle) {
            if (fileHandle.isTransferred()) {
              result++;
            }
          });
          return result;
        },

        /**
         * Creates a FileHandle instance from the given HTML5 file object which is automatically stored
         * in the underlying repository so it can be retrieved using this service elsewhere.
         * @param file
         * @returns {*} the created FileHandle
         */
        createLocalFileHandle: function (file, exifMap, transferToServerFunction) {
          var fileHandle = this.getFileHandleByHtmlFile(file);

          // if fileHandle already exists, return the existing one
          if (fileHandle) {
            return fileHandle;
          }
          fileHandle = FileHandleFactory.createLocalFileHandle(file, exifMap, transferToServerFunction);
          if (!this.isValid(fileHandle)) {
            $log.warn('created fileHandle invalid', fileHandle);
            return;
          }

          FileHandleRepository.putFileHandle(fileHandle);
          return fileHandle;
        },


        /**
         * Creates a FileHandle instance from the given database image id which is automatically stored
         * in the underlying repository so it can be retrieved using this service elsewhere.
         * @param refCountId a database physical picture refcount id from the server side
         * @param fileName the file name to set for the server FileHandle
         * @param {Number} width the original image width
         * @param {Number} height the original image height
         * @param {Number} index the index in the FileHandleRepository
         * @returns {FileHandle} the created FileHandle
         */
        createServerFileHandle: function (refCountId, fileName, width, height, index) {
          var fileHandle = FileHandleRepository.getFileHandleById(refCountId);
          if (fileHandle) {
            return fileHandle;
          }

          fileHandle = FileHandleFactory.createServerFileHandle(refCountId, fileName, width, height);
          // We currently dont need the rotation from the server
          fileHandle.setRotation(0);
          fileHandle.setValid(true);
          FileHandleRepository.putFileHandle(fileHandle, index);

          return fileHandle;
        },


        createCloudFileHandle: function (cloudPhoto, eventId) {
          var fileHandle = FileHandleRepository.getFileHandleById(cloudPhoto.id);
          if (fileHandle) {
            return fileHandle;
          }

          var serverFileHandle = FileHandleRepository.getFileHandleByMyPhotosPictureId(cloudPhoto.id);
          if (serverFileHandle) {
            return serverFileHandle;
          }

          fileHandle = FileHandleFactory.createCloudFileHandle(cloudPhoto, eventId);
          // We currently dont need the rotation from the server
          fileHandle.setRotation(0);
          fileHandle.setValid(true);
          FileHandleRepository.putFileHandle(fileHandle);

          return fileHandle;
        },

        isValid: function (fileHandle) {

          if (fileHandle === undefined) {
            $log.warn('fileHandle undefined');
            return false;
          }

          if (fileHandle.isUploadFailed()) {
            return false;
          }

          if (fileHandle.isValid()) {
            $log.debug('fileHandle already checked for validity');
            return true;
          }

          if (typeof fileHandle.transferToServerFunction !== 'function') {
            $log.warn('The "transferToServerFunction" parameter of the FileHandle is not a callable function.');
            return false;
          }

          var file = fileHandle.getFile();

          if (!file) {
            $log.warn('uploader no file?');
            NotificationService.addNotification('', MessageService.getMessage('notification.noFile'), 'danger', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
            return false;
          }

          if (!this.getFileExtensionRegEx().test(file.name)) {
            $log.debug('extension not supported');
            NotificationService.addNotification(file.name, MessageService.getMessage('notification.wrongExtension'), 'danger', 10000);
            return false;
          }

          if (file.size > this.getMaxFileSize()) {
            $log.debug('The allowed maximum file size is exceeded ', this.getMaxFileSize());
            NotificationService.addNotification(file.name, MessageService.getMessage('notification.maximumFileSizeExceeded', [this.getMaxFileSize() / 1024 / 1024]), 'danger', 10000);
            return false;
          }

          if (file.size <= 0) {
            $log.debug('The given file has no content');
            NotificationService.addNotification('', MessageService.getMessage('notification.fileWithoutContent'), 'danger', 10000);
            return false;
          }

          fileHandle.setValid(true);
          return true;
        },

        getFileExtensionRegEx: function () {
          var fileExtensionsString = '';
          var allowedFileExtensions = BaseConfigService.getUploadConfig().allowedFileExtensions;
          for (var i = 0; i < allowedFileExtensions.length; i++) {
            fileExtensionsString += allowedFileExtensions[i];
            fileExtensionsString += ('|' + allowedFileExtensions[i].toUpperCase());

            if (i < allowedFileExtensions.length - 1) {
              fileExtensionsString += '|';
            }
          }
          return new RegExp('\\.(' + fileExtensionsString + ')$', 'i');
        },

        getMaxFileSize: function () {
          return BaseConfigService.getUploadConfig().maxFileSizeMB * 1024 * 1024;
        },

        /**
         * Gets the thumbnail for the passed fileHandleId. A promise is returned, because the thumbnail might not exists yet and has to be created.
         * It also contains a "waiting on thumbnail" queue if a bunch of requests at the same time want to have the same thumbnail. In this case only
         * the first requests creates the thumbnail and any further requests will wait for the first.
         *
         * @param fileHandleId
         * @param maxSize
         * @param fitTo fit image size to 'width' or 'height'
         * @param useMultiStepDownScaling use multistep downscale algorithm for image downscaling?
         * @returns {promise}
         */
        getThumbnail: function (fileHandleId, maxSize, fitTo, useMultiStepDownScaling) {
          var fileHandle = FileHandleRepository.getFileHandle(fileHandleId);
          if (!fileHandle) {
            return $q.reject('Unknown fileHandleId ' + fileHandleId);
          }
          var deferred = $q.defer();
          var result;
          if (!fileHandle.getFile()) { // server picture thumbnail

            result = FileHandleRepository.getThumbnailForFileHandle(fileHandleId, maxSize, fitTo, useMultiStepDownScaling);
            if (result) {
              // $log.debug('cache hit thumbnail', fileHandleId);
              if (angular.isArray(result)) {
                // result is an array, that means the thumbnail is currently in creation and we can add our promise in the waiting queue
                result.push(deferred);
              } else {
                // result is a thumbnail, we can resolve the promise
                deferred.resolve(result);
              }
              return deferred.promise;
            }

            var isCloudPhoto = fileHandle.getMyPhotosPictureId() && fileHandle.getRefCountId() === -1;
            return ImagingService.createThumbnailForServerImage(fileHandle, maxSize, fitTo, isCloudPhoto).then(
              function ok(imageObj) {
                /*
                 We've just accessed the image and got the original width/height without any extra effort. We check now, if we have already cached
                 the image dimension or else put that values.
                 */
                // ATTENTION: We don't get the real image size, but the thumbnail size. We assume that is no problem, because currently we use only the aspect ratio.

                FileHandleRepository.putThumbnailForFileHandle(fileHandleId, maxSize, fitTo, useMultiStepDownScaling, imageObj);
                if (!FileHandleRepository.getDimensionForFileHandle(fileHandleId)) {
                  FileHandleRepository.putDimensionForFileHandle(fileHandleId, {
                    width: imageObj.width,
                    height: imageObj.height
                  });
                }

                return imageObj;
              });
          }

          // local HTML5 thumbnail
          result = FileHandleRepository.getThumbnailForFileHandle(fileHandleId, maxSize, fitTo, useMultiStepDownScaling);
          if (result) {
            // $log.debug('cache hit thumbnail', fileHandleId);
            if (angular.isArray(result)) {
              // result is an array, that means the thumbnail is currently in creation and we can add our promise in the waiting queue
              result.push(deferred);
            } else {
              // result is a thumbnail, we can resolve the promise
              deferred.resolve(result);
            }
            return deferred.promise;
          }

          var waitingForThumbnail = [];
          FileHandleRepository.putThumbnailForFileHandle(fileHandleId, maxSize, fitTo, useMultiStepDownScaling, waitingForThumbnail);

          ImagingService.createCanvasThumbnail(fileHandle, maxSize, fitTo, useMultiStepDownScaling).then(
            function ok(imageObj) {
              FileHandleRepository.putThumbnailForFileHandle(fileHandleId, maxSize, fitTo, useMultiStepDownScaling, imageObj);
              /*
               We've just accessed the image and got the original width/height without any extra effort. We check now, if we have already cached
               the image dimension or else put that values.
               */
              var swapDimensions = fileHandle && (fileHandle.getRotation() === 90 || fileHandle.getRotation() === 270);
              if (!FileHandleRepository.getDimensionForFileHandle(fileHandleId)) {
                FileHandleRepository.putDimensionForFileHandle(fileHandleId, {
                  width: swapDimensions ? imageObj.srcHeight : imageObj.srcWidth,
                  height: swapDimensions ? imageObj.srcWidth : imageObj.srcHeight
                });
              }

              deferred.resolve(imageObj);
              // resolve the promises in the waiting queue (if any)
              waitingForThumbnail.forEach(function iterPromises(promise) {
                promise.resolve(imageObj);
              });
            },
            function error(err) {
              deferred.reject(err);
            });

          return deferred.promise;
        },

        /**
         * Gets a promise, that returns the image dimension of the passed file handle.
         *
         * @param fileHandleId
         * @return {promise} with {width, height} param
         */
        getImageDimension: function (fileHandleId) {
          var fileHandle = FileHandleRepository.getFileHandle(fileHandleId);
          if (!fileHandle) {
            return $q.reject('Unknown fileHandleId ' + fileHandleId);
          }

          var dimension = FileHandleRepository.getDimensionForFileHandle(fileHandleId);
          if (dimension) {
            // $log.log('cache hit dimension', fileHandleId);
            return $q.when(dimension);
          }


          var promise;
          if (!fileHandle.getFile()) {
            promise = ImagingService.readImageDimensionsForServerImage(fileHandle);
          } else {
            promise = ImagingService.readImageDimensionsForHtml5File(fileHandle);
          }

          return promise.then(
            function ok(dimension) {
              FileHandleRepository.putDimensionForFileHandle(fileHandleId, dimension);
              return dimension;
            });
        },

        createFileHandleThumbKey: function (fileHandleId, targetSize) {
          var fileHandle = fileHandleService.getFileHandle(fileHandleId);
          var thumbnailKey = {
            multiStepDownScaling: false,
            originalWidth: fileHandle.getWidth(),
            originalHeight: fileHandle.getHeight()
          };

          return fileHandleService.getImageDimension(fileHandleId)
            .then(function (dimensions) {
              if (thumbnailKey.originalWidth === 0 || thumbnailKey.originalHeight === 0) {
                thumbnailKey.originalWidth = dimensions.width;
                thumbnailKey.originalHeight = dimensions.height;
              }
              // adapt image dimensions to target size
              if (dimensions.width >= dimensions.height) {
                thumbnailKey.width = targetSize;
                thumbnailKey.height = targetSize * (dimensions.height / dimensions.width);
              } else {
                thumbnailKey.width = targetSize * (dimensions.width / dimensions.height);
                thumbnailKey.height = targetSize;
              }

              return thumbnailKey;
            }, function (error) {
              $log.error('Failed to create thumbnail key for fileHandleId: ' + fileHandleId, error);
            });
        },

        /**
         * Examines the given project and updates the usage counts of the project's file handles in the data model.
         * @param project the project to examine for file handle usages
         */
        updateFileHandleUsageCounts: function (project) {

          var counter = {};
          project.getDesignAreas().forEach(function iterDesignAreas(designArea) {
            designArea.getImageBackgroundItems().concat(designArea.getImageItems()).forEach(function iterImageItems(image) {
              if (counter[image.getFileHandleId()]) {
                counter[image.getFileHandleId()]++;
              } else {
                counter[image.getFileHandleId()] = 1;
              }
            });
          });
          var fileHandles = fileHandleService.getFileHandles();
          fileHandles.forEach(function iterateFileHandles(fileHandle) {
            if (counter[fileHandle.getId()]) {
              fileHandle.setUsageCount(counter[fileHandle.getId()]);
            } else {
              fileHandle.setUsageCount(0);
            }
          });
        },

        /**
         *
         * @return {Number} number of all FileHandles
         */
        getFileHandlesCount: function () {
          return fileHandleService.getFileHandles().length;
        },

        /**
         *
         * @return {Number} the number of visible FileHandles
         */
        getVisibleFileHandlesCount: function () {
          return fileHandleService.getVisibleFileHandles().length;
        }
      };

      return fileHandleService;
    }
  ])
  ;
})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A service providing low level image operations. You should not use this service directly to get a thumbnail from a file handle. Use the FileHandleService instead.
 */
(function () {
  'use strict';

  angular.module('tatooine').factory('ImagingService', [
    '$q', '$log', '$window', 'SafeApply', 'QueueFactory', 'PhotoSourcesService',
    function ($q, $log, $window, SafeApply, QueueFactory, PhotoSourcesService) {
      var URL = $window.URL || $window.webkitURL;
      var queue = QueueFactory.newQueue();
      // downscalefactor 2 means that the image sides are 'halfed' for every call of this method
      var downscaleFactor = 2;


      /**
       * Multistep downscaling method; calls itself recursively until a minimum width/height is reached
       */
      var multiStepDownscaling = function multiStepDownscaling(source) {
        var canvas = document.createElement('canvas');
        canvas.width = source.width / downscaleFactor;
        canvas.height = source.height / downscaleFactor;
        canvas.getContext('2d').drawImage(source, 0, 0, canvas.width, canvas.height);
        return canvas;
      };

      // worker function
      /**
       *
       * @param next
       * @param deferred
       * @param fileHandle
       * @param maxSize max image size to fit to
       * @param fitTo fit the image size to 'width' or 'height'
       * @param multiStepDownScale use multistep downscale algorithm for creating the image?
       */
      function createCanvasUrlWorker(next, deferred, fileHandle, maxSize, fitTo, multiStepDownScale) {
        var objUrl = URL.createObjectURL(fileHandle.getFile());
        var image = new Image();

        // when the image is fully loaded
        function onLoad() {

          /*console.time('worker');*/
          // determine target image dimensions
          var targetWidth = image.width;
          var targetHeight = image.height;

          var exifOrientation = fileHandle.getExifOrientation();
          // these exif rotations represent 90 or 270 degrees
          var swapDimensions = exifOrientation === 5 || exifOrientation === 6 || exifOrientation === 7 || exifOrientation === 8;

          if (swapDimensions && fitTo === 'width') {
            fitTo = 'height';
          } else if (swapDimensions && fitTo === 'height') {
            fitTo = 'width';
          }

          if (fitTo === 'width') {

            targetHeight *= maxSize / targetWidth;
            targetWidth = maxSize;

          } else if (fitTo === 'height') {

            targetWidth *= maxSize / targetHeight;
            targetHeight = maxSize;

          }

          // multistep downscaling improves image quality
          // IPS-11544: removed scaling for photoselection, because it increases the processing time
          if (multiStepDownScale) {
            //console.time(file.name);
            var downScaledTargetWidth = targetWidth * downscaleFactor;
            var downScaledTargetHeight = targetHeight * downscaleFactor;
            do {
              image = multiStepDownscaling(image);
            } while (image.width > downScaledTargetWidth || image.height > downScaledTargetHeight);
            //console.timeEnd(file.name);
          }

          var canvas = document.createElement('canvas');
          var context2d = canvas.getContext('2d');
          var fillColor = 'white'; // background color to remove transparency

          if (exifOrientation === 3 || exifOrientation === 4) {
            fileHandle.setRotation(180);
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            context2d.fillStyle = fillColor;
            context2d.fillRect(0, 0, canvas.width, canvas.height);
            context2d.rotate(Math.PI);
            context2d.drawImage(image, -targetWidth, -targetHeight, targetWidth, targetHeight);
          } else if (exifOrientation === 5 || exifOrientation === 6) {
            fileHandle.setRotation(90);
            canvas.width = targetHeight;
            canvas.height = targetWidth;
            context2d.fillStyle = fillColor;
            context2d.fillRect(0, 0, canvas.width, canvas.height);
            context2d.rotate(Math.PI / 2);
            context2d.drawImage(image, 0, -targetHeight, targetWidth, targetHeight);
          } else if (exifOrientation === 7 || exifOrientation === 8) {
            fileHandle.setRotation(270);
            canvas.width = targetHeight;
            canvas.height = targetWidth;
            context2d.fillStyle = fillColor;
            context2d.fillRect(0, 0, canvas.width, canvas.height);
            context2d.rotate(-Math.PI / 2);
            context2d.drawImage(image, -targetWidth, 0, targetWidth, targetHeight);
          } else {
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            context2d.fillStyle = fillColor;
            context2d.fillRect(0, 0, canvas.width, canvas.height);
            context2d.drawImage(image, 0, 0, targetWidth, targetHeight);
          }

          SafeApply.do(function applyCanvasImageRetrieved() {

            var imageObj = {
              data: canvas,
              width: targetWidth,
              height: targetHeight,
              srcWidth: image.width,
              srcHeight: image.height
            };
            fileHandle.setThumbnailReady(true);
            deferred.resolve(imageObj);
          });
          canvas = undefined;
          cleanup();
          next();

        }

        function onError() {
          SafeApply.do(function applyCanvasImageCreationFailed() {
            deferred.reject('Could not create thumbnail for file ' + fileHandle.getFile().name);
          });
          cleanup();

          next();
        }

        function cleanup() {
          angular.element(image).off('load', onLoad);
          angular.element(image).off('error', onError);
          URL.revokeObjectURL(objUrl);
          image = undefined;
          objUrl = undefined;
          deferred = undefined;
        }

        angular.element(image).on('load', onLoad);
        angular.element(image).on('error', onError);

        // start loading the image
        image.src = objUrl;
      }

      /**
       * Create the thumbnail URL for the given refCountId.
       * @param {FileHandle} fileHandle a FileHandle
       * @param thumbSize an optional thumbnail size
       * @returns {string}
       */
      function makeThumbnailUrl(fileHandle, thumbWidth, thumbHeight) {
        var sizeParam = 'vga';

        if (thumbWidth > thumbHeight) {
          if (thumbWidth > 640) {
            sizeParam = 'xga';
          }
        } else {
          if (thumbHeight > 480) {
            sizeParam = 'xga';
          }
        }

        return 'do.showPictureCache?type=rc&size=' + sizeParam + '&id=' + fileHandle.getRefCountId() + '&exiftransformed=true&src=tatooine';
      }

      function makeThumbnailUrlFromCloudFileHandle(fileHandle, size) {
        return PhotoSourcesService.getMyPhotosPhoto(fileHandle.getMyPhotosPictureId(), 300);
      }

      function readDimensionFromUrl(imgUrl, revoke, fileHandle) {
        var deferred = $q.defer();

        var image = new Image();

        var swapDimensions = fileHandle && (fileHandle.getRotation() === 90 || fileHandle.getRotation() === 270);

        var onImageLoaded = function () {
          image.removeEventListener('load', onImageLoaded);
          var dimensions = {
            width: swapDimensions ? image.height : image.width,
            height: swapDimensions ? image.width : image.height
          };
          deferred.resolve(dimensions);
          image = undefined;
          deferred = undefined;

          if (revoke) {
            URL.revokeObjectURL(imgUrl);
          }
        };

        image.addEventListener('load', onImageLoaded);

        var onImageError = function () {
          image.removeEventListener('error', onImageError);
          deferred.reject('Could not read dimensions for url ' + imgUrl);
          deferred = undefined;
          image = undefined;
        };

        image.addEventListener('error', onImageError);

        // start image loading
        image.src = imgUrl;
        return deferred.promise;
      }

      // definition of the public service functions
      return {

        /**
         * Reads the image dimensions from the specified HTML5 file.
         * @param file
         * @returns {*} a Promise that returns a dimension object on success
         */
        readImageDimensionsForHtml5File: function (fileHandle) {
          $log.debug('ImagingService.readImageDimensionsForHtml5File: ', fileHandle.getFile().name);
          var objUrl = URL.createObjectURL(fileHandle.getFile());
          return readDimensionFromUrl(objUrl, true, fileHandle);
        },

        /**
         *
         * @param {FileHandle} fileHandle
         * @returns {Promise} with {width, height} obj as first argument.
         */
        readImageDimensionsForServerImage: function (fileHandle) {
          $log.debug('ImagingService.readImageDimensionsForServerImage: ', fileHandle.getRefCountId());
          return readDimensionFromUrl(makeThumbnailUrl(fileHandle), false);
        },


        /**
         * Creates a thumbnail (as a HTML5 canvas) from the specified HTML5 file using the given maximum dimensions.
         * @param fileHandle
         * @param maxSize
         * @param fitTo fit image size to 'width' or 'height'
         * @param multiStepDownScaling use multistep downscaling algorithm for downscaling operation
         * @returns {Object {image, srcWidth, srcHeight} } a Promise that returns an object with the canvas object and the source size on success.
         */
        createCanvasThumbnail: function (fileHandle, maxSize, fitTo, multiStepDownScaling) {

          var deferred = $q.defer();

          queue.addTask(function (next) {
            $log.debug('ImagingService.createCanvasThumbnail: ', fileHandle.getFile().name, maxSize, fitTo, multiStepDownScaling);
            createCanvasUrlWorker(next, deferred, fileHandle, maxSize, fitTo, multiStepDownScaling);
          });
          return deferred.promise;
        },

        /**
         *
         * @param fileHandle
         * @param maxSize
         * @param fitTo fit size to 'width' or 'height'
         * @returns {promiseContainer.promise|*|promise|Q.promise}
         */
        createThumbnailForServerImage: function (fileHandle, maxSize, fitTo, isCloudPhoto) {

          if (!isCloudPhoto) {
            $log.debug('ImagingService.createThumbnailForServerImage: ', fileHandle.getRefCountId());
          } else {
            $log.debug('ImagingService.createThumbnailForMyPhotosImage: ', fileHandle.getMyPhotosPictureId());
          }


          var deferred = $q.defer();

          var image = new Image();

          var onImagedLoaded = function () {

            var targetWidth = image.width;
            var targetHeight = image.height;


            if (fitTo === 'width') {

              targetHeight *= maxSize / targetWidth;
              targetWidth = maxSize;

            } else if (fitTo === 'height') {

              targetWidth *= maxSize / targetHeight;
              targetHeight = maxSize;

            }

            var imageObj = {
              data: image,
              width: targetWidth,
              height: targetHeight,
              srcWidth: fileHandle.getWidth(),
              srcHeight: fileHandle.getHeight()
            };


            var canvasImage = document.createElement('canvas');
            canvasImage.width = targetWidth;
            canvasImage.height = targetHeight;
            canvasImage.getContext('2d').drawImage(imageObj.data, 0, 0, targetWidth, targetHeight);

            imageObj.data = canvasImage;

            fileHandle.setThumbnailReady(true);

            image.removeEventListener('load', onImagedLoaded);
            deferred.resolve(imageObj);
            image = undefined;
            deferred = undefined;
          };

          image.addEventListener('load', onImagedLoaded);

          var onImageError = function () {
            image.removeEventListener('error', onImagedLoaded);
            deferred.reject('Could not load image with refCountId ' + fileHandle.getRefCountId());
            image = undefined;
            deferred = undefined;

          };

          image.addEventListener('error', onImageError);
          var imageUrl;
          if (!isCloudPhoto) {
            imageUrl = makeThumbnailUrl(fileHandle, maxSize, fitTo);
          } else {
            imageUrl = makeThumbnailUrlFromCloudFileHandle(fileHandle, 300);
          }
          // start image loading
          image.src = imageUrl;
          return deferred.promise;
        },

        canvasQueueInProcess: function () {
          return queue.isQueueRunning();
        }
      };
    }

  ])
  ;

})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';

  angular.module('tatooine').factory('UploadService', [
    '$rootScope', '$log', 'AppConstants', 'EventConstants', 'Utils', 'FileHandleService', 'NotificationService', 'MessageService',
    function ($rootScope, $log, AppConstants, EventConstants, Utils, FileHandleService, NotificationService, MessageService) {

      var bitrates = [];
      var maxBitratesForCalculation = 7;
      var uploadSpeedBytesPerSecond;
      var numberOfUploadedFiles = 0;

      function calculateMedian(values) {
        var copiedValues = angular.copy(values);
        copiedValues.sort(function (a, b) {
          return a - b;
        });
        var half = Math.floor(copiedValues.length / 2);
        if (copiedValues.length % 2) {
          return copiedValues[half];
        } else {
          return (copiedValues[half - 1] + copiedValues[half]) / 2.0;
        }
      }

      /**
       * Queue for type FileHandle. It automatically starts the internal QueueWorker if an element is added.
       */
      var UploadQueue = (function () {

        /**
         * The internal UploadQueueWorker gets FileHandles with transfer tasks from
         * the UploadQueue and restarts itself as often as needed to finish the queue.
         */
        var UploadQueueWorker = (function () {
          var isRunning = false;

          // worker private process() should only be called from public run()
          function process() {
            if (UploadQueue.hasTasks()) {
              isRunning = true;

              var fileHandle = UploadQueue.getNextFileHandle();

              if (!fileHandle.isTransferred()) {
                // upload data specific return value of transfer function
                var jqXHR = fileHandle.transferToServerFunction();
                var startTime = new Date().getTime();
                jqXHR.complete(function (result, textStatus, jqXHR) {
                  var endTime = new Date().getTime();
                  var durationInSeconds = (endTime - startTime) / 1000;
                  var fileSize = fileHandle.getFile().size;

                  var bitrate = fileSize * 8 / durationInSeconds;
                  bitrates.push(bitrate);
                  if (bitrates.length > maxBitratesForCalculation) {
                    bitrates.shift();
                  }
                  uploadSpeedBytesPerSecond = calculateMedian(bitrates) / 8;
                  $log.debug('calculated upload speed b/s', uploadSpeedBytesPerSecond);
                  // the absolute only responsibility here is the queue. For anything else (like error handling),
                  // use the callback methods of the service/directive that initially put the tasks into this queue
                  process();
                });
              } else {
                // fileHandle was already transferred, so the next queueEntry can be processed
                process();
              }
            } else {
              isRunning = false;
            }
          }

          // public run() of worker should only be called when something is added to the upload Queue
          return {
            run: function run() {
              if (!isRunning) {
                isRunning = true;
                process();
              }
            }
          };
        })(); // end internal UploadQueueWorker


        /**
         * The uploadQueue is filled with push(), the priorityQueue with pushWithPriority().
         * The queue 'dequeues' with the getNextFileHandle method first from the priorityQueue and only then from the uploadQueue.
         */
        var uploadQueue = [];
        var priorityQueue = [];

        var filesInProgress = [];

        return {
          hasTasks: function hasTasks() {
            return uploadQueue.length !== 0 || priorityQueue.length !== 0;
          },

          getRemainingFileHandles: function () {
            var remainingFileHandles = [];

            filesInProgress.forEach(function iterate(fileHandle) {
              if (!Utils.isInArray(remainingFileHandles, fileHandle)) {
                remainingFileHandles.push(fileHandle);
              }
            });

            priorityQueue.forEach(function iterate(fileHandle) {
              if (!Utils.isInArray(remainingFileHandles, fileHandle)) {
                remainingFileHandles.push(fileHandle);
              }
            });

            uploadQueue.forEach(function iterate(fileHandle) {
              if (!Utils.isInArray(remainingFileHandles, fileHandle)) {
                remainingFileHandles.push(fileHandle);
              }
            });

            return remainingFileHandles;
          },

          getRemainingFileSize: function () {
            var remainingFileHandles = this.getRemainingFileHandles();
            var totalSize = 0;
            remainingFileHandles.forEach(function (fileHandle) {
              totalSize = totalSize + fileHandle.getFile().size - fileHandle.getUploadedSize();
            });
            return totalSize;
          },

          getNextFileHandle: function () {
            var nextFileHandle;
            if (priorityQueue.length > 0) {
              nextFileHandle = priorityQueue.shift();
            } else {
              nextFileHandle = uploadQueue.shift();
            }
            filesInProgress.push(nextFileHandle);
            return nextFileHandle;
          },

          push: function push(fileHandle) {
            if (!fileHandle.isTransferred() && typeof fileHandle.transferToServerFunction === 'function') {
              uploadQueue.push(fileHandle);
              UploadQueueWorker.run();
            }
          },

          pushWithPriority: function pushWithPriority(fileHandle, retryAttempt) {
            if (!fileHandle.isTransferred() && typeof fileHandle.transferToServerFunction === 'function') {
              if (retryAttempt) {
                priorityQueue.unshift(fileHandle);
              } else {
                priorityQueue.push(fileHandle);
              }
              UploadQueueWorker.run();
            }
          },

          uploadFinished: function (fileHandle) {
            // remove file from all arrays it could have potentially been in
            Utils.removeFromArray(filesInProgress, fileHandle);
            Utils.removeFromArray(uploadQueue, fileHandle);
            Utils.removeFromArray(priorityQueue, fileHandle);
          }
        };
      })();


      // definition of the public service functions
      var uploadService = {

        getRemainingFileHandles: function () {
          return UploadQueue.getRemainingFileHandles();
        },

        getRemainingTimeMinutes: function () {
          if (uploadSpeedBytesPerSecond) {
            return Math.ceil(UploadQueue.getRemainingFileSize() / uploadSpeedBytesPerSecond / 60);
          }
          return uploadSpeedBytesPerSecond;
        },

        addFile: function (fileHandle, transferFunction, startUpload) {
          if (fileHandle) {

            if (startUpload) {
              UploadQueue.push(fileHandle);
            }

            // this binds a watcher to the usage count of a fileHandle. When it is used,
            // the fileHandles file should be uploaded
            var unBindUploadServiceFileHandleUsageWatcher = $rootScope.$watch(function watchFileHandleUsageCount() {
              return fileHandle.usageCount;
            }, function onFileHandleUsageCountChanged(newVal, oldVal) {

              if (!fileHandle.isTransferred() && newVal === 1 && oldVal === 0) {
                UploadQueue.pushWithPriority(fileHandle);
              }

              // this could be done in the if clause above, but to be safe we do it separately
              if (fileHandle.isTransferred()) {
                unBindUploadServiceFileHandleUsageWatcher();
              }
            });
          }
        },

        startUpload: function (fileHandle) {
          UploadQueue.push(fileHandle);
        },

        finishFile: function (file, refCountId) {
          var fileHandle = FileHandleService.getFileHandleByHtmlFile(file);
          if (fileHandle) {
            fileHandle.setRefCountId(refCountId);
            fileHandle.setTransferred();
            UploadQueue.uploadFinished(fileHandle);
            numberOfUploadedFiles++;
            $log.debug('file transfer finished for: ', fileHandle);
          } else {
            $log.error('No FileHandle found for transferred file: ', file, refCountId);
          }
        },

        /**
         * Retries to transfer file to server.

         * @return false if all retry attempts were made.
         */
        retryFile: function (file) {

          var fileHandle = FileHandleService.getFileHandleByHtmlFile(file);
          fileHandle.increaseFailedTransferAttempts();
          UploadQueue.uploadFinished(fileHandle);

          if (fileHandle.getFailedTransferAttempts() < AppConstants.MAX_UPLOAD_ATTEMPTS) {
            $log.warn('upload failed, attempt retry for: ', fileHandle);
            fileHandle.setUploadedSize(0);
            UploadQueue.pushWithPriority(fileHandle, true);
            return true;
          }

          // TODO   I think a cleanup is needed here. Images for FileHandles that are broken should be removed from
          // TODO   all designAreas and the customer needs to know which file was broken
          NotificationService.addNotification('', MessageService.getMessage('notification.upload.failed', [fileHandle.getFileName()]),
            'danger', AppConstants.NOTIFICATION_UNLIMITED_TIMEOUT, AppConstants.NOTIFICATION_UNLIMITED_TIMEOUT);
          $log.error('Upload failed. No retries left for file ', fileHandle);

          $rootScope.$broadcast(EventConstants.IMAGE_UPLOAD_FAILED, fileHandle.getId());

          return false;
        },

        getNumberOfUploadedFiles: function () {
          return numberOfUploadedFiles;
        }
      };
      return uploadService;
    }
  ]);
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Provides a service for storing image file in the indexedDB
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('IndexedDBService', [
    '$log', '$window', '$q', '$timeout', 'AppConstants', 'SafeApply', 'UploadService', 'FileHandleService', 'DeviceDetectionService',
    function ($log, $window, $q, $timeout, AppConstants, SafeApply, UploadService, FileHandleService, DeviceDetectionService) {

      var serviceActive = DeviceDetectionService.isBrowserChrome() || DeviceDetectionService.isBrowserIE() || DeviceDetectionService.isBrowserFirefox();

      var checkServiceActive = function () {
        if (!serviceActive) {
          throw 'IndexedDBService is not active!';
        }
      };

      var deactivateService = function (exception) {
        if (serviceActive) {
          $log.error('Deactivating indexedDBService.', exception);
          indexedDBService.removeAllImageFiles();
          serviceActive = false;
        }
      };

      /*
       * Wraps the given function into a try-catch-block.
       * If an exception is thrown, the service will be deactivated.
       */
      var addExceptionHandling = function (thisObject, fn) {
        return function () {
          try {
            return fn.apply(thisObject, arguments);
          } catch (e) {
            deactivateService(e);
          }
        };
      };

      if (serviceActive) {
        var imageStore = new $window.IDBStore({
          storeName: 'Images',
          storePrefix: 'Tatooine-',
          dbVersion: AppConstants.INDEXED_DB_IMAGE_STORE_VERSION,
          keyPath: 'imageFileId',
          autoIncrement: false,
          indexes: [
            {name: 'projectId', keyPath: 'projectId', unique: false, multiEntry: false},
            {name: 'tsAdded', keyPath: 'tsAdded', unique: false, multiEntry: false},
            {name: 'userRelatedProject', keyPath: 'userRelatedProject', unique: false, multiEntry: false}
          ],
          onStoreReady: function () {
            indexedDBService.removeExpiredImageFiles(AppConstants.INDEXED_DB_IMAGE_STORE_EXPIRATION_DAYS, false);
            indexedDBService.removeExpiredImageFiles(AppConstants.INDEXED_DB_IMAGE_STORE_EXPIRATION_ANONYMOUS_DAYS, true);
          },
          onError: function (error) {
            $log.error('Initializing indexedDB failed. Deactivating IndexedDBService.', error);
            deactivateService(error);
          }
        });
      }

      var createImageFileId = function (aProjectId, htmlFile) {
        var lastModifiedSeconds = Math.floor(htmlFile.lastModifiedDate.getTime() / 1000);
        return [aProjectId, htmlFile.name, htmlFile.size, lastModifiedSeconds].join('|');
      };


      // definition of the public service functions
      var indexedDBService = {
        jqFileUploadInitialized: $q.defer(),

        getImageFiles: function (projectId) {
          checkServiceActive();
          var deferred = $q.defer();

          var queryOptions = {index: 'projectId',
            keyRange: imageStore.makeKeyRange({only: projectId}),
            onError: function onError(e) {
              $log.error('getImageFiles failed', projectId, e);
              deactivateService(e);
              deferred.reject(e);
            }};

          imageStore.query(function onSuccess(data) {
            deferred.resolve(data);
          }, queryOptions);
          return deferred.promise;
        },

        putImageFile: function (aProjectId, isUserRelatedProject, htmlFile) {
          var deferred = $q.defer();
          checkServiceActive();
          var newEntry = {imageFileId: createImageFileId(aProjectId, htmlFile), projectId: aProjectId, name: htmlFile.name, size: htmlFile.size, lastModified: htmlFile.lastModifiedDate.getTime(),
            userRelatedProject: (isUserRelatedProject ? 1 : 0), file: htmlFile, tsAdded: new Date().getTime()};
          imageStore.put(newEntry, function onSuccess() {
            $log.debug('Image file successfully put into imageStore.', aProjectId, newEntry);
            deferred.resolve();
          }, function onError(e) {
            $log.error('Putting image file into imageStore failed. Deactivating indexedDBService.', aProjectId, newEntry, e);
            deactivateService(e);
            deferred.reject();
          });
          return deferred.promise;
        },

        putImageFiles: function (aProjectId, isUserRelatedProject, htmlFiles) {
          if (htmlFiles.length < 0) {
            return $q.when();
          }
          var promises = [];
          htmlFiles.forEach(function iterateFiles(htmlFile) {
            promises.push(indexedDBService.putImageFile(aProjectId, isUserRelatedProject, htmlFile));
          });
          return $q.all(promises);
        },

        makeImagesFilesUserRelated: function (aProjectId) {
          $log.debug('Make image files in indexedDB user related.', aProjectId);
          checkServiceActive();
          indexedDBService.getImageFiles(aProjectId).then(function ok(imageFiles) {
            imageFiles.forEach(function (imageFile) {
              if (!imageFile.userRelatedProject) {
                indexedDBService.putImageFile(aProjectId, true, imageFile.file);
              }
            });
          });
        },

        /**
         * Remove the given htmlFile from the IndexedDB
         * @param aProjectId
         * @param htmlFile
         */
        removeImageFile: function (aProjectId, htmlFile) {
          checkServiceActive();
          var imageFileId = createImageFileId(aProjectId, htmlFile);
          imageStore.remove(imageFileId, function onSuccess() {
            $log.debug('Removing image file from imageStore finished.', imageFileId);
          }, function onError(e) {
            $log.error('Removing image file from imageStore failed.', imageFileId, e);
            deactivateService(e);
          });
        },

        removeAllImageFiles: function () {
          try {
            imageStore.clear(function onSuccess() {
              $log.debug('Removing all image files from imageStore finished.');
            }, function onError(e) {
              $log.error('Removing all image files from imageStore failed.');
            });
          } catch (e) {
            $log.error('Error while removing all image files from imageStore.', e);
          }
        },

        removeImageFilesForProject: function (aProjectId) {
          checkServiceActive();
          var queryOptions = {index: 'projectId',
            keyRange: imageStore.makeKeyRange({only: aProjectId}),
            onError: function onError(e) {
              $log.error('Selecting image files for project failed', aProjectId, e);
              deactivateService(e);
            }};
          imageStore.query(function onQuerySuccess(data) {
            var keyArray = [];
            data.forEach(function iterateItems(item) {
              keyArray.push(item.imageFileId);
            });
            if (keyArray.length === 0) {
              $log.debug('No image files for project found.', aProjectId);
              return;
            }
            imageStore.removeBatch(keyArray, function onRemoveSuccess() {
              $log.debug('Batch removal of image file from imageStore finished.', keyArray.length, aProjectId, keyArray);
            }, function onError(e) {
              $log.error('Batch removal of image files from imageStore failed.', keyArray.length, aProjectId, keyArray, e);
              deactivateService(e);
            });
          }, queryOptions);
        },

        removeExpiredImageFiles: function (expirationPeriodDays, keepUserRelatedProjects) {
          checkServiceActive();
          var expirationPeriodMillis = expirationPeriodDays * 24 * 60 * 60 * 1000;
          var maxTsAdded = new Date().getTime() - expirationPeriodMillis;
          var queryOptions = {index: 'tsAdded',
            keyRange: imageStore.makeKeyRange({upper: maxTsAdded}),
            onError: function onError(e) {
              $log.error('Selecting expired image files from imageStore failed', expirationPeriodDays, e);
              deactivateService(e);
            }};
          imageStore.query(function onQuerySuccess(data) {
            var keyArray = [];
            data.forEach(function iterateItems(item) {
              if (!keepUserRelatedProjects || item.userRelatedProject === 0) {
                keyArray.push(item.imageFileId);
              }
            });
            if (keyArray.length === 0) {
              $log.debug('No expired image files found.', expirationPeriodDays, keepUserRelatedProjects);
              return;
            }
            imageStore.removeBatch(keyArray, function onRemoveSuccess() {
              $log.debug(keyArray.length + ' expired image files successfully removed from imageStore.', expirationPeriodDays);
            }, function onError(e) {
              $log.error('Removing expired image files from imageStore failed.', e);
              deactivateService(e);
            });
          }, queryOptions);
        },

        addToFileUpload: function (projectId) {
          this.jqFileUploadInitialized.promise.then(function jqUploadInitialized() {
            checkServiceActive();
            indexedDBService.getImageFiles(projectId).then(function ok(images) {
              if (indexedDBService.isActive()) {
                var htmlFiles = [];
                images.forEach(function iterateImages(image) {
                  image.file.loadedFromIndexedDB = true;
                  htmlFiles.push(image.file);
                });
                if (htmlFiles.length > 0) {
                  var jqInput = angular.element('#uploaderInput');
                  jqInput.fileupload('add', {files: htmlFiles});
                }
              }
            });
          });
        },

        isActive: function () {
          return serviceActive;
        },

        resolveJqFileUploadInitialized: function () {
          this.jqFileUploadInitialized.resolve();
        }

      };

      // add exception handling to all public service functions
      Object.keys(indexedDBService).forEach(function (key) {
        if (typeof indexedDBService[key] === 'function') {
          indexedDBService[key] = addExceptionHandling(indexedDBService, indexedDBService[key]);
        }
      });

      return indexedDBService;
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * @author: Sascha Friedrich
 * Date: 18.12.2015
 */
(function () {
  'use strict';
  /* global Caman */
  angular.module('tatooine').factory('PhotoEffectService', [
    '$q', '$log', '$window', 'SafeApply', '$modal', 'QueueFactory', 'FileHandleService', 'UploadService', 'DesignAreaService', 'ProjectService', 'ImagingService', 'ImageItemFactory',
    function ($q, $log, $window, SafeApply, $modal, QueueFactory, FileHandleService, UploadService, DesignAreaService, ProjectService, ImagingService, ImageItemFactory) {


      var modalProgress;
      var effectStore = {};
      var baseCanvasImages = [];

      var URL = $window.URL || $window.webkitURL;
      var caman = Caman;

      var effects = [
        {
          'ceweName': 'Kein Effekt',
          'effectName': 'none'
        },
// instagram start
        {
          'ceweName': '1977',
          'effectName': '1977'
        },
        {
          'ceweName': 'Brannan',
          'effectName': 'brannan'
        },
        {
          'ceweName': 'Gotham',
          'effectName': 'gotham'
        },
        {
          'ceweName': 'Hefe',
          'effectName': 'hefe'
        },
        {
          'ceweName': 'Nashville',
          'effectName': 'nashville'
        },
        {
          'ceweName': 'Kelvin',
          'effectName': 'lordkelvin'
        },
        {
          'ceweName': 'X-Pro',
          'effectName': 'xpro'
        },
// instagram End
        {
          'ceweName': 'Gradient',
          'effectName': 'BodoMextures_03'
        },
        {
          'ceweName': 'Tatooine Light',
          'effectName': 'BodoMextures_05'
        },
        {
          'ceweName': 'Pink Dream',
          'effectName': 'BodoMextures_06'
        },
        {
          'ceweName': 'Golden Bullseye',
          'effectName': 'BodoMextures_07'
        },
        {
          'ceweName': 'Yellow Lights',
          'effectName': 'BodoMextures_08'
        },
        {
          'ceweName': 'Soft Light',
          'effectName': 'BodoMextures_09'
        },
        {
          'ceweName': 'Fresko',
          'effectName': 'BodoMextures_10'
        },
        {
          'ceweName': 'Golden Shower',
          'effectName': 'BodoMextures_12'
        },
        {
          'ceweName': 'Sunlight',
          'effectName': 'BodoMextures_13'
        },
        {
          'ceweName': 'Dark Focus',
          'effectName': 'BodoMextures_14'
        },
        {
          'ceweName': 'Comic',
          'effectName': 'comic'
        },
        {
          'ceweName': 'Noise',
          'effectName': 'noiseFilter'
        },
// Caman start
        {
          'ceweName': 'Kloor',
          'effectName': 'clarity'
        },
        {
          'ceweName': 'Dweer Process',
          'effectName': 'crossProcess'
        },
        {
          'ceweName': 'Orangehuut',
          'effectName': 'orangePeel'
        },
        {
          'ceweName': 'Blank Suenn',
          'effectName': 'glowingSun'
        },
        {
          'ceweName': 'Suennopgang',
          'effectName': 'sunrise'
        },
        {
          'ceweName': 'hazyDays',
          'effectName': 'hazyDays'
        },
        {
          'ceweName': 'Her Majesty',
          'effectName': 'herMajesty'
        },
        {
          'ceweName': 'Concentrate',
          'effectName': 'concentrate'
        },
        {
          'ceweName': 'Lomo',
          'effectName': 'lomo'
        },
        {
          'ceweName': 'Love',
          'effectName': 'love'
        },
        {
          'ceweName': 'Grungy',
          'effectName': 'grungy'
        },
        {
          'ceweName': 'Jarques',
          'effectName': 'jarques'
        },
        {
          'ceweName': 'Heart',
          'effectName': 'BodoMextures_04'
        },
        {
          'ceweName': 'Old Boot',
          'effectName': 'oldBoot'
        },
        {
          'ceweName': 'Hemingway',
          'effectName': 'hemingway'
        },
        {
          'ceweName': 'Nostalgia',
          'effectName': 'nostalgia'
        },
        {
          'ceweName': 'Vintage',
          'effectName': 'vintage'
        },
        {
          'ceweName': 'Pinhole',
          'effectName': 'pinhole'
        },
        {
          'ceweName': 'Sin City',
          'effectName': 'sinCity'
        }
// Caman end
      ];

      caman.Filter.register('comic', function () {
        this.posterize(4);
        return this;
      });

      caman.Filter.register('noiseFilter', function () {
        this.noise(20);
        return this;
      });

      caman.Filter.register('BodoMextures_03', function () {
        this.newLayer(function () {
          this.setBlendingMode('overlay');
          return this.overlayImage('/web/javax.faces.resource/app/tatooine/images/effects/BodoMextures_03.jpg.jsf');
        });
        return this;
      });
      caman.Filter.register('BodoMextures_04', function () {
        this.newLayer(function () {
          this.setBlendingMode('softLight');
          return this.overlayImage('/web/javax.faces.resource/app/tatooine/images/effects/BodoMextures_04.jpg.jsf');
        });
        return this;
      });
      caman.Filter.register('BodoMextures_05', function () {
        this.newLayer(function () {
          this.setBlendingMode('darken');
          return this.overlayImage('/web/javax.faces.resource/app/tatooine/images/effects/BodoMextures_05.jpg.jsf');
        });
        return this;
      });
      caman.Filter.register('BodoMextures_06', function () {
        this.newLayer(function () {
          this.setBlendingMode('softLight');
          return this.overlayImage('/web/javax.faces.resource/app/tatooine/images/effects/BodoMextures_06.jpg.jsf');
        });
        return this;
      });
      caman.Filter.register('BodoMextures_07', function () {
        this.newLayer(function () {
          this.setBlendingMode('softLight');
          return this.overlayImage('/web/javax.faces.resource/app/tatooine/images/effects/BodoMextures_07.jpg.jsf');
        });
        return this;
      });
      caman.Filter.register('BodoMextures_08', function () {
        this.newLayer(function () {
          this.setBlendingMode('softLight');
          return this.overlayImage('/web/javax.faces.resource/app/tatooine/images/effects/BodoMextures_08.jpg.jsf');
        });
        return this;
      });
      caman.Filter.register('BodoMextures_09', function () {
        this.newLayer(function () {
          this.setBlendingMode('softLight');
          return this.overlayImage('/web/javax.faces.resource/app/tatooine/images/effects/BodoMextures_09.jpg.jsf');
        });
        return this;
      });
      caman.Filter.register('BodoMextures_10', function () {
        this.newLayer(function () {
          this.setBlendingMode('overlay');
          return this.overlayImage('/web/javax.faces.resource/app/tatooine/images/effects/BodoMextures_10.jpg.jsf');
        });
        return this;
      });

      caman.Filter.register('BodoMextures_12', function () {
        this.newLayer(function () {
          this.setBlendingMode('overlay');
          return this.overlayImage('/web/javax.faces.resource/app/tatooine/images/effects/BodoMextures_12.jpg.jsf');
        });
        return this;
      });
      caman.Filter.register('BodoMextures_13', function () {
        this.newLayer(function () {
          this.setBlendingMode('overlay');
          return this.overlayImage('/web/javax.faces.resource/app/tatooine/images/effects/BodoMextures_13.jpg.jsf');
        });
        return this;
      });
      caman.Filter.register('BodoMextures_14', function () {
        this.newLayer(function () {
          this.setBlendingMode('multiply');
          return this.overlayImage('/web/javax.faces.resource/app/tatooine/images/effects/BodoMextures_14.jpg.jsf');
        });
        return this;
      });


      function blobToFile(theBlob, fileName) {
        //A Blob() is almost a File() - it's just missing the two properties below which we will add
        theBlob.lastModifiedDate = new Date();
        theBlob.name = fileName;
        return theBlob;
      }

      function dataURItoBlob(dataURI) {

        var byteString;

        if (dataURI.split(',')[0].indexOf('base64') >= 0) {
          byteString = atob(dataURI.split(',')[1]);
        } else {
          byteString = window.unescape(dataURI.split(',')[1]);

        }
        // separate out the mime component
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

        // write the bytes of the string to a typed array
        var ia = new Uint8Array(byteString.length);

        for (var i = 0; i < byteString.length; i++) {

          ia[i] = byteString.charCodeAt(i);

        }
        return new Blob([ia], {type: mimeString});
      }

      function getSelectedItem() {
        var designArea = ProjectService.getSelectedDesignArea();
        if (designArea) {
          var item = designArea.getSelectedItemBox();
          if (item instanceof ImageItemFactory.getClass()) {
            return item;
          }
        }
      }


      // Listen to all CamanJS instances
      caman.Event.listen('renderFinished', function () {
        if (modalProgress) {
          modalProgress.close();
          modalProgress = undefined;
        }
      });


      // definition of the public service functions
      var photoEffectService = {

        addEffectToCanvasAndStoreOriginalImage: function (canvas, fileHandle, effect) {
          var deferred = $q.defer();
          if (effect === 'none') {
            deferred.resolve(fileHandle);
            return deferred.promise;
          }
          if (fileHandle.getFile()) {
            var objectUrl = URL.createObjectURL(fileHandle.getFile());
            caman(canvas, objectUrl, function () {
              this[effect]();
              var totalJobs = this.renderer.renderQueue.length;
              this.renderer.renderQueue.forEach(function iterateRenderJobs(job, index) {
                job.totalJobs = totalJobs;
                job.index = index;
              });
              this.render(function () {
                var blob = dataURItoBlob(this.toBase64());
                var fileBlob = blobToFile(blob, fileHandle.getFile().name + '_' + effect + '.jpg');
                var uploadData = angular.copy(fileHandle.getFileUploadData());
                uploadData.files[0] = fileBlob;
                uploadData.originalFiles[0] = fileBlob;
                var newFileHandle = FileHandleService.createLocalFileHandle(fileBlob, fileHandle.getExifMap(), uploadData.submit.bind(uploadData));
                var fileUploadData = {
                  response: uploadData.response,
                  state: uploadData.state,
                  submit: uploadData.submit,
                  originalFiles: uploadData.originalFiles,
                  files: uploadData.files
                };
                newFileHandle.setFileUploadData(fileUploadData);
                UploadService.addFile(newFileHandle, newFileHandle.transferToServerFunction, false);

                deferred.resolve(newFileHandle);
              });
            });
          } else {
            deferred.reject('no local file');
            $log.debug(fileHandle);
            var dimensions = ImagingService.readImageDimensionsForServerImage(fileHandle);

            if (modalProgress) {
              modalProgress.close();
              modalProgress = undefined;
            }

          }
          return deferred.promise;
        },


        addEffectToCanvas: function (canvas, effect) {
          $log.debug('addEffectToCanvas FUNCTION', canvas);
          var deferred = $q.defer();
          if (canvas instanceof HTMLCanvasElement) {
            $log.debug('INSTANCE OF HTML CANVAS ELEMENT');
            caman(canvas, function () {
              this.revert();
              this[effect]();
              this.render(function () {
                deferred.resolve(canvas);
              });
            });
          } else {
            $log.debug('no canvas found, maybe a server image?');
            deferred.reject('no canvas');
          }
          return deferred.promise;
        },


        addEffectToServerImage: function (imageObj, effect) {
          var deferred = $q.defer();
          //var tempCanvas = document.createElement('canvas');
          $log.debug(imageObj);
          caman(imageObj.data, function () {
            this.revert();
            this[effect]();
            this.render(function () {
              /*
               tempCanvas.width = imageObj.data.width;
               tempCanvas.height = imageObj.data.height;
               tempCanvas.getContext('2d').drawImage(imageObj.data, 0, 0);
               var img_uri= tempCanvas.toDataURL('image/jpg');
               imageObj.data.src = img_uri;
               */
              deferred.resolve(imageObj);
            });
          });
          return deferred.promise;
        },


        removeEffectFromCanvas: function (canvas) {
          var deferred = $q.defer();
          caman(canvas, function () {
            this.revert();
            this.render(function () {
              deferred.resolve(canvas);
            });
          });
          return deferred.promise;
        },

        getEffects: function () {
          return effects;
        },

        getEffectForFileHandleId: function (fileHandleId) {
          return effectStore[fileHandleId];
        },
        setEffectForFileHandleId: function (fileHandleId, effect) {
          effectStore[fileHandleId] = effect;
        },

        getEffectStore: function () {
          return effectStore;
        },
        clearEffectStore: function () {
          effectStore = {};
        },

        getBaseCanvasImages: function () {
          return baseCanvasImages;
        },

        putBaseCanvasImage: function (baseCanvasImage) {
          baseCanvasImages.push(baseCanvasImage);
        },

        clearBaseCanvasItems: function () {
          baseCanvasImages = [];
        },

        revertBaseCanvasImages: function () {
          var promises = [];
          angular.forEach(baseCanvasImages, function (baseCanvasWithEffect) {
            promises.push(photoEffectService.removeEffectFromCanvas(baseCanvasWithEffect));
          });
          photoEffectService.clearBaseCanvasItems();
          return $q.all(promises);
        },

        getEffectStoreLength: function () {
          var count = 0;
          angular.forEach(effectStore, function (effectName, fileHandleId) {
            count++;
          });
          return count;
        },

        applyEffectsFromEffectStore: function () {
          modalProgress = $modal.open({
            size: 'lg',
            keyboard: false,
            backdrop: 'static',
            templateUrl: 'photoEffectProgressLightbox',
            controller: 'PhotoEffectProgressLightboxController'
          });
          angular.forEach(effectStore, function (effectName, fileHandleId) {
            var baseFileHandle = FileHandleService.getFileHandle(fileHandleId);
            var tempCanvas = document.createElement('canvas');
            photoEffectService.addEffectToCanvasAndStoreOriginalImage(tempCanvas, baseFileHandle, effectName).then(function (newFileHandle) {
              var selectedDesignArea = ProjectService.getProject().getSelectedDesignArea();

              var imageItemsForFileHandleId = selectedDesignArea.getImageItemsForFileHandleId(fileHandleId);

              imageItemsForFileHandleId.forEach(function iterate(imageItem) {
                var centerX = imageItem.getCenterX();
                var centerY = imageItem.getCenterY();
                var width = imageItem.getWidth();
                var height = imageItem.getHeight();
                var viewPort = imageItem.getViewPort();
                var rotation = imageItem.getRotation();
                DesignAreaService.addImageItem(newFileHandle, selectedDesignArea, centerX, centerY).then(function () {
                  var newImageItemForFileId = selectedDesignArea.getImageItemsForFileHandleId(newFileHandle.getId());
                  newImageItemForFileId.setWidth(width);
                  newImageItemForFileId.setHeight(height);
                  newImageItemForFileId.setViewPort(viewPort);
                  newImageItemForFileId.setRotation(rotation);
                  selectedDesignArea.removeItemBox(imageItem);
                });
              });
            });
          });
        }

      };
      return photoEffectService;
    }

  ])
  ;

})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('FontFactory', [
    '$log',
    function ($log) {

      function Font() {
        this.family = null;
      }

      Font.prototype.getFamily = function () {
        return this.family;
      };

      Font.prototype.$$setFamily = function (family) {
        this.family = family;
      };


      return {

        createFont: function (fontFamily) {

          if (fontFamily === null) {
            throw new Error('Can\'t create a font. One or more parameters a missing or invalid.');
          }
          var font = new Font();

          font.$$setFamily(fontFamily);

          return font;
        },

        getPrototype: function () {
          return new Font();
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Provides a service for supported ips fonts.
 */
(function () {
  'use strict';

  angular.module('tatooine').factory('FontService', [
    '$log', '$q', '$resource', '$http', '$cacheFactory', 'FontFactory',
    function ($log, $q, $resource, $http, $cacheFactory, FontFactory) {
      var cacheForServerColors = $cacheFactory('serverColors');

      // definition of the public service functions
      var fontService = {

        getFonts: function () {

          var fontsUrl = 'photobook/fonts.rest';

          $log.debug('Request font from server:' + fontsUrl);

          // since we are expecting an array for the fonts request we need to use this pretty verbose way of $resource stuff
          var FontResource = $resource(fontsUrl, {}, {
            query: {
              method: 'GET',
              isArray: true
            }
          });



          return FontResource.query(function ok(fonts) {

            // make Font class instances of server font objects
            fonts.forEach(function iteratedFont(font) {
              fonts[fonts.indexOf(font)] = angular.extend(FontFactory.getPrototype(), font);
            });

            return fonts;

          }).$promise;

        },

        getFontColors: function () {

          var key = 'fontColors';
          var deferred = $q.defer();
          var cachedFontColors = cacheForServerColors.get(key);

          if (cachedFontColors && cachedFontColors.length >= 0) {
            $log.debug('Retrieved colors from the cache');
            deferred.resolve(cachedFontColors);
          }

          else {
            var colorUrl = 'photobook/fonts/colors.rest';

            $log.debug('Request supported font colors from server:' + colorUrl);

            // we use the lower level http level here because $resource wants an object or an array of objects.
            // but we just want the hex codes (as strings) and no complex objects here
            $http.get(colorUrl).success(function (data) {
              $log.debug('Put colors from server to cache by key:', key);
              cacheForServerColors.put(key, data);
              deferred.resolve(data);
            });
          }
          return deferred.promise;
        }
      };

      return fontService;
    }
  ])
  ;
})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A directive that adds guided tours to the Tatooine editor
 *
 * @since 14.08.2014
 * @author Frank Bruns
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwGuidedTours', [
    '$log', '$window', '$timeout', '$interpolate', 'AppValues', 'AppConstants', 'EventConstants', 'MessageService', 'GuidedTourService', 'ProjectService', 'FileHandleService', 'AuthenticationService', 'localStorageService','BookPreviewService',
    function ($log, $window, $timeout, $interpolate, AppValues, AppConstants, EventConstants, MessageService, GuidedTourService, ProjectService, FileHandleService, AuthenticationService, localStorageService,BookPreviewService) {

      return {
        restrict: 'A',
        scope: {},
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/guidedtours/cwGuidedTours.html.jsf',
        link: function (scope, element, attrs) {

          var tourStepTemplate = '<div class="panel panel-heading h4">{{heading}}</div><div>{{content}}</div>';

          var cssClasses = 'panel panel-default cw-guided-tour-box';
          var overlayOpacity = 0.5;

          var labelBtnNext = MessageService.getMessage('guidedTour.button.nextStep');
          var labelBtnPrevious = MessageService.getMessage('guidedTour.button.previousStep');
          var labelBtnSkip = MessageService.getMessage('guidedTour.button.skipTour');
          var labelBtnDone = MessageService.getMessage('guidedTour.button.tourDone');

          var knowsInitialIntroductionTour = localStorageService.get('initialIntroductionTourDone');
          scope.tourInitialIntroductionDone = knowsInitialIntroductionTour ? knowsInitialIntroductionTour : false;
          scope.onTourInitialIntroductionDone = function () {
            localStorageService.set('initialIntroductionTourDone', true);
            $log.debug('Initial guided tour finished.');
            scope.tourInitialIntroductionDone = true;
          };

          scope.onTourDetailViewDone = function () {
            localStorageService.set('detailViewTourDone', true);
            $log.debug('detailView tour finished.');
          };

          scope.$on('$destroy', function destroy() {
            projectChangedWatch();
          });

          var projectChangedWatch = scope.$watch(function watchProjectChanged() {
            return ProjectService.getProject().getId();
          }, function onProjectIdChanged(newValue, oldValue) {
            if (newValue && oldValue) {
              registerInitialTour();
            }
          });


          var registerInitialTour = function () {
            $timeout(function startDelayed() {
              scope.tourInitialIntroduction = {
                steps: [
                  {
                    intro: $interpolate(tourStepTemplate)({heading: MessageService.getMessage('guidedTour.initialTour.step.welcome.heading'), content: MessageService.getMessage('guidedTour.initialTour.step.welcome.content')}),
                    position: 'bottom'
                  },
                  {
                    element: $window.document.getElementById('buttonAddPhotosToSelection'),
                    intro: $interpolate(tourStepTemplate)({heading: MessageService.getMessage('guidedTour.initialTour.step.addPhotos.heading'), content: MessageService.getMessage('guidedTour.initialTour.step.addPhotos.content')}),
                    position: 'bottom'
                  },
                  {
                    element: $window.document.getElementById('photoSelectionScrollArea'),
                    intro: $interpolate(tourStepTemplate)({heading: MessageService.getMessage('guidedTour.initialTour.step.photoSelectionArea.heading'), content: MessageService.getMessage('guidedTour.initialTour.step.photoSelectionArea.content')}),
                    position: 'bottom'
                  },
                  {
                    element: $window.document.getElementById('designAreasContainer'),
                    intro: $interpolate(tourStepTemplate)({heading: MessageService.getMessage('guidedTour.initialTour.step.usePhotos.heading'), content: MessageService.getMessage('guidedTour.initialTour.step.usePhotos.content')}),
                    position: 'top'
                  }
//                {
//                  element: $window.document.getElementById('buttonAutoFill'),
//                  intro: $interpolate(tourStepTemplate)({heading: MessageService.getMessage('guidedTour.initialTour.step.autoFill.heading'), content: MessageService.getMessage('guidedTour.initialTour.step.autoFill.content')}),
//                  position: 'top'
//                }
                ],
                showStepNumbers: false,
                showBullets: true,
                exitOnOverlayClick: true,
                exitOnEsc: true,
                scrollToElement: false,
                overlayOpacity: overlayOpacity,
                tooltipClass: cssClasses,
                nextLabel: labelBtnNext,
                prevLabel: labelBtnPrevious,
                skipLabel: labelBtnSkip,
                doneLabel: labelBtnDone
              };

              GuidedTourService.registerGuidedTour('initialIntroduction', scope.startTourInitialIntroduction);

              var alreadyKnowsTour = localStorageService.get('initialIntroductionTourDone');
              if (!alreadyKnowsTour && !BookPreviewService.isPreviewActive()) {
                scope.startTourInitialIntroduction();
              }
            }, 1500);
          };

          registerInitialTour();

          var removeWatchTourDetailView = scope.$watch(function watchChangeToDetailView() {
            // initial tour must be finished
            return ProjectService.getProject() && ProjectService.getProject().isDetailView() && ProjectService.getSelectedDesignArea();
          }, function onChangeToDetailView(newValue, oldValue) {
            if (newValue) {
              $timeout(function initTourDelayed() {
                var designArea = ProjectService.getSelectedDesignArea();
                var designAreaToolbarDomId = 'designArea-' + designArea.getId() + '-toolbar-' + (designArea.isRightPageBlocked() ? 'left' : 'right');
                scope.tourDetailView = {
                  steps: [
                    {
                      element: $window.document.getElementById('designArea-' + designArea.getId()),
                      intro: $interpolate(tourStepTemplate)({heading: MessageService.getMessage('guidedTour.detailView.step.designArea.heading'), content: MessageService.getMessage('guidedTour.detailView.step.designArea.content')}),
                      position: 'top'
                    },
                    {
                      element: $window.document.getElementById(designAreaToolbarDomId),
                      intro: $interpolate(tourStepTemplate)({heading: MessageService.getMessage('guidedTour.detailView.step.toolbar.heading'), content: MessageService.getMessage('guidedTour.detailView.step.toolbar.content')}),
                      position: designArea.isRightPageBlocked() ? 'right' : 'left'
                    },
                    {
                      element: $window.document.getElementById('btnUndo'),
                      intro: $interpolate(tourStepTemplate)({heading: MessageService.getMessage('guidedTour.detailView.step.undoRedo.heading'), content: MessageService.getMessage('guidedTour.detailView.step.undoRedo.content')}),
                      position: 'left'
                    },
                    {
                      element: $window.document.getElementById('btnToStoryBoard'),
                      intro: $interpolate(tourStepTemplate)({heading: MessageService.getMessage('guidedTour.detailView.step.btnStoryBoard.heading'), content: MessageService.getMessage('guidedTour.detailView.step.btnStoryBoard.content')}),
                      position: 'right'
                    }
                  ],
                  showStepNumbers: false,
                  showBullets: true,
                  exitOnOverlayClick: true,
                  exitOnEsc: true,
                  scrollToElement: false,
                  overlayOpacity: overlayOpacity,
                  tooltipClass: cssClasses,
                  nextLabel: labelBtnNext,
                  prevLabel: labelBtnPrevious,
                  skipLabel: labelBtnSkip,
                  doneLabel: labelBtnDone
                };

                GuidedTourService.registerGuidedTour('detailView', scope.startTourDetailView);

                $timeout(function startTourDelayed() {
                  var alreadyKnowsTour = localStorageService.get('detailViewTourDone');
                  if (!alreadyKnowsTour && scope.tourInitialIntroductionDone) {
                    scope.startTourDetailView();
                  }
                }, 500);

              });

            }

          });

//          var removeWatchTourAutoFill = scope.$watch(function watchPhotoSelectionItemCount() {
//            // initial tour must be finished and the user should have a certain amount of photos available for the auto-fill to make sense
//            return scope.tourInitialIntroductionDone && FileHandleService.getFileHandlesCount() >= 50;
//          }, function (newValue, oldValue) {
//
//            if (newValue === true) {
//
//              removeWatchTourAutoFill();
//
//              $timeout(function initTourDelayed() {
//
//                scope.tourAutoFill = {
//                  steps: [
//                    {
//                      element: $window.document.getElementById('buttonAutoFill'),
//                      intro: $interpolate(tourStepTemplate)({heading: MessageService.getMessage('guidedTour.autoFill.step.autoFill.heading'), content: MessageService.getMessage('guidedTour.autoFill.step.autoFill.content')}),
//                      position: 'top'
//                    }
//                  ],
//                  showStepNumbers: false,
//                  showBullets: false,
//                  exitOnOverlayClick: true,
//                  exitOnEsc: true,
//                  scrollToElement: false,
//                  overlayOpacity: overlayOpacity,
//                  tooltipClass: cssClasses,
//                  nextLabel: labelBtnNext,
//                  prevLabel: labelBtnPrevious,
//                  skipLabel: labelBtnSkip,
//                  doneLabel: labelBtnDone
//                };
//
//                GuidedTourService.registerGuidedTour('autoFill', scope.startTourAutoFill);
//
//                $timeout(function startTourDelayed() {
//                  if (!ProjectService.getProject().isAutoFillUsed()) {
//                    scope.startTourAutoFill();
//                  }
//                }, 60 * 2000);
//
//              });
//
//            }
//
//          });

        }
      };
    }
  ])
  ;
})
();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A service that gives access to guided tours.
 *
 * @since 14.08.2014
 * @author Frank Bruns
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('GuidedTourService', [
    '$log','$timeout',
    function ($log,$timeout) {

      var guidedTours = {};

      // definition of the public service functions
      return {

        registerGuidedTour: function (name, startMethod) {
          guidedTours[name] = startMethod;
        },

        startTour: function(name,step) {
          $timeout(function startDelayed(){
            guidedTours[name](step ? step : 1);
          });

        }

      };

    }

  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A service to handle text resource messages based on the message repository.
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('NotificationService', [
    '$log', 'AppConstants', 'OperatorService', 'MessageService', 'toastr',
    function ($log, AppConstants, OperatorService, MessageService, toastr) {
      // definition of the public service functions

      var tooManyNotificationShown = false;


      var notificationService = {
        /**
         * @param title(empty String if no title needed)
         * @param message not as textResourcesKey
         * @param alertType ('warning', 'danger', 'success' or 'info', info is default)
         * @param {Number} timeOut . Notification will disapear in ms
         * @param {Number} (optional) hoverTimeout the timeout of the toast after the toast was hovered by the user
         */
        addNotification: function (title, message, alertType, timeOut, hoverTimeout) {

          var extendedTimeout = hoverTimeout || AppConstants.NOTIFICATION_DEFAULT_TIMEOUT;

          if (alertType === 'warning') {
            return toastr.warning(message, title, {
              closeButton: true,
              timeOut: timeOut,
              extendedTimeOut: extendedTimeout
            });
          } else if (alertType === 'danger') {
            return toastr.error(message, title, {
              closeButton: true,
              timeOut: timeOut,
              extendedTimeOut: extendedTimeout
            });
          } else if (alertType === 'success') {
            return toastr.success(message, title, {
              closeButton: true,
              timeOut: timeOut,
              extendedTimeOut: extendedTimeout
            });
          } else {
            return toastr.info(message, title, {
              closeButton: true,
              timeOut: timeOut,
              extendedTimeOut: extendedTimeout
            });
          }
        },

        /**
         * @param {String} htmlSnippet plain html for the notification content e.g. '<input type="checkbox" checked>'
         * @param {String} title(empty String if no title needed)
         * @param {String} htmlMessage not as textResourcesKey
         * @param {String} alertType ('warning', 'danger', 'success' or 'info', info is default)
         * @param {Number} timeOut . Notification will disapear in ms
         */
        addHtmlNotification: function (title, htmlMessage, alertType, timeOut) {

          var options;

          if (timeOut) {
            options = {
              allowHtml: true,
              closeButton: true,
              timeOut: timeOut
            };
          } else {
            options = {
              allowHtml: true,
              closeButton: true,
              tapToDismiss: true,
              progressBar: false,
              timeOut: 1000 * 60 * 60,
              extendedTimeOut: 1000 * 60 * 60
            };
          }
          if (alertType === 'warning') {
            return toastr.warning(htmlMessage, title, options);
          } else if (alertType === 'danger') {
            return toastr.error(htmlMessage, title, options);
          } else if (alertType === 'success') {
            return toastr.success(htmlMessage, title, options);
          } else {
            return toastr.info(htmlMessage, title, options);
          }
        },
        /**
         * @param iconClass css Class for the icon. class should be like #toast-container > .toast-myCustomClass {...
         * @param title(empty String if no title needed)
         * @param message not as textResourcesKey
         * @param alertType ('warning', 'danger', 'success' or 'info', info is default)
         * @param {Number} timeOut . Notification will disapear in ms
         */
        addCustomIconNotification: function (iconClass, title, message, alertType, timeOut) {
          if (alertType === 'warning') {
            return toastr.warning(message, title, {
              closeButton: true,
              iconClass: 'toast-warning ' + iconClass,
              timeOut: timeOut
            });
          } else if (alertType === 'danger') {
            return toastr.error(message, title, {
              closeButton: true,
              iconClass: 'toast-error ' + iconClass,
              timeOut: timeOut
            });
          } else if (alertType === 'success') {
            return toastr.success(message, title, {
              closeButton: true,
              iconClass: 'toast-success ' + iconClass,
              timeOut: timeOut
            });
          } else {
            return toastr.info(message, title, {
              closeButton: true,
              iconClass: 'toast-info ' + iconClass,
              timeOut: timeOut
            });
          }
        },
        /**
         * removes a notification
         * @param notification
         */
        removeNotification: function (notification) {
          toastr.clear(notification);
        },

        addTooManyPhotosNotification: function () {
          if (!tooManyNotificationShown) {
            notificationService.addHtmlNotification(MessageService.getMessage('notification.manyPhotosWarning.header'), '<p>' + MessageService.getMessage('notification.manyPhotosWarning.text', [OperatorService.getDesktopRecommendationLimit()]) + '</p><p><a target="_blank" class="btn btn-primary" href="' + OperatorService.getDesktopRecommendationTargetUrl() +'">' + MessageService.getMessage('notification.manyPhotosWarning.linkToSoftwareText') + '</a>' +
              '<button class="btn btn-default">' + MessageService.getMessage('notification.manyPhotosWarning.closeNotifcationText') + '</button></p>', 'warning', null);
            tooManyNotificationShown = true;
          }
        }

      };

      return notificationService;
    }

  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Provides a service for ips gallery
 *
 * @author Sascha Friedrich
 * @author Christoph Suhren
 * @author Frank Bruns
 */
(function () {
  'use strict';

  angular.module('tatooine').factory('IpsAlbumService', [
    '$log', '$q', '$resource', '$http', 'FileHandleService',
    function ($log, $q, $resource, $http, FileHandleService) {

      // definition of the public service functions
      var ipsAlbumService = {

        getAlbums: function () {

          var deferred = $q.defer();
          var albumsUrl = 'galleryListFolders.do?xml=false';
          $log.debug('Request ips-gallery albums from server:' + albumsUrl);

          $http.get(albumsUrl).success(function (data) {
            deferred.resolve(data);
          });

          return deferred.promise;

        },

        getAlbumItems: function (albumId) {

          var deferred = $q.defer();
          var albumItemsUrl = 'galleryGetAlbumImages.do?xml=false&id=' + albumId;
          $log.debug('Request ips-gallery albumItems from album:' + albumId);
          $http.get(albumItemsUrl).success(function (data) {
            $log.debug('album items', data.imageList);
            deferred.resolve(data.imageList);
          });


          return deferred.promise;
        },

        createExifDataForAlbum: function (albumId) {
          var exifUrl = 'photobook/album/exif/' + albumId + '.rest';
          var ExifResource = $resource(exifUrl);
          var exif = ExifResource.query(function (data) {
            $log.debug('loaded exif from album:', albumId);

            data.forEach(function (item) {
              var fileHandle = FileHandleService.getFileHandleById(item.refCountId);
              if (fileHandle) {
                fileHandle.setExif(item.exif);
              }
            });
          });
          return exif.$promise;
        },

        createExifDataForRefCountId: function (refCountId) {
          var exifUrl = 'photobook/albumItem/exif/' + refCountId + '.rest';
          var ExifResource = $resource(exifUrl);
          var exif = ExifResource.get(function (data) {
            $log.debug('loaded exif from refCountId:', refCountId);
            var fileHandle = FileHandleService.getFileHandleById(refCountId);
            if (fileHandle) {
              $log.debug(data);
              fileHandle.setExif(data.exif);
            }
          });
          return exif.$promise;
        }
      };

      return ipsAlbumService;
    }
  ])
  ;
})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This directive is a UI component that displays different photo sources.
 * @author: Sascha Friedrich
 * Date: 16.12.2015
 */
(function () {
  'use strict';
  angular.module('tatooine').directive('cwPhotoSources', [
    '$log', '$modal', 'BaseConfigService', 'PhotoSourcesService',
    function ($log, $modal, BaseConfigService, PhotoSourcesService) {
      return {
        replace: false,
        scope: {
          showMyPhotosSource: '=showMyphotosSource'
        },
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/photosources/cwPhotoSources.html.jsf',
        link: function (scope, element, attrs) {


          scope.showDropDownFilter = PhotoSourcesService.getUsedMyPhotosEvents().length > 0;

          var dialogPassThroughDataForInit = {
            showMyPhotosSource: scope.showMyPhotosSource,
            forceMyPhotosDialog: BaseConfigService.hasOpenMyPhotosDialogParamInUrl()
          };


          var fileNameWatch = scope.$watch(function getUsedMyPhotosEvents() {
            return PhotoSourcesService.getUsedMyPhotosEvents().length;
          }, function onUsedMyPhotosEventsChanged(newValue, oldValue) {
            scope.showDropDownFilter = newValue > 0;
          });


          scope.openPhotoSourcesDialog = function () {

            var photoSourcesLightbox = $modal.open({
              size: 'lg',
              //backdrop: 'static',
              templateUrl: 'photoSourcesLightbox',
              controller: 'PhotoSourcesLightboxController',
              resolve: {
                passThrough: function () {
                  return dialogPassThroughDataForInit;
                }
              }
            });

            photoSourcesLightbox.result.then(function (response) {
            }, function (dimissed) {
              // killed the dialog
            });


          };

          if (BaseConfigService.hasOpenMyPhotosDialogParamInUrl()) {
            scope.openPhotoSourcesDialog();
          }


        }
      };
    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 * @author Sascha Friedrich
 */

(function () {
  'use strict';
  angular.module('tatooine').controller('PhotoSourcesLightboxController', [
    '$scope', '$log', '$window', '$q', 'orderByFilter', '$modalInstance', 'AppConstants', 'Utils', 'FileHandleService', 'ProjectService', 'passThrough', 'MessageService', 'PhotoSourcesService', 'AuthenticationService', 'IpsAlbumService', 'BaseConfigService', 'NotificationService',
    function ($scope, $log, $window, $q, orderByFilter, $modalInstance, AppConstants, Utils, FileHandleService, ProjectService, passThrough, MessageService, PhotoSourcesService, AuthenticationService, IpsAlbumService, BaseConfigService, NotificationService) {
      $scope.modal = {};
      $scope.modal.headPhoto = [];

      var fileHandlesCountWatch = $scope.$watch(function watchFileHandlesCount() {
        return FileHandleService.getFileHandlesCount();
      }, function onFileHandlesCountChanged(newValue, oldValue) {
        if (newValue > oldValue) {
          $modalInstance.dismiss('cancel');
        }
      });

      var getYearFromUnixTimeStamp = function (ts) {
        var date = new Date(ts);
        return date.getFullYear();
      };

      var showMyPhotosLoginProcessDialog = function () {
        $scope.modal.myPhotosLoginInProcess = true;
        $scope.modal.text = MessageService.getMessage('photoSources.myPhotos.myPhotosLogin');
      };

      var handleMyPhotosInit = function () {
        $scope.modal.specificExternalSourceInProcess = true;
        PhotoSourcesService.checkMyPhotosSessionOverIPS().then(function (ipsData) {
          if (ipsData.cldId) {
            PhotoSourcesService.setMyPhotosCldId(ipsData.cldId);
            $scope.showMyPhotosEvents();
          } else {
            if (!PhotoSourcesService.getMyPhotosCldId()) {
              showMyPhotosLoginProcessDialog();
            } else {
              $scope.showMyPhotosEvents();
            }
          }
        });
      };

      function clearDialog() {
        // general
        $scope.modal.invalidInput = false;
        $scope.modal.specificExternalSourceInProcess = false;
        $scope.modal.header = MessageService.getMessage('photoSources.header');
        $scope.modal.text = MessageService.getMessage('photoSources.text');
        $scope.modal.isSSO = BaseConfigService.isSSOSession();

        $scope.modal.myPhotosLoginInProcess = false;
        $scope.modal.myPhotosEventChooserInProcess = false;
        $scope.modal.myPhotos.email = '';
        $scope.modal.myPhotos.password = '';
        $scope.modal.selectedEvent = null;
        $scope.modal.eventPhotos = [];
      }

      if (passThrough) {
        $scope.modal.showMyPhotosSource = passThrough.showMyPhotosSource;
        $scope.modal.myPhotos = {};

        if (passThrough.forceMyPhotosDialog) {
          handleMyPhotosInit();
          BaseConfigService.removeOpenMyPhotosDialogParamFromUrl();
        }
      }

      $scope.close = function (forceClose) {
        if ($scope.modal.specificExternalSourceInProcess && !forceClose) {
          clearDialog();
        }
        else {
          $modalInstance.dismiss('cancel');
        }
      };

      $scope.selectEvent = function (event) {
        $scope.modal.selectedEvent = event;
      };

      $scope.putEventIntoPhotoSelection = function () {
        PhotoSourcesService.getMyPhotosEventPhotos($scope.modal.selectedEvent.id).then(function (data) {
          if (data.photos) {
            angular.forEach(data.photos, function (photo) {
              FileHandleService.createCloudFileHandle(photo, $scope.modal.selectedEvent.id);
            });

            if (!PhotoSourcesService.addUsedMyPhotosEvent($scope.modal.selectedEvent)) {
              if (data.photos.length > 1) {
                NotificationService.addNotification('CEWE MYPHOTOS', MessageService.getMessage('notification.severalNewPhotosAdded', [data.availablePhotosCount]), 'info', 5000);
              } else {
                NotificationService.addNotification('CEWE MYPHOTOS', MessageService.getMessage('notification.oneNewPhotoAdded'), 'info', 5000);
              }
            }
            FileHandleService.setActiveFilter($scope.modal.selectedEvent);
            $scope.close(true);
          }
        });

      };

      $scope.showMyPhotosEvents = function () {
        /* we are now definitly loggedIn in MyPhotos, so we can update our serverFileHandles if the user wasnt loggedIn into myPhotos */
        var cloudFileHandles = FileHandleService.getFileHandlesWithCloudBackground();
        cloudFileHandles.forEach(function (cloudFileHandle) {
          if (cloudFileHandle.getRefCountId() !== -1 && !cloudFileHandle.getMyPhotosEventName() && !cloudFileHandle.getMyPhotosEventId()) {
            PhotoSourcesService.checkAndUpdateFileHandleForEventInfos(cloudFileHandle);
          }
        });

        $scope.modal.myPhotosLoginInProcess = false;
        $scope.modal.myPhotosEventChooserInProcess = true;
        $scope.modal.myPhotosPhotosChooserInProcess = false;

        $scope.modal.text = MessageService.getMessage('photoSources.myPhotos.chooseEvent.text');
        PhotoSourcesService.getMyPhotosEvents(1).then(function (myPhotosEvents) {
          if (myPhotosEvents && myPhotosEvents !== $scope.orderedMyPhotosEvents) {
            $scope.orderedMyPhotosEvents = orderByFilter(myPhotosEvents, '-startDate');
          }
        });
      };
      $scope.initMyPhotos = function () {
        handleMyPhotosInit();
      };

      $scope.handleMyPhotosLogin = function () {
        $scope.modal.selectedPhotos = [];
        $scope.modal.allPhotosSwitch = false;
        if (!PhotoSourcesService.getMyPhotosCldId()) {
          PhotoSourcesService.createMyPhotosSession($scope.modal.myPhotos.email, $scope.modal.myPhotos.password).then(function ok(myPhotosData) {
            PhotoSourcesService.setMyPhotosLogin($scope.modal.myPhotos.email);
            PhotoSourcesService.setMyPhotosPassword($scope.modal.myPhotos.password);
            PhotoSourcesService.putMyPhotosLoginIntoIps().then(function (myPhotosIpsData) {
              $log.debug('myPhotosIpsData', myPhotosIpsData);
              PhotoSourcesService.setMyPhotosCldId(myPhotosIpsData.cldId);
              $scope.showMyPhotosEvents();
            });
          }, function error(result) {
            $log.error('myPhotos login failed: ', result);
            $scope.modal.invalidInput = true;
            $scope.modal.invalidMsg = MessageService.getMessage('photoSources.myPhotos.failedLogin');
            return $q.reject(result);
          });
        } else {
          $scope.showMyPhotosEvents();
        }
      };

      $scope.getHeadPhoto = function (event) {
        if (PhotoSourcesService.getMyPhotosCldId()) {
          return PhotoSourcesService.getMyPhotosPhoto(event.photoIds[0], 100);
        }
      };

      $scope.getPhotoUrl = function (photoId) {
        return PhotoSourcesService.getMyPhotosPhoto(photoId, 300);
      };


      /**
       *
       * @param index the current index of the ordered myPhotos events
       * @returns {boolean} returns true if the year in the orderedMyPhotosEvents list has changed
       */
      $scope.isBreakNeeded = function (index) {
        var currentIndex = index;
        var lastIndex = currentIndex - 1;
        if (currentIndex === 0 && !$scope.modal.eventSearch) {
          return true;
        }

        if ($scope.modal.eventSearch) {
          return false;
        }

        if ($scope.orderedMyPhotosEvents[currentIndex] && $scope.orderedMyPhotosEvents[lastIndex]) {
          if ($scope.orderedMyPhotosEvents[currentIndex].startDate && $scope.orderedMyPhotosEvents[lastIndex].startDate) {
            return getYearFromUnixTimeStamp($scope.orderedMyPhotosEvents[currentIndex].startDate) !== getYearFromUnixTimeStamp($scope.orderedMyPhotosEvents[lastIndex].startDate);
          }
        }
        return false;
      };

      $scope.getFormattedPeriod = function (tsBegin, tsEnd) {
        var begin = Utils.getDateForUnixTimeStamp(tsBegin);
        var end = Utils.getDateForUnixTimeStamp(tsEnd);
        if (begin === end) {
          return begin;
        }
        return begin + ' - ' + end;
      };

      $scope.getYearFromIndex = function (index) {
        if ($scope.orderedMyPhotosEvents[index] && $scope.orderedMyPhotosEvents[index].startDate) {
          return getYearFromUnixTimeStamp($scope.orderedMyPhotosEvents[index].startDate);
        }
      };


      clearDialog();

    }
  ])
  ;
})
();/*
 * Copyright (C) 2016, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

(function () {
  'use strict';
  angular.module('tatooine').factory('PhotoSourcesService', [
    '$rootScope', '$log', '$http', '$window', '$q', 'AppConstants', 'Utils', '$resource',
    function ($rootScope, $log, $http, $window, $q, AppConstants, Utils, $resource) {

      var myPhotosData = {
        myPhotosLogin: undefined,
        myPhotosPassword: undefined,
        myPhotosCldId: undefined,
        myPhotosLinked: undefined,
        myPhotosPhotos: undefined,
        usedMyPhotosEvents: []
      };

      var getMyPhotosBaseUrl = function () {
        if (window.tatooine.baseConfig.systemStatus === 'develop') {
          return AppConstants.MYPHOTOS_BASE_URL_DEV;
        } else if (window.tatooine.baseConfig.systemStatus === 'test') {
          return AppConstants.MYPHOTOS_BASE_URL_TEST;
        } else {
          return AppConstants.MYPHOTOS_BASE_URL;
        }
      };

      var updateFileHandleForEventInfos = function (fileHandle) {
        photoSourcesService.getMyPhotosPhotoInformation(fileHandle.getMyPhotosPictureId()).then(function (myPhotosPhotoInfo) {
          if (myPhotosPhotoInfo.eventId) {
            fileHandle.setMyPhotosEventId(myPhotosPhotoInfo.eventId);
            photoSourcesService.getMyPhotosEventInformation(myPhotosPhotoInfo.eventId).then(function (event) {
              fileHandle.setMyPhotosEventName(event.name);
              photoSourcesService.addUsedMyPhotosEvent(event);
            });
          }
        });
      };
      // definition of the public service functions
      var photoSourcesService = {
        /**
         * @param email
         * @param password
         * @returns {Promise}
         */
        createMyPhotosSession: function (email, password) {
          var authResourceUrl = getMyPhotosBaseUrl() + '/account/session';

          var loginData = {
            'login': email,
            'password': password,
            'deviceName' : 'CEWE Photobook Editor'
          };

          var config = {
            headers: {
              'apiAccessKey': AppConstants.MYPHTOTOS_API_KEY,
              'clientVersion': '4.2.0-DefaultMyPhotosService'
            }
          };

          return $http.post(authResourceUrl, loginData, config).then(
            Utils.unwrapHttpSuccessResponseFn(),
            Utils.createHttpErrorHandlerFn('create myphotos session')
          );
        },

        getMyPhotosEvents: function (representatives) {
          var eventUrl = getMyPhotosBaseUrl() + '/photoEvents';
          if (representatives && representatives > 0) {
            eventUrl = eventUrl + '?representatives=' + representatives;
          }
          var config = {
            headers: {
              'clientVersion': '4.2.0-DefaultMyPhotosService',
              'cldId': photoSourcesService.getMyPhotosCldId()
            }
          };
          return $http.get(eventUrl, config).then(
            Utils.unwrapHttpSuccessResponseFn(),
            Utils.createHttpErrorHandlerFn('events')
          ).then(function unwrapEvents(response) {
            return response.albums;
          }).then(function addDisplayNames(events) {
            angular.forEach(events, function (myPhotosEvent) {
              myPhotosEvent.displayName = photoSourcesService.getDisplayName(myPhotosEvent);
            });
            return events;
          });

        },

        checkAndUpdateFileHandleForEventInfos: function (fileHandle) {
          if (!photoSourcesService.getMyPhotosCldId()) {
            photoSourcesService.checkMyPhotosSessionOverIPS().then(function (data) {
              if (data.cldId) {
                photoSourcesService.setMyPhotosCldId(data.cldId);
                updateFileHandleForEventInfos(fileHandle);
              }
            });
          } else {
            updateFileHandleForEventInfos(fileHandle);
          }
        },

        getMyPhotosPhoto: function (photoId, size) {
          size = size ? size : 100;
          return getMyPhotosBaseUrl() + '/photos/' + photoId + '.jpg?cldId=' + photoSourcesService.getMyPhotosCldId() + '&clientVersion=4.2.0-DefaultMyPhotosService&size=' + size;
        },

        getMyPhotosEventPhotos: function (eventId) {
          var photosUrl = getMyPhotosBaseUrl() + '/photoEvents/' + eventId + '/allPhotos';

          var config = {
            headers: {
              'clientVersion': '4.2.0-DefaultMyPhotosService',
              'cldId': photoSourcesService.getMyPhotosCldId()
            },
            cache: true
          };

          return $http.get(photosUrl, config).then(
            Utils.unwrapHttpSuccessResponseFn(),
            Utils.createHttpErrorHandlerFn('cldId')
          );
        },

        getMyPhotosPhotoInformation: function (myPhotosPictureId) {
          var photosUrl = getMyPhotosBaseUrl() + '/photos/' + myPhotosPictureId;

          var config = {
            headers: {
              'clientVersion': '4.2.0-DefaultMyPhotosService',
              'cldId': photoSourcesService.getMyPhotosCldId()
            },
            cache: true
          };

          return $http.get(photosUrl, config).then(
            Utils.unwrapHttpSuccessResponseFn(),
            Utils.createHttpErrorHandlerFn('unable to get photo information for picture with id: ' + myPhotosPictureId)
          );

        },


        getMyPhotosEventInformation: function (myPhotosEventId) {
          var photosUrl = getMyPhotosBaseUrl() + '/photoEvents/' + myPhotosEventId;

          var config = {
            headers: {
              'clientVersion': '4.2.0-DefaultMyPhotosService',
              'cldId': photoSourcesService.getMyPhotosCldId()
            },
            cache: true
          };

          return $http.get(photosUrl, config).then(
            Utils.unwrapHttpSuccessResponseFn(),
            Utils.createHttpErrorHandlerFn('unable to get event information for picture with id: ' + myPhotosEventId)
          ).then(function addDisplayName(myPhotosEvent) {
            myPhotosEvent.displayName = photoSourcesService.getDisplayName(myPhotosEvent);
            return myPhotosEvent;
          });

        },

        checkMyPhotosSessionOverIPS: function () {
          var deferred = $q.defer();
          if (photoSourcesService.getMyPhotosCldId()) {
            deferred.resolve({cldId: photoSourcesService.getMyPhotosCldId()});
            return deferred.promise;
          }
          var url = 'myPhotos/cldId.rest';
          return $http.get(url).then(
            Utils.unwrapHttpSuccessResponseFn(),
            Utils.createHttpErrorHandlerFn('cldId')
          );
        },

        setMyPhotosCldId: function (cldId) {
          myPhotosData.myPhotosCldId = cldId;
        },

        getMyPhotosCldId: function () {
          return myPhotosData.myPhotosCldId;
        },

        setMyPhotosLogin: function (email) {
          myPhotosData.myPhotosLogin = email;
        },

        getMyPhotosLogin: function () {
          return myPhotosData.myPhotosLogin;
        },

        setMyPhotosPassword: function (pw) {
          myPhotosData.myPhotosPassword = pw;
        },

        getMyPhotosPassword: function () {
          return myPhotosData.myPhotosPassword;
        },

        addUsedMyPhotosEvent: function (event) {
          var alreadyUsed = false;
          angular.forEach(photoSourcesService.getUsedMyPhotosEvents(), function (usedEvent) {
            if (event.id === usedEvent.id) {
              alreadyUsed = true;
            }
          });
          if (!alreadyUsed) {
            myPhotosData.usedMyPhotosEvents.push(event);
            $log.debug('Added event to used events', event, myPhotosData.usedMyPhotosEvents);
            return alreadyUsed;
          }
          return alreadyUsed;
        },

        getUsedMyPhotosEvents: function () {
          return myPhotosData.usedMyPhotosEvents;
        },

        putMyPhotosLoginIntoIps: function () {
          var cmpData = {
            myPhotosLogin: photoSourcesService.getMyPhotosLogin(),
            myPhotosPassword: photoSourcesService.getMyPhotosPassword()
          };

          if (photoSourcesService.getMyPhotosCldId() !== null) {
            cmpData.myPhotosCldId = photoSourcesService.getMyPhotosCldId();
          }
          var resourceUrl = 'myPhotos/login.rest';
          return $resource(resourceUrl).save(cmpData).$promise;
        },

        /**
         * Makes a ips albumitem from a cloud fileHandle
         *
         * @returns {data with refCountId}
         */
        makeAlbumItemFromCloudPicture: function (eventId, cloudPictureId) {
          myPhotosData.myPhotosLogin = photoSourcesService.getMyPhotosLogin();
          myPhotosData.myPhotosPassword = photoSourcesService.getMyPhotosPassword();
          if (photoSourcesService.getMyPhotosCldId() !== null) {
            myPhotosData.myPhotosCldId = photoSourcesService.getMyPhotosCldId();
          }
          var resourceUrl = 'myPhotos/albumItemIdForCloudPicture.rest?cloudEventId=' + eventId + '&cloudPictureId=' + cloudPictureId;

          return $resource(resourceUrl).save(myPhotosData).$promise;
        },

        getDisplayName: function (event) {
          if (event.name) {
            return event.name;
          }
          var begin = Utils.getDateForUnixTimeStamp(event.startDate);
          var end = Utils.getDateForUnixTimeStamp(event.endDate);
          if (begin === end) {
            return begin;
          }
          return begin + ' - ' + end;
        }

      };

      return photoSourcesService;

    }

  ])
  ;
})
();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 * Does price requests to the de.cewecolor.ips.photobook.wizard.action.GetPhotoBookPriceAction interface.
 * ToDo: You may want to cache the price requests, because the result for a given input does not change.
 *
 * @author Holger Cremer
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('PriceService', [
    '$log', '$q', '$http', 'ProductService',
    function ($log, $q, $http, ProductService) {

      // definition of the public service functions
      return {

        /**
         * @param {number} productId
         * @param {number} pageCount
         * @returns a promise, that has { totalSum, pagePrice } as parameter object.
         */
        calculatePrice: function (productId, pageCount) {
          var endpointUrl = 'photobook/price/' + productId + '/' + pageCount + '.rest';

          return $http({
            method: 'GET',
            url: endpointUrl
          }).then(
            function ok(response) {
              $log.debug('received product price from sever.', response);
              return response.data;
            },
            function error(response) {
              // TODO: we need some global error handling
              $log.error('ERROR: Can\'t get the price data: ', response);
            });
        },


        /**
         * @param {number} productAId
         * @param {number} productBId
         * @param {number} pageCount
         * @returns a promise, that has { totalSum, pagePrice } as parameter object.
         */
        calculatePriceDifference: function (productAId, productBId, pageCount) {

          var deferred = $q.defer();

          var productA = ProductService.getProductById(productAId);
          var productB = ProductService.getProductById(productBId);

          if (productA.getMaxNumberOfPages() < pageCount || productB.getMaxNumberOfPages() < pageCount) {
            $log.error('ERROR: the current pages are not possible for the given products', productA.getId(), productB.getId());
            deferred.reject();
            return deferred.promise;
          }

          var endpointUrl = 'photobook/price/' + productAId + '/' + productBId + '/' + pageCount + '.rest';

          return $http({
            method: 'GET',
            url: endpointUrl
          }).then(
            function ok(response) {
              $log.debug('received product prices from sever.', response);
              return response.data;
            },
            function error(response) {
              // TODO: we need some global error handling
              $log.error('ERROR: Can\'t get the price data: ', response);
            });
        }

      };

    }
  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Contains general information about available products (to switch) and more specific information about the chosen product.
 * @author Silvia Peter (silvia.peter@cewe.de)
 * @author Sascha Friedrich
 * Date: 25.10.13
 * Time: 13:33
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('ProductRepository', [
    '$log',
    function ($log) {

      // TODO Silvia 29.10.13: Test if the product ID is within the available products.
      var repo = {
        // needs to be set.
        products: undefined

      };

      // definition of the public repository functions
      return {

        getProducts: function () {
          return repo.products;
        },

        setProduct: function (product) {
          for (var i = 0; i < repo.products.length; i++) {
            if (repo.products[i].id === product.id) {
              repo.products[i] = product;
            }
          }
        },

        setProducts: function (products) {
          repo.products = products;
        },

        getProductById: function(productId) {
          for (var i = 0; i < repo.products.length; i++) {
            if (repo.products[i].id === productId) {
              return repo.products[i];
            }
          }
        }

      };

    }
  ])
  ;

})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * @author Silvia Peter (silvia.peter@cewe.de)
 * Date: 25.10.13
 * Time: 13:38
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('ProductService', [
    '$log', '$resource', '$q', 'Utils', 'ProductRepository', 'ProductFactory',
    function ($log, $resource, $q, Utils, ProductRepository, ProductFactory) {

      var supportedProductsInitialized = false;
      var possibleUpsellingProducts = [];

      var mini = {
        type: 'mini',
        covers: [
          {
            type: 'softcover',
            papers: [
              {
                type: 'digital_standard',
                productId: 8581
              }
            ]
          }
        ]
      };

      var compactPanorama = {
        type: 'compact_panorama',
        covers: [
          {
            type: 'softcover',
            papers: [
              {
                type: 'digital_standard',
                productId: 10812
              }
            ]
          },
          {
            type: 'hardcover',
            papers: [
              {
                type: 'digital_standard',
                productId: 10801
              },
              {
                type: 'digital_glossy',
                productId: 8586
              },
              {
                type: 'photopaper_matte',
                productId: 8588
              },
              {
                type: 'photopaper_glossy',
                productId: 7031
              }
            ]
          }
        ]
      };

      var quad = {
        type: 'quad',
        covers: [
          {
            type: 'softcover',
            papers: [
              {
                type: 'digital_standard',
                productId: 10231
              },
              {
                type: 'digital_glossy',
                productId: 8844
              }
            ]
          },
          {
            type: 'hardcover',
            papers: [
              {
                type: 'digital_standard',
                productId: 10221
              },
              {
                type: 'digital_glossy',
                productId: 8840
              },
              {
                type: 'photopaper_matte',
                productId: 10751
              },
              {
                type: 'photopaper_glossy',
                productId: 8842
              }
            ]
          }
        ]
      };


      var large = {
        type: 'large',
        covers: [
          {
            type: 'softcover',
            papers: [
              {
                type: 'digital_standard',
                productId: 10171
              },
              {
                type: 'digital_glossy',
                productId: 8846
              }
            ]
          },
          {
            type: 'hardcover',
            papers: [
              {
                type: 'digital_standard',
                productId: 10141
              },
              {
                type: 'digital_glossy',
                productId: 8258
              },
              {
                type: 'digital_premium_matte',
                productId: 8794
              },
              {
                type: 'photopaper_matte',
                productId: 8590
              },
              {
                type: 'photopaper_glossy',
                productId: 8592
              }
            ]
          }
        ]
      };


      var largeAcross = {
        type: 'large_across',
        covers: [
          {
            type: 'softcover',
            papers: [
              {
                type: 'digital_standard',
                productId: 8579
              },
              {
                type: 'digital_glossy',
                productId: 8848
              }
            ]
          },
          {
            type: 'hardcover',
            papers: [
              {
                type: 'digital_standard',
                productId: 10759
              },
              {
                type: 'digital_glossy',
                productId: 8275
              },
              {
                type: 'digital_premium_matte',
                productId: 8796
              },
              {
                type: 'photopaper_matte',
                productId: 10733
              },
              {
                type: 'photopaper_glossy',
                productId: 8594
              }
            ]
          }
        ]
      };


      var xl = {
        type: 'xl',
        covers: [
          {
            type: 'hardcover',
            papers: [
              {
                type: 'digital_standard',
                productId: 10264
              },
              {
                type: 'digital_glossy',
                productId: 8292
              },
              {
                type: 'digital_premium_matte',
                productId: 8792
              },
              {
                type: 'photopaper_matte',
                productId: 10742
              },
              {
                type: 'photopaper_glossy',
                productId: 8596
              }
            ]
          }
        ]
      };


      var xxl = {
        type: 'xxl',
        covers: [
          {
            type: 'hardcover',
            papers: [
              {
                type: 'digital_standard',
                productId: 10773
              },
              {
                type: 'digital_glossy',
                productId: 8575
              },
              {
                type: 'digital_premium_matte',
                productId: 7027
              }
            ]
          }
        ]
      };


      var xxlAcross = {
        type: 'xxl_across',
        covers: [
          {
            type: 'hardcover',
            papers: [
              {
                type: 'digital_standard',
                productId: 10787
              },
              {
                type: 'digital_glossy',
                productId: 8577
              },
              {
                type: 'digital_premium_matte',
                productId: 7029
              },
              {
                type: 'photopaper_matte',
                productId: 8704
              },
              {
                type: 'photopaper_glossy',
                productId: 8706
              }
            ]
          }
        ]
      };

      var editorSupportedProducts = [
        mini,
        compactPanorama,
        quad,
        large,
        largeAcross,
        xl,
        xxl,
        xxlAcross
      ];


      // definition of the public service functions
      var productService = {

        /**
         * Fetches the available products from the server.
         * @returns {*}
         */
        initProducts: function () {
          var productsUrl = 'photobook/products.rest';
          var Products = $resource(productsUrl);

          var initializedProducts = [];
          var products = Products.query(function () {
            products.forEach(function iterateProducts(product) {
              initializedProducts.push(ProductFactory.createProduct(product));
            });
            ProductRepository.setProducts(initializedProducts);
          });
          return products.$promise;
        },

        getProductById: function (productId) {
          return ProductRepository.getProductById(productId);
        },

        getProducts: function () {
          return ProductRepository.getProducts();
        },

        getSupportedPhotobookProducts: function () {
          if (supportedProductsInitialized) {
            return editorSupportedProducts;
          }

          var i = 0;

          // remove unsupported paper types
          editorSupportedProducts.forEach(function iterateFormats(format) {
            format.covers.forEach(function iterateCovers(cover) {
              for (i = cover.papers.length - 1; i >= 0; i--) { // product id not available --> remove paper type
                if (!productService.getProductById(cover.papers[i].productId)) {
                  Utils.removeFromArray(cover.papers, cover.papers[i]);
                }
              }
            });
          });

          // remove unsupported cover types
          editorSupportedProducts.forEach(function iterateFormats(format) {
            for (i = format.covers.length - 1; i >= 0; i--) {
              if (format.covers[i].papers.length <= 0) { // no paper types available --> remove cover type
                Utils.removeFromArray(format.covers, format.covers[i]);
              }
            }
          });

          // remove unsupported formats
          for (i = editorSupportedProducts.length - 1; i >= 0; i--) {
            if (editorSupportedProducts[i].covers.length <= 0) { // no cover types available --> remove format
              Utils.removeFromArray(editorSupportedProducts, editorSupportedProducts[i]);
            }
          }

          supportedProductsInitialized = true;

          return editorSupportedProducts;
        },


        hasSameDimensionsForPages: function (productA, productB, pagesCount) {
          var sameDimensions = true;
          // Check Cover
          if (productA.getCoverPageHeightForPages(pagesCount) !== productB.getCoverPageHeightForPages(pagesCount) ||
            productA.getCoverPageWidthForPages(pagesCount) !== productB.getCoverPageWidthForPages(pagesCount) ||
            productA.getCoverSpineWidthForPages(pagesCount) !== productB.getCoverSpineWidthForPages(pagesCount) ||
            productA.getCoverExtraHorizontal() !== productB.getCoverExtraHorizontal() ||
            productA.getCoverExtraVertical() !== productB.getCoverExtraVertical() ||
            productA.getCoverBleedMarginHorizontal() !== productB.getCoverBleedMarginHorizontal() ||
            productA.getCoverBleedMarginVertical() !== productB.getCoverBleedMarginVertical()) {
            sameDimensions = false;
          }

          // check designAreas
          if (productA.getDoublePageHeight() !== productB.getDoublePageHeight() ||
            productA.getDoublePageWidth() !== productB.getDoublePageWidth()) {
            sameDimensions = false;
          }
          return sameDimensions;
        },

        isCompatibleForConversion: function (productA, productB) {
          return (productA.getOrientation() === productB.getOrientation());
        },

        getPossibleUpsellingProducts: function () {
          return possibleUpsellingProducts;
        },

        setPossibleUpsellingProducts: function (upsellingProducts) {
          possibleUpsellingProducts = upsellingProducts;
        },

        getUpsellingOptions: function (project) {
          var currentProduct = productService.getProductById(project.getProductId());
          var upsellingProducts = [];
          if (currentProduct.getPaper() === 'digitalprint') {
            productService.getProducts().forEach(function (possibleUpsellingProduct) {
              if (productService.hasSameDimensionsForPages(possibleUpsellingProduct, currentProduct, project.getPagesCount()) &&
                possibleUpsellingProduct.getPaper() === 'glossy' && possibleUpsellingProduct.getMaxNumberOfPages() >= project.getPagesCount()) {
                upsellingProducts.push(possibleUpsellingProduct);
              }
            });
          }

          if (currentProduct.getPaper() === 'fotopaper') {
            productService.getProducts().forEach(function (possibleUpsellingProduct) {
              if (productService.hasSameDimensionsForPages(possibleUpsellingProduct, currentProduct, project.getPagesCount()) &&
                possibleUpsellingProduct.getPaper() === 'fotopaper-glossy' && possibleUpsellingProduct.getMaxNumberOfPages() >= project.getPagesCount()) {
                upsellingProducts.push(possibleUpsellingProduct);
              }
            });
          }


          return upsellingProducts;
        }



      };
      return productService;

    }

  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Creates new Products.
 *
 * @author Sascha Friedrich
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('ProductFactory', [
    '$log',
    function ($log) {

      function Product() {

        this.id = undefined;
        this.doublePageWidth = undefined;
        this.doublePageHeight = undefined;

        this.name = undefined;
        this.paper = undefined;
        this.type = undefined;
        this.orientation = undefined;
        this.bleedMarginHorizontal = undefined;
        this.bleedMarginVertical = undefined;
        this.minNumberOfPages = undefined;
        this.maxNumberOfPages = undefined;
        this.minFontSize = undefined;

        this.coverExtraHorizontal = undefined;
        this.coverExtraVertical = undefined;
        this.coverWidth = {};
        this.coverHeight = {};
        this.coverSpineWidth = {};
        this.coverSpineTextMaxFontSize = {};
        this.coverBleedMarginHorizontal = undefined;
        this.coverBleedMarginVertical = undefined;
        this.optimalDotsPerMM = undefined;
        this.greenDotsPerMM = undefined;
        this.yellowDotsPerMM = undefined;

        this.hasSpineLogo = undefined;

        this.barCode = {
          bottom: 0,
          height: 0,
          left: 0,
          pageNr: 0,
          width: 0
        };

        this.safetyMargin = undefined;

        this.fullBackgroundOnEachPage = undefined;
        this.onlyMonochromeBackgroundsOnCover = undefined;
      }

      /**
       *
       * @return {Number}
       */
      Product.prototype.getId = function () {
        return this.id;
      };

      /**
       *
       * @param {Number} id
       */
      Product.prototype.setId = function (id) {
        this.id = id;
      };


      Product.prototype.getName = function () {
        return this.name;
      };

      Product.prototype.setName = function (name) {
        this.name = name;
      };

      Product.prototype.setPaper = function(paper) {
        this.paper = paper;
      };

      Product.prototype.getPaper = function() {
        return this.paper;
      };

      Product.prototype.getType = function () {
        return this.id;
      };

      Product.prototype.setType = function (type) {
        this.type = type;
      };

      Product.prototype.getOrientation = function () {
        return this.orientation;
      };

      Product.prototype.setOrientation = function (orientation) {
        this.orientation = orientation;
      };

      Product.prototype.getPrice = function () {
        return this.price;
      };

      Product.prototype.setPrice = function (price) {
        this.price = price;
      };

      Product.prototype.getFormattedPrice = function () {
        return this.formattedPrice;
      };

      Product.prototype.setFormattedPrice = function (formattedPrice) {
        this.formattedPrice = formattedPrice;
      };

      Product.prototype.getTextResource = function () {
        return this.textResource;
      };

      Product.prototype.setTextResource = function (textResource) {
        this.textResource = textResource;
      };

      Product.prototype.getDescriptionResource = function () {
        return this.descriptionResource;
      };

      Product.prototype.setDescriptionResource = function (descriptionResource) {
        this.descriptionResource = descriptionResource;
      };

      /**
       *
       * @param {Number} pageCount
       * @return {Number}
       */
      Product.prototype.getCoverPageWidthForPages = function (pageCount) {
        return this.coverWidth[pageCount];
      };

      /**
       *
       * @param {Number} pages
       * @param {Number} value
       */
      Product.prototype.setCoverPageWidthForPages = function (pages, value) {
        this.coverWidth[pages] = value;
      };

      /**
       *
       * @param {Number} pageCount
       * @return {Number}
       */
      Product.prototype.getCoverPageHeightForPages = function (pageCount) {
        return this.coverHeight[pageCount];
      };

      /**
       *
       * @param {Number} pages
       * @param {Number} value
       */
      Product.prototype.setCoverPageHeightForPages = function (pages, value) {
        this.coverHeight[pages] = value;
      };

      /**
       *
       * @return {Number}
       */
      Product.prototype.getDoublePageWidth = function () {
        return this.doublePageWidth;
      };

      /**
       *
       * @param {Number} doublePageWidth
       */
      Product.prototype.setDoublePageWidth = function (doublePageWidth) {
        this.doublePageWidth = doublePageWidth;
      };

      /**
       *
       * @return {Number}
       */
      Product.prototype.getBleedMarginHorizontal = function () {
        return this.bleedMarginHorizontal;
      };

      /**
       *
       * @param {Number} bleedMarginHorizontal
       */
      Product.prototype.setBleedMarginHorizontal = function (bleedMarginHorizontal) {
        this.bleedMarginHorizontal = bleedMarginHorizontal;
      };

      /**
       *
       * @return {Number}
       */
      Product.prototype.getBleedMarginVertical = function () {
        return this.bleedMarginVertical;
      };

      /**
       *
       * @param {Number} bleedMarginVertical
       */
      Product.prototype.setBleedMarginVertical = function (bleedMarginVertical) {
        this.bleedMarginVertical = bleedMarginVertical;
      };

      /**
       *
       * @return {Number}
       */
      Product.prototype.getDoublePageHeight = function () {
        return this.doublePageHeight;
      };

      /**
       *
       * @param {Number} doublePageHeight
       */
      Product.prototype.setDoublePageHeight = function (doublePageHeight) {
        this.doublePageHeight = doublePageHeight;
      };

      /**
       *
       * @param {Number} pageCount
       * @return {Number}
       */
      Product.prototype.getCoverExtraHorizontal = function () {
        return this.coverExtraHorizontal;
      };

      /**
       *
       * @param {Number} pages
       * @param {Number} value
       */
      Product.prototype.setCoverExtraHorizontal = function (value) {
        this.coverExtraHorizontal = value;
      };

      /**
       *
       * @param {Number} pageCount
       * @return {Number}
       */
      Product.prototype.getCoverExtraVertical = function () {
        return this.coverExtraVertical;
      };

      /**
       *
       * @param {Number} pages
       * @param {Number} value
       */
      Product.prototype.setCoverExtraVertical = function (value) {
        this.coverExtraVertical = value;
      };

      /**
       *
       * @param {Number} pageCount
       * @return {Number}
       */
      Product.prototype.getCoverSpineWidthForPages = function (pageCount) {
        return this.coverSpineWidth[pageCount];
      };

      /**
       *
       * @param {Number} pages
       * @param {Number} value
       */
      Product.prototype.setCoverSpineWidthForPages = function (pages, value) {
        this.coverSpineWidth[pages] = value;
      };

      /**
       *
       * @param {Number} pageCount
       * @return {Number}
       */
      Product.prototype.getCoverSpineTextMaxFontSizeForPages = function (pageCount) {
        return this.coverSpineTextMaxFontSize[pageCount];
      };

      /**
       *
       * @param {Number} pages
       * @param {Number} value
       */
      Product.prototype.setCoverSpineTextMaxFontSize = function (pages, value) {
        this.coverSpineTextMaxFontSize[pages] = value;
      };

      /**
       *
       * @return {Number}
       */
      Product.prototype.getMinNumberOfPages = function () {
        return this.minNumberOfPages;
      };

      /**
       *
       * @param {Number} min
       */
      Product.prototype.setMinNumberOfPages = function (min) {
        this.minNumberOfPages = min;
      };

      /**
       *
       * @return {Number}
       */
      Product.prototype.getMaxNumberOfPages = function () {
        return this.maxNumberOfPages;
      };

      /**
       *
       * @param {Number} max
       */
      Product.prototype.setMaxNumberOfPages = function (max) {
        this.maxNumberOfPages = max;
      };

      /**
       *
       * @param {Number} minFontSize
       */
      Product.prototype.setMinFontSize = function (minFontSize) {
        this.minFontSize = minFontSize;
      };

      /**
       *
       * @return {Number}
       */
      Product.prototype.getMinFontSize = function () {
        return this.minFontSize;
      };

      /**
       *
       * @param {Number} pageCount
       * @return {Number}
       */
      Product.prototype.getCoverBleedMarginHorizontal = function () {
        return this.coverBleedMarginHorizontal;
      };

      /**
       *
       * @param {Number} pages
       * @param {Number} value
       */
      Product.prototype.setCoverBleedMarginHorizontal = function (value) {
        this.coverBleedMarginHorizontal = value;
      };

      /**
       *
       * @param {Number} pageCount
       * @return {Number}
       */
      Product.prototype.getCoverBleedMarginVertical = function () {
        return this.coverBleedMarginVertical;
      };

      /**
       *
       * @param {Number} pages
       * @param {Number} value
       */
      Product.prototype.setCoverBleedMarginVertical = function (value) {
        this.coverBleedMarginVertical = value;
      };

      /**
       *
       * @return {Number}
       */
      Product.prototype.getSafetyMargin = function () {
        return this.safetyMargin;
      };

      /**
       *
       * @param {Number} value
       */
      Product.prototype.setSafetyMargin = function (value) {
        this.safetyMargin = value;
      };

      /**
       *
       * @return {Boolean} is the product meant to have a spine logo?
       */
      Product.prototype.getHasSpineLogo = function () {
        return this.hasSpineLogo;
      };

      /**
       * Is the product meant to have a spine logo?
       * @param {Boolean} trueOrFalse
       */
      Product.prototype.setHasSpineLogo = function (trueOrFalse) {
        this.hasSpineLogo = trueOrFalse;
      };

      Product.prototype.getBarCode = function () {
        return this.barCode;
      };

      Product.prototype.setBarCodeAttribute = function (attribute, value) {
        this.barCode[attribute] = value;
      };

      /**
       *
       * @return {Number}
       */
      Product.prototype.getOptimalDotsPerMM = function () {
        return this.optimalDotsPerMM;
      };

      /**
       *
       * @param {Number} optimalDotsPerMM
       */
      Product.prototype.setOptimalDotsPerMM = function (optimalDotsPerMM) {
        this.optimalDotsPerMM = optimalDotsPerMM;
      };

      /**
       *
       * @return {Number}
       */
      Product.prototype.getGreenDotsPerMM = function () {
        return this.greenDotsPerMM;
      };

      /**
       *
       * @param {Number} greenDotsPerMM
       */
      Product.prototype.setGreenDotsPerMM = function (greenDotsPerMM) {
        this.greenDotsPerMM = greenDotsPerMM;
      };

      /**
       *
       * @return {Number}
       */
      Product.prototype.getYellowDotsPerMM = function () {
        return this.yellowDotsPerMM;
      };

      /**
       *
       * @param {Number} yellowDotsPerMM
       */
      Product.prototype.setYellowDotsPerMM = function (yellowDotsPerMM) {
        this.yellowDotsPerMM = yellowDotsPerMM;
      };

      Product.prototype.getFullBackgroundOnEachPage = function () {
        return this.fullBackgroundOnEachPage;
      };

      Product.prototype.getOnlyMonochromeBackgroundsOnCover = function () {
        return this.onlyMonochromeBackgroundsOnCover;
      };

      Product.prototype.setFullBackgroundOnEachPage = function (fullBackgroundOnEachPage) {
        this.fullBackgroundOnEachPage = fullBackgroundOnEachPage;
      };

      Product.prototype.setOnlyMonochromeBackgroundsOnCover = function (onlyMonochromeBackgroundsOnCover) {
        this.onlyMonochromeBackgroundsOnCover = onlyMonochromeBackgroundsOnCover;
      };


      return {

        createProduct: function (product) {
          var initializedProduct = new Product();
          initializedProduct.setId(product.id);
          initializedProduct.setType(product.type);
          initializedProduct.setOrientation(product.productInfo.orientation);
          initializedProduct.setFormattedPrice(product.formattedPrice);
          initializedProduct.setTextResource(product.textResource);
          initializedProduct.setName(product.textResource);
          initializedProduct.setDescriptionResource(product.descriptionResource);
          initializedProduct.setDoublePageWidth(product.productInfo.inbookPageDimensions.doublePageWidth);
          initializedProduct.setDoublePageHeight(product.productInfo.inbookPageDimensions.doublePageHeight);
          initializedProduct.setMinNumberOfPages(product.productInfo.minNumberOfPages);
          initializedProduct.setMaxNumberOfPages(product.productInfo.maxNumberOfPages);
          initializedProduct.setMinFontSize(product.productInfo.minFontSize);
          initializedProduct.setBleedMarginHorizontal(product.productInfo.inbookPageDimensions.bleedMarginHorizontal);
          initializedProduct.setBleedMarginVertical(product.productInfo.inbookPageDimensions.bleedMarginVertical);
          initializedProduct.setSafetyMargin(product.productInfo.safetyMargin);
          initializedProduct.setPaper(product.productInfo.paper);
          initializedProduct.setOptimalDotsPerMM(product.productInfo.optimalDotsPerMM);
          initializedProduct.setGreenDotsPerMM(product.productInfo.greenDotsperMM);
          initializedProduct.setYellowDotsPerMM(product.productInfo.yellowDotsperMM);
          initializedProduct.setHasSpineLogo(product.productInfo.hasSpineLogo);
          initializedProduct.setFullBackgroundOnEachPage(product.productInfo.fullBackgroundOnEachPage);
          initializedProduct.setOnlyMonochromeBackgroundsOnCover(product.productInfo.onlyMonochromeBackgroundsOnCover);

          angular.forEach(product.productInfo.coverPageDimensions, function (value, pages) {
            initializedProduct.setCoverExtraHorizontal(value.coverExtraHorizontal);
            initializedProduct.setCoverExtraVertical(value.coverExtraVertical);
            initializedProduct.setCoverPageWidthForPages(pages, value.doublePageWidth);
            initializedProduct.setCoverPageHeightForPages(pages, value.doublePageHeight);
            initializedProduct.setCoverSpineWidthForPages(pages, value.spineWidth);
            initializedProduct.setCoverSpineTextMaxFontSize(pages, value.spineTextMaxFontSize);
            initializedProduct.setCoverBleedMarginHorizontal(value.bleedMarginHorizontal);
            initializedProduct.setCoverBleedMarginVertical(value.bleedMarginVertical);
          });
          if (product.productInfo.barcodes) {
            angular.forEach(product.productInfo.barcodes[0], function (value, object) {
              initializedProduct.setBarCodeAttribute(object, value);
            });
          }
          return initializedProduct;
        },

        getPrototype: function () {
          return new Product();
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Creates DesignArea instances for the project data model.
 *
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('DesignAreaFactory', [
    '$log', '$filter', '$document', 'AppConstants', 'AppValues', 'SafeApply', 'Utils', 'FileHandleService', 'TemplateBackgroundItemFactory', 'ImageItemFactory', 'TextItemFactory', 'ClipartItemFactory', 'FontFactory', 'ViewPortFactory', 'LayoutFactory', 'LayoutBoxFactory',
    function ($log, $filter, $document, AppConstants, AppValues, SafeApply, Utils, FileHandleService, TemplateBackgroundItemFactory, ImageItemFactory, TextItemFactory, ClipartItemFactory, FontFactory, ViewPortFactory, LayoutFactory, LayoutBoxFactory) {
      var filter = $filter('filter');
      var designAreaCounter = 0;

      function DesignArea() {

        this.id = 'area_' + designAreaCounter++;
        this.templateBackgroundItems = [];
        this.imageBackgroundItems = [];
        this.imageItems = [];
        this.textItems = [];
        this.clipartItems = [];

        this.$$initNg();
        this.$$initReporting();
      }

      DesignArea.prototype.$$initReporting = function () {
        this.designAreaReporting = {
          layoutIdLeft: '-1',
          layoutModifiedLeft: false,
          layoutIdRight: '-1',
          layoutModifiedRight: false
        };
      };

      DesignArea.prototype.$$initNg = function () {
        this.ng = {
          detailInteractionMode: false,
          selected: false,
          type: 'inbook',
          spineWidth: 0,
          centerFoldWidth: 2,
          leftPageBlocked: false,
          rightPageBlocked: false,
          width: 0,
          height: 0,
          safetyMargin: 0,
          bleedMarginHorizontal: 0,
          bleedMarginVertical: 0,
          cssWidth: 0,
          cssHeight: 0,
          zIndex: 'auto',
          cssAnimationClass: '', // a css animation class
          layouts: {},
          textRestrictionBox: {},
          barCode: {},
          spineLogoEnabled: false,
          spineContentRotation: 90,
          spineLogoElementId: 0,
          spineMaxWidth: 0,
          buttonBarInitialized: false,
          textItemEditBoxInitialized: false,
          triggerCanvasUpdate: false,
          modelStateVersion: 0,
          pointsOfInterest: {
            x: [],
            y: [],
            rot: []
          }
        };
      };

      DesignArea.prototype.getPointsOfInterest = function (xyRot) {
        return this.ng.pointsOfInterest[xyRot];
      };

      DesignArea.prototype.setPointOfInterest = function (xyRot, value) {
        this.ng.pointsOfInterest[xyRot].push(value);
      };

      DesignArea.prototype.getAllPointsOfInterest = function () {
        return this.ng.pointsOfInterest;
      };

      DesignArea.prototype.clearAllPointsOfInterest = function () {
        this.ng.pointsOfInterest = {x: [], y: [], rot: []};
      };

      DesignArea.prototype.removeItemBoxPois = function (itembox, x, y, rot) {
        var self = this;
        if (x) {
          var xValuesToRemove = [itembox.getWidth(), itembox.getCenterX() - itembox.getWidth() / 2, itembox.getCenterX() + itembox.getWidth() / 2];
          xValuesToRemove.forEach(function (xValueToRemove) {
            if (self.ng.pointsOfInterest.x.indexOf(xValueToRemove)) {
              Utils.removeFromArray(self.ng.pointsOfInterest.x, xValueToRemove);
            }
          });
        }
      };
      DesignArea.prototype.getId = function () {
        return this.id;
      };

      DesignArea.prototype.setId = function (id) {
        this.id = id;
      };

      DesignArea.prototype.getNg = function () {
        return this.ng;
      };

      /**
       * This is basically used by the UndoRedoService.
       * @param ng
       */
      DesignArea.prototype.setNg = function (ng) {
        this.ng = ng;

        var self = this;

        // need to convert the layouts objects to class instances of Layout again
        ['left', 'right'].forEach(function (pageHalf) {

          if (self.getLayoutFromPageHalf(pageHalf)) {

            var layout = angular.extend(LayoutFactory.getPrototype(), self.getLayoutFromPageHalf(pageHalf));
            var layoutBoxes = layout.getBoxes();
            for (var i = 0; i < layoutBoxes.length; i++) {
              layoutBoxes[i] = angular.extend(LayoutBoxFactory.getPrototype(), layoutBoxes[i]);
            }

            self.ng.layouts[pageHalf] = layout;
          }

        });
      };

      DesignArea.prototype.getReportingData = function () {
        return this.designAreaReporting;
      };

      /**
       * This is basically used by the UndoRedoService and when a persisted project is restored from the server.
       * @param designAreaReportingData
       */
      DesignArea.prototype.setReportingData = function (designAreaReportingData) {
        this.designAreaReporting = designAreaReportingData;
      };


      DesignArea.prototype.getLayoutFromPageHalf = function (pagehalf) {
        return this.ng.layouts[pagehalf];
      };

      /**
       * Attaches a Layout to the specified half page of the DesignArea. This is not applying the
       * layouts to the DesignArea (see DesignAreaService for that). It is merely for later reference about which Layout was used on what DesignArea.
       * @param pageHalf
       * @param layout
       */
      DesignArea.prototype.attachLayoutToPageHalf = function (pageHalf, layout) {

        this.ng.layouts[pageHalf] = layout;

        if (pageHalf === 'left') {
          this.designAreaReporting.layoutIdLeft = layout.isCustomLayout() ? '-1' : '' + layout.getId();
          this.designAreaReporting.layoutModifiedLeft = false;
        } else if (pageHalf === 'right') {
          this.designAreaReporting.layoutIdRight = layout.isCustomLayout() ? '-1' : '' + layout.getId();
          this.designAreaReporting.layoutModifiedRight = false;
        }
      };


      /**
       * Recalculates the reporting data about whether or not a potential layouts was manipulated by the user on the specified page half.
       * @param pageHalf
       */
      DesignArea.prototype.updateLayoutModified = function (pageHalf) {

        var layout = this.ng.layouts[pageHalf];

        // no layouts attached to page half --> delete potential reporting entries
        if (!layout) {
          this.setLayoutModified(pageHalf, false);

          if (pageHalf === 'left') {
            this.designAreaReporting.layoutIdLeft = '-1';
          } else if (pageHalf === 'right') {
            this.designAreaReporting.layoutIdRight = '-1';
          }

          return;
        }


        var imageItems = this.getImageItems(pageHalf, true);
        var textItems = this.getTextItems(pageHalf, true);

        // in detail mode: number of boxes defined in layouts differs from actual number of item boxes on design area? --> layouts was modified by user
        if (this.isDetailInteractionMode() &&
          (layout.getTextBoxes().length !== textItems.length || layout.getImageBoxes().length !== imageItems.length)) {

          if ((pageHalf === 'left' && this.designAreaReporting.layoutIdLeft) ||
            (pageHalf === 'right' && this.designAreaReporting.layoutIdRight)) {
            this.setLayoutModified(pageHalf, true);
          }

        } else { // check if one or more item boxes were manipulated by the user

          var allItems = imageItems.concat(textItems);

          for (var i = 0; i < allItems.length; i++) {
            if (allItems[i].isLayoutModified()) {

              if (pageHalf === 'left') {
                this.designAreaReporting.layoutModifiedLeft = true;
              } else if (pageHalf === 'right') {
                this.designAreaReporting.layoutModifiedRight = true;
              }

            }
          }

        }

      };

      DesignArea.prototype.isLayoutModified = function (pageHalf) {
        this.updateLayoutModified(pageHalf);
        if (pageHalf === 'left') {
          return this.designAreaReporting.layoutModifiedLeft;
        } else if (pageHalf === 'right') {
          return this.designAreaReporting.layoutModifiedRight;
        }

      };

      DesignArea.prototype.setLayoutModified = function (pageHalf, trueOrFalse) {
        if (pageHalf === 'left') {
          this.designAreaReporting.layoutModifiedLeft = trueOrFalse;
        } else if (pageHalf === 'right') {
          this.designAreaReporting.layoutModifiedRight = trueOrFalse;
        }
      };


      DesignArea.prototype.getPageHalfOrientation = function () {
        var designAreaWidth = this.getWidth();
        var designAreaHeight = this.getHeight();
        // TODO Sascha Friedrich 16.05.14, make this a bit more reliable, and maybe its better in productService?
        if (designAreaHeight === designAreaWidth / 2) {
          return  'quadratic';
        }
        if (designAreaHeight > designAreaWidth / 2) {
          return  'portrait';
        }
        if (designAreaHeight < designAreaWidth / 2) {
          return  'landscape';
        }
      };

      DesignArea.prototype.getPageHalfFromItemBox = function (itemBox) {
        if (itemBox.getCenterX() <= this.getWidth() / 2) {
          return 'left';
        }
        return 'right';
      };


      /**
       *
       * @return {Array} array with all items on the DesignArea
       */
      DesignArea.prototype.getAllItems = function (sorted) {
        var allItems = this.getTemplateBackgroundItems().concat(this.getImageBackgroundItems()).concat(this.getImageAndTextAndClipartItems());
        return sorted ? allItems.sort(Utils.layerIndexComparator) : allItems;
      };

      /**
       *
       * @param pageHalf the page half to consider (optional)
       * @return {Array} an array containing all ImageItems and TextItems on the DesignArea (or optional page half)
       */
      DesignArea.prototype.getImageAndTextItems = function (pageHalf) {
        return this.getImageItems(pageHalf).concat(this.getTextItems(pageHalf));
      };

      /**
       *
       * @param pageHalf the page half to consider (optional)
       * @return {Array} an array containing all ImageItems, TextItems and ClipartItems on the DesignArea (or optional page half)
       */
      DesignArea.prototype.getImageAndTextAndClipartItems = function (pageHalf) {
        return this.getImageItems(pageHalf).concat(this.getTextItems(pageHalf)).concat(this.getClipartItems(pageHalf));
      };

      /**
       * @param itemBox
       * @return {boolean} is the given item box among the DesignArea's ImageItems that are used as backgrounds?
       */
      DesignArea.prototype.hasImageBackgroundItem = function (itemBox) {
        return this.getImageBackgroundItems().indexOf(itemBox) >= 0;
      };

      /**
       * @param itemBox
       * @return {boolean} is the given item box among the DesignArea's ImageItems?
       */
      DesignArea.prototype.hasImageItem = function (itemBox) {
        return this.getImageItems().indexOf(itemBox) >= 0;
      };

      /**
       * @param itemBox
       * @return {boolean} is the given item box among the DesignArea's ClipartItems?
       */
      DesignArea.prototype.hasClipartItem = function (itemBox) {
        return this.getClipartItems().indexOf(itemBox) >= 0;
      };

      /**
       * @param itemBox
       * @return {boolean} is the given item box among the DesignArea's TextItems?
       */
      DesignArea.prototype.hasTextItem = function (itemBox) {
        return this.getTextItems().indexOf(itemBox) >= 0;
      };


      DesignArea.prototype.addTextItem = function (textItem) {
        textItem.setRestrictionBox(this.getTextRestrictionBox());
        this.textItems.push(textItem);

        if (textItem.getCenterX() <= this.getWidth() / 2) {
          this.updateLayoutModified('left');
        } else {
          this.updateLayoutModified('right');
        }

        this.incrementModelStateVersion();

      };

      /**
       * Returns the TextItems of the DesignArea. If the optional page half parameter is specified (i.e. 'left' or 'right') only the items on
       * that page half are returned
       * @param pageHalf 'left' or 'right' (optional)
       * @param positionEditable if true only text items with variable position will be returned (e.g. the spine text will be omitted) (optional)
       * @returns {Array} TextItems on the DesignArea
       */
      DesignArea.prototype.getTextItems = function (pageHalf, positionEditable) {

        if (pageHalf === 'left' || pageHalf === 'right') {

          var result = [];

          for (var i = 0; i < this.textItems.length; i++) {

            if (pageHalf === 'left' && this.textItems[i].getCenterX() <= this.getWidth() / 2 ||
              pageHalf === 'right' && this.textItems[i].getCenterX() > this.getWidth() / 2) {
              result.push(this.textItems[i]);
            }

          }
          if (positionEditable) {
            return filter(result, function (item) {
              return item.isPositionEditable();
            });
          }
          return result;

        } else {
          return this.textItems;
        }
      };

      DesignArea.prototype.getSpineTextItem = function () {
        if (!this.isCover()) {
          return null;
        }
        var fixedTextItems = filter(this.textItems, function (item) {
          return !item.isPositionEditable();
        });
        for (var i = 0; i < fixedTextItems.length; i++) {
          var currentTextItem = fixedTextItems[i];
          if (currentTextItem.getRotation() === 90 || currentTextItem.getRotation() === 270) {
            return currentTextItem;
          }
        }
        return null;
      };

      DesignArea.prototype.setTextItems = function (textItems) {

        // make real TextItem instances out of the specified textItems, because for example undo/redo actions could have removed the object types due
        // to the use of angular.to/fromJson()
        for (var i = 0; i < textItems.length; i++) {
          textItems[i] = angular.extend(TextItemFactory.getPrototype(), textItems[i]);
          textItems[i].font = angular.extend(FontFactory.getPrototype(), textItems[i].font);
        }

        this.textItems = textItems;
        this.incrementModelStateVersion();
      };

      /**
       *
       * @param {TemplateBackgroundItem} backgroundItem set right page TemplateBackgroundItem
       */
      DesignArea.prototype.setTemplateBackgroundItemLeft = function (backgroundItem) {
        this.templateBackgroundItems[0] = backgroundItem;
        this.incrementModelStateVersion();
      };

      /**
       *
       * @param {TemplateBackgroundItem} backgroundItem set right page TemplateBackgroundItem
       */
      DesignArea.prototype.setTemplateBackgroundItemRight = function (backgroundItem) {

        var index = this.isCover() ? 0 : 1;

        this.templateBackgroundItems[index] = backgroundItem;
        this.incrementModelStateVersion();
      };

      /**
       * @returns {TemplateBackgroundItem} left page TemplateBackgroundItem instance
       */
      DesignArea.prototype.getTemplateBackgroundItemLeft = function () {
        return this.templateBackgroundItems[0];
      };

      /**
       * @returns {TemplateBackgroundItem} right page TemplateBackgroundItem instance, for cover pages it doesn't matter if you call for left or right background
       */
      DesignArea.prototype.getTemplateBackgroundItemRight = function () {
        return this.isCover() ? this.templateBackgroundItems[0] : this.templateBackgroundItems[1];
      };


      /**
       *
       * @param {Array} templateBackgroundItems
       */
      DesignArea.prototype.setTemplateBackgroundItems = function (templateBackgroundItems) {

        // make real TemplateBackgroundItem instances out of the specified templateBackgroundItems, because for example undo/redo actions could have removed the object types due
        // to the use of angular.to/fromJson()
        for (var i = 0; i < templateBackgroundItems.length; i++) {
          templateBackgroundItems[i] = angular.extend(TemplateBackgroundItemFactory.getPrototype(), templateBackgroundItems[i]);
        }

        this.templateBackgroundItems = templateBackgroundItems;
        this.incrementModelStateVersion();

      };


      /**
       * @returns {Array} array of TemplateBackgroundItem instances
       */
      DesignArea.prototype.getTemplateBackgroundItems = function () {
        return this.templateBackgroundItems;
      };


      /**
       *
       * @param {ImageItem} imageItem to put on left DesignArea half
       */
      DesignArea.prototype.setImageBackgroundItemLeft = function (imageItem) {
        imageItem.checkSafetyArea();
        imageItem.setUsedAsBackgroundImage('left');

        for (var i = this.imageBackgroundItems.length - 1; i >= 0; i--) {
          var item = this.imageBackgroundItems[i];

          // find existing left page image background to remove
          if (item.getCenterX() < this.getWidth() / 2 && item.getWidth() <= this.getWidth() * 3 / 4) { // significantly smaller than the full design area? --> single page background
            this.removeItemBox(item);
          }

          // find existing full page image background and remove it
          if (item.getWidth() > this.getWidth() * 3 / 4) { // significantly larger than the half design area? --> doublepage background
            this.removeItemBox(item);
          }
        }

        this.imageBackgroundItems.push(imageItem);
        this.incrementModelStateVersion();

      };

      /**
       *
       * @param {ImageItem} imageItem to put on right DesignArea half
       */
      DesignArea.prototype.setImageBackgroundItemRight = function (imageItem) {
        imageItem.checkSafetyArea();
        imageItem.setUsedAsBackgroundImage('right');

        for (var i = this.imageBackgroundItems.length - 1; i >= 0; i--) {
          var item = this.imageBackgroundItems[i];

          // find existing right page image background to remove
          if (item.getCenterX() > this.getWidth() / 2 && item.getWidth() <= this.getWidth() * 3 / 4) { // significantly smaller than the full design area? --> single page background
            this.removeItemBox(item);
          }

          // find existing full page image background and remove it
          if (item.getWidth() > this.getWidth() * 3 / 4) { // significantly larger than the half design area? --> doublepage background
            this.removeItemBox(item);
          }
        }

        this.imageBackgroundItems.push(imageItem);
        this.incrementModelStateVersion();
      };

      /**
       *
       * @param {ImageItem} imageItem to expand over both DesignArea halfs
       */
      DesignArea.prototype.setImageBackgroundItemBoth = function (imageItem) {
        imageItem.checkSafetyArea();
        imageItem.setUsedAsBackgroundImage('left');
        for (var i = this.imageBackgroundItems.length - 1; i >= 0; i--) {
          this.removeItemBox(this.imageBackgroundItems[i]);
        }
        this.imageBackgroundItems.push(imageItem);
        this.incrementModelStateVersion();
      };

      /**
       *
       * @return {Array} the ImageItems used as background on the DesignArea
       */
      DesignArea.prototype.getImageBackgroundItems = function () {
        return this.imageBackgroundItems;
      };

      /**
       *
       * @return {ImageItem} the image background item on the left page, if any. Will return a doublepage sized background, too.
       */
      DesignArea.prototype.getImageBackgroundItemLeft = function () {

        for (var i = 0; i < this.imageBackgroundItems.length; i++) {
          var item = this.imageBackgroundItems[i];

          // find and return existing left page image background
          if (item.getCenterX() < this.getWidth() / 2 && item.getWidth() <= this.getWidth() * 3 / 4) { // significantly smaller than the full design area? --> single page background
            return item;
          }

          // find and return existing full page image background
          if (item.getWidth() > this.getWidth() * 3 / 4) { // significantly larger than the half design area? --> doublepage background
            return item;
          }
        }

      };


      /**
       *
       * @return {ImageItem} the image background item on the right page, if any. Will return a doublepage sized background, too.
       */
      DesignArea.prototype.getImageBackgroundItemRight = function () {

        for (var i = 0; i < this.imageBackgroundItems.length; i++) {
          var item = this.imageBackgroundItems[i];

          // find and return existing right page image background
          if (item.getCenterX() > this.getWidth() / 2 && item.getWidth() <= this.getWidth() * 3 / 4) { // significantly smaller than the full design area? --> single page background
            return item;
          }

          // find and return existing full page image background
          if (item.getWidth() > this.getWidth() * 3 / 4) { // significantly larger than the half design area? --> doublepage background
            return item;
          }
        }

      };

      DesignArea.prototype.setImageBackgroundItems = function (imageItems) {
        // make real ImageItem instances out of the specified imageBackgroundItems, because for example undo/redo actions could have removed the object types due
        // to the use of angular.to/fromJson()
        for (var i = 0; i < imageItems.length; i++) {
          var imageBackgroundItem = angular.extend(ImageItemFactory.getPrototype(), imageItems[i]);
          imageBackgroundItem.setUsedAsBackgroundImage(i === 0 ? 'left' : 'right');
          imageItems[i] = imageBackgroundItem;
        }

        this.imageBackgroundItems = imageItems;
      };

      /**
       *
       * @param {ImageItem} imageItem
       */
      DesignArea.prototype.addImageItem = function (imageItem) {
        imageItem.checkSafetyArea();
        this.imageItems.push(imageItem);
        if (imageItem.getCenterX() <= this.getWidth() / 2) {
          this.updateLayoutModified('left');
        } else {
          this.updateLayoutModified('right');
        }
        this.incrementModelStateVersion();

      };

      /**
       *
       * @param {ImageItem} imageItem
       */
      DesignArea.prototype.addClipartItem = function (clipartItem) {
        clipartItem.checkSafetyArea();
        this.clipartItems.push(clipartItem);
        this.incrementModelStateVersion();
      };


      /**
       * Returns the ImageItems of the DesignArea. If the optional page half parameter is specified (i.e. 'left' or 'right') only the items on
       * that page half are returned
       * @param pageHalf 'left' or 'right' (optional)
       * @returns {Array} ImageItems on the DesignArea
       */
      DesignArea.prototype.getImageItems = function (pageHalf) {

        if (pageHalf === 'left' || pageHalf === 'right') {

          var result = [];

          for (var i = 0; i < this.imageItems.length; i++) {

            if (pageHalf === 'left' && this.imageItems[i].getCenterX() <= this.getWidth() / 2 ||
              pageHalf === 'right' && this.imageItems[i].getCenterX() > this.getWidth() / 2) {
              result.push(this.imageItems[i]);
            }

          }

          return result;

        } else {
          return this.imageItems;
        }
      };


      /**
       *
       * @param fileHandleId
       * @return {Array} ImageItems corresponding to the specified FileHandle id
       */
      DesignArea.prototype.getImageItemsForFileHandleId = function (fileHandleId) {
        var imageItemsForFileHandleId = [];
        this.getImageItems().forEach(function (imageItem) {
          if (imageItem.getFileHandleId() === fileHandleId) {
            imageItemsForFileHandleId.push(imageItem);
          }
        });
        return imageItemsForFileHandleId;
      };

      /**
       * Returns the ClipartItems of the DesignArea. If the optional page half parameter is specified (i.e. 'left' or 'right') only the items on
       * that page half are returned
       * @param pageHalf 'left' or 'right' (optional)
       * @returns {Array} ClipartItems on the DesignArea
       */
      DesignArea.prototype.getClipartItems = function (pageHalf) {

        if (pageHalf === 'left' || pageHalf === 'right') {
          var result = [];

          for (var i = 0; i < this.clipartItems.length; i++) {
            if (pageHalf === 'left' && this.clipartItems[i].getCenterX() <= this.getWidth() / 2 ||
              pageHalf === 'right' && this.clipartItems[i].getCenterX() > this.getWidth() / 2) {
              result.push(this.clipartItems[i]);
            }
          }
          return result;

        } else {
          return this.clipartItems;
        }
      };


      DesignArea.prototype.setImageItems = function (imageItems) {

        // make real ImageItem instances out of the specified imageItems, because for example undo/redo actions could have removed the object types due
        // to the use of angular.to/fromJson()
        for (var i = 0; i < imageItems.length; i++) {
          imageItems[i] = angular.extend(ImageItemFactory.getPrototype(), imageItems[i]);
          imageItems[i].viewport = angular.extend(ViewPortFactory.getPrototype(), imageItems[i].viewport);
        }

        this.imageItems = imageItems;
        this.incrementModelStateVersion();
      };

      DesignArea.prototype.setClipartItems = function (clipartItems) {

        // make real ClipartItem instances out of the specified clipartItems, because for example undo/redo actions could have removed the object types due
        // to the use of angular.to/fromJson()
        for (var i = 0; i < clipartItems.length; i++) {
          clipartItems[i] = angular.extend(ClipartItemFactory.getPrototype(), clipartItems[i]);
        }

        this.clipartItems = clipartItems;
        this.incrementModelStateVersion();
      };


      DesignArea.prototype.getPortraitImageItemsForHalfPage = function (pageHalf) {

        var imageItems = this.getImageItems(pageHalf);

        var result = [];

        for (var i = 0; i < imageItems.length; i++) {
          if (imageItems[i].getThumbKey()) {
            if (imageItems[i].getThumbKey().height > imageItems[i].getThumbKey().width) {
              result.push(imageItems[i]);
            }
          }
        }
        return result;
      };

      DesignArea.prototype.getLandscapeImageItemsForHalfPage = function (pageHalf) {

        var imageItems = this.getImageItems(pageHalf);

        var result = [];

        for (var i = 0; i < imageItems.length; i++) {
          if (imageItems[i].getThumbKey()) {
            if (imageItems[i].getThumbKey().width >= imageItems[i].getThumbKey().height) {
              result.push(imageItems[i]);
            }
          }
        }
        return result;
      };


      DesignArea.prototype.setImageItemsForPageHalf = function (pageHalf, imageItems) {

        for (var i = 0; i < imageItems.length; i++) {
          imageItems[i] = angular.extend(ImageItemFactory.getPrototype(), imageItems[i]);
          imageItems[i].viewport = angular.extend(ViewPortFactory.getPrototype(), imageItems[i].viewport);
        }
        if (pageHalf === 'left') {
          var rightImages = this.getImageItems('right');
          this.imageItems = imageItems.concat(rightImages);
        }
        else if (pageHalf === 'right') {
          var leftImages = this.getImageItems('left');
          this.imageItems = imageItems.concat(leftImages);
        }
        this.incrementModelStateVersion();
      };


      DesignArea.prototype.isDetailInteractionMode = function () {
        return this.ng.detailInteractionMode;
      };

      DesignArea.prototype.setDetailInteractionMode = function (trueOrFalse) {
        this.ng.detailInteractionMode = trueOrFalse;
      };

      DesignArea.prototype.isSelected = function () {
        return this.ng.selected;
      };

      DesignArea.prototype.setSelected = function (trueOrFalse) {
        this.ng.selected = trueOrFalse;
      };

      DesignArea.prototype.deselectAllItems = function () {

        var self = this;
        var allItems = this.getAllItems(false);

        allItems.forEach(function (itemBox) {

          if (itemBox.isSelected()) {
            itemBox.setSelected(false);
          }
        });

      };

      DesignArea.prototype.isCover = function () {
        return this.ng.type === 'cover';
      };

      DesignArea.prototype.setType = function (type) {
        this.ng.type = type;
      };

      DesignArea.prototype.getType = function () {
        return this.ng.type;
      };

      DesignArea.prototype.isLeftPageBlocked = function () {
        return this.ng.leftPageBlocked;
      };

      DesignArea.prototype.setLeftPageBlocked = function (trueOrFalse) {
        this.ng.leftPageBlocked = trueOrFalse;
      };

      DesignArea.prototype.isRightPageBlocked = function () {
        return this.ng.rightPageBlocked;
      };

      DesignArea.prototype.setRightPageBlocked = function (trueOrFalse) {
        this.ng.rightPageBlocked = trueOrFalse;
      };

      DesignArea.prototype.setButtonBarInitialized = function (trueOrFalse) {
        this.ng.buttonBarInitialized = trueOrFalse;
      };

      DesignArea.prototype.isButtonBarInitialized = function () {
        return this.ng.buttonBarInitialized;
      };

      DesignArea.prototype.setTextItemEditBoxInitialized = function (trueOrFalse) {
        this.ng.textItemEditBoxInitialized = trueOrFalse;
      };

      DesignArea.prototype.isTextItemEditBoxInitialized = function () {
        return this.ng.textItemEditBoxInitialized;
      };

      /**
       * The version number of the model state is meant for watches to quickly find out if the model state changed by comparing the old version
       * number with the current one. This avoids the need for deep watches on the model structure which has pretty poor perfomance.
       * @return {number} the version number of the model state
       */
      DesignArea.prototype.getModelStateVersion = function () {
        return this.ng.modelStateVersion;
      };

      DesignArea.prototype.setModelStateVersion = function (modelStateVersion) {
        this.ng.modelStateVersion = modelStateVersion;
      };

      DesignArea.prototype.incrementModelStateVersion = function () {
        this.ng.modelStateVersion++;
      };

      /**
       * @param {Boolean} trueOrFalse trigger a canvas update (re-draw)?
       */
      DesignArea.prototype.setTriggerCanvasUpdate = function (trueOrFalse) {
        this.ng.triggerCanvasUpdate = trueOrFalse;
      };

      /**
       *
       * @param trueOrFalse
       * @return {Boolean} is a canvas update (re-draw) meant to be triggered?
       */
      DesignArea.prototype.isTriggerCanvasUpdate = function () {
        return this.ng.triggerCanvasUpdate;
      };

      DesignArea.prototype.getWidth = function () {
        return this.ng.width;
      };

      DesignArea.prototype.setWidth = function (width) {
        if (width !== this.ng.width) {
          this.ng.width = width;
          if (this.isCover()) {
            var backgroundItem = this.getTemplateBackgroundItemLeft();
            backgroundItem.setWidth(this.ng.width + 2 * this.ng.bleedMarginHorizontal);
            backgroundItem.setCenterX(this.ng.width / 2);
          }
        }
      };

      DesignArea.prototype.getSafetyMargin = function () {
        return this.ng.safetyMargin;
      };

      DesignArea.prototype.setSafetyMargin = function (safetyMargin) {
        this.ng.safetyMargin = safetyMargin;
      };

      DesignArea.prototype.setTextRestrictionBox = function (textRestrictionBox) {
        this.ng.textRestrictionBox = textRestrictionBox;
      };

      DesignArea.prototype.getTextRestrictionBox = function () {
        return this.ng.textRestrictionBox;
      };

      DesignArea.prototype.getBleedMarginHorizontal = function () {
        return this.ng.bleedMarginHorizontal;
      };

      DesignArea.prototype.setBleedMarginHorizontal = function (bleedMarginHorizontal) {
        this.ng.bleedMarginHorizontal = bleedMarginHorizontal;
      };

      DesignArea.prototype.getBleedMarginVertical = function () {
        return this.ng.bleedMarginVertical;
      };

      DesignArea.prototype.setBleedMarginVertical = function (bleedMarginVertical) {
        this.ng.bleedMarginVertical = bleedMarginVertical;
      };

      DesignArea.prototype.getSpineWidth = function () {
        // FIXME Frank Bruns 05.02.2015: The spine width is in 1/10 millimeters here although we should use pixels as in getWidth(). Why is that?
        return this.ng.spineWidth;
      };

      DesignArea.prototype.setSpineWidth = function (spineWidth, keepItemPositions) {
        if (this.ng.spineWidth === spineWidth) {
          return;
        }
        var deltaSpineWidth = (spineWidth - this.ng.spineWidth);
        this.ng.spineWidth = spineWidth;
        if (!keepItemPositions) {
          this.getImageAndTextAndClipartItems('right').forEach(function (item) {
            item.setCenterX(item.getCenterX() + deltaSpineWidth * AppConstants.MM_TO_PX);
          });
        }
        var spineTextItem = this.getSpineTextItem();
        if (spineTextItem) {
          spineTextItem.setHeight(spineWidth * AppConstants.MM_TO_PX);
          spineTextItem.setCenterX(this.getWidth() / 2);
          spineTextItem.setImageRenderingNeeded(true);
        }

        var newTextRestrictionBox = {top: this.getSafetyMargin(),
          left: this.getSafetyMargin(),
          width: this.getWidth() - 2 * this.getSafetyMargin(),
          height: this.getHeight() - 2 * this.getSafetyMargin()};
        this.setTextRestrictionBox(newTextRestrictionBox);

        this.getTextItems().forEach(function (item) {
          item.setRestrictionBox(newTextRestrictionBox);
        });

        var newSafetyArea = {innerRect: {left: this.getSafetyMargin(),
          top: this.getSafetyMargin(),
          width: this.getWidth() - 2 * this.getSafetyMargin(),
          height: this.getHeight() - 2 * this.getSafetyMargin()},
          outerRect: {left: -this.getBleedMarginHorizontal(),
            top: -this.getBleedMarginVertical(),
            width: this.getWidth() + 2 * this.getBleedMarginHorizontal(),
            height: this.getHeight() + 2 * this.getBleedMarginVertical()}
        };
        this.getImageItems().forEach(function (item) {
          item.setSafetyArea(newSafetyArea);
        });
      };

      DesignArea.prototype.isSpineLogoEnabled = function () {
        return this.ng.spineLogoEnabled;
      };

      DesignArea.prototype.setSpineLogoEnabled = function (trueOrFalse) {
        this.ng.spineLogoEnabled = trueOrFalse;
      };

      DesignArea.prototype.getSpineContentRotation = function () {
        return this.ng.spineContentRotation;
      };

      DesignArea.prototype.setSpineContentRotation = function (value) {
        this.ng.spineContentRotation = value;
      };

      DesignArea.prototype.getSpineLogoElementId = function () {
        return this.ng.spineLogoElementId;
      };
      DesignArea.prototype.setSpineLogoElementId = function (spineLogoElementId) {
        this.ng.spineLogoElementId = spineLogoElementId;
      };

      DesignArea.prototype.getSpineMaxWidth = function () {
        return this.ng.spineMaxWidth;
      };

      DesignArea.prototype.setSpineMaxWidth = function (spineMaxWidth) {
        this.ng.spineMaxWidth = spineMaxWidth;
      };

      DesignArea.prototype.getHeight = function () {
        return this.ng.height;
      };

      DesignArea.prototype.setHeight = function (height) {
        this.ng.height = height;
      };

      DesignArea.prototype.getCssWidth = function () {
        return this.ng.cssWidth;
      };

      DesignArea.prototype.setCssWidth = function (width) {
        this.ng.cssWidth = width;
        AppValues.designAreaScale = this.getCanvasWidth() / this.getCssWidth();
      };

      DesignArea.prototype.setPrintAreaCssDimension = function (printAreaCssWidth, printAreaCssHeight) {
        this.setCssWidth(printAreaCssWidth * (1 + 2 * AppConstants.CANVAS_PADDING_PERCENT));
        this.setCssHeight(printAreaCssHeight * (1 + 2 * AppConstants.CANVAS_PADDING_PERCENT));
      };

      DesignArea.prototype.getPrintAreaCssHeight = function () {
        return this.getCssHeight() / (1 + 2 * AppConstants.CANVAS_PADDING_PERCENT);
      };


      DesignArea.prototype.getCssHeight = function () {
        return this.ng.cssHeight;
      };

      DesignArea.prototype.setCssHeight = function (height) {
        this.ng.cssHeight = height;
      };

      DesignArea.prototype.getZIndex = function() {
        return this.ng.zIndex;
      };

      DesignArea.prototype.setZIndex = function(zIndex) {
        this.ng.zIndex = zIndex;
      };

      DesignArea.prototype.getPaddingHorizontal = function () {
        return this.getWidth() * AppConstants.CANVAS_PADDING_PERCENT;
      };

      DesignArea.prototype.getPaddingVertical = function () {
        return this.getHeight() * AppConstants.CANVAS_PADDING_PERCENT;
      };

      DesignArea.prototype.getCanvasWidth = function () {
        return this.getWidth() + 2 * this.getPaddingHorizontal();
      };

      DesignArea.prototype.getCanvasHeight = function () {
        return this.getHeight() + 2 * this.getPaddingVertical();
      };

      /**
       *
       * @return {ItemBox} the currently selected ItemBox on the DesignArea, if any.
       */
      DesignArea.prototype.getSelectedItemBox = function () {
        if (this.isSelected()) {
          var allItems = this.getAllItems(false);
          for (var i = 0; i < allItems.length; i++) {
            if (allItems[i].isSelected()) {
              return allItems[i];
            }
          }
        }
      };

      /**
       *
       * @param {ItemBox} itemBox the ItemBox to remove from this DesignArea
       */
      DesignArea.prototype.removeItemBox = function (itemBox) {

        var itemBoxes = null;

        if (this.hasImageBackgroundItem(itemBox) || this.hasImageItem(itemBox)) {

          itemBoxes = this.hasImageBackgroundItem(itemBox) ? this.getImageBackgroundItems() : this.getImageItems();

          if (itemBox.getFileHandleId()) {
            var fileHandle = FileHandleService.getFileHandle(itemBox.getFileHandleId());
            fileHandle.decreaseUsageCount();
          }

        } else if (this.hasTextItem(itemBox)) {

          itemBoxes = this.getTextItems();

        } else if (this.hasClipartItem(itemBox)) {

          itemBoxes = this.getClipartItems();

        } else {
          $log.error('Could not find itemBox.', itemBox);
          return; // unknown item type, do nothing
        }

        Utils.removeFromArray(itemBoxes, itemBox);
        this.incrementModelStateVersion();


        if (this.getTextItems('left', true).length <= 0 && this.getImageItems('left').length <= 0) {
          delete this.ng.layouts.left;
        }

        if (this.getTextItems('right', true).length <= 0 && this.getImageItems('right').length <= 0) {
          delete this.ng.layouts.right;
        }

        if (itemBox instanceof ImageItemFactory.getClass() || itemBox instanceof TextItemFactory.getClass()) {
          this.updateLayoutModified('left');
          this.updateLayoutModified('right');
        }
      };

      /**
       * Removes all ImageItems corresponding to the specified FileHandle id from this DesignArea.
       * @param fileHandleId the FileHandle id to remove the image for
       */
      DesignArea.prototype.removeImageItemsByFileHandleId = function (fileHandleId) {
        var imageItems = this.getImageItemsForFileHandleId(fileHandleId);

        var self = this;
        imageItems.forEach(function iterate(imageItem) {
          $log.warn('Removing ImageItem corresponding to a broken FileHandle. ', self, imageItem);
          self.removeItemBox(imageItem);
        });
      };


      /**
       * Clear the complete content from the specified page half, resp. the whole DesignArea.
       * @param pageHalf (optionally) limit the operation to the specified page half, 'left' or 'right'
       */
      DesignArea.prototype.clearContent = function (pageHalf) {
        var items = this.getImageAndTextAndClipartItems(pageHalf).concat(this.getImageBackgroundItems(pageHalf));
        var self = this;
        items.forEach(function remove(itemBox) {
          self.removeItemBox(itemBox);
        });
        this.incrementModelStateVersion();
      };


      DesignArea.prototype.moveLayerDown = function (itemBox) {

        var itemBoxes = this.getAllItems(true);
        var itemBoxIndex = itemBoxes.indexOf(itemBox);
        if (itemBoxIndex > 0) {
          var newLayerIndex = itemBoxes[itemBoxIndex - 1].getLayerIndex();
          if (newLayerIndex < AppConstants.MIN_UNRESERVED_LAYER_INDEX) {
            $log.warn('move layer down not allowed for itemBox', itemBox);
            return;
          }
          itemBoxes[itemBoxIndex - 1].setLayerIndex(itemBox.getLayerIndex());
          itemBox.setLayerIndex(newLayerIndex);
          this.incrementModelStateVersion();
        }
      };

      DesignArea.prototype.moveToBottomLayer = function (itemBox) {

        var itemBoxes = this.getAllItems(true);
        var itemBoxIndex = itemBoxes.indexOf(itemBox);
        if (itemBoxIndex > 0) {
          var bottommostItemBox, newLayerIndex;
          for (var i = 0; i < itemBoxes.length; i++) {
            if (!bottommostItemBox && itemBoxes[i].getLayerIndex() >= AppConstants.MIN_UNRESERVED_LAYER_INDEX) {
              bottommostItemBox = itemBoxes[i];
              newLayerIndex = bottommostItemBox.getLayerIndex();
            }
            if (itemBoxes[i].getLayerIndex() >= AppConstants.MIN_UNRESERVED_LAYER_INDEX) {
              itemBoxes[i].setLayerIndex(itemBoxes[i].getLayerIndex() + 1);
            }

          }
          itemBox.setLayerIndex(newLayerIndex);
          this.incrementModelStateVersion();
        }
      };

      DesignArea.prototype.moveLayerUp = function (itemBox) {

        var itemBoxes = this.getAllItems(true);
        var itemBoxIndex = itemBoxes.indexOf(itemBox);
        if (itemBoxIndex > 0 && itemBoxIndex <= itemBoxes.length - 2) {
          var newLayerIndex = itemBoxes[itemBoxIndex + 1].getLayerIndex();
          itemBoxes[itemBoxIndex + 1].setLayerIndex(itemBox.getLayerIndex());
          itemBox.setLayerIndex(newLayerIndex);
          this.incrementModelStateVersion();
        }
      };

      DesignArea.prototype.moveToTopLayer = function (itemBox) {
        itemBox.setLayerIndex(this.getNextFreeLayerIndex());
        this.incrementModelStateVersion();
      };

      /**
       * Swaps the layers (z-index) of the specified items
       * @param itemBoxOne
       * @param itemBoxTwo
       */
      DesignArea.prototype.swapLayers = function (itemBoxOne, itemBoxTwo) {

        var newLayerIndexOne = itemBoxTwo.getLayerIndex();
        itemBoxTwo.setLayerIndex(itemBoxOne.getLayerIndex());
        itemBoxOne.setLayerIndex(newLayerIndexOne);
        this.incrementModelStateVersion();
      };

      DesignArea.prototype.fitToDimensions = function (maxWidth, maxHeight) {
        if (this.isDetailInteractionMode()) {
          if (maxWidth < AppConstants.DETAIL_DESIGN_AREA_MIN_DIMENSION.width) {
            maxWidth = AppConstants.DETAIL_DESIGN_AREA_MIN_DIMENSION.width;
          }
          if (maxHeight < AppConstants.DETAIL_DESIGN_AREA_MIN_DIMENSION.height) {
            maxHeight = AppConstants.DETAIL_DESIGN_AREA_MIN_DIMENSION.height;
          }
        }

        var aspectRatio = this.getWidth() / this.getHeight();

        var newWidth = maxWidth;
        var newHeight = maxWidth / aspectRatio;

        if (newHeight > maxHeight) {
          newHeight = maxHeight;
          newWidth = maxHeight * aspectRatio;
        }

        this.setPrintAreaCssDimension(newWidth, newHeight);
      };

      DesignArea.prototype.setToStoryboardSize = function () {
        // subtract 20px for scroll bar
        var containerWidth = $document.width() - 20;
        var designAreasPerRow = AppConstants.STORYBOARD_MAX_DESIGN_AREAS_PER_ROW;
        var aspectRatio = this.getWidth() / this.getHeight();
        // 50 = the padding to the left and the right for each design area in storyboard mode, 10 = additional spacing
        var spacing = 2 * 50 + 10;
        var newCssWidth = containerWidth / designAreasPerRow - spacing;
        if (newCssWidth < AppConstants.STORYBOARD_DESIGN_AREA_MIN_DIMENSION.width) {
          designAreasPerRow = Math.max(AppConstants.STORYBOARD_MIN_DESIGN_AREAS_PER_ROW,
            Math.floor(containerWidth / (AppConstants.STORYBOARD_DESIGN_AREA_MIN_DIMENSION.width + spacing)));
          newCssWidth = containerWidth / designAreasPerRow - spacing;
        }
        var newCssHeight = newCssWidth / aspectRatio;
        while (designAreasPerRow > AppConstants.STORYBOARD_MIN_DESIGN_AREAS_PER_ROW &&
          newCssHeight < AppConstants.STORYBOARD_DESIGN_AREA_MIN_DIMENSION.height) {
          designAreasPerRow--;
          newCssWidth = containerWidth / designAreasPerRow - spacing;
          newCssHeight = newCssWidth / aspectRatio;
        }

        this.setPrintAreaCssDimension(newCssWidth, newCssHeight);
        this.setTriggerCanvasUpdate(true);
      };

      DesignArea.prototype.getBarCode = function () {
        return this.ng.barCode;
      };

      DesignArea.prototype.setBarCode = function (barCode) {
        this.ng.barCode = barCode;
      };

      DesignArea.prototype.setBarCodeAttribute = function (attribute, value) {
        this.ng.barCode[attribute] = value;
      };

      DesignArea.prototype.getNextFreeLayerIndex = function () {
        var nextFreeLayerIndex = AppConstants.MIN_UNRESERVED_LAYER_INDEX;
        this.getAllItems(false).forEach(function iterateItems(item) {
          nextFreeLayerIndex = Math.max(nextFreeLayerIndex, item.getLayerIndex() + 1);
        });
        return nextFreeLayerIndex;
      };


      return {

        getClass: function () {
          return DesignArea;
        },

        getPrototype: function () {
          return new DesignArea();
        },

        createDesignArea: function (width, height, bleedMarginHorizontal, bleedMarginVertical, safetyMargin, backgroundItemLeft, backgroundItemRight) {

          if (width === null || width <= 0 || height === null || height <= 0) {
            throw new Error('Can\'t create a DesignArea with insufficiently defined width (' + width + ') or height (' + height + ')');
          }

          var designArea = new DesignArea();
          designArea.setWidth(width);
          designArea.setHeight(height);
          designArea.setSafetyMargin(safetyMargin);
          designArea.setBleedMarginHorizontal(bleedMarginHorizontal);
          designArea.setBleedMarginVertical(bleedMarginVertical);

          designArea.setTemplateBackgroundItemLeft(backgroundItemLeft);
          if (backgroundItemRight) {
            designArea.setTemplateBackgroundItemRight(backgroundItemRight);
          }

          var textRestrictionBox = {top: safetyMargin,
            left: safetyMargin,
            width: width - 2 * safetyMargin,
            height: height - 2 * safetyMargin};
          designArea.setTextRestrictionBox(textRestrictionBox);

          return designArea;
        }

      };
    }
  ])
  ;
})
();/**
 * Creates Box instances with common attributes for all project relevant boxes that are considered to be abstract and are only for subclasses to
 * use with prototypical inheritance.
 *
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('ItemBoxPrototypeFactory', [
    '$log',
    function ($log) {

      function ItemBox() {

        this.baseElement = {
          centerX: 0,
          centerY: 0,
          width: 0,
          height: 0,
          rotation: 0,
          layerIndex: undefined,
          borderWidth: 0,
          borderColor: '#000000',
          itemConstraints: {
            contentEditable: true,
            positionEditable: true,
            layerEditable: true,
            borderAllowed: false,
            removable: true
          }
        };

        this.ng = {
          modelStateVersion: 0,
          selected: false,
          mouseDown: false,
          buttonBarOrientation: 'below',
          fadeIn: false,
          layoutModifiedByUser: false,
          restrictionBox: null,
          safetyArea: null,
          contextView: false
        };

      }

      ItemBox.prototype.setRestrictionBox = function (restrictionBox) {
        this.ng.restrictionBox = restrictionBox;
      };

      ItemBox.prototype.checkRestrictionBox = function (baseElement, event) {
        if (!this.ng.restrictionBox) {
          return baseElement;
        }
        if (baseElement.rotation % 90 !== 0) {
          return baseElement;
        }

        var correctDimension = (event.target.name.indexOf('scale') === 0 || event.target.name.indexOf('crop') === 0);

        var swapDimensions = baseElement.rotation === 90 || baseElement.rotation === 270;
        var localWidth = swapDimensions ? baseElement.height : baseElement.width;
        var localHeight = swapDimensions ? baseElement.width : baseElement.height;

        // check top border
        if (baseElement.centerY - localHeight / 2 < this.ng.restrictionBox.top) {
          if (correctDimension) {
            localHeight = (baseElement.centerY + localHeight / 2) - this.ng.restrictionBox.top;
          }
          baseElement.centerY = this.ng.restrictionBox.top + localHeight / 2;
        }
        // check left border
        if (baseElement.centerX - localWidth / 2 < this.ng.restrictionBox.left) {
          if (correctDimension) {
            localWidth = (baseElement.centerX + localWidth / 2) - this.ng.restrictionBox.left;
          }
          baseElement.centerX = this.ng.restrictionBox.left + localWidth / 2;
        }
        // check right border
        if (baseElement.centerX + localWidth / 2 > this.ng.restrictionBox.left + this.ng.restrictionBox.width) {
          if (correctDimension) {
            localWidth = this.ng.restrictionBox.left + this.ng.restrictionBox.width - (baseElement.centerX - localWidth / 2);
          }
          baseElement.centerX = this.ng.restrictionBox.left + this.ng.restrictionBox.width - localWidth / 2;
        }
        // check bottom border
        if (baseElement.centerY + localHeight / 2 > this.ng.restrictionBox.top + this.ng.restrictionBox.height) {
          if (correctDimension) {
            localHeight = this.ng.restrictionBox.top + this.ng.restrictionBox.height - (baseElement.centerY - localHeight / 2);
          }
          baseElement.centerY = this.ng.restrictionBox.top + this.ng.restrictionBox.height - localHeight / 2;
        }

        baseElement.width = swapDimensions ? localHeight : localWidth;
        baseElement.height = swapDimensions ? localWidth : localHeight;
        return baseElement;
      };

      /**
       * The version number of the model state is meant for watches to quickly find out if the model state changed by comparing the old version
       * number with the current one. This avoids the need for deep watches on the model structure which has pretty poor perfomance.
       * @return {number} the version number of the model state
       */
      ItemBox.prototype.getModelStateVersion = function () {
        return this.ng.modelStateVersion;
      };

      ItemBox.prototype.incrementModelStateVersion = function () {
        this.ng.modelStateVersion++;
      };

      ItemBox.prototype.getCenterX = function () {
        return this.baseElement.centerX;
      };

      ItemBox.prototype.setCenterX = function (centerX) {
        if (this.baseElement.centerX !== centerX) {
          this.baseElement.centerX = centerX;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.getCenterY = function () {
        return this.baseElement.centerY;
      };

      ItemBox.prototype.setCenterY = function (centerY) {
        if (this.baseElement.centerY !== centerY) {
          this.baseElement.centerY = centerY;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.getWidth = function () {
        return this.baseElement.width;
      };

      ItemBox.prototype.setWidth = function (width) {
        if (this.baseElement.width !== width) {
          this.baseElement.width = width;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.getHeight = function () {
        return this.baseElement.height;
      };

      ItemBox.prototype.setHeight = function (height) {
        if (this.baseElement.height !== height) {
          this.baseElement.height = height;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.getRight = function () {
        return this.getCenterX() + this.getWidth() / 2;
      };

      ItemBox.prototype.getLeft = function () {
        return this.getCenterX() - this.getWidth() / 2;
      };

      ItemBox.prototype.getRotation = function () {
        return this.baseElement.rotation;
      };

      ItemBox.prototype.setRotation = function (rotation) {
        if (this.baseElement.rotation !== rotation) {
          this.baseElement.rotation = (rotation + 360) % 360;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.setLayerIndex = function (layerIndex) {
        if (layerIndex !== this.baseElement.layerIndex) {
          this.baseElement.layerIndex = layerIndex;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.getLayerIndex = function () {
        return this.baseElement.layerIndex;
      };

      /**
       *
       * @param {Number} borderWidthInMm the border with to set in tenth milimeters
       */
      ItemBox.prototype.setBorderWidth = function (borderWidthInTenthMm) {
        if (borderWidthInTenthMm !== this.baseElement.borderWidth) {
          this.baseElement.borderWidth = borderWidthInTenthMm;
          this.incrementModelStateVersion();
        }
      };

      /**
       *
       * @return {number} the border with in tenth milimeters
       */
      ItemBox.prototype.getBorderWidth = function () {
        return this.baseElement.borderWidth;
      };

      /**
       *
       * @param {String} borderWidthInMm the border color to set as CSS style string (e.g. #ff00ff or rgb(1.0, 0.0, 1.0))
       */
      ItemBox.prototype.setBorderColor = function (borderColor) {
        if (borderColor !== this.baseElement.borderColor) {
          this.baseElement.borderColor = borderColor;
          this.incrementModelStateVersion();
        }
      };

      /**
       *
       * @return {String} the border color
       */
      ItemBox.prototype.getBorderColor = function () {
        return this.baseElement.borderColor;
      };

      ItemBox.prototype.setSelected = function (trueOrFalse) {
        if (this.ng.selected !== trueOrFalse) {
          this.ng.selected = trueOrFalse;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.isSelected = function () {
        return this.ng.selected;
      };

      ItemBox.prototype.isMouseDown = function () {
        return this.ng.mouseDown;
      };

      ItemBox.prototype.setMouseDown = function (trueOrFalse) {
        if (this.ng.mouseDown !== trueOrFalse) {
          this.ng.mouseDown = trueOrFalse;
          this.incrementModelStateVersion();
        }
      };

      /**
       * Returns the button bar orientation for the item box
       * @return {string} orientation like 'above' or 'below'
       */
      ItemBox.prototype.getButtonBarOrientation = function () {
        return this.ng.buttonBarOrientation;
      };

      /**
       * Sets the button bar orientation for the item box
       * @param orientation {String} orientation like 'above' or 'below'
       */
      ItemBox.prototype.setButtonBarOrientation = function (orientation) {
        if (this.ng.buttonBarOrientation !== orientation) {
          this.ng.buttonBarOrientation = orientation;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.setFadeIn = function (doFadeIn) {
        if (this.ng.fadeIn !== doFadeIn) {
          this.ng.fadeIn = doFadeIn;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.isFadeIn = function () {
        return this.ng.fadeIn;
      };

      ItemBox.prototype.isLayoutModified = function () {
        return this.ng.layoutModifiedByUser;
      };

      ItemBox.prototype.setLayoutModified = function (trueOrFalse) {
        if (this.ng.layoutModifiedByUser !== trueOrFalse) {
          this.ng.layoutModifiedByUser = trueOrFalse;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.setItemConstraints = function (itemConstraints) {
        this.baseElement.itemConstraints = itemConstraints;
      };

      ItemBox.prototype.isContentEditable = function () {
        return this.baseElement.itemConstraints.contentEditable;
      };

      ItemBox.prototype.setContentEditable = function (trueOrFalse) {
        if (this.baseElement.itemConstraints.contentEditable !== trueOrFalse) {
          this.baseElement.itemConstraints.contentEditable = trueOrFalse;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.isPositionEditable = function () {
        return this.baseElement.itemConstraints.positionEditable;
      };

      ItemBox.prototype.setPositionEditable = function (trueOrFalse) {
        if (this.baseElement.itemConstraints.positionEditable !== trueOrFalse) {
          this.baseElement.itemConstraints.positionEditable = trueOrFalse;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.isLayerEditable = function () {
        return this.baseElement.itemConstraints.layerEditable;
      };

      ItemBox.prototype.setLayerEditable = function (trueOrFalse) {
        if (this.baseElement.itemConstraints.layerEditable !== trueOrFalse) {
          this.baseElement.itemConstraints.layerEditable = trueOrFalse;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.isBorderAllowed = function () {
        return this.baseElement.itemConstraints.borderAllowed;
      };

      ItemBox.prototype.setBorderAllowed = function (trueOrFalse) {
        if (this.baseElement.itemConstraints.borderAllowed !== trueOrFalse) {
          this.baseElement.itemConstraints.borderAllowed = trueOrFalse;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.isRemovable = function () {
        return this.baseElement.itemConstraints.removable;
      };

      ItemBox.prototype.setRemovable = function (trueOrFalse) {
        if (this.baseElement.itemConstraints.removable !== trueOrFalse) {
          this.baseElement.itemConstraints.removable = trueOrFalse;
          this.incrementModelStateVersion();
        }
      };

      ItemBox.prototype.isContextView = function () {
        return this.ng.contextView;
      };


      ItemBox.prototype.setContextView = function (trueOrFalse) {
        this.ng.contextView = trueOrFalse;
      };

      return {

        getClass: function () {
          return ItemBox;
        },

        getPrototype: function () {
          return new ItemBox();
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Provides a service for common design area data model tasks.
 */
(function () {
  'use strict';
  /* global createjs */

  angular.module('tatooine').factory('DesignAreaService', [
    '$log', '$q', '$timeout', 'Utils', 'AppConstants', 'AppValues', 'SafeApply', 'ImagingService', 'FileHandleService', 'ProjectService', 'ProductService', 'LayoutService', 'ImageItemFactory', 'TextItemFactory', 'ClipartItemFactory', 'NotificationService', 'MessageService',
    function ($log, $q, $timeout, Utils, AppConstants, AppValues, SafeApply, ImagingService, FileHandleService, ProjectService, ProductService, LayoutService, ImageItemFactory, TextItemFactory, ClipartItemFactory, NotificationService, MessageService) {


      var tweenLayoutTimeline = null;
      var swapImagesTweenRunning = false;
      var dragedDesignArea;
      // TODO Frank Bruns 01.04.2014: Maybe make an injectable constant from this (see canvasDesignAreaFactory, too)
      /**
       * Create an ImageItem data model with the generated thumbnail as a source image
       * and add it to the specified CanvasDesignArea at the specified position.
       *
       * @param designAreaModel
       * @param fileHandleThumbKey
       * @param fileHandle
       * @param centerX
       * @param centerY
       * @param pageHalfForBackground (optional for use as image backgrounds) --> 'left', 'right', 'both'
       * @return {Promise} an always successful promise
       */
      var addImageItemBoxModel = function (designAreaModel, fileHandleThumbKey, fileHandle, centerX, centerY, pageHalfForBackground) {

        var fileHandleId = fileHandle.getId();

        // Only the newly added itemBox should be selected (= toolFrame is shown).
        designAreaModel.deselectAllItems();

        // Only select the itemBox in detail interaction mode.
        var itemPreSelected = false;
        if (designAreaModel.isDetailInteractionMode()) {
          itemPreSelected = true;
        }

        var itemBoxSize = {
          width: 0,
          height: 0
        };

        if (pageHalfForBackground) {
          if (designAreaModel.isCover()) {
            itemBoxSize.width = pageHalfForBackground === 'both' ? designAreaModel.getWidth() : designAreaModel.getWidth() / 2 - (designAreaModel.getSpineWidth() / 2) * AppConstants.MM_TO_PX;
          } else {
            itemBoxSize.width = pageHalfForBackground === 'both' ? designAreaModel.getWidth() : designAreaModel.getWidth() / 2;
          }
          itemBoxSize.height = designAreaModel.getHeight();
        } else {
          var aspectRatio = fileHandleThumbKey.width / fileHandleThumbKey.height;
          if (aspectRatio > 1) {
            itemBoxSize.width = AppConstants.IMAGE_ITEM_BOX_DEFAULT_SIZE_PX;
            itemBoxSize.height = AppConstants.IMAGE_ITEM_BOX_DEFAULT_SIZE_PX / aspectRatio;
          } else {
            itemBoxSize.width = AppConstants.IMAGE_ITEM_BOX_DEFAULT_SIZE_PX * aspectRatio;
            itemBoxSize.height = AppConstants.IMAGE_ITEM_BOX_DEFAULT_SIZE_PX;
          }
        }


        // if the item would be placed on a blocked page half, we move it over to the not blocked area
        var itemLeftEdge = centerX - itemBoxSize.width / 2;
        var itemRightEdge = centerX + itemBoxSize.width / 2;
        if (designAreaModel.isLeftPageBlocked() && itemLeftEdge < designAreaModel.getWidth() / 2) {
          centerX = designAreaModel.getWidth() / 2 + itemBoxSize.width / 2;
        } else if (designAreaModel.isRightPageBlocked() && itemRightEdge > designAreaModel.getWidth() / 2) {
          centerX = designAreaModel.getWidth() / 2 - itemBoxSize.width / 2;
        }

        var safetyArea = {
          innerRect: {
            left: designAreaModel.getSafetyMargin(),
            top: designAreaModel.getSafetyMargin(),
            width: designAreaModel.getWidth() - 2 * designAreaModel.getSafetyMargin(),
            height: designAreaModel.getHeight() - 2 * designAreaModel.getSafetyMargin()
          },
          outerRect: {
            left: -designAreaModel.getBleedMarginHorizontal(),
            top: -designAreaModel.getBleedMarginVertical(),
            width: designAreaModel.getWidth() + 2 * designAreaModel.getBleedMarginHorizontal(),
            height: designAreaModel.getHeight() + 2 * designAreaModel.getBleedMarginVertical()
          }
        };

        var imageItem = ImageItemFactory.createImageItem(centerX, centerY, itemBoxSize.width, itemBoxSize.height, 0, designAreaModel.getNextFreeLayerIndex(), safetyArea);
        imageItem.setFileHandleId(fileHandleId);
        imageItem.setThumbKey(fileHandleThumbKey, true);
        imageItem.setSelected(itemPreSelected);
        imageItem.setFadeIn(true);
        if (fileHandle.getMyPhotosPictureId()) {
          imageItem.setMyPhotosPictureId(fileHandle.getMyPhotosPictureId());
        }

        var product = ProductService.getProductById(ProjectService.getProject().getProductId());
        var greenDotsPerMM = product.getGreenDotsPerMM();
        var yellowDotsPerMM = product.getYellowDotsPerMM();

        imageItem.setGreenDotsPerMM(greenDotsPerMM);
        imageItem.setYellowDotsPerMM(yellowDotsPerMM);
        imageItem.setOriginalImageWidth(fileHandle.getWidth());
        imageItem.setOriginalImageHeight(fileHandle.getHeight());
        imageItem.checkViewPort();

        if (pageHalfForBackground === 'left') {
          designAreaModel.setImageBackgroundItemLeft(imageItem);
        } else if (pageHalfForBackground === 'right') {
          designAreaModel.setImageBackgroundItemRight(imageItem);
        } else if (pageHalfForBackground === 'both') {
          designAreaModel.setImageBackgroundItemBoth(imageItem);
        } else {
          designAreaModel.addImageItem(imageItem);
        }

        if (fileHandle.getMyPhotosPictureId()) {
          imageItem.setMyPhotosPictureId(fileHandle.getMyPhotosPictureId());
        }

        return $q.when();
      };

      var applyLayoutBoxToItemBox = function (layoutBox, itemBox, pageOffset, aspectRatioLayoutToPage, withAnimation) {
        itemBox.setLayoutModified(false);


        var itemBoxBounds = {
          width: itemBox.getWidth(),
          height: itemBox.getHeight()
        };

        var widthPercent = 1;
        var heightPercent = 1;
        var leftPercent = 1;
        var rightPercent = 1;
        var topPercent = 1;
        var bottomPercent = 1;

        if (itemBox instanceof ImageItemFactory.getClass()) {
          itemBoxBounds.width += itemBox.getImageMargins().left + itemBox.getImageMargins().right;
          itemBoxBounds.height += itemBox.getImageMargins().top + itemBox.getImageMargins().bottom;


          widthPercent = itemBox.getWidth() / itemBoxBounds.width;
          heightPercent = itemBox.getHeight() / itemBoxBounds.height;
          leftPercent = itemBox.getImageMargins().left / itemBox.getWidth();
          rightPercent = itemBox.getImageMargins().right / itemBox.getWidth();
          topPercent = itemBox.getImageMargins().top / itemBox.getHeight();
          bottomPercent = itemBox.getImageMargins().bottom / itemBox.getHeight();
        }

        var width = layoutBox.getWidth() * AppConstants.MM_TO_PX * aspectRatioLayoutToPage.x * widthPercent;
        var height = layoutBox.getHeight() * AppConstants.MM_TO_PX * aspectRatioLayoutToPage.y * heightPercent;


        var newImageMargins = {
          left: width * leftPercent,
          right: width * rightPercent,
          top: height * topPercent,
          bottom: height * bottomPercent
        };
        if (itemBox instanceof ImageItemFactory.getClass()) {
          itemBox.setImageMargins(newImageMargins);
        }

        var centerX = pageOffset + layoutBox.getCenterX() * AppConstants.MM_TO_PX * aspectRatioLayoutToPage.x + newImageMargins.left / 2 - newImageMargins.right / 2;
        var centerY = layoutBox.getCenterY() * AppConstants.MM_TO_PX * aspectRatioLayoutToPage.y + newImageMargins.top / 2 - newImageMargins.bottom / 2;


        var rotation = layoutBox.getRotation();

        if (withAnimation) {

          var tweenTo = {
            centerX: centerX,
            centerY: centerY,
            width: width,
            height: height,
            rotation: (rotation + 360) % 360
          };

          var tween = createjs.Tween.get(itemBox.baseElement, {override: true}).to(tweenTo, 400, createjs.Ease.sineInOut).call(function end() {
            if (itemBox instanceof TextItemFactory.getClass()) {
              itemBox.setImageRenderingNeeded(true);
            } else {
              itemBox.checkSafetyArea();
              if (itemBox instanceof ImageItemFactory.getClass()) {
                itemBox.resetViewPortToFitIntelligently();
              }
            }
          });
          tweenLayoutTimeline.addTween(tween);

        } else {

          itemBox.setCenterX(centerX);
          itemBox.setCenterY(centerY);
          itemBox.setWidth(width);
          itemBox.setHeight(height);
          itemBox.setRotation(rotation);
          if (itemBox instanceof TextItemFactory.getClass()) {
            itemBox.setImageRenderingNeeded(true);
          } else {
            itemBox.checkSafetyArea();
            itemBox.resetViewPortToFitIntelligently();
          }
        }

      };


      // definition of the public service functions
      var designAreaService = {

        /**
         * Adds the specified photo, represented by the HTML5 file handle, as an ImageItem to the specified design area model at the
         * given coordinates.
         * @param photoFileHandle a FileHandle instance
         * @param designArea the design area model to add the photo to
         * @param centerX the center x coordinate to add the photo at
         * @param centerY the center y coordinate to add the photo at
         */
        addImageItem: function (photoFileHandle, designArea, centerX, centerY) {
          var self = this;
          return FileHandleService.createFileHandleThumbKey(photoFileHandle.getId(), AppConstants.EDITOR_IMAGE_TARGET_SIZE_PX)
            .then(function thumbKeyCreated(thumbKey) {

              return addImageItemBoxModel(designArea, thumbKey, photoFileHandle, centerX, centerY).then(function ok() {

                photoFileHandle.increaseUsageCount();

              });

            }, function (error) {
              $log.error('Failed to add photo to design area model.', error);
            });
        },

        /**
         * Adds a photo, represented by the HTML5 file handle, as an ImageItem to the specified design area model. The photo
         * will be added at the current mouse position on the specified CanvasDesignArea.
         * @param photoFileHandle
         * @param designAreaModel
         * @param canvasDesignArea
         */
        addImageItemOrReplaceImage: function (photoFileHandle, designAreaModel, canvasDesignArea, centerX, centerY) {
          var self = this;
          // get the mouse coordinates now, because after the promise is resolved the user might have moved mouse "away"

          // we need to add the padding, because we try to find an item on the *stage*, but the centerX/centerY coordinates refer to the *print area*
          var canvasItemBox = canvasDesignArea.getCanvasItemBoxAt(centerX + designAreaModel.getPaddingHorizontal(),
            centerY + designAreaModel.getPaddingVertical(), true);
          var hitOtherCanvasImageItem = canvasItemBox && canvasItemBox.getModel() instanceof ImageItemFactory.getClass() && !canvasItemBox.getModel().isUsedAsBackgroundImage();

          return FileHandleService.createFileHandleThumbKey(photoFileHandle.getId(), AppConstants.EDITOR_IMAGE_TARGET_SIZE_PX).then(
            function thumbKeyCreated(thumbKey) {

              // if there was already an ImageItem box at the given position replace its content with the new one
              if (hitOtherCanvasImageItem && canvasDesignArea.model.isDetailInteractionMode()) {

                var oldFileHandle = FileHandleService.getFileHandleById(canvasItemBox.model.getFileHandleId());
                oldFileHandle.decreaseUsageCount();
                canvasItemBox.getModel().setFileHandleId(photoFileHandle.getId());
                canvasItemBox.getModel().setThumbKey(thumbKey, true);
                canvasItemBox.getModel().setThumbKeyLoaded(false);
                canvasItemBox.getModel().setOriginalImageWidth(photoFileHandle.getWidth());
                canvasItemBox.getModel().setOriginalImageHeight(photoFileHandle.getHeight());
                canvasItemBox.getModel().setFadeIn(true);

                photoFileHandle.increaseUsageCount();

              } else {
                return addImageItemBoxModel(designAreaModel, thumbKey, photoFileHandle, centerX, centerY).then(function ok() {
                  photoFileHandle.increaseUsageCount();
                });
              }

            }, function (error) {
              $log.error('Failed to add photo to design area model.', error);
            });

        },

        /**
         * Adds a new TextItem based on the given TextItemTemplate to the specified DesignArea.
         * @param textItemTemplate a TextItemTemplate instance to create the TextItem from
         * @param designArea the DesignArea model to add the TextItem to
         * @param centerX the center x coordinate to add the photo at
         * @param centerY the center y coordinate to add the photo at
         */
        addTextItem: function (textItemTemplate, designArea, centerX, centerY, overwriteAttributes) {

          designArea.deselectAllItems();
          var textItem = TextItemFactory.createTextItem(textItemTemplate, centerX, centerY, AppConstants.TEXT_ITEM_BOX_DEFAULT_SIZE_PX.width,
            AppConstants.TEXT_ITEM_BOX_DEFAULT_SIZE_PX.height, 0, designArea.getNextFreeLayerIndex());

          if (overwriteAttributes) {
            // overwrite some textItemTemplate attributes with some other values
            textItem.setFontSize(15);
            textItem.setBackgroundColor('none');
          }
          textItem.setText('');
          textItem.setFadeIn(true);

          textItem.setSelected(designArea.isDetailInteractionMode());
          designArea.addTextItem(textItem);
          return textItem;

        },

        /**
         *
         * @param {BackgroundItemTemplate} backgroundTemplate
         * @param {DesignArea} designArea
         * @param pageHalf
         */
        addTemplateBackgroundItem: function (backgroundTemplate, designArea, pageHalf) {

          var product = ProductService.getProductById(ProjectService.getProject().getProductId());

          // check if the product allows only single color backgrounds on the cover
          if (product.getOnlyMonochromeBackgroundsOnCover() && backgroundTemplate.getCategoryKey() !== '' && backgroundTemplate.getCategoryKey() !== 'category-colours' && designArea.isCover()) {
            var categoryName = MessageService.getMessage('category-colours');
            var title = MessageService.getMessage('notification.backgrounds.onlyMonochromeOnCover.title', ['\'' + categoryName + '\'']);
            var message = MessageService.getMessage('notification.backgrounds.onlyMonochromeOnCover', ['<b>' + categoryName + '</b>']);
            NotificationService.addHtmlNotification(title, message, 'info', 12000);
            return;
          }

          // prevent 'single sided' flagged backgrounds from being put onto the cover of landscape format books
          if (designArea.isCover() && backgroundTemplate.isLandscapeSingleSided() && designArea.getPageHalfOrientation() === 'landscape') {
            var messageContent = MessageService.getMessage('notification.backgrounds.notPossibleOnCover');
            NotificationService.addNotification('', messageContent, 'info', 10000);
            return;
          }


          designArea.deselectAllItems();

          var leftItem = designArea.getTemplateBackgroundItemLeft();
          leftItem.setFadeIn(true);

          var rightItem = designArea.getTemplateBackgroundItemRight();
          rightItem.setFadeIn(true);

          if (pageHalf === 'left') {
            leftItem.setDesignElementId(backgroundTemplate.getDesignElementId());
            if (designArea.getImageBackgroundItemLeft()) {
              designArea.removeItemBox(designArea.getImageBackgroundItemLeft());
            }
          } else {
            rightItem.setDesignElementId(backgroundTemplate.getDesignElementId());
            if (designArea.getImageBackgroundItemRight()) {
              designArea.removeItemBox(designArea.getImageBackgroundItemRight());
            }
          }


          // determine image section(s)
          if (designArea.isCover()) {
            rightItem.setImageSection(4);
          } else if (product.getFullBackgroundOnEachPage() ||
            (designArea.getPageHalfOrientation() === 'landscape' && backgroundTemplate.isLandscapeSingleSided())) {
            // The new background has to be applied 'single sided', caused by product specific constraints
            // or by the background specific flag 'landscapeSingleSided'.
            // Once the image section '4' has been set, it must not be changed.
            if (pageHalf === 'left') {
              leftItem.setImageSection(4);
              if (rightItem.getImageSection() !== 4) {
                rightItem.setImageSection(2);
              }
            } else {
              if (leftItem.getImageSection() !== 4) {
                leftItem.setImageSection(2);
              }
              rightItem.setImageSection(4);
            }
          } else if (leftItem.getDesignElementId() === rightItem.getDesignElementId()) {
            leftItem.setImageSection(1);
            rightItem.setImageSection(3);
          } else {
            if (pageHalf === 'left') {
              leftItem.setImageSection(2);
              if (rightItem.getImageSection() !== 4) {
                rightItem.setImageSection(2);
              }
            } else {
              if (leftItem.getImageSection() !== 4) {
                leftItem.setImageSection(2);
              }
              rightItem.setImageSection(2);
            }
          }
        },

        addImageBackgroundItem: function (photoFileHandle, designArea, pageHalf) {

          var self = this;
          var targetSize = AppValues.canvasWidth;
          return FileHandleService.createFileHandleThumbKey(photoFileHandle.getId(), targetSize).then(function thumbKeyCreated(thumbKey) {
            var centerX = designArea.getWidth() / 2;
            var spineWidth = designArea.isCover() ? designArea.getSpineWidth() * AppConstants.MM_TO_PX : 0;

            if (pageHalf === 'left') {
              centerX = (designArea.getWidth() - spineWidth) * 1 / 4;
            } else if (pageHalf === 'right') {
              centerX = (designArea.getWidth() - spineWidth ) * 3 / 4 + spineWidth;
            }

            return addImageItemBoxModel(designArea, thumbKey, photoFileHandle, centerX, designArea.getHeight() / 2, pageHalf).then(function ok() {

              photoFileHandle.increaseUsageCount();

            });

          }, function (error) {
            $log.error('Failed to add photo to design area model.', error);
          });

        },

        addClipartItem: function (clipartItemTemplate, designArea, canvasDesignArea, centerX, centerY) {
          var safetyArea = {
            innerRect: {
              left: designArea.getSafetyMargin(),
              top: designArea.getSafetyMargin(),
              width: designArea.getWidth() - 2 * designArea.getSafetyMargin(),
              height: designArea.getHeight() - 2 * designArea.getSafetyMargin()
            },
            outerRect: {
              left: -designArea.getBleedMarginHorizontal(),
              top: -designArea.getBleedMarginVertical(),
              width: designArea.getWidth() + 2 * designArea.getBleedMarginHorizontal(),
              height: designArea.getHeight() + 2 * designArea.getBleedMarginVertical()
            }
          };
          var clipart = ClipartItemFactory.createClipartItem(clipartItemTemplate.getDesignElementId(), centerX, centerY, 0, 0, 0, designArea.getNextFreeLayerIndex(), safetyArea);
          designArea.addClipartItem(clipart);
        },

        /**
         * Swaps the image ItemBoxes on the specified DesignArea page half randomly.
         * @param designAreaModel
         * @param pageHalf
         */
        swapImages: function (designAreaModel, pageHalf) {

          if (swapImagesTweenRunning) {
            return; // do nothing if current tween still running
          }
          swapImagesTweenRunning = true;

          var currentImages = designAreaModel.getImageItems(pageHalf);

          var shuffledIndices = [];
          for (var i = 0; i < currentImages.length; i++) {
            shuffledIndices.push(i);
          }
          shuffledIndices = Utils.shuffleArray(shuffledIndices);


          // create a tween timeline to be able to tween the item boxes to the new positions as a group
          var swapImagesTimeline = new createjs.Timeline();
          swapImagesTimeline.on('change', function change() {
            SafeApply.do(function applyViewPortReset() {
              currentImages.forEach(function calcViewport(imageItem) {
                // calculates a fitting viewport based on heuristics
                imageItem.resetViewPortToFitIntelligently();
              });
            });
          });


          var tweenDuration = 400;
          var imageItemOne = null;
          var imageItemTwo = null;

          for (i = 0; i < currentImages.length; i++) {

            if (2 * i + 1 >= currentImages.length) {
              continue;
            }

            imageItemOne = currentImages[shuffledIndices[2 * i]];
            imageItemTwo = currentImages[shuffledIndices[2 * i + 1]];

            var tweenOneTo = {
              centerX: imageItemTwo.getCenterX(),
              centerY: imageItemTwo.getCenterY(),
              width: imageItemTwo.getWidth(),
              height: imageItemTwo.getHeight(),
              rotation: imageItemTwo.getRotation()
            };

            var tweenTwoTo = {
              centerX: imageItemOne.getCenterX(),
              centerY: imageItemOne.getCenterY(),
              width: imageItemOne.getWidth(),
              height: imageItemOne.getHeight(),
              rotation: imageItemOne.getRotation()
            };


            var tweenOne = createjs.Tween.get(imageItemOne.baseElement, {override: true}).to(tweenOneTo, tweenDuration, createjs.Ease.sineInOut);
            swapImagesTimeline.addTween(tweenOne);

            var tweenTwo = createjs.Tween.get(imageItemTwo.baseElement, {override: true}).to(tweenTwoTo, tweenDuration, createjs.Ease.sineInOut);
            swapImagesTimeline.addTween(tweenTwo);

          }

          $timeout(function releaseTweenLock() {
            designAreaModel.swapLayers(imageItemOne, imageItemTwo);
            swapImagesTweenRunning = false;
          }, tweenDuration);

        },

        /**
         *
         * @param designAreaModel the DesignArea to find the half page width for
         * @returns {number} the width of the half DesignArea (considers cover pages with spines, for example)
         */
        getHalfPageWidth: function (designAreaModel) {

          var productId = ProjectService.getProject().getProductId();
          var pagesCount = ProjectService.getProject().getPagesCount();

          var spineWidth = ProductService.getProductById(productId).getCoverSpineWidthForPages(pagesCount) * AppConstants.MM_TO_PX;

          var halfPageWidth = designAreaModel.getWidth() / 2;

          if (designAreaModel.isCover()) {
            halfPageWidth = halfPageWidth - spineWidth / 2;
          }

          return halfPageWidth;
        },

        /**
         * Calculates an aspect ratio between the Layout dimensions and the DesignArea dimensions, for example to be able to apply layouts with
         * a different aspect ratio than the design area to the design area.
         * @param designAreaModel
         * @param layout
         * @returns {{x: number, y: number}}
         */
        getAspectRatioLayoutToPage: function (designAreaModel, layout) {

          var halfPageWidth = designAreaService.getHalfPageWidth(designAreaModel);
          if (layout) {
            var aspectRatioLayoutToPage = {
              x: (halfPageWidth / AppConstants.MM_TO_PX) / layout.getWidth(),
              y: (designAreaModel.getHeight() / AppConstants.MM_TO_PX) / layout.getHeight()
            };

            return aspectRatioLayoutToPage;
          }
        },

        applyRandomLayout: function (designAreaModel, pageHalf) {
          // apply a random layouts to the design area page half if in storyboard view
          if (designAreaModel.isDetailInteractionMode() || !designAreaModel.isLayoutModified(pageHalf)) {
            var portraitImagesCount = designAreaModel.getPortraitImageItemsForHalfPage(pageHalf).length;
            var landscapeImagesCount = designAreaModel.getLandscapeImageItemsForHalfPage(pageHalf).length;
            var textsCount = designAreaModel.getTextItems(pageHalf, true).length;
            var designAreaOrientation = designAreaModel.getPageHalfOrientation();
            var designAreaType = designAreaModel.getType();
            LayoutService.getRandomLayout(portraitImagesCount, landscapeImagesCount, textsCount, designAreaOrientation, designAreaType, true, false).then(function ok(layout) {
              if (layout) {
                designAreaService.applyLayout(designAreaModel, layout, pageHalf, true);
              }
            });
          }

        },


        setDesignAreaInDragProcess: function (designArea) {
          dragedDesignArea = designArea;
        },

        getDesignAreaToDrop: function () {
          return dragedDesignArea;
        },

        removeDesignAreaToDrop: function () {
          dragedDesignArea = undefined;
        },

        bringClipartAndTextItemsToFront: function (designAreaModel) {
          designAreaModel.getAllItems(true).forEach(function iterateItems(item) {
            if (item instanceof ClipartItemFactory.getClass() || item instanceof TextItemFactory.getClass()) {
              item.setLayerIndex(designAreaModel.getNextFreeLayerIndex());
            }
          });
        },

        /**
         * Applies the given Layout instance to the specified page half (can be 'left' or 'right') of the given DesignArea.
         * @param designAreaModel the design area model to apply the layouts to
         * @param layout the Layout to apply
         * @param pageHalf 'left' or 'right'
         * @param withAnimation play tween animation when layouts if applied?
         */
        applyLayout: function (designAreaModel, layout, pageHalf, withAnimation) {

          designAreaModel.attachLayoutToPageHalf(pageHalf, layout);

          var halfPageWidth = designAreaService.getHalfPageWidth(designAreaModel);

          // calculate an aspect ratio between the layouts dimensions and the page dimensions to be able to apply layouts with a different
          // aspect ratio that the design area to the design area.
          var aspectRatioLayoutToPage = designAreaService.getAspectRatioLayoutToPage(designAreaModel, layout);

          var productId = ProjectService.getProject().getProductId();
          var pagesCount = ProjectService.getProject().getPagesCount();

          var spineWidth = ProductService.getProductById(productId).getCoverSpineWidthForPages(pagesCount) * AppConstants.MM_TO_PX;


          // if the Layout is meant to be applied on the right half of the DesignArea, add an offset to the Layout
          var pageOffset = 0;
          if (pageHalf === 'right') {

            pageOffset = halfPageWidth;

            if (designAreaModel.isCover()) {
              pageOffset = pageOffset + spineWidth;
            }

          }


          var imageItems = designAreaModel.getImageItems(pageHalf);
          imageItems.forEach(function iterateImageItems(imageItem) {
            if (imageItem.getDecoFrameId()) {
              withAnimation = false;
            }
          });
          if (withAnimation) {
            // create a tween timeline to be able to tween the item boxes to the new layouts positions as a group
            var itemsToTween = designAreaModel.getImageItems(pageHalf).concat(designAreaModel.getTextItems(pageHalf, true));

            if (tweenLayoutTimeline) {
              tweenLayoutTimeline.removeAllEventListeners();
            }
            tweenLayoutTimeline = new createjs.Timeline();
            tweenLayoutTimeline.on('change', function change() {

              SafeApply.do(function applyViewPortReset() {
                itemsToTween.forEach(function calcViewport(itemBox) {
                  if (itemBox instanceof TextItemFactory.getClass()) {
                    itemBox.incrementModelStateVersion(); // just to trigger its watch for redrawing with the newly tweened model state
                    return;
                  }
                  // calculates a fitting viewport based on heuristics
                  itemBox.resetViewPortToFitIntelligently();
                });
              });
            });

          }

          var imageItemsLandscape = designAreaModel.getLandscapeImageItemsForHalfPage(pageHalf);
          var imageItemsPortrait = designAreaModel.getPortraitImageItemsForHalfPage(pageHalf);
          var textItems = designAreaModel.getTextItems(pageHalf, true);

          // apply the actual layouts boxes' data to the image and text items
          // try to put imageItems and textItems in layouts boxes

          // copy the layout boxes to avoid removing them from the original array during the following while-loop code
          var layoutBoxes = angular.copy(layout.getBoxes());
          var layoutBox;
          var itemBox;
          var layoutedItemBoxes = [];
          var layerIndexesOfLayoutedItemBoxes = [];
          while (layoutBoxes.length > 0 && (imageItemsLandscape.length > 0 || imageItemsPortrait.length > 0 || textItems.length > 0)) {
            itemBox = null;
            layoutBox = layoutBoxes.shift();
            if (layoutBox.isImageBox()) {
              var isLandscapeBox = layoutBox.getWidth() * aspectRatioLayoutToPage.x >= layoutBox.getHeight() * aspectRatioLayoutToPage.y;

              if (isLandscapeBox) {
                if (imageItemsLandscape.length > 0) {
                  itemBox = imageItemsLandscape.shift();
                } else if (imageItemsPortrait.length > 0) {
                  itemBox = imageItemsPortrait.shift();
                }
              } else {
                if (imageItemsPortrait.length > 0) {
                  itemBox = imageItemsPortrait.shift();
                } else if (imageItemsLandscape.length > 0) {
                  itemBox = imageItemsLandscape.shift();
                }
              }

            } else if (layoutBox.isTextBox() && textItems.length > 0) {
              itemBox = textItems.shift();
            }

            if (itemBox) {
              applyLayoutBoxToItemBox(layoutBox, itemBox, pageOffset, aspectRatioLayoutToPage, withAnimation);
              layoutedItemBoxes.push(itemBox);
              layerIndexesOfLayoutedItemBoxes.push(itemBox.getLayerIndex());
            }
          }

          // apply layer of layoutBoxes to itemBoxes
          layerIndexesOfLayoutedItemBoxes.sort(function compareNumbers(a, b) {
            return a - b;
          });
          for (var i = 0; i < layoutedItemBoxes.length; i++) {
            layoutedItemBoxes[i].setLayerIndex(layerIndexesOfLayoutedItemBoxes[i]);
          }

          if (designAreaModel.getSelectedItemBox()) {
            var selectedItemBox = designAreaModel.getSelectedItemBox();
            selectedItemBox.setSelected(false);
          }
          designAreaModel.incrementModelStateVersion();

        }
      };

      return designAreaService;

    }
  ])
  ;
})
();
/**
 * Creates ImageItem instances for the project data model.
 *
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('ImageItemFactory', [
    '$log', 'AppConstants', 'ItemBoxPrototypeFactory', 'ViewPortFactory',
    function ($log, AppConstants, ItemBoxPrototypeFactory, ViewPortFactory) {

      var imageItemCounter = 0;

      function ImageItem() {

        // call super class constructor to instantiate its variables
        ItemBoxPrototypeFactory.getClass().call(this);

        this.baseElement.id = imageItemCounter++;
        this.viewport = ViewPortFactory.getPrototype();
        this.refCountId = -1;
        this.originalImageWidth = undefined;
        this.originalImageHeight = undefined;
        this.originalFileName = '';
        this.alphaMaskId = undefined;
        this.decoFrameId = undefined;
        this.myPhotosPicutreId = undefined;

        this.ng.thumbKey = null;
        this.ng.resetViewPortAfterThumbLoaded = false;
        this.ng.fileHandleId = null;
        this.ng.greenDotsPerMM = null;
        this.ng.yellowDotsPerMM = null;
        this.ng.badQuality = false;

        this.ng.keepMaskAspectRatio = false;

        this.ng.imageMargins = {
          top: 0,
          right: 0,
          bottom: 0,
          left: 0
        };

        this.setBorderAllowed(true);
      }

      ImageItem.prototype = Object.create(ItemBoxPrototypeFactory.getClass().prototype);
      ImageItem.prototype.constructor = ImageItem;


      ImageItem.prototype.getId = function () {
        return this.baseElement.id;
      };

      ImageItem.prototype.getRefCountId = function () {
        return this.refCountId;
      };

      ImageItem.prototype.setRefCountId = function (refCountId) {
        if (this.refCountId !== refCountId) {
          this.refCountId = refCountId;
          this.incrementModelStateVersion();
        }
      };

      ImageItem.prototype.getFileHandleId = function () {
        return this.ng.fileHandleId;
      };

      ImageItem.prototype.setFileHandleId = function (fileHandleId) {
        if (this.ng.fileHandleId !== fileHandleId) {
          this.ng.fileHandleId = fileHandleId;
          this.incrementModelStateVersion();
        }
      };

      ImageItem.prototype.isFormatPortrait = function () {
        return this.getWidth() < this.getHeight();
      };

      ImageItem.prototype.isFormatLandscape = function () {
        return !this.isFormatPortrait();
      };

      ImageItem.prototype.setViewPort = function (viewport) {
        this.viewport = viewport;
        this.checkViewPort();
        this.incrementModelStateVersion();
      };

      ImageItem.prototype.getViewPort = function () {
        return this.viewport;
      };

      ImageItem.prototype.getOriginalImageWidth = function () {
        return this.originalImageWidth;
      };

      ImageItem.prototype.setOriginalImageWidth = function (originalImageWidth) {
        this.originalImageWidth = originalImageWidth;
      };

      ImageItem.prototype.getOriginalImageHeight = function () {
        return this.originalImageHeight;
      };

      ImageItem.prototype.setOriginalImageHeight = function (originalImageHeight) {
        this.originalImageHeight = originalImageHeight;
      };

      ImageItem.prototype.setOriginalFileName = function (fileName) {
        this.originalFileName = fileName;
      };

      ImageItem.prototype.getOriginalFileName = function () {
        return this.originalFileName;
      };

      ImageItem.prototype.getAlphaMaskId = function () {
        return this.alphaMaskId;
      };

      ImageItem.prototype.setAlphaMaskId = function (maskId) {
        if (maskId !== this.alphaMaskId) {
          this.alphaMaskId = maskId;
          if (maskId) {
            this.removeDecoFrameId();
          }
          this.incrementModelStateVersion();
        }
      };

      ImageItem.prototype.applyAlphaMaskTemplate = function (alphaMaskTemplate) {
        this.setAlphaMaskId(alphaMaskTemplate.getDesignElementId());
        this.ng.keepMaskAspectRatio = alphaMaskTemplate.getKeepAspectRatio();
      };

      ImageItem.prototype.removeAlphaMaskId = function () {
        this.setAlphaMaskId(undefined);
      };

      ImageItem.prototype.isKeepMaskAspectRatio = function () {
        return this.ng.keepMaskAspectRatio;
      };

      ImageItem.prototype.setKeepMaskAspectRatio = function (trueOrFalse) {
        this.ng.keepMaskAspectRatio = trueOrFalse;
      };

      ImageItem.prototype.setDecoFrameId = function (decoFrameId) {
        if (decoFrameId !== this.decoFrameId) {
          this.decoFrameId = decoFrameId;
          if (decoFrameId) {
            this.removeAlphaMaskId();
          }
          this.incrementModelStateVersion();
        }
      };

      ImageItem.prototype.getDecoFrameId = function () {
        return this.decoFrameId;
      };

      ImageItem.prototype.removeDecoFrameId = function () {
        this.setImageMargins(AppConstants.TOOLFRAME_DEFAULT_IMAGE_MARGINS);
        this.setDecoFrameId(undefined);
      };

      ImageItem.prototype.getGreenDotsPerMM = function () {
        return this.ng.greenDotsPerMM;
      };

      ImageItem.prototype.setGreenDotsPerMM = function (greenDotsPerMM) {
        this.ng.greenDotsPerMM = greenDotsPerMM;
      };

      ImageItem.prototype.getYellowDotsPerMM = function () {
        return this.ng.yellowDotsPerMM;
      };
      ImageItem.prototype.setYellowDotsPerMM = function (yellowDotsPerMM) {
        this.ng.yellowDotsPerMM = yellowDotsPerMM;
      };

      ImageItem.prototype.isBadQualiy = function () {
        return this.ng.badQuality;
      };
      ImageItem.prototype.setBadQuality = function (trueOrFalse) {
        this.ng.badQuality = trueOrFalse;
      };

      ImageItem.prototype.setMyPhotosPictureId = function (myPhotosPictureId) {
        this.myPhotosPicutreId = myPhotosPictureId;
      };

      ImageItem.prototype.getMyPhotosPicutreId = function () {
        return this.myPhotosPicutreId;
      };

      ImageItem.prototype.getImageMargins = function () {
        return this.ng.imageMargins;
      };

      ImageItem.prototype.setImageMargins = function (imageMargins) {
        this.ng.imageMargins = imageMargins;
      };

      /**
       *
       * @return {boolean} Viewport needs to be reset after the thumbnail was loaded?
       */
      ImageItem.prototype.isResetViewPortAfterThumbLoaded = function () {
        return this.ng.resetViewPortAfterThumbLoaded;
      };

      /**
       *
       * @return {boolean} is the ImageItem used as background image?
       */
      ImageItem.prototype.isUsedAsBackgroundImage = function () {
        return !this.isPositionEditable();
      };

      ImageItem.prototype.setUsedAsBackgroundImage = function (pageHalf) {
        this.setPositionEditable(false);
        this.setLayerIndex(pageHalf === 'left' ? 3 : 4);
      };

      /**
       * Resets the ViewPort to fit into the item's boundings. The viewport gets centered in horizontal and vertical direction by default.
       */
      ImageItem.prototype.resetViewPort = function () {

        this.ng.resetViewPortAfterThumbLoaded = false;

        var viewport = this.getViewPort();
        var aspectRatioItemBox = this.getWidth() / this.getHeight();
        var aspectRatioContent = viewport.getFullWidth() / viewport.getFullHeight();


        // fit the viewport into the box by taking into account whether we have a portrait or landscape format image

        if (aspectRatioContent >= aspectRatioItemBox) { // content best fits vertically

          viewport.setWidth(viewport.getFullWidth() * (aspectRatioItemBox / aspectRatioContent));
          viewport.setHeight(viewport.getFullHeight());

        } else { // content best fits horizontally

          viewport.setWidth(viewport.getFullWidth());
          viewport.setHeight(viewport.getFullHeight() * (aspectRatioContent / aspectRatioItemBox));

        }


        // center viewport in both directions
        viewport.setX((viewport.getFullWidth() - viewport.getWidth()) / 2);
        viewport.setY((viewport.getFullHeight() - viewport.getHeight()) / 2);

        this.setViewPort(viewport);
      };

      /**
       * Tries to find a nicely fitting viewport based on heuritics and sets it to the item box.
       */
      ImageItem.prototype.resetViewPortToFitIntelligently = function () {

        // center the viewport and fit it to the box
        this.resetViewPort();

        var viewport = this.getViewPort();
        var aspectRatioItemBox = this.getWidth() / this.getHeight();
        var aspectRatioContent = viewport.getFullWidth() / viewport.getFullHeight();

        // zoom in a little bit if the box aspect ratio is very wide or narrow
//        if (aspectRatioItemBox > 1 && aspectRatioItemBox < (16 / 9) || aspectRatioItemBox < 1 && aspectRatioItemBox > (9 / 16)) {
//          viewport.setWidth(viewport.getWidth() * 0.9);
//          viewport.setHeight(viewport.getHeight() * 0.9);
//          viewport.setX((viewport.getFullWidth() - viewport.getWidth()) / 2); // center in x direction after the zoom operation
//        }


        // landscape content is
        if (aspectRatioContent > 1) {

          // landscape format content focuses its viewport more on the bottom
          viewport.setY((viewport.getFullHeight() - viewport.getHeight()) * 0.725);

        } else { // portrait format content

          // portrait format content focuses its viewport more on the top
          viewport.setY((viewport.getFullHeight() - viewport.getHeight()) * 0.275);

        }

        this.setViewPort(viewport);

      };


      ImageItem.prototype.getThumbKey = function () {
        return this.ng.thumbKey;
      };

      /**
       * Sets the key of the new thumbnail to set
       * @param thumbKey
       * @param resetViewPort (optional) reset the ItemBox's Viewport after the thumbnail has been loaded?
       */
      ImageItem.prototype.setThumbKey = function (thumbKey, resetViewPort) {
        if (this.ng.thumbKey !== thumbKey) {
          this.ng.thumbKey = thumbKey;
          this.incrementModelStateVersion();
        }

        if (resetViewPort) {
          this.ng.resetViewPortAfterThumbLoaded = resetViewPort;
          this.incrementModelStateVersion();
        }
      };

      ImageItem.prototype.isThumbKeyLoaded = function () {
        return this.ng.thumbKey.loaded;
      };

      ImageItem.prototype.setThumbKeyLoaded = function (trueOrFalse) {
        if (this.ng.thumbKey.loaded !== trueOrFalse) {
          this.ng.thumbKey.loaded = trueOrFalse;
          this.incrementModelStateVersion();
        }
      };

      ImageItem.prototype.setSelected = function (trueOrFalse) {

        // call super method
        ItemBoxPrototypeFactory.getClass().prototype.setSelected.call(this, trueOrFalse);

      };

      ImageItem.prototype.setSafetyArea = function (safetyArea) {
        this.ng.safetyArea = safetyArea;
      };

      /**
       * calculates the quality for this imageItem
       * @param width (optional) if no value is passed, the model value of this item is used
       * @param height (optional) if no value is passed, the model value of this item is used
       * @param viewPort (optional) if no value is passed, the model value of this item is used
       */
      ImageItem.prototype.calculateQuality = function (width, height, viewPort) {
        var currentViewPort = viewPort || this.getViewPort();
        var originalViewPortWidth = currentViewPort.getWidth() / currentViewPort.getFullWidth() * this.getOriginalImageWidth();
        var originalViewPortHeight = currentViewPort.getHeight() / currentViewPort.getFullHeight() * this.getOriginalImageHeight();
        var widthMM = (width || this.getWidth()) / AppConstants.MM_TO_PX / 10;
        var heightMM = (height || this.getHeight()) / AppConstants.MM_TO_PX / 10;
        var dpMM = Math.min(originalViewPortWidth / widthMM, originalViewPortHeight / heightMM);
        var calculatedQuality;
        if (dpMM >= this.getGreenDotsPerMM()) {
          calculatedQuality = 'green';
        } else if (dpMM >= this.getYellowDotsPerMM()) {
          calculatedQuality = 'yellow';
        } else {
          calculatedQuality = 'red';
        }

        return calculatedQuality;
      };

      ImageItem.prototype.checkSafetyArea = function () {
        var result = angular.copy(this.baseElement);

        if (!this.ng.safetyArea) {
          return result;
        }
        if (this.getRotation() % 90 !== 0) {
          return result;
        }

        var swapDimensions = this.getRotation() === 90 || this.getRotation() === 270;
        // check margin top
        var top = swapDimensions ? result.centerY - result.width / 2 : result.centerY - result.height / 2;
        if (top < this.ng.safetyArea.innerRect.top && top > this.ng.safetyArea.outerRect.top) {
          var deltaTop = top - this.ng.safetyArea.outerRect.top;
          result.centerY = result.centerY - deltaTop / 2;
          if (swapDimensions) {
            result.width += deltaTop;
          } else {
            result.height += deltaTop;
          }
        }
        // check margin bottom
        var bottom = swapDimensions ? result.centerY + result.width / 2 : result.centerY + result.height / 2;
        if (bottom > this.ng.safetyArea.innerRect.top + this.ng.safetyArea.innerRect.height &&
          bottom < this.ng.safetyArea.outerRect.top + this.ng.safetyArea.outerRect.height) {
          var deltaBottom = this.ng.safetyArea.outerRect.top + this.ng.safetyArea.outerRect.height - bottom;
          result.centerY = result.centerY + deltaBottom / 2;
          if (swapDimensions) {
            result.width += deltaBottom;
          } else {
            result.height += deltaBottom;
          }
          // check margin top again
          top = swapDimensions ? result.centerY - result.width / 2 : result.centerY - result.height / 2;
          if (top < this.ng.safetyArea.innerRect.top && top > this.ng.safetyArea.outerRect.top) {
            result.centerY = this.ng.safetyArea.outerRect.top + this.ng.safetyArea.outerRect.height / 2;
            if (swapDimensions) {
              result.width = this.ng.safetyArea.outerRect.height;
            } else {
              result.height = this.ng.safetyArea.outerRect.height;
            }
          }
        }

        // check margin left
        var left = swapDimensions ? result.centerX - result.height / 2 : result.centerX - result.width / 2;
        if (left < this.ng.safetyArea.innerRect.left && left > this.ng.safetyArea.outerRect.left) {
          var deltaLeft = left - this.ng.safetyArea.outerRect.left;
          result.centerX = result.centerX - deltaLeft / 2;
          if (swapDimensions) {
            result.height += deltaLeft;
          } else {
            result.width += deltaLeft;
          }
        }
        // check margin right
        var right = swapDimensions ? result.centerX + result.height / 2 : result.centerX + result.width / 2;
        if (right > this.ng.safetyArea.innerRect.left + this.ng.safetyArea.innerRect.width &&
          right < this.ng.safetyArea.outerRect.left + this.ng.safetyArea.outerRect.width) {
          var deltaRight = this.ng.safetyArea.outerRect.left + this.ng.safetyArea.outerRect.width - right;
          result.centerX = result.centerX + deltaRight / 2;
          if (swapDimensions) {
            result.height += deltaRight;
          } else {
            result.width += deltaRight;
          }
          // check margin left again
          left = swapDimensions ? result.centerX - result.height / 2 : result.centerX - result.width / 2;
          if (left < this.ng.safetyArea.innerRect.left && left > this.ng.safetyArea.outerRect.left) {
            result.centerX = this.ng.safetyArea.outerRect.left + this.ng.safetyArea.outerRect.width / 2;
            if (swapDimensions) {
              result.height = this.ng.safetyArea.outerRect.width;
            } else {
              result.width = this.ng.safetyArea.outerRect.width;
            }
          }
        }
        var itemBoxChanged = this.getCenterX() !== result.centerX || this.getCenterY() !== result.centerY ||
          this.getWidth() !== result.width || this.getHeight() !== result.height;
        if (itemBoxChanged) {
          this.setCenterX(result.centerX);
          this.setCenterY(result.centerY);
          this.setWidth(result.width);
          this.setHeight(result.height);
          this.checkViewPort();
        }
        return result;
      };

      ImageItem.prototype.checkViewPort = function () {
        var tolerancePercent = 0.01;
        var viewPort = this.getViewPort();
        var calculatedViewPortHeight = this.getHeight() / this.getWidth() * viewPort.getWidth();
        var calculatedViewPortWidth = this.getWidth() / this.getHeight() * viewPort.getHeight();
        if (calculatedViewPortHeight <= viewPort.getFullHeight() &&
          Math.abs(viewPort.getHeight() - calculatedViewPortHeight) > viewPort.getFullHeight() * tolerancePercent) {
          viewPort.setHeight(calculatedViewPortHeight);
        } else if (calculatedViewPortWidth <= viewPort.getFullWidth() &&
          Math.abs(viewPort.getWidth() - calculatedViewPortWidth) > viewPort.getFullWidth() * tolerancePercent) {
          viewPort.setWidth(calculatedViewPortWidth);
        }
      };


      ImageItem.prototype.recalculateViewPort = function () {
        var aspectRatioItemBox = this.getWidth() / this.getHeight();
        var aspectRatioViewPort = this.getViewPort().getWidth() / this.getViewPort().getHeight();
        var newHeight;
        var newWidth;
        if (aspectRatioItemBox < aspectRatioViewPort) {
          newWidth = this.getViewPort().getHeight() * aspectRatioItemBox;
          this.getViewPort().setWidth(newWidth);
        } else if (aspectRatioItemBox >= aspectRatioViewPort) {
          newHeight = this.getViewPort().getWidth() / aspectRatioItemBox;
          this.getViewPort().setHeight(newHeight);
        }
      };

      return {

        getClass: function () {
          return ImageItem;
        },

        getPrototype: function () {
          return new ImageItem();
        },

        createImageItem: function (centerX, centerY, width, height, rotation, layerIndex, safetyArea, alphaMaskId, decoFrameId) {

          if (centerX === undefined || centerY === undefined || width === undefined || width <= 0 || height === undefined || height <= 0 ||
            rotation === undefined || layerIndex === undefined || layerIndex <= 2 || safetyArea === undefined) {
            throw new Error('Can\'t create ImageItem. One or more parameters a missing or invalid.');
          }

          var imageItem = new ImageItem();

          imageItem.setCenterX(centerX);
          imageItem.setCenterY(centerY);
          imageItem.setWidth(width);
          imageItem.setHeight(height);
          imageItem.setRotation(rotation);
          imageItem.setLayerIndex(layerIndex);
          imageItem.setAlphaMaskId(alphaMaskId);
          imageItem.setDecoFrameId(decoFrameId);

          imageItem.ng.safetyArea = safetyArea;

          return imageItem;
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Creates ClipartItem instances for the project data model.
 *
 * @author Sascha Friedrich
 * @author Christoph Suhren
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('ClipartItemFactory', [
    '$log', 'AppConstants', 'ItemBoxPrototypeFactory',
    function ($log, AppConstants, ItemBoxPrototypeFactory) {

      var clipartItemCounter = 0;

      function ClipartItem() {

        // call super class constructor to instantiate its variables
        ItemBoxPrototypeFactory.getClass().call(this);

        this.baseElement.id = clipartItemCounter++;
        this.designElementId = null;

      }

      ClipartItem.prototype = Object.create(ItemBoxPrototypeFactory.getClass().prototype);
      ClipartItem.prototype.constructor = ClipartItem;


      ClipartItem.prototype.getId = function () {
        return this.baseElement.id;
      };

      ClipartItem.prototype.getDesignElementId = function () {
        return this.designElementId;
      };

      ClipartItem.prototype.setDesignElementId = function (designElementId) {
        this.designElementId = designElementId;
        this.incrementModelStateVersion();
      };

      ClipartItem.prototype.setSelected = function (trueOrFalse) {

        // call super method
        ItemBoxPrototypeFactory.getClass().prototype.setSelected.call(this, trueOrFalse);

      };

      ClipartItem.prototype.setSafetyArea = function (safetyArea) {
        this.ng.safetyArea = safetyArea;
      };


      ClipartItem.prototype.checkSafetyArea = function () {
        var result = angular.copy(this.baseElement);

        if (!this.ng.safetyArea) {
          return result;
        }
        if (this.getRotation() % 90 !== 0) {
          return result;
        }

        var swapDimensions = this.getRotation() === 90 || this.getRotation() === 270;
        // check margin top
        var top = swapDimensions ? result.centerY - result.width / 2 : result.centerY - result.height / 2;
        if (top < this.ng.safetyArea.innerRect.top && top > this.ng.safetyArea.outerRect.top) {
          var deltaTop = top - this.ng.safetyArea.outerRect.top;
          result.centerY = result.centerY - deltaTop / 2;
          if (swapDimensions) {
            result.width += deltaTop;
          } else {
            result.height += deltaTop;
          }
        }
        // check margin bottom
        var bottom = swapDimensions ? result.centerY + result.width / 2 : result.centerY + result.height / 2;
        if (bottom > this.ng.safetyArea.innerRect.top + this.ng.safetyArea.innerRect.height &&
          bottom < this.ng.safetyArea.outerRect.top + this.ng.safetyArea.outerRect.height) {
          var deltaBottom = this.ng.safetyArea.outerRect.top + this.ng.safetyArea.outerRect.height - bottom;
          result.centerY = result.centerY + deltaBottom / 2;
          if (swapDimensions) {
            result.width += deltaBottom;
          } else {
            result.height += deltaBottom;
          }
          // check margin top again
          top = swapDimensions ? result.centerY - result.width / 2 : result.centerY - result.height / 2;
          if (top < this.ng.safetyArea.innerRect.top && top > this.ng.safetyArea.outerRect.top) {
            result.centerY = this.ng.safetyArea.outerRect.top + this.ng.safetyArea.outerRect.height / 2;
            if (swapDimensions) {
              result.width = this.ng.safetyArea.outerRect.height;
            } else {
              result.height = this.ng.safetyArea.outerRect.height;
            }
          }
        }

        // check margin left
        var left = swapDimensions ? result.centerX - result.height / 2 : result.centerX - result.width / 2;
        if (left < this.ng.safetyArea.innerRect.left && left > this.ng.safetyArea.outerRect.left) {
          var deltaLeft = left - this.ng.safetyArea.outerRect.left;
          result.centerX = result.centerX - deltaLeft / 2;
          if (swapDimensions) {
            result.height += deltaLeft;
          } else {
            result.width += deltaLeft;
          }
        }
        // check margin right
        var right = swapDimensions ? result.centerX + result.height / 2 : result.centerX + result.width / 2;
        if (right > this.ng.safetyArea.innerRect.left + this.ng.safetyArea.innerRect.width &&
          right < this.ng.safetyArea.outerRect.left + this.ng.safetyArea.outerRect.width) {
          var deltaRight = this.ng.safetyArea.outerRect.left + this.ng.safetyArea.outerRect.width - right;
          result.centerX = result.centerX + deltaRight / 2;
          if (swapDimensions) {
            result.height += deltaRight;
          } else {
            result.width += deltaRight;
          }
          // check margin left again
          left = swapDimensions ? result.centerX - result.height / 2 : result.centerX - result.width / 2;
          if (left < this.ng.safetyArea.innerRect.left && left > this.ng.safetyArea.outerRect.left) {
            result.centerX = this.ng.safetyArea.outerRect.left + this.ng.safetyArea.outerRect.width / 2;
            if (swapDimensions) {
              result.height = this.ng.safetyArea.outerRect.width;
            } else {
              result.width = this.ng.safetyArea.outerRect.width;
            }
          }
        }
        var itemBoxChanged = this.getCenterX() !== result.centerX || this.getCenterY() !== result.centerY ||
          this.getWidth() !== result.width || this.getHeight() !== result.height;
        if (itemBoxChanged) {
          this.setCenterX(result.centerX);
          this.setCenterY(result.centerY);
          this.setWidth(result.width);
          this.setHeight(result.height);
          //this.checkViewPort();
        }
        return result;
      };

      return {

        getClass: function () {
          return ClipartItem;
        },

        getPrototype: function () {
          return new ClipartItem();
        },

        createClipartItem: function (designElementId, centerX, centerY, width, height, rotation, layerIndex, safetyArea) {
          if (designElementId === undefined || designElementId <= 0 || centerX === undefined || centerY === undefined || rotation === undefined ||
            layerIndex === undefined || layerIndex <= 2 || safetyArea === undefined) {
            throw new Error('Can\'t create ClipartItem. One or more parameters a missing or invalid.');
          }

          var clipartItem = new ClipartItem();

          clipartItem.setDesignElementId(designElementId);
          clipartItem.setCenterX(centerX);
          clipartItem.setCenterY(centerY);
          clipartItem.setWidth(width);
          clipartItem.setHeight(height);
          clipartItem.setRotation(rotation);
          clipartItem.setLayerIndex(layerIndex);

          clipartItem.ng.safetyArea = safetyArea;

          return clipartItem;
        }

      };
    }
  ]);
})();/**
 * Creates TextItem instances for the project data model.
 *
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('TextItemFactory', [
    '$log', 'ItemBoxPrototypeFactory', 'AppConstants',
    function ($log, ItemBoxPrototypeFactory, AppConstants) {

      var textItemCounter = 0;

      function TextItem() {

        // call super class constructor to instantiate its variables
        ItemBoxPrototypeFactory.getClass().call(this);

        this.baseElement.id = textItemCounter++;
        this.text = null;
        this.placeholderText = null;
        this.textAnchor = null;
        this.fill = null;
        this.backgroundColor = null;
        this.font = null;
        this.fontSize = null;
        this.fontWeight = null;
        this.fontStyle = null;
        this.textDecoration = null;
        this.padding = '0';
        this.verticalAlign = null;

        this.ng.imageRenderingNeeded = false;
      }

      TextItem.prototype = Object.create(ItemBoxPrototypeFactory.getClass().prototype);
      TextItem.prototype.constructor = TextItem;


      TextItem.prototype.getId = function () {
        return this.baseElement.id;
      };

      TextItem.prototype.getText = function () {
        return this.text;
      };

      TextItem.prototype.setText = function (text) {
        if (this.text !== text) {
          this.text = text;
          this.incrementModelStateVersion();
        }
      };

      /**
       * Returns the text that is meant to be shown if there is no real text content available yet.
       * The placeholder text will not get produced.
       * @return {null|*} the TextItem's placeholder text
       */
      TextItem.prototype.getPlaceholderText = function () {
        return this.placeholderText;
      };

      /**
       * Sets a placeholder text that will be shown if there is no real text content available yet.
       * The placeholder text will not get produced.
       * @param text the TextItem's placeholder text
       */
      TextItem.prototype.setPlaceholderText = function (text) {
        if (this.placeholderText !== text) {
          this.placeholderText = text;
          this.incrementModelStateVersion();
        }
      };

      TextItem.prototype.isBlank = function () {
        return !this.text || (this.text === this.placeholderText);
      };

      TextItem.prototype.getTextAlign = function () {
        if (this.textAnchor === 'start') {
          return 'left';
        }
        if (this.textAnchor === 'middle') {
          return 'center';
        }
        if (this.textAnchor === 'end') {
          return 'right';
        }
        return null;
      };

      TextItem.prototype.getTextAnchor = function () {
        return this.textAnchor;
      };

      TextItem.prototype.setTextAnchor = function (textAnchor) {
        if (this.textAnchor !== textAnchor) {
          this.textAnchor = textAnchor;
          this.incrementModelStateVersion();
        }
      };

      TextItem.prototype.getFontWeight = function () {
        return this.fontWeight;
      };

      TextItem.prototype.setFontWeight = function (fontWeight) {
        if (this.fontWeight !== fontWeight) {
          this.fontWeight = fontWeight;
          this.incrementModelStateVersion();
        }
      };

      TextItem.prototype.getFontStyle = function () {
        return this.fontStyle;
      };

      TextItem.prototype.setFontStyle = function (fontStyle) {
        if (this.fontStyle !== fontStyle) {
          this.fontStyle = fontStyle;
          this.incrementModelStateVersion();
        }
      };

      TextItem.prototype.getTextDecoration = function () {
        return this.textDecoration;
      };

      TextItem.prototype.setTextDecoration = function (textDecoration) {
        if (this.textDecoration !== textDecoration) {
          this.textDecoration = textDecoration;
          this.incrementModelStateVersion();
        }
      };

      TextItem.prototype.getTextColor = function () {
        return this.getFill();
      };

      TextItem.prototype.setTextColor = function (textColor) {
        this.setFill(textColor);
      };

      TextItem.prototype.getFill = function () {
        return this.fill;
      };

      TextItem.prototype.setFill = function (fill) {
        if (this.fill !== fill) {
          this.fill = fill;
          this.incrementModelStateVersion();
        }
      };

      TextItem.prototype.getBackgroundColor = function () {
        return this.backgroundColor;
      };

      TextItem.prototype.setBackgroundColor = function (backgroundColor) {
        if (this.backgroundColor !== backgroundColor) {
          this.backgroundColor = backgroundColor;
          this.incrementModelStateVersion();
        }
      };

      TextItem.prototype.getPadding = function () {
        return this.padding;
      };

      TextItem.prototype.setPadding = function (padding) {
        if (this.padding !== padding) {
          this.padding = padding;
          this.incrementModelStateVersion();
        }
      };

      TextItem.prototype.getVerticalAlign = function () {
        return this.verticalAlign;
      };

      TextItem.prototype.setVerticalAlign = function (verticalAlign) {
        if (this.verticalAlign !== verticalAlign) {
          this.verticalAlign = verticalAlign;
          this.incrementModelStateVersion();
        }
      };

      /**
       * Sets wether or not we need a new image for the text content, rendered by the server.
       * @param trueOrFalse
       */
      TextItem.prototype.setImageRenderingNeeded = function (trueOrFalse) {
        if (this.ng.imageRenderingNeeded !== trueOrFalse) {
          this.ng.imageRenderingNeeded = trueOrFalse;
          this.incrementModelStateVersion();
        }
      };

      /**
       * Do we need a new image for the text content, rendered by the server?
       * @return {boolean}
       */
      TextItem.prototype.isImageRenderingNeeded = function () {
        return this.ng.imageRenderingNeeded;
      };

      /**
       * @return {Font}
       */
      TextItem.prototype.getFont = function () {
        return this.font;
      };

      /**
       * @param {Font} font
       */
      TextItem.prototype.setFont = function (font) {
        if (this.font !== font) {
          this.font = font;
          this.incrementModelStateVersion();
        }
      };

      TextItem.prototype.getFontSize = function () {
        return this.fontSize;
      };

      TextItem.prototype.setFontSize = function (fontSize) {
        if (this.fontSize !== fontSize) {
          this.fontSize = fontSize;
          this.incrementModelStateVersion();
        }
      };


      TextItem.prototype.setSelected = function (trueOrFalse) {

        // call super method
        ItemBoxPrototypeFactory.getClass().prototype.setSelected.call(this, trueOrFalse);

        if (!trueOrFalse) {
          this.setImageRenderingNeeded(true);
        }

        this.incrementModelStateVersion();
      };

      return {

        getClass: function () {
          return TextItem;
        },

        getPrototype: function () {
          return new TextItem();
        },

        /**
         *
         * @param {TextItemTemplate} textItemTemplate
         * @param centerX
         * @param centerY
         * @param width
         * @param height
         * @param rotation
         * @return {TextItem}
         */
        createTextItem: function (textItemTemplate, centerX, centerY, width, height, rotation, layerIndex) {
          if (textItemTemplate === undefined || centerX === undefined || centerY === undefined ||
            width === undefined || width <= 0 || height === undefined || height <= 0 || rotation === undefined ||
            layerIndex === undefined || layerIndex < AppConstants.MIN_UNRESERVED_LAYER_INDEX) {
            throw new Error('Can\'t create TextItem. One or more parameters a missing or invalid.');
          }

          var textItem = new TextItem();

          textItem.setText(textItemTemplate.getText());
          textItem.setPlaceholderText(textItemTemplate.getPlaceholderText());
          textItem.setTextAnchor(textItemTemplate.getTextAnchor());
          textItem.setTextColor(textItemTemplate.getTextColor());
          textItem.setBackgroundColor(textItemTemplate.getBackgroundColor());
          textItem.setFont(textItemTemplate.getFont());
          textItem.setFontSize(textItemTemplate.getFontSize());
          textItem.setFontStyle(textItemTemplate.getFontStyle());
          textItem.setFontWeight(textItemTemplate.getFontWeight());
          textItem.setTextDecoration(textItemTemplate.getTextDecoration());
          textItem.setPadding(textItemTemplate.getPadding());
          textItem.setVerticalAlign(textItemTemplate.getVerticalAlign());


          textItem.setCenterX(centerX);
          textItem.setCenterY(centerY);
          textItem.setWidth(width);
          textItem.setHeight(height);
          textItem.setRotation(rotation);
          textItem.setLayerIndex(layerIndex);

          return textItem;
        }

      };
    }
  ]);
})();/**
 * Creates BackgroundItem instances for the project data model.
 *
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('TemplateBackgroundItemFactory', [
    '$log', 'ItemBoxPrototypeFactory',
    function ($log, ItemBoxPrototypeFactory) {

      var backgroundItemCounter = 0;

      function TemplateBackgroundItem() {
        // call super class constructor to instantiate its variables
        ItemBoxPrototypeFactory.getClass().call(this);

        this.baseElement.id = backgroundItemCounter++;
        this.designElementId = null;
        this.imageSection = null;
      }

      TemplateBackgroundItem.prototype = Object.create(ItemBoxPrototypeFactory.getClass().prototype);
      TemplateBackgroundItem.prototype.constructor = TemplateBackgroundItem;


      TemplateBackgroundItem.prototype.getId = function () {
        return this.baseElement.id;
      };

      TemplateBackgroundItem.prototype.getDesignElementId = function () {
        return this.designElementId;
      };

      TemplateBackgroundItem.prototype.setDesignElementId = function (designElementId) {
        this.designElementId = designElementId;
        this.incrementModelStateVersion();
      };


      TemplateBackgroundItem.prototype.getImageSection = function () {
        return this.imageSection;
      };

      TemplateBackgroundItem.prototype.setImageSection = function (imageSection) {
        this.imageSection = imageSection;
        this.incrementModelStateVersion();
      };

      return {

        getClass: function () {
          return TemplateBackgroundItem;
        },

        getPrototype: function () {
          return new TemplateBackgroundItem();
        },

        /**
         *
         * @param {BackgroundItemTemplate} backgroundItemTemplate
         * @param imageSection section of the background to be used (1, 2 or 3), defined in "ALREARID" specification
         * @return {TemplateBackgroundItem}
         */
        createBackgroundItem: function (backgroundTemplate, imageSection, centerX, centerY, width, height, layerIndex) {

          if (backgroundTemplate === undefined || imageSection === undefined || layerIndex === undefined || layerIndex < 1 || layerIndex > 2) {
            throw new Error('Can\'t create TemplateBackgroundItem. One or more parameters a missing or invalid.');
          }

          var backgroundItem = new TemplateBackgroundItem();

          backgroundItem.setDesignElementId(backgroundTemplate.getDesignElementId());
          backgroundItem.setImageSection(imageSection);
          backgroundItem.setCenterX(centerX);
          backgroundItem.setCenterY(centerY);
          backgroundItem.setWidth(width);
          backgroundItem.setHeight(height);
          backgroundItem.setLayerIndex(layerIndex);

          return backgroundItem;
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Created by helena.korbmacher on 17.03.14.
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('ViewPortFactory', [
    '$log',
    function ($log) {

      function ViewPort() {

        this.x = 0;
        this.y = 0;
        this.width = 0;
        this.height = 0;
        this.fullWidth = 0;
        this.fullHeight = 0;

      }

      ViewPort.prototype.getX = function () {
        return this.x;
      };

      ViewPort.prototype.setX = function (x) {
        this.x = x;
      };

      ViewPort.prototype.getY = function () {
        return this.y;
      };

      ViewPort.prototype.setY = function (y) {
        this.y = y;
      };

      ViewPort.prototype.getWidth = function () {
        return this.width;
      };

      ViewPort.prototype.setWidth = function (width) {
        this.width = width;
      };

      ViewPort.prototype.getHeight = function () {
        return this.height;
      };

      ViewPort.prototype.setHeight = function (height) {
        this.height = height;
      };

      ViewPort.prototype.getFullWidth = function () {
        return this.fullWidth;
      };

      ViewPort.prototype.setFullWidth = function (width) {
        this.fullWidth = width;
      };

      ViewPort.prototype.getFullHeight = function () {
        return this.fullHeight;
      };

      ViewPort.prototype.setFullHeight = function (height) {
        this.fullHeight = height;
      };

      ViewPort.prototype.convertToIntegers = function () {
        this.setX(Math.round(this.getX()));
        this.setY(Math.round(this.getY()));
        this.setWidth(Math.round(this.getWidth()));
        this.setHeight(Math.round(this.getHeight()));
      };

      return {

        getClass: function() {
          return ViewPort;
        },

        getPrototype: function () {
          return new ViewPort();
        },

        /**
         * Creates a new instance of class ViewPort
         * @param x x coordinate of the viewport relative to the full width
         * @param y y coordinate of the viewport relative to the full height
         * @param width width of the viewport relative to the full width
         * @param height height of the viewport relative to the full height
         * @param fullWidth full width of the image the viewport is based on
         * @param fullHeight full height of the image the viewport is based on
         * @returns {ViewPort}
         */
        createViewPort: function (x, y, width, height, fullWidth, fullHeight) {

          if (x === null || x < 0 || y === null || y < 0 || width === null || width <= 0 || height === null || height <= 0 ||
            fullWidth === null || fullWidth < 0 || fullHeight === null || fullHeight < 0) {
            throw new Error('Can\'t create a ViewPort. One or more parameters a missing or invalid.');
          }

          var viewPort = new ViewPort();

          viewPort.setX(x);
          viewPort.setY(y);
          viewPort.setWidth(width);
          viewPort.setHeight(height);
          viewPort.setFullWidth(fullWidth);
          viewPort.setFullHeight(fullHeight);

          return viewPort;
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Creates new projects.
 *
 * @author Holger Cremer
 * @author Silvia Peter
 * @author Sascha Friedrich
 */
(function () {
  'use strict';
  angular.module('tatooine').factory('ProjectFactory', [
    '$log', 'AppConstants', 'AppValues', 'BaseConfigService', 'DesignAreaFactory', 'TemplateBackgroundItemFactory', 'BackgroundItemTemplateFactory', 'TextItemFactory', 'TextItemTemplateFactory', 'FontFactory', 'OperatorService', 'MessageService',
    function ($log, AppConstants, AppValues, BaseConfigService, DesignAreaFactory, TemplateBackgroundItemFactory, BackgroundItemTemplateFactory, TextItemFactory, TextItemTemplateFactory, FontFactory, OperatorService, MessageService) {

      function Project() {

        this.title = '';
        this.baseProduct = {
          projectId: {
            id: -1,
            accessCode: undefined,
            userRelated: false
          },
          clientVersion: BaseConfigService.getClientVersion(),
          productId: null,
          designAreas: [],
          unusedProjectImages: []
        };

        this.$$initNg();

      }

      Project.prototype.$$initNg = function () {
        this.ng = {
          detailViewEnabled: false,
          modelStateVersion: 0,
          unsavedChanges: false,
          autoFillUsed: false,
          selectedDesignElementTabIndex: 0,
          userTextItemTemplates: [],
          magneticLinesActive: true
        };
      };

      Project.prototype.removeAllNgData = function () {
        delete this.ng;
        this.getDesignAreas().forEach(function iterDesignAreas(designArea){
          delete designArea.ng;
          designArea.getAllItems().forEach(function iterItems(item) {
            delete item.ng;
          });
        });
      };

      Project.prototype.isBlank = function () {
        var designAreas = this.getDesignAreas();
        for (var i = 0; i < designAreas.length; i++) {
          if (designAreas[i].getTemplateBackgroundItemLeft().getDesignElementId() !== 201 ||
            designAreas[i].getTemplateBackgroundItemRight().getDesignElementId() !== 201) {
            return false;
          }

          if (designAreas[i].getImageBackgroundItems() && designAreas[i].getImageBackgroundItems().length > 0) {
            return false;
          }

          if (designAreas[i].getImageItems() && designAreas[i].getImageItems().length > 0) {
            return false;
          }
          var textItems = designAreas[i].getTextItems();
          if (textItems) {
            for (var j = 0; j < textItems.length; j++) {
              if (!textItems[j].isBlank()) {
                return false;
              }
            }
          }
        }
        return true;
      };

      Project.prototype.getClientVersion = function () {
        return this.baseProduct.clientVersion;
      };

      Project.prototype.setClientVersion = function (clientVersion) {
        this.baseProduct.clientVersion = clientVersion;
      };

      Project.prototype.getId = function () {
        return this.baseProduct.projectId.id;
      };

      Project.prototype.setId = function (id) {
        this.baseProduct.projectId.id = id;
      };

      Project.prototype.getAccessCode = function () {
        return this.baseProduct.projectId.accessCode;
      };

      Project.prototype.setAccessCode = function (accessCode) {
        this.baseProduct.projectId.accessCode = accessCode;
      };

      Project.prototype.isUserRelated = function () {
        return this.baseProduct.projectId.userRelated;
      };

      Project.prototype.setUserRelated = function (trueOrFalse) {
        this.baseProduct.projectId.userRelated = trueOrFalse;
      };

      Project.prototype.getTitle = function () {
        return this.title;
      };

      Project.prototype.setTitle = function (title) {
        this.title = title;
      };

      Project.prototype.getProductId = function () {
        return this.baseProduct.productId;
      };

      Project.prototype.setProductId = function (productId) {
        this.baseProduct.productId = productId;
      };

      Project.prototype.getDesignAreas = function () {
        return this.baseProduct.designAreas;
      };

      Project.prototype.getAllImageItems = function () {
        var allImageItems = [];
        this.getDesignAreas().forEach(function iterateDesignAreas(designArea) {
          allImageItems = allImageItems.concat(designArea.getImageItems());
        });
        return allImageItems;
      };

      Project.prototype.setUnusedProjectImages = function (projectImages) {
        this.baseProduct.unusedProjectImages = projectImages;
      };

      Project.prototype.getUnusedProjectImages = function () {
        return this.baseProduct.unusedProjectImages;
      };

      Project.prototype.getSelectedDesignArea = function () {
        var designAreas = this.getDesignAreas();
        for (var i = 0; i < designAreas.length; i++) {
          if (designAreas[i].isSelected()) {
            return designAreas[i];
          }
        }
      };

      Project.prototype.getDesignAreaForPageNo = function (pageNo) {
        var designAreas = this.getDesignAreas();
        var designAreaIndex = Math.floor(pageNo / 2) + 1;
        if (designAreaIndex > designAreas.length - 1) {
          return undefined;
        }
        return designAreas[designAreaIndex];
      };

      Project.prototype.isDetailView = function () {
        return this.ng.detailViewEnabled;
      };

      Project.prototype.setDetailView = function (trueOrFalse) {
        this.ng.detailViewEnabled = trueOrFalse;
      };

      Project.prototype.isStoryBoardView = function () {
        return !this.isDetailView();
      };

      Project.prototype.getModelStateVersion = function () {
        return this.ng.modelStateVersion;
      };

      Project.prototype.incrementModelStateVersion = function () {
        this.ng.modelStateVersion++;
        this.setUnsavedChanges(true);
      };

      /**
       *
       * @return {boolean} flag whether the project contains unsaved changes or not
       */
      Project.prototype.hasUnsavedChanges = function () {
        return this.ng.unsavedChanges;
      };

      /**
       *
       * @param {boolean} trueOrFalse set a flag wether the project has unsaved changes or not
       */
      Project.prototype.setUnsavedChanges = function (trueOrFalse) {
        this.ng.unsavedChanges = trueOrFalse;
      };

      Project.prototype.isAutoFillUsed = function () {
        return this.ng.autoFillUsed;
      };

      Project.prototype.setAutoFillUsed = function (trueOrFalse) {
        this.ng.autoFillUsed = trueOrFalse;
      };

      Project.prototype.getSelectedDesignElementTabIndex = function () {
        return this.ng.selectedDesignElementTabIndex;
      };

      Project.prototype.setSelectedDesignElementTabIndex = function (tabIndex) {
        this.ng.selectedDesignElementTabIndex = tabIndex;
      };

      Project.prototype.getUserTextItemTemplates = function () {
        return this.ng.userTextItemTemplates;
      };

      Project.prototype.addUserTextItemTemplate = function (textItemTemplate) {
        var index = this.ng.userTextItemTemplates.indexOf(textItemTemplate);
        if (index === -1) {
          this.ng.userTextItemTemplates.push(textItemTemplate);
        }
        else {
          this.ng.userTextItemTemplates.splice(index, 1);
          this.ng.userTextItemTemplates.push(textItemTemplate);
        }
        if (this.ng.userTextItemTemplates.length > 10) {
          this.ng.userTextItemTemplates.shift();
        }
        $log.debug(this.ng.userTextItemTemplates.length);
      };


      /**
       *
       * @returns {number} the numer of (single) pages in the project, contains no editable and no cover pages
       */
      Project.prototype.getPagesCount = function () {

        var designAreas = this.getDesignAreas();
        if (designAreas) {
          return (designAreas.length - AppConstants.DESIGN_AREAS_ARE_COVER) * AppConstants.DESIGN_AREAS_ON_PAGE - AppConstants.NOT_EDITABLE_PAGES;
        }
      };

      Project.prototype.setMagneticLinesActive = function (trueOrFalse) {
        this.ng.magneticLinesActive = trueOrFalse;
      };

      Project.prototype.isMagneticLinesActive = function () {
        return this.ng.magneticLinesActive;
      };

      return {

        getClass: function () {
          return Project;
        },

        getPrototype: function () {
          return new Project();
        },

        /**
         *
         * @param {Product} product
         * @param {Number} pages
         * @param bookTitle
         * @param {Boolean} createSpineAndTitleTextItem
         * @param spineConfig
         * @return {Project} the created Project
         */
        createProject: function (product, pages, bookTitle, createSpineAndTitleTextItem, spineConfig) {

          if (product === null || pages === null || pages < 26) {
            throw new Error('Can\'t create a Project. One or more parameters a missing or invalid.');
          }

          if (pages > product.getMaxNumberOfPages() || pages < product.getMinNumberOfPages()) {
            throw new Error('Pages do no fit to this project, pages: ' + pages);
          }

          var project = new Project();

          project.baseProduct.productId = product.getId();

          AppConstants.MM_TO_PX = 1 / (product.getDoublePageWidth() / AppValues.canvasWidth);

          var coverWidth = product.getCoverPageWidthForPages(pages) * AppConstants.MM_TO_PX;
          var coverHeight = product.getCoverPageHeightForPages(pages) * AppConstants.MM_TO_PX;
          var safetyMargin = product.getSafetyMargin() * AppConstants.MM_TO_PX;


          var doublePageWidth = product.getDoublePageWidth() * AppConstants.MM_TO_PX;
          var doublePageHeight = product.getDoublePageHeight() * AppConstants.MM_TO_PX;
          var bleedMarginHorizontal = product.getBleedMarginHorizontal() * AppConstants.MM_TO_PX;
          var bleedMarginVertical = product.getBleedMarginVertical() * AppConstants.MM_TO_PX;
          var coverBleedMarginHorizontal = product.getCoverBleedMarginHorizontal() * AppConstants.MM_TO_PX;
          var coverBleedMarginVertical = product.getCoverBleedMarginVertical() * AppConstants.MM_TO_PX;

          var defaultBackgroundItemTemplate = BackgroundItemTemplateFactory.createBackgroundItemTemplate(AppConstants.BACKGROUND_DEFAULT_ID);

          // 14 empty designAreas means, there are 26 pages in the photobook, which is the minimum.
          var allPages = (pages + AppConstants.NOT_EDITABLE_PAGES) / AppConstants.DESIGN_AREAS_ON_PAGE + AppConstants.DESIGN_AREAS_ARE_COVER;

          for (var i = 0; i < allPages; i++) {
            var isCover = i === 0;
            var isLeftPageBlocked = i === 1;
            var isRightPageBlocked = i === allPages - 1;
            var designArea = null;

            if (isCover) {
              var backgroundItemCover = TemplateBackgroundItemFactory.createBackgroundItem(defaultBackgroundItemTemplate, 4,
                  coverWidth / 2, coverHeight / 2, coverWidth + coverBleedMarginHorizontal * 2, coverHeight + coverBleedMarginVertical * 2, 1);

              designArea = DesignAreaFactory.createDesignArea(coverWidth, coverHeight, coverBleedMarginHorizontal, coverBleedMarginVertical,
                safetyMargin, backgroundItemCover);

            } else {

              var backgroundItemWidth = doublePageWidth / 2 + bleedMarginHorizontal;
              var backgroundItemHeight = doublePageHeight + bleedMarginVertical * 2;

              var backgroundItemLeft = TemplateBackgroundItemFactory.createBackgroundItem(defaultBackgroundItemTemplate, 2,
                  doublePageWidth * 0.25 - bleedMarginHorizontal / 2, doublePageHeight / 2,
                backgroundItemWidth, backgroundItemHeight, 1);

              var backgroundItemRight = TemplateBackgroundItemFactory.createBackgroundItem(defaultBackgroundItemTemplate, 2,
                  doublePageWidth * 0.75 + bleedMarginHorizontal / 2, doublePageHeight / 2,
                backgroundItemWidth, backgroundItemHeight, 2);

              designArea = DesignAreaFactory.createDesignArea(doublePageWidth, doublePageHeight, bleedMarginHorizontal, bleedMarginVertical,
                safetyMargin, backgroundItemLeft, backgroundItemRight);
            }

            if (isLeftPageBlocked) {
              designArea.setLeftPageBlocked(true);
            }
            if (isRightPageBlocked) {
              designArea.setRightPageBlocked(true);
            }

            designArea.setType(isCover ? 'cover' : 'inbook');

            if (designArea.isCover()) {

              var spineWidth = product.getCoverSpineWidthForPages(pages);
              designArea.setSpineWidth(spineWidth);
              designArea.setBarCode(product.getBarCode());
              project.setTitle(bookTitle ? bookTitle : '');
              if (createSpineAndTitleTextItem) {
                var placeholderText = MessageService.getMessage('project.textItem.placeholderText');
                var spineTextTemplate = TextItemTemplateFactory.createTextItemTemplate(project.getTitle(), placeholderText, 'middle', '#000000', 'none',
                  FontFactory.createFont('Ancona Ex'), product.getCoverSpineTextMaxFontSizeForPages(pages), 'normal', 'normal', 'none', '0', 'middle');
                var spineTextItem = TextItemFactory.createTextItem(spineTextTemplate, coverWidth / 2, coverHeight / 2,
                    coverHeight - 2 * safetyMargin, spineWidth * AppConstants.MM_TO_PX, spineConfig.spineLogoContentRotation, designArea.getNextFreeLayerIndex());
                spineTextItem.setPositionEditable(false);
                designArea.addTextItem(spineTextItem);

                var titleTextFontSize = Math.round(product.getCoverPageWidthForPages(pages) * 0.004);
                var titleTextTemplate = TextItemTemplateFactory.createTextItemTemplate(project.getTitle(), placeholderText, 'middle', '#000000', 'none',
                  FontFactory.createFont('Ancona Ex'), titleTextFontSize, 'normal', 'normal', 'none', '5pt', 'top');

                var textBoxWidth = coverWidth * 0.38;
                var textBoxHeight = textBoxWidth * 0.15;

                var titleTextItem = TextItemFactory.createTextItem(titleTextTemplate, coverWidth * 0.75 + spineWidth * AppConstants.MM_TO_PX / 2,
                    coverHeight * 0.38 - textBoxHeight / 2, textBoxWidth, textBoxHeight, 0, designArea.getNextFreeLayerIndex());
                designArea.addTextItem(titleTextItem);

              }
              if (spineConfig.spineLogoEnabled) {
                designArea.setSpineLogoEnabled(spineConfig.spineLogoEnabled);
                designArea.setSpineLogoElementId(spineConfig.spineLogoElementId);
                designArea.setSpineMaxWidth(spineConfig.maxSpineWidth);
                designArea.setSpineContentRotation(spineConfig.spineLogoContentRotation);
              }

            }

            project.getDesignAreas().push(designArea);
          }

          return project;
        }

      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Creates and stores the project the user is currently working on, be it a photobook or some other product.
 * @author Silvia Peter (silvia.peter@cewe.de)
 * Date: 26.07.13
 * Time: 14:22
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('ProjectRepository', [
    '$log',
    function ($log) {

      var repo = {
        project: undefined // needs to be created in createProject()
      };


      // definition of the public repository functions
      return {

        getProject: function () {
          return repo.project;
        },

        setProject: function(project) {
          repo.project = project;
        }

      };

    }
  ])
  ;

})
  ();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Allows to save or load a project while communicating with a RESTful service.
 * @author Silvia Peter (silvia.peter@cewe.de)
 * @author Sascha Friedrich
 * @author Frank Bruns
 */
(function () {
  'use strict';
  /* global tv4 */
  /* global JSV */
  angular.module('tatooine').factory('ProjectService', [
    '$rootScope', '$log', '$http', '$document', '$window', '$resource', '$q', '$route', '$location', '$timeout', '$modal', 'AppConstants', 'AppValues', 'EventConstants', 'Utils', 'BaseConfigService', 'TrackingService', 'OperatorService',
    'AuthenticationService', 'ProductService', 'FileHandleService', 'LayoutService', 'MessageService', 'BackgroundTemplateService', 'PhotoSourcesService', 'ProjectFactory', 'DesignAreaFactory', 'TemplateBackgroundItemFactory',
    'ImageItemFactory', 'ViewPortFactory', 'TextItemFactory', 'TextItemTemplateFactory', 'BackgroundItemTemplateFactory', 'ClipartItemFactory', 'FontFactory', 'LayoutFactory',
    'ProjectRepository', 'IpsAlbumService', 'NotificationService', 'UploadService', 'LeaveEditorService', 'IndexedDBService',
    function ($rootScope, $log, $http, $document, $window, $resource, $q, $route, $location, $timeout, $modal, AppConstants, AppValues, EventConstants, Utils, BaseConfigService, TrackingService, OperatorService, AuthenticationService, ProductService, FileHandleService, LayoutService, MessageService, BackgroundTemplateService, PhotoSourcesService, ProjectFactory, DesignAreaFactory, TemplateBackgroundItemFactory, ImageItemFactory, ViewPortFactory, TextItemFactory, TextItemTemplateFactory, BackgroundItemTemplateFactory, ClipartItemFactory, FontFactory, LayoutFactory, ProjectRepository, IpsAlbumService, NotificationService, UploadService, LeaveEditorService, IndexedDBService) {

      /**
       * Does a validation against a JSON schema Version 4. Throws an exception if the validation fails.
       * @param schema

       function validateForSaveTv4(schema) {
        var projectData = ProjectRepository.getProject();
        var valid = tv4.validate(projectData, schema);
        if (valid) {
          $log.info('Validation successful (TV4)');
        }
        else {
          $log.info('Validation errors (TV4):', tv4.error);
          throw new Error('The internal model is not valid against the json schema.');
        }
      }*/


      /**
       * Does a validation against the given schema. Throws an exception if the validation fails.
       * @param schema
       * @param project
       */
      function validateForSaveJSV(schema, project) {

        var env = JSV.createEnvironment();

        var validationResult = env.validate(project, schema);
        if (validationResult.errors.length === 0) {
          $log.debug('JSON schema validation successful', schema);
        } else {
          $log.error('JSON schema validation failed. Errors: ', validationResult.errors);
          throw new Error('The project model model is not valid against the json schema.');
        }
      }

      var startMyProjectsDialog = function () {

        var myProjectsLightbox = $modal.open({
          size: 'lg',
          templateUrl: 'myProjectsLightbox',
          controller: 'MyProjectsLightboxController'
        });

        return myProjectsLightbox.result;
      };


      function startSaveStatusDialog(infoTextKey) {
        var additionalInfoText = (infoTextKey ? MessageService.getMessage(infoTextKey) : '');
        var dialogPassThroughData = {infoText: additionalInfoText};

        var saveProjectStatusLightbox = $modal.open({
          size: 'lg',
          templateUrl: 'saveProjectStatusLightbox',
          controller: 'SaveProjectStatusLightboxController',
          resolve: {
            passThrough: function () {
              return dialogPassThroughData;
            }
          }
        });
        return saveProjectStatusLightbox.result;
      }

      // definition of the public service functions
      var projectService = {

        initProject: function (pagesCount, productId, bookTitle, createSpineAndTitleTextItem) {
          var product = ProductService.getProductById(productId);
          return projectService.createProject(product, pagesCount, bookTitle, createSpineAndTitleTextItem);
        },


        /**
         * Deletes the current project on server side (if it has been saved so far)
         */
        deleteCurrentProject: function () {
          var projectId = BaseConfigService.getProjectIdFromUrl();
          if (!projectId) {
            $log.info('Delete project not required, because current project has not been saved yet.');
            return $q.when();
          }
          $log.info('Deleting project with ID: ', projectId);
          var projectUrl = 'photobook/' + projectId + '.rest';
          var ProjectResource = $resource(projectUrl);

          var deleteProjectResult = ProjectResource.delete();
          deleteProjectResult.$promise.finally(function deleteProjectFinished() {
            BaseConfigService.removeProjectIdFromUrl();
            projectService.getProject().setId(-1);
            if (IndexedDBService.isActive()) {
              var parsedProjectId = parseInt(projectId, 10);
              IndexedDBService.removeImageFilesForProject(parsedProjectId);
            }
          });
          return deleteProjectResult.$promise;
        },


        /**
         * Validates the given project and sends it to the server.
         *
         * @param {Project} project
         */
        saveProject: function (suppressNotifications) {
          var project = projectService.getProject();

          var deferred = $q.defer();

          $log.info('Save project called.');
          project.setClientVersion(BaseConfigService.getClientVersion());
          var copiedProject = angular.copy(project);

          // clean up pixel based coordinate value to make them integer values since the server demands integers and
          // not floating point values.
          var currentProduct = ProductService.getProductById(project.getProductId());
          copiedProject.getDesignAreas().forEach(function iterateDesignAreas(designArea) {
            var bleedMarginHorizontal = designArea.isCover() ? currentProduct.getCoverBleedMarginHorizontal() : currentProduct.getBleedMarginHorizontal();
            var bleedMarginVertical = designArea.isCover() ? currentProduct.getCoverBleedMarginVertical() : currentProduct.getBleedMarginVertical();

            var pxToMm = 1 / AppConstants.MM_TO_PX;
            designArea.getAllItems(true).forEach(function iterateItemBoxes(itemBox) {
              itemBox.setCenterX(Math.round(itemBox.getCenterX() * pxToMm + bleedMarginHorizontal));
              itemBox.setCenterY(Math.round(itemBox.getCenterY() * pxToMm + bleedMarginVertical));
              itemBox.setWidth(Math.round(itemBox.getWidth() * pxToMm));
              itemBox.setHeight(Math.round(itemBox.getHeight() * pxToMm));

              if (designArea.hasImageItem(itemBox) || designArea.hasImageBackgroundItem(itemBox)) {
                itemBox.getViewPort().convertToIntegers();
                // put the refCountId of the source image into the image item box
                var fileHandle = FileHandleService.getFileHandle(itemBox.getFileHandleId());
                if (fileHandle && fileHandle.isTransferred()) {
                  itemBox.setRefCountId(fileHandle.getRefCountId());
                }
              }

            });

          });
          var unusedProjectImages = [];
          FileHandleService.getUnusedFileHandles().forEach(function iterateFileHandles(fileHandle) {
            if (fileHandle.isTransferred() && fileHandle.getRefCountId() > 0) {
              unusedProjectImages.push({
                refCountId: fileHandle.getRefCountId(),
                filename: fileHandle.getFileName()
              });
            }
          });
          copiedProject.setUnusedProjectImages(unusedProjectImages);

          // 1. Get the schema.
          // 2. Validate.
          // 3. Save.
          var jsonSchemaUrl = 'photobook/metadata/schema.rest';
          var saveProjectUrl = 'photobook.rest';

          var JsonSchemaResource = $resource(jsonSchemaUrl);
          var saveProjectParams = {
            skipSessionTimeout: 'true'
          };

          var SaveProjectResource = $resource(saveProjectUrl, saveProjectParams);

          var loadSchemaResult = JsonSchemaResource.get(function schemaLoaded(schema) {


            $rootScope.$broadcast(EventConstants.PROJECT_SAVE_IN_PROGRESS, copiedProject);

            copiedProject.removeAllNgData();

            $log.info('Saving project', copiedProject);
            $log.debug('Fetched JSON schema', schema);
            validateForSaveJSV(schema, copiedProject);

            var oldModelStateVersion = project.getModelStateVersion();

            var saveProjectResult = SaveProjectResource.save(copiedProject);

            $q.all([loadSchemaResult.$promise, saveProjectResult.$promise]).then(function ok(both) {

                $log.debug('clientProjectId', copiedProject.getId());

                var firstSave = (project.getId() < 0);

                project.setId(saveProjectResult.id);
                project.setAccessCode(saveProjectResult.accessCode);
                project.setUserRelated(saveProjectResult.userRelated);
                $log.info('Successfully saved project -> project id:', project.getId() + ', accessCode: ' + saveProjectResult.accessCode);
                BaseConfigService.setProjectIdIntoUrl(saveProjectResult.id);
                if (!AuthenticationService.isLoggedIn()) {
                  BaseConfigService.setAccessCodeIntoUrl(saveProjectResult.accessCode);
                } else {
                  BaseConfigService.removeAccessCodeFromUrl();
                }

                // if the model state version from before the save operation is the same as after the save
                // we can assume that now there are no more unsaved changes in the project model.
                if (oldModelStateVersion === project.getModelStateVersion()) {
                  $log.debug('project model didn\'t change since save operation started.');
                  if (UploadService.getRemainingFileHandles() <= 0) {
                    project.setUnsavedChanges(false);
                  }
                } else {
                  $log.debug('project model changed since save operation started.');
                }

                if (firstSave) {
                  // track project id on first save operation
                  TrackingService.trackByEVar('eVar46', saveProjectResult.id, 'Project id');
                  // put all local files into indexedDB on first save
                  var htmlFiles = [];
                  FileHandleService.getFileHandles().forEach(function iterateFileHandles(fileHandle) {
                    if (fileHandle.getFile() && !fileHandle.isTransferred() && IndexedDBService.isActive()) {
                      htmlFiles.push(fileHandle.getFile());
                    }
                  });
                  IndexedDBService.putImageFiles(saveProjectResult.id, AuthenticationService.isLoggedIn(), htmlFiles).then(function ok() {
                    $rootScope.$broadcast(EventConstants.PROJECT_SAVED, project);
                    deferred.resolve(both);
                  }, function error() {
                    if (OperatorService.isUploadUnusedImagesEnabled()) {
                      htmlFiles.forEach(function iterateFiles(file) {
                        var fileHandle = FileHandleService.getFileHandleByHtmlFile(file);
                        if (!fileHandle.isTransferred()) {
                          UploadService.startUpload(fileHandle);
                        }
                      });
                      $rootScope.$broadcast(EventConstants.PROJECT_SAVED, project);
                      deferred.resolve(both);
                    } else {
                      $rootScope.$broadcast(EventConstants.PROJECT_SAVED, project);
                      deferred.resolve(both);
                    }
                  });
                } else {
                  $rootScope.$broadcast(EventConstants.PROJECT_SAVED, project);
                  deferred.resolve(both);
                }

              }, function failed(both) {
                $log.error('Failed to save project!', saveProjectResult);
                deferred.reject(both);
                if (both.data && both.data.message) {
                  var messages = both.data.message.split('#');
                  if (messages && messages.length >= 1) {
                    var missedFileHandle = FileHandleService.getFileHandleById(messages[messages.length - 1]);
                    if (missedFileHandle) {
                      NotificationService.addNotification(missedFileHandle.getFileName(),
                        MessageService.getMessage('notification.save.specficImageMissing.failed'), 'danger', 5000);
                    }
                  }
                }
                $rootScope.$broadcast(EventConstants.PROJECT_SAVE_FAILED, project);
                if (!suppressNotifications) {
                  NotificationService.addNotification('', MessageService.getMessage('notification.save.failed'), 'danger', 5000);
                }
              }
            )
            ;
          }, function loadSchemaFailed() {
            $log.error('Failed to load schema!', loadSchemaResult);
            deferred.reject();
          });

          return deferred.promise;

        },

        /**
         * Loads a project from the server and sets it as the new active one.
         */
        loadProject: function (projectId, accessCode) {

          $log.info('Loading project with id', projectId);

          var deferred = $q.defer();

          var projectUrl = 'photobook/' + projectId + '.rest';
          var loadParam = {'accessCode': accessCode};
          var ProjectResource = $resource(projectUrl, loadParam);

          var result = ProjectResource.get(function ok() {

            var serverProject = angular.extend(ProjectFactory.getPrototype(), result);
            $log.debug('project loaded sucessfully: ', serverProject);

            // init an empty project that will get filled with the project data that was just loaded from the server
            projectService.initProject(serverProject.getPagesCount(), serverProject.getProductId(), serverProject.getTitle(), false);

            var clientProject = projectService.getProject();
            var clientProduct = ProductService.getProductById(clientProject.baseProduct.productId);
            serverProject = angular.extend(ProjectFactory.getPrototype(), serverProject);

            clientProject.setId(serverProject.getId());
            clientProject.setAccessCode(serverProject.getAccessCode());
            // fill the design areas of the client project with data from the server project
            for (var daIndex = 0; daIndex < clientProject.getDesignAreas().length; daIndex++) {

              serverProject.getDesignAreas()[daIndex] = angular.extend(DesignAreaFactory.getPrototype(), serverProject.getDesignAreas()[daIndex]);

              var clientDesignArea = clientProject.getDesignAreas()[daIndex];
              var serverDesignArea = serverProject.getDesignAreas()[daIndex];

              var safetyArea = {
                innerRect: {
                  left: clientDesignArea.getSafetyMargin(),
                  top: clientDesignArea.getSafetyMargin(),
                  width: clientDesignArea.getWidth() - 2 * clientDesignArea.getSafetyMargin(),
                  height: clientDesignArea.getHeight() - 2 * clientDesignArea.getSafetyMargin()
                },
                outerRect: {
                  left: -clientDesignArea.getBleedMarginHorizontal(),
                  top: -clientDesignArea.getBleedMarginVertical(),
                  width: clientDesignArea.getWidth() + 2 * clientDesignArea.getBleedMarginHorizontal(),
                  height: clientDesignArea.getHeight() + 2 * clientDesignArea.getBleedMarginVertical()
                }
              };

              // transfer item box data from the persisted project

              // just replace the default design area template backgrounds with the loaded server side data
              for (var itemIndex = 0; itemIndex < serverDesignArea.getTemplateBackgroundItems().length; itemIndex++) {
                var serverTemplateBackgroundItem = angular.extend(TemplateBackgroundItemFactory.getPrototype(), serverDesignArea.getTemplateBackgroundItems()[itemIndex]);

                clientDesignArea.getTemplateBackgroundItems()[itemIndex].setDesignElementId(serverTemplateBackgroundItem.getDesignElementId());
                clientDesignArea.getTemplateBackgroundItems()[itemIndex].setImageSection(serverTemplateBackgroundItem.getImageSection());
              }


              var mmToPx = AppConstants.MM_TO_PX;
              var bleedMarginHorizontal = clientDesignArea.isCover() ? clientProduct.getCoverBleedMarginHorizontal() * mmToPx : clientProduct.getBleedMarginHorizontal() * mmToPx;
              var bleedMarginVertical = clientDesignArea.isCover() ? clientProduct.getCoverBleedMarginVertical() * mmToPx : clientProduct.getBleedMarginVertical() * mmToPx;

              // enrich server model ImageItems to fit the needs of the client model
              var centerX, centerY, width, height, rotation;

              var clientImageBackgroundItems = [];

              var allServerImageItems = serverDesignArea.getImageItems().concat(serverDesignArea.getImageBackgroundItems());
              for (itemIndex = 0; itemIndex < allServerImageItems.length; itemIndex++) {

                var serverImageItem = angular.extend(ImageItemFactory.getPrototype(), allServerImageItems[itemIndex]);

                centerX = serverImageItem.getCenterX() * mmToPx - bleedMarginHorizontal;
                centerY = serverImageItem.getCenterY() * mmToPx - bleedMarginVertical;
                width = serverImageItem.getWidth() * mmToPx;
                height = serverImageItem.getHeight() * mmToPx;
                rotation = serverImageItem.getRotation();
                var borderWidth = serverImageItem.getBorderWidth();
                var borderColor = serverImageItem.getBorderColor();

                var viewPort = angular.extend(ViewPortFactory.getPrototype(), serverImageItem.getViewPort());

                var clientImageItem = ImageItemFactory.createImageItem(centerX, centerY, width, height, rotation, serverImageItem.getLayerIndex(), safetyArea,
                  serverImageItem.getAlphaMaskId(), serverImageItem.getDecoFrameId());

                clientImageItem.setViewPort(viewPort);
                clientImageItem.setRefCountId(serverImageItem.getRefCountId());

                if (borderWidth && borderColor) {
                  clientImageItem.setBorderWidth(borderWidth);
                  clientImageItem.setBorderColor(borderColor);
                }

                clientImageItem.setOriginalImageWidth(serverImageItem.getOriginalImageWidth());
                clientImageItem.setOriginalImageHeight(serverImageItem.getOriginalImageHeight());
                clientImageItem.setOriginalFileName(serverImageItem.getOriginalFileName());
                clientImageItem.setGreenDotsPerMM(clientProduct.getGreenDotsPerMM());
                clientImageItem.setYellowDotsPerMM(clientProduct.getYellowDotsPerMM());

                // create fileHandle objects for the project imageItems that have refcount ids (i.e. are uploaded to our servers)
                if (clientImageItem.getRefCountId() > 0) {
                  var fileHandle = FileHandleService.createServerFileHandle(
                    clientImageItem.getRefCountId(), clientImageItem.getOriginalFileName(),
                    clientImageItem.getOriginalImageWidth(), clientImageItem.getOriginalImageHeight());

                  fileHandle.increaseUsageCount();
                  clientImageItem.setFileHandleId(fileHandle.getId());

                  if (serverImageItem.getMyPhotosPicutreId()) {
                    fileHandle.setMyPhotosPictureId(serverImageItem.getMyPhotosPicutreId());
                    clientImageItem.setMyPhotosPictureId(fileHandle.getMyPhotosPictureId());
                    PhotoSourcesService.checkAndUpdateFileHandleForEventInfos(fileHandle);
                  }

                }
                if (Utils.isInArray(serverDesignArea.getImageBackgroundItems(), allServerImageItems[itemIndex])) { // we need to compare on the unextended serverImageItem, thus accessing it by allServerImages array
                  clientImageBackgroundItems.push(clientImageItem); // collect background ImageItems in order to set in whole to the DesignArea --> no need for deciding on the page half now
                } else {
                  clientDesignArea.addImageItem(clientImageItem);
                }
              }

              clientDesignArea.setImageBackgroundItems(clientImageBackgroundItems);

              // enrich server model TextItems to fit the needs of the client model
              for (itemIndex = 0; itemIndex < serverDesignArea.getTextItems().length; itemIndex++) {

                var serverTextItem = angular.extend(TextItemFactory.getPrototype(), serverDesignArea.getTextItems()[itemIndex]);
                serverTextItem.setFont(angular.extend(FontFactory.getPrototype(), serverTextItem.getFont()));

                var placeholderText = MessageService.getMessage('project.textItem.placeholderText');

                var textItemTemplate = TextItemTemplateFactory.createTextItemTemplate(serverTextItem.getText(), placeholderText,
                  serverTextItem.getTextAnchor(), serverTextItem.getTextColor(), serverTextItem.getBackgroundColor(), serverTextItem.getFont(),
                  serverTextItem.getFontSize(), serverTextItem.getFontStyle(), serverTextItem.getFontWeight(), serverTextItem.getTextDecoration(),
                  serverTextItem.getPadding(), serverTextItem.getVerticalAlign());

                centerX = Math.round(serverTextItem.getCenterX() * mmToPx - bleedMarginHorizontal);
                centerY = Math.round(serverTextItem.getCenterY() * mmToPx - bleedMarginVertical);
                width = Math.round(serverTextItem.getWidth() * mmToPx);
                height = Math.round(serverTextItem.getHeight() * mmToPx);
                rotation = Math.round(serverTextItem.getRotation());

                var clientTextItem = TextItemFactory.createTextItem(textItemTemplate, centerX, centerY, width, height, rotation, serverTextItem.getLayerIndex());

                clientTextItem.setContentEditable(serverTextItem.isContentEditable());
                clientTextItem.setPositionEditable(serverTextItem.isPositionEditable());

                clientDesignArea.addTextItem(clientTextItem);
              }

              // enrich server model ClipartItems to fit the needs of the client model
              for (itemIndex = 0; itemIndex < serverDesignArea.getClipartItems().length; itemIndex++) {
                var serverClipartItem = angular.extend(ClipartItemFactory.getPrototype(), serverDesignArea.getClipartItems()[itemIndex]);

                centerX = Math.round(serverClipartItem.getCenterX() * mmToPx - bleedMarginHorizontal);
                centerY = Math.round(serverClipartItem.getCenterY() * mmToPx - bleedMarginVertical);
                width = Math.round(serverClipartItem.getWidth() * mmToPx);
                height = Math.round(serverClipartItem.getHeight() * mmToPx);
                rotation = Math.round(serverClipartItem.getRotation());

                var clientClipartItem = ClipartItemFactory.createClipartItem(serverClipartItem.getDesignElementId(), centerX, centerY, width, height, rotation, serverClipartItem.getLayerIndex(), safetyArea);

                clientDesignArea.addClipartItem(clientClipartItem);
              }


              // attach created Layouts to the DesignArea in case the persisted reporting data had layouts
              if (serverDesignArea.getReportingData().layoutIdLeft !== '-1') {
                var layoutIdLeft = serverDesignArea.getReportingData().layoutIdLeft;
                var layoutLeft = LayoutFactory.createLayoutFromDesignAreaContent(layoutIdLeft, clientDesignArea, 'left');
                if (layoutLeft) {
                  clientDesignArea.attachLayoutToPageHalf('left', layoutLeft);
                }
              }
              if (serverDesignArea.getReportingData().layoutIdRight !== '-1') {
                var layoutIdRight = serverDesignArea.getReportingData().layoutIdRight;
                var layoutRight = LayoutFactory.createLayoutFromDesignAreaContent(layoutIdRight, clientDesignArea, 'right');
                if (layoutRight) {
                  clientDesignArea.attachLayoutToPageHalf('right', layoutRight);
                }
              }
              clientDesignArea.setReportingData(serverDesignArea.getReportingData());
            }
            // create file handles for unused images
            serverProject.getUnusedProjectImages().forEach(function (projectImage) {
              FileHandleService.createServerFileHandle(projectImage.refCountId, projectImage.filename, projectImage.width, projectImage.height);
            });

            deferred.resolve();
            $rootScope.$broadcast(EventConstants.PROJECT_LOADED, projectId);

            IpsAlbumService.createExifDataForAlbum(projectId);

            TrackingService.trackByEVar('eVar46', projectId, 'Project id');

          }, function error(result) {
            if (result.status === 401) {
              if (!AuthenticationService.isLoggedIn()) {
                AuthenticationService.ensureUserLoggedIn('loginRegister.loginToLoad', null, null, false).then(function loggedIn() {
                  projectService.loadProject(projectId, accessCode).then(function ok() {
                    $rootScope.$broadcast(EventConstants.PROJECT_LOADED, projectId);
                  });
                });
              }
            }
            deferred.reject();
          });
          return deferred.promise;
        },

        /**
         *
         * @return {Project}
         */
        getProject: function () {
          return ProjectRepository.getProject();
        },


        /**
         * Makes the given project the current project and enriches it with necessary AngularJS UI specific attributes.
         * @param {Project} project
         */
        setProject: function (project, isNewProject) {
          // FYI - Frank Bruns 12.02.2014: The use of angular.extend() is motivated by the fact that project data that has been loaded from the server
          // contains instances of type Object and not of the classes we have defined for Project, DesignArea or ItemBox. Thus, the methods that
          // have been defined on these classes are not available on the Object instances. With angular.extend() we can extend specified
          // target instances with properties from specified source instances, making them real instances of class Project, DesignArea, ItemBox, etc.
          project = angular.extend(ProjectFactory.getPrototype(), project);
          // create fileHandle objects for the project imageItems that have refcount ids (i.e. are uploaded to our servers)
          for (var daIndex = 0; daIndex < project.getDesignAreas().length; daIndex++) {

            project.getDesignAreas()[daIndex] = angular.extend(DesignAreaFactory.getPrototype(), project.getDesignAreas()[daIndex]);

            var designArea = project.getDesignAreas()[daIndex];
            designArea.setNg(designArea.ng); // some class instance conversions happen inside this method

            var itemIndex, fileHandle;

            for (itemIndex = 0; itemIndex < designArea.getImageItems().length; itemIndex++) {

              var itemBoxImage = angular.extend(ImageItemFactory.getPrototype(), designArea.getImageItems()[itemIndex]);
              itemBoxImage.viewport = angular.extend(ViewPortFactory.getPrototype(), itemBoxImage.viewport);

              if (itemBoxImage.getRefCountId() > 0) {
                fileHandle = FileHandleService.createServerFileHandle(itemBoxImage.getRefCountId(), itemBoxImage.getOriginalFileName(),
                  itemBoxImage.getOriginalImageWidth(), itemBoxImage.getOriginalImageHeight());
                itemBoxImage.setFileHandleId(fileHandle.getId());
              }

              designArea.getImageItems()[itemIndex] = itemBoxImage;
            }

            for (itemIndex = 0; itemIndex < designArea.getTextItems().length; itemIndex++) {
              var itemBoxText = angular.extend(TextItemFactory.getPrototype(), designArea.getTextItems()[itemIndex]);
              designArea.getTextItems()[itemIndex].font = angular.extend(FontFactory.getPrototype(), designArea.getTextItems()[itemIndex].font);
              designArea.getTextItems()[itemIndex] = itemBoxText;
            }

            for (itemIndex = 0; itemIndex < designArea.getTemplateBackgroundItems().length; itemIndex++) {
              var itemBoxBackground = angular.extend(TemplateBackgroundItemFactory.getPrototype(), designArea.getTemplateBackgroundItems()[itemIndex]);
              designArea.getTemplateBackgroundItems()[itemIndex] = itemBoxBackground;
            }

            for (itemIndex = 0; itemIndex < designArea.getClipartItems().length; itemIndex++) {
              var itemBoxClipart = angular.extend(ClipartItemFactory.getPrototype(), designArea.getClipartItems()[itemIndex]);
              designArea.getClipartItems()[itemIndex] = itemBoxClipart;
            }

          }
          FileHandleService.updateFileHandleUsageCounts(project);

          ProjectRepository.setProject(project);
          if (!isNewProject) {
            $rootScope.$broadcast(EventConstants.PROJECT_TO_SCOPE_NEEDED, project);
            $log.info('restore project data to ', project);
          }
        },


        isSaveProjectNeeded: function () {
          var deferred = $q.defer();
          if (!AuthenticationService.isLoggedIn() && !projectService.getProject().isUserRelated() && projectService.getProject().isBlank()) {
            // we do not want to save empty projects
            projectService.deleteCurrentProject().finally(function doFinally() {
              deferred.resolve(false);
            });
          } else if ((!AuthenticationService.isLoggedIn() && !projectService.getProject().isBlank()) ||
            projectService.getProject().hasUnsavedChanges() ||
            UploadService.getRemainingFileHandles().length > 0) {
            // the user is not logged in and the project is not blank or it has unsaved changes
            // ask the user, if the project should be saved
            var dialogInfoTextKey = AuthenticationService.isLoggedIn() ? 'saveChoice.unsavedChanges' : 'saveChoice.unsavedProject';
            var saveProjectChoiceDialogData = {
              header: MessageService.getMessage('saveChoice.header'),
              text: MessageService.getMessage(dialogInfoTextKey)
            };

            var saveProjectChoiceLightbox = $modal.open({
              templateUrl: 'saveProjectChoiceLightbox',
              controller: 'SaveProjectChoiceLightboxController',
              resolve: {
                passThrough: function () {
                  return saveProjectChoiceDialogData;
                }
              }
            });
            saveProjectChoiceLightbox.result.then(function saveProjectChoiceLightboxClosed(response) {
              if (!response.keepProject && !projectService.getProject().isUserRelated() && !AuthenticationService.isLoggedIn()) {
                projectService.deleteCurrentProject().finally(function doFinally() {
                  deferred.resolve(response.keepProject);
                });
              }
              else {
                deferred.resolve(response.keepProject);
              }
            }, function saveProjectChoiceLightboxDismissed() {
              deferred.reject();
            });
          } else {
            // there are no unsaved changes
            // so it is not necessary to save the current project
            deferred.resolve(false);
          }
          return deferred.promise;
        },

        saveCurrentProjectModal: function (infoMessageKey) {
          var deferred = $q.defer();
          projectService.saveProject().then(function () {
            if (UploadService.getRemainingFileHandles().length > 0) {
              startSaveStatusDialog(infoMessageKey).then(function ok() {
                deferred.resolve();
              }, function dismissed() {
                $log.debug('saveProjectStatusLightbox dismissed');
                deferred.reject();
              });
            } else {
              deferred.resolve();
            }
          });
          return deferred.promise;
        },

        /**
         *
         * @param {Product} product
         * @param pagesCount
         * @param bookTitle
         */
        createProject: function (product, pagesCount, bookTitle, createSpineAndTitleTextItem) {

          var spineConfig = {
            spineLogoEnabled: OperatorService.isSpineLogoEnabled() && product.getHasSpineLogo(),
            spineLogoContentRotation: OperatorService.getSpineContentRotation(),
            spineLogoElementId: OperatorService.getLogoElementId(),
            maxSpineWidth: product.getCoverSpineWidthForPages(product.getMaxNumberOfPages())
          };

          var project = ProjectFactory.createProject(product, pagesCount ? pagesCount : 26, bookTitle, createSpineAndTitleTextItem, spineConfig);
          projectService.setProject(project, true);
        },

        addPagePackage: function () {
          var project = projectService.getProject();

          var product = ProductService.getProductById(project.getProductId());
          // add design areas
          var doublePageWidth = product.getDoublePageWidth() * AppConstants.MM_TO_PX;
          var doublePageHeight = product.getDoublePageHeight() * AppConstants.MM_TO_PX;

          var maxPages = product.getMaxNumberOfPages();


          // TODO 09.09.14 do we really need to create backgroundItems in this place?
          var bleedMarginHorizontal = product.getBleedMarginHorizontal() * AppConstants.MM_TO_PX;
          var bleedMarginVertical = product.getBleedMarginVertical() * AppConstants.MM_TO_PX;
          var safetyMargin = product.getSafetyMargin() * AppConstants.MM_TO_PX;

          var backgroundItemWidth = doublePageWidth / 2 + bleedMarginHorizontal;
          var backgroundItemHeight = doublePageHeight + bleedMarginVertical * 2;

          if (AppValues.doublePagePackageSize + project.getPagesCount() <= maxPages) {
            for (var i = 0; i < AppValues.doublePagePackageSize; i++) {
              var backgroundItemLeft = TemplateBackgroundItemFactory.createBackgroundItem(BackgroundItemTemplateFactory.createBackgroundItemTemplate(AppConstants.BACKGROUND_DEFAULT_ID), 2,
                doublePageWidth * 0.25 - bleedMarginHorizontal / 2, doublePageHeight / 2, backgroundItemWidth, backgroundItemHeight, 1);
              var backgroundItemRight = TemplateBackgroundItemFactory.createBackgroundItem(BackgroundItemTemplateFactory.createBackgroundItemTemplate(AppConstants.BACKGROUND_DEFAULT_ID), 2,
                doublePageWidth * 0.75 + bleedMarginHorizontal / 2, doublePageHeight / 2, backgroundItemWidth, backgroundItemHeight, 2);

              var designArea = DesignAreaFactory.createDesignArea(doublePageWidth, doublePageHeight, bleedMarginHorizontal, bleedMarginVertical,
                safetyMargin, backgroundItemLeft, backgroundItemRight);

              projectService.getProject().getDesignAreas().push(designArea);
            }


            var designAreas = projectService.getProject().getDesignAreas();
            designAreas.forEach(function iterDesignAreas(designArea) {
              if (designArea.isCover()) {
                designArea.setWidth(product.getCoverPageWidthForPages(project.getPagesCount()) * AppConstants.MM_TO_PX);
                designArea.setSpineWidth(product.getCoverSpineWidthForPages(project.getPagesCount()));
                designArea.setToStoryboardSize();
              }
              if (designArea.isRightPageBlocked()) {
                designArea.setRightPageBlocked(false);
              }
            });
            designAreas[designAreas.length - 1].setRightPageBlocked(true);
            NotificationService.addNotification('', MessageService.getMessage('notification.addAdditionalPagesDone', [AppValues.doublePagePackageSize * 2, projectService.getProject().getPagesCount()]), 'info', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
          }
        },

        removePagePackage: function (project) {
          if (!project) {
            project = projectService.getProject();
          }
          var product = ProductService.getProductById(project.getProductId());

          var minPages = product.getMinNumberOfPages();

          if (project.getPagesCount() - AppValues.doublePagePackageSize > minPages) {
            // rdy to remove design areas

            var designAreas = project.getDesignAreas();

            var removedDesignAreas = designAreas.splice(designAreas.length - AppValues.doublePagePackageSize, AppValues.doublePagePackageSize);
            removedDesignAreas.forEach(function iterRemovedAreas(removedArea) {
              var toRemoveImages = removedArea.getImageItems();

              toRemoveImages.forEach(function iterToRemoveImages(toRemoveImage) {
                removedArea.removeItemBox(toRemoveImage);
              });
            });

            designAreas.forEach(function iterDesignAreas(designArea) {
              if (designArea.isCover()) {
                designArea.setWidth(product.getCoverPageWidthForPages(project.getPagesCount()) * AppConstants.MM_TO_PX);
                designArea.setSpineWidth(product.getCoverSpineWidthForPages(project.getPagesCount()));
                designArea.setToStoryboardSize();
              }
            });

            designAreas[designAreas.length - 1].setRightPageBlocked(true);
            NotificationService.addNotification('', MessageService.getMessage('notification.removeAdditionalPagesDone', [AppValues.doublePagePackageSize * 2, projectService.getProject().getPagesCount()]), 'info', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
          }


        },

        toggleCanvasStoryBoardDetailView: function (fullHeadAreaHeight, designArea) {
          var oldIsDetailView = projectService.getProject().isDetailView();

          var project = projectService.getProject();


          if (designArea) {
            var windowElement = angular.element($window);
            designArea.fitToDimensions(windowElement.width() - 2 * AppConstants.DESIGN_AREA_FLYOUT_WIDTH, windowElement.height() - fullHeadAreaHeight - 85);
            // Enable interaction with the itemBoxes on the designArea.
            designArea.setDetailInteractionMode(true);
            projectService.getProject().setDetailView(true);


            for (var i = 0; i < designArea.getImageItems().length; i++) {
              if (designArea.getImageItems()[i].isBadQualiy()) {
                NotificationService.addCustomIconNotification('toast-badQuality', MessageService.getMessage('notification.badQualityTitle'), MessageService.getMessage('notification.badQualityDescription'), 'warning', 10000);
                i = designArea.getImageItems().length;
              }
            }
          } else {
            project.getDesignAreas().forEach(function iterDesignAreas(designArea) {
              designArea.setToStoryboardSize();
            });

            // disable the detail interaction mode for the currently active design area in the project since
            // we are in storyboard mode now. That means, the itemboxes cannot be selected.
            var selectedDesignArea = projectService.getSelectedDesignArea();
            if (!selectedDesignArea) {
              selectedDesignArea = projectService.getProject().getDesignAreas()[0];
              selectedDesignArea.setSelected(true);
            }
            selectedDesignArea.setDetailInteractionMode(false);
            projectService.getProject().setDetailView(false);
          }


          if (oldIsDetailView && projectService.getProject().isStoryBoardView() || projectService.getProject().isDetailView()) {
            // clear the cache of so far randomly returned Layouts and add all used Layouts in the project to the used layouts cache
            LayoutService.clearReturnedRandomLayoutsCache();
            LayoutService.clearUsedLayoutsCache();
            var designAreas = project.getDesignAreas();
            designAreas.forEach(function iterDesginAreas(designArea) {
              LayoutService.cacheLayoutsFromDesignArea(designArea, project);
            });
          }
        },

        /**
         * Returns the currently selected design area data model among all design area data models in the project.
         * @returns {DesignArea} the selected design area data model in the project
         */
        getSelectedDesignArea: function () {
          var project = projectService.getProject();
          if (project) {
            var designAreas = project.getDesignAreas();

            for (var i = 0; i < designAreas.length; i++) {
              if (designAreas[i].isSelected()) {
                return designAreas[i];
              }
            }
          }
        },

        /**
         * Returns the design area data model for the given id.
         * @returns {*} the design area data model in the project for the given id
         */
        getDesignAreaById: function (id) {
          var project = projectService.getProject();
          if (project) {
            var designAreas = project.getDesignAreas();

            for (var i = 0; i < designAreas.length; i++) {
              if (designAreas[i].id === id) {
                return designAreas[i];
              }
            }
          }
        },

        selectDesignArea: function (designArea) {
          var designAreas = projectService.getProject().getDesignAreas();
          designAreas.forEach(function iterateDesignAreas(da) {
            if (da === designArea) {
              da.setSelected(true);
            } else {
              da.setSelected(false);
            }
          });
        },

        /**
         * Rest Service Call which deletes the project from shoppingCart by itemId
         * thus we dont want to have multipli books in the cart if the customer edit the book again
         */
        deleteProjectFromShoppingCart: function (shoppingCartItemId) {
          var projectUrl = 'photobook/shoppingcart/items/' + shoppingCartItemId + '.rest';
          var ProjectResource = $resource(projectUrl);
          var result = ProjectResource.delete(function ok() {
            $log.debug('Deleted shoppingCartItem from ShoppingCart! itemId:', shoppingCartItemId);
          }, function error() {
            $log.error('Something went wrong by deleting shoppingCartItem from ShoppingCart!');
          });
        },

        /**
         * Checks if all used images on this designArea are uploaded
         * @param designAreaModel
         * @param pagehalf (optional)
         * @returns (boolean)
         */

        allUsedImagesOnDesignAreaUploaded: function (designAreaModel, pagehalf) {
          var fileHandle, images;
          for (var j = 0; j < (pagehalf ? designAreaModel.getImageItems(pagehalf).length : designAreaModel.getImageItems().length); j++) {
            if (pagehalf ? designAreaModel.getImageItems(pagehalf)[j] : designAreaModel.getImageItems()[j]) {
              fileHandle = FileHandleService.getFileHandle(pagehalf ? designAreaModel.getImageItems(pagehalf)[j].getFileHandleId() : designAreaModel.getImageItems()[j].getFileHandleId());
              if (fileHandle && !fileHandle.isTransferred()) {
                return false;
              }
            }
          }
          return true;
        },

        loadExternalProjects: function () {
          var deferred = $q.defer();
          var url = 'projects/photobooks.rest';
          $log.debug('Request user projects from server:' + url);
          $http.get(url).success(function (data) {
            deferred.resolve(data);
          });
          return deferred.promise;

        },

        handleOpenMyProjects: function (saveCurrentProject) {
          $log.debug('handleOpenProject, saveCurrentProject: ', saveCurrentProject);
          if (BaseConfigService.isSSOSession()) {
            // SSO
            if (saveCurrentProject) {
              // The user decided to keep/save current project
              var infoTextKey = AuthenticationService.isLoggedIn() ? 'saveStatus.finished.openProject' : 'saveStatus.finished.sso.redirectToLogin.openProject';
              return projectService.saveCurrentProjectModal(infoTextKey).then(function projectSaved() {
                AuthenticationService.ensureUserLoggedIn('loginRegister.failedSaving', {openProjectDialog: true}, null, false).then(function loggedIn() {
                  startMyProjectsDialog();
                });
              });
            } else {
              // do *not* save current project
              return AuthenticationService.ensureUserLoggedIn('loginRegister.loginToOpen', {openProjectDialog: true}, null, false).then(function loggedIn() {
                return startMyProjectsDialog();
              });
            }
          } else {
            // *NO* SSO
            if (saveCurrentProject) {
              // The user decided to keep/save current project
              return AuthenticationService.ensureUserLoggedIn('loginRegister.failedSaving', null, null, false).then(function loggedIn() {
                projectService.saveCurrentProjectModal('saveStatus.finished.openProject').then(function () {
                  startMyProjectsDialog();
                });
              });
            } else {
              // do *not* save current project
              return AuthenticationService.ensureUserLoggedIn('loginRegister.loginToOpen', null, null, false).then(function loggedIn() {
                return startMyProjectsDialog();
              });
            }
          }
        },


        /*
         * Checks if all used images in the whole project are uploaded
         * @returns (boolean)
         */

        allUsedImagesUploaded: function () {
          var project = projectService.getProject();
          var designAreas = project.getDesignAreas();
          for (var i = 0; i < designAreas.length; i++) {
            if (!projectService.allUsedImagesOnDesignAreaUploaded(designAreas[i])) {
              return false;
            }
          }
          return true;
        },

        changeProjectProduct: function (targetProductId) {

          var deferred = $q.defer();

          var currentProduct = ProductService.getProductById(projectService.getProject().getProductId());
          var currentProject = projectService.getProject();
          var targetProduct = ProductService.getProductById(targetProductId);

          var copyCurrentProject = angular.copy(currentProject);

          var spineConfig = {
            spineLogoEnabled: OperatorService.isSpineLogoEnabled() && targetProduct.getHasSpineLogo(),
            spineLogoContentRotation: OperatorService.getSpineContentRotation(),
            spineLogoElementId: OperatorService.getLogoElementId(),
            maxSpineWidth: targetProduct.getCoverSpineWidthForPages(targetProduct.getMaxNumberOfPages())
          };

          if (targetProductId === currentProduct.getId()) {
            $log.debug('Nothing to change: called product is the same as the current in the project');
            deferred.resolve();
            return deferred.promise;
          }

          if (ProductService.hasSameDimensionsForPages(targetProduct, currentProduct, copyCurrentProject.getPagesCount())) {
            $log.debug('Target product has same dimension for pages, switching the productId');
            currentProject.setProductId(targetProductId);
            deferred.resolve();
            return deferred.promise;

          } else {
            var conversionAllowed = ProductService.isCompatibleForConversion(targetProduct, currentProduct);
            if (!conversionAllowed) {
              $log.error('Cant convert to product with different aspect ratio');
              deferred.reject();
              return deferred.promise;
            }


            if (copyCurrentProject.getPagesCount() > targetProduct.getMaxNumberOfPages()) {
              var pagesToDeleteCount = copyCurrentProject.getPagesCount() - targetProduct.getMaxNumberOfPages();

              while (copyCurrentProject.getPagesCount() > targetProduct.getMaxNumberOfPages()) {
                projectService.removePagePackage(copyCurrentProject);
              }

              if (copyCurrentProject.getPagesCount() !== targetProduct.getMaxNumberOfPages()) {
                $log.error('Cant convert to product. PagesCount does not fit to project', copyCurrentProject);
                deferred.reject();
                return deferred.promise;
              }

            }

            $log.debug('Project has same aspect ratio, trying to convert project');

            // TODO: its not really a constant anymore
            var oldMmToPx = AppConstants.MM_TO_PX;
            AppConstants.MM_TO_PX = 1 / (targetProduct.getDoublePageWidth() / AppValues.canvasWidth);

            var pages = copyCurrentProject.getPagesCount();

            var currentDesignAreas = copyCurrentProject.getDesignAreas();
            currentDesignAreas.forEach(function (designArea) {
              designArea.setSafetyMargin(targetProduct.getSafetyMargin() * AppConstants.MM_TO_PX);

              if (designArea.isCover()) {
                var targetCoverWidth = targetProduct.getCoverPageWidthForPages(pages);
                var targetCoverHeight = targetProduct.getCoverPageHeightForPages(pages);
                var currentCoverWidth = currentProduct.getCoverPageWidthForPages(pages);
                var currentCoverHeight = currentProduct.getCoverPageHeightForPages(pages);

                var targetCoverWidthWithoutSpine = (targetCoverWidth - targetProduct.getCoverSpineWidthForPages(pages)) / 2;
                var currentCoverWidthWithoutSpine = (currentCoverWidth - currentProduct.getCoverSpineWidthForPages(pages)) / 2;

                //var coverScaleXWithoutSpine = targetCoverWidthWithoutSpine / currentCoverWidthWithoutSpine;
                var coverScaleX = targetCoverWidth / currentCoverWidth;
                var coverScaleY = targetCoverHeight / currentCoverHeight;

                designArea.setWidth(targetCoverWidth * AppConstants.MM_TO_PX);
                designArea.setHeight(targetCoverHeight * AppConstants.MM_TO_PX);

                designArea.setBleedMarginHorizontal(targetProduct.getCoverBleedMarginHorizontal() * AppConstants.MM_TO_PX);
                designArea.setBleedMarginVertical(targetProduct.getCoverBleedMarginVertical() * AppConstants.MM_TO_PX);

                //SPINE

                designArea.setBarCode(targetProduct.getBarCode());

                designArea.getImageAndTextAndClipartItems().forEach(function (item) {
                  if (item !== spineTextItem) {
                    item.setWidth((item.getWidth() / oldMmToPx) * AppConstants.MM_TO_PX * coverScaleX);
                    item.setHeight((item.getHeight() / oldMmToPx) * AppConstants.MM_TO_PX * coverScaleY);
                    item.setCenterX((item.getCenterX() / oldMmToPx) * AppConstants.MM_TO_PX * coverScaleX);
                    item.setCenterY((item.getCenterY() / oldMmToPx) * AppConstants.MM_TO_PX * coverScaleY);
                  }
                  if (item instanceof ImageItemFactory.getClass()) {
                    item.recalculateViewPort();
                  }

                });

                designArea.setSpineWidth(targetProduct.getCoverSpineWidthForPages(pages), true);
                var spineTextItem = designArea.getSpineTextItem();
                if (spineTextItem) {
                  spineTextItem.setFontSize(Math.round(spineTextItem.getFontSize() * coverScaleX));
                }
                // adjust the size and position of the background item
                var leftTemplateBackgroundItem = designArea.getTemplateBackgroundItemLeft();
                leftTemplateBackgroundItem.setCenterX(designArea.getWidth() / 2);
                leftTemplateBackgroundItem.setCenterY(designArea.getHeight() / 2);
                leftTemplateBackgroundItem.setWidth(designArea.getWidth() + designArea.getBleedMarginHorizontal() * 2);
                leftTemplateBackgroundItem.setHeight(designArea.getHeight() + designArea.getBleedMarginVertical() * 2);

                // keeps the cover background color for switch to xxl books if the category is already colours.
                if (targetProduct.getFullBackgroundOnEachPage()) {
                  BackgroundTemplateService.getBackgroundTemplatesByCategory('category-colours').then(function (allowedBackgroundTemplates) {
                    var rightTemplateBackgroundItem = designArea.getTemplateBackgroundItemRight();
                    var leftAllowed = false;
                    var rightAllowed = false;
                    allowedBackgroundTemplates.forEach(function (allowedBackgroundTemplate) {
                      if (allowedBackgroundTemplate.designElementId === leftTemplateBackgroundItem.getDesignElementId()) {
                        leftAllowed = true;
                      }
                      if (allowedBackgroundTemplate.designElementId === rightTemplateBackgroundItem.getDesignElementId()) {
                        rightAllowed = true;
                      }
                    });
                    if (!leftAllowed || !rightAllowed) {
                      // the current background is not allowed for the cover, so we have to remove it
                      leftTemplateBackgroundItem.setDesignElementId(AppConstants.BACKGROUND_DEFAULT_ID);
                      rightTemplateBackgroundItem.setDesignElementId(AppConstants.BACKGROUND_DEFAULT_ID);
                    }
                  });
                }

                if (spineConfig.spineLogoEnabled) {
                  designArea.setSpineLogoEnabled(spineConfig.spineLogoEnabled);
                  designArea.setSpineLogoElementId(spineConfig.spineLogoElementId);
                  designArea.setSpineMaxWidth(spineConfig.maxSpineWidth);
                  designArea.setSpineContentRotation(spineConfig.spineLogoContentRotation);
                }


              } else {
                designArea.setWidth(targetProduct.getDoublePageWidth() * AppConstants.MM_TO_PX);
                designArea.setHeight(targetProduct.getDoublePageHeight() * AppConstants.MM_TO_PX);
                designArea.setBleedMarginHorizontal(targetProduct.getBleedMarginHorizontal() * AppConstants.MM_TO_PX);
                designArea.setBleedMarginVertical(targetProduct.getBleedMarginVertical() * AppConstants.MM_TO_PX);


                var targetDesignAreaWidth = targetProduct.getDoublePageWidth();
                var targetDesignAreaHeight = targetProduct.getDoublePageHeight();
                var currentDesignAreaWidth = currentProduct.getDoublePageWidth();
                var currentDesignAreaHeight = currentProduct.getDoublePageHeight();

                var scaleX = (targetDesignAreaWidth / currentDesignAreaWidth);
                var scaleY = (targetDesignAreaHeight / currentDesignAreaHeight);

                designArea.getImageAndTextAndClipartItems().forEach(function (item) {
                  item.setWidth((item.getWidth() / oldMmToPx) * AppConstants.MM_TO_PX * scaleX);
                  item.setHeight((item.getHeight() / oldMmToPx) * AppConstants.MM_TO_PX * scaleY);
                  item.setCenterX((item.getCenterX() / oldMmToPx) * AppConstants.MM_TO_PX * scaleX);
                  item.setCenterY((item.getCenterY() / oldMmToPx) * AppConstants.MM_TO_PX * scaleY);

                  if (item instanceof ImageItemFactory.getClass()) {
                    item.recalculateViewPort();
                  }

                });

                // adjust the size and position of the background items
                var backgroundItemLeft = designArea.getTemplateBackgroundItemLeft();
                backgroundItemLeft.setCenterX(designArea.getWidth() * 0.25 - designArea.getBleedMarginHorizontal() / 2);
                backgroundItemLeft.setCenterY(designArea.getHeight() / 2);
                backgroundItemLeft.setWidth(designArea.getWidth() / 2 + designArea.getBleedMarginHorizontal());
                backgroundItemLeft.setHeight(designArea.getHeight() + designArea.getBleedMarginVertical() * 2);
                if (targetProduct.getFullBackgroundOnEachPage()) {
                  backgroundItemLeft.setImageSection(4);
                }

                var backgroundItemRight = designArea.getTemplateBackgroundItemRight();
                backgroundItemRight.setCenterX(designArea.getWidth() * 0.75 + designArea.getBleedMarginHorizontal() / 2);
                backgroundItemRight.setCenterY(designArea.getHeight() / 2);
                backgroundItemRight.setWidth(designArea.getWidth() / 2 + designArea.getBleedMarginHorizontal());
                backgroundItemRight.setHeight(designArea.getHeight() + designArea.getBleedMarginVertical() * 2);
                if (targetProduct.getFullBackgroundOnEachPage()) {
                  backgroundItemRight.setImageSection(4);
                }
              }

            });
            LayoutService.clearUsedLayoutsCache();
            copyCurrentProject.setProductId(targetProductId);
            projectService.setProject(copyCurrentProject);
            var upsellingProducts = [];
            ProductService.setPossibleUpsellingProducts(upsellingProducts);
          }
          deferred.resolve();
          return deferred.promise;
        }

      };


      return projectService;
    }
  ])
  ;
})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';

  angular.module('tatooine').factory('UndoRedoService', [
    '$rootScope', '$log', '$q', 'AppConstants', 'ProjectService', 'FileHandleService', 'ProductService', 'MessageService', 'NotificationService', 'EventConstants',
    function ($rootScope, $log, $q, AppConstants, ProjectService, FileHandleService, ProductService, MessageService, NotificationService, EventConstants) {


      var undoStack = [];
      var redoStack = [];

      var undoRedoService = {
        /**
         * Clears both stacks.
         */
        clearStacks: function () {
          $log.debug('Clearing undo/redo stack.');
          undoStack = [];
          redoStack = [];
        },

        /**
         * Pushes the entire project onto the undo stack while calling pushModelData(). <br />
         *
         * @returns {Deferred} a handle, call 'resolve' if the user action was successfully or call 'reject' for a fail.
         */
        pushProject: function () {
          var currentProject = ProjectService.getProject();
          currentProject.mmToPx = AppConstants.MM_TO_PX;
          var deferred = this.pushModelData(currentProject);
          currentProject = null;
          return deferred;
        },

        /**
         * Pushes model data onto the undo stack and empties the redo stack. Model Data should either be a project or a design area. <br />
         * A transaction-like behavior is provided through the promise mechanism. Only then is the model state pushed onto the stack, if
         * the external action has been successful.
         *
         * @param modelData
         * @returns {Deferred} a handle, call 'resolve' if the user action was successfully or call 'reject' for a fail.
         */
        pushModelData: function (modelData) {

          var serializedModelData = angular.copy(modelData);

          var deferred = $q.defer();
          deferred.promise.then(
            function ok() {
              $log.debug('Pushing model data to undo stack', modelData);
              undoStack.push(serializedModelData);
              redoStack = [];
              // there should be no memory leak, if resolve or reject is called, but to be sure...
              serializedModelData = null;
            });

          return deferred;
        },

        /**
         * Removes the last data entry that was pushed to the undo/redo stack. A transaction-like behavior is provided through the promise mechanism.
         * Only then is the model state popped from the stack, if the external action has been successful.
         * @returns {Deferred} a handle, call 'resolve' if the user action was successfully or call 'reject' for a fail.
         */
        popModelData: function () {

          var deferred = $q.defer();
          deferred.promise.then(
            function ok() {
              $log.debug('Removing last model data entry from undo/redo stack');
              undoStack.pop();
            });

          return deferred;
        },


        /**
         * Executes undo, which means that the last element on the stack (project, designArea) replaces
         * the current. Undo is only possible, if a state has been saved with a push method. The undo action enables redo.
         */
        undo: function () {
          if (undoStack.length < 1) {
            return;
          }

          var lastStateSerialized = undoStack.pop();
          var lastState = lastStateSerialized;
          $log.debug('Setting new state from Undo: ', lastState);

          // Checks, if the element on top of the stack is a project or designArea (f.e. double page).
          if (lastState.baseProduct) { // has baseProduct attribute? --> must be a Project
            // Gets the current model of the project for undo action.
            var currentState = ProjectService.getProject();

            currentState.mmToPx = AppConstants.MM_TO_PX;
            // Saves the state of the project to the redoStack.
            var currentStateSerialized = angular.copy(currentState);
            redoStack.push(currentStateSerialized);

            if (lastState.getProductId() !== currentState.getProductId()) {
              var lastStateProduct = ProductService.getProductById(lastState.getProductId());
              NotificationService.addNotification('', MessageService.getMessage('notification.productOption.changeProduct.undo', [lastStateProduct.getName()]), 'info', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
            }

            AppConstants.MM_TO_PX = lastState.mmToPx;
            ProjectService.setProject(lastState);
            deSelectItemBoxOnNewState(lastState);
          } else if (lastState.imageItems) { // has imageItems array attribute --> must be a DesignArea.
            // Gets the current model of the design area for undo action.
            var designAreaModel = ProjectService.getDesignAreaById(lastState.id);
            var newModelStateVersion = designAreaModel.getModelStateVersion() + 1;

            // Saves the state of the design area to the redoStack.
            var currentDesignAreaSerialized = angular.copy(designAreaModel);
            redoStack.push(currentDesignAreaSerialized);

            // This is the current undo action, TODO maybe put this in a ProjectService later
            $log.debug('Returning to state', lastState);
            designAreaModel.setTemplateBackgroundItems(lastState.getTemplateBackgroundItems());
            designAreaModel.setImageBackgroundItems(lastState.getImageBackgroundItems());
            designAreaModel.setImageItems(lastState.getImageItems());
            designAreaModel.setTextItems(lastState.getTextItems());
            designAreaModel.setClipartItems(lastState.getClipartItems());
            designAreaModel.setReportingData(lastState.getReportingData());

            // keep some UI properties from current design area model
            var cssWidth = designAreaModel.getCssWidth();
            var cssHeight = designAreaModel.getCssHeight();
            var selected = designAreaModel.isSelected();
            var detailMode = designAreaModel.isDetailInteractionMode();

            designAreaModel.setNg(lastState.getNg());
            designAreaModel.setModelStateVersion(newModelStateVersion);


            designAreaModel.setCssWidth(cssWidth);
            designAreaModel.setCssHeight(cssHeight);
            designAreaModel.setSelected(selected);
            designAreaModel.setDetailInteractionMode(detailMode);
            designAreaModel.setTriggerCanvasUpdate(true);

            if (!designAreaModel.isDetailInteractionMode()) {
              deSelectItemBoxOnNewState(lastState);
            }

          }

          FileHandleService.updateFileHandleUsageCounts(ProjectService.getProject());
        },

        /**
         * Executes redo, which means that the last element on the stack (project, designArea) replaces
         * the current. Redo is only possible, if an undo was executed as the last saved action before.
         */
        redo: function () {
          if (redoStack.length < 1) {
            return;
          }

          var lastStateSerialized = redoStack.pop();
          var lastState = lastStateSerialized;
          $log.debug('Setting new state from Redo: ', lastState);
          // Checks, if the element on top of the stack is a project or design area (f.e. double page).
          if (lastState.baseProduct) { // has baseProduct attribute? --> must be a Project
            // Gets the current model of the project for redo action.
            var currentState = ProjectService.getProject();

            // Saves the state of the project to the undoStack.
            var currentStateSerialized = angular.copy(currentState);
            undoStack.push(currentStateSerialized);

            if (lastState.getProductId() !== currentState.getProductId()) {
              var lastStateProduct = ProductService.getProductById(lastState.getProductId());
              NotificationService.addNotification('', MessageService.getMessage('notification.productOption.changeProduct.redo', [lastStateProduct.getName()]), 'info', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
              AppConstants.MM_TO_PX = lastState.mmToPx;
            }
            deSelectItemBoxOnNewState(lastState);
            ProjectService.setProject(lastState);

          } else if (lastState.imageItems) { // has imageItems array attribute --> must be a DesignArea
            // Gets the current model of the design area for redo action.
            var designAreaModel = ProjectService.getDesignAreaById(lastState.id);
            var newModelStateVersion = designAreaModel.getModelStateVersion() + 1;

            // Saves the the state of the design area to the undoStack.
            var currentDesignAreaSerialized = angular.copy(designAreaModel);
            undoStack.push(currentDesignAreaSerialized);

            // This is the current redo action, TODO maybe put this in a ProjectService later
            $log.debug('Returning to state', lastState);
            designAreaModel.setTemplateBackgroundItems(lastState.getTemplateBackgroundItems());
            designAreaModel.setImageBackgroundItems(lastState.getImageBackgroundItems());
            designAreaModel.setImageItems(lastState.getImageItems());
            designAreaModel.setTextItems(lastState.getTextItems());
            designAreaModel.setClipartItems(lastState.getClipartItems());
            designAreaModel.setReportingData(lastState.getReportingData());

            // keep some UI properties from current design area model
            var cssWidth = designAreaModel.getCssWidth();
            var cssHeight = designAreaModel.getCssHeight();
            var selected = designAreaModel.isSelected();
            var detailMode = designAreaModel.isDetailInteractionMode();

            designAreaModel.setNg(lastState.getNg());
            designAreaModel.setModelStateVersion(newModelStateVersion);

            designAreaModel.setCssWidth(cssWidth);
            designAreaModel.setCssHeight(cssHeight);
            designAreaModel.setSelected(selected);
            designAreaModel.setDetailInteractionMode(detailMode);
            designAreaModel.setTriggerCanvasUpdate(true);

            if (!designAreaModel.isDetailInteractionMode()) {
              deSelectItemBoxOnNewState(lastState);
            }
          }

          FileHandleService.updateFileHandleUsageCounts(ProjectService.getProject());
        },


        /**
         * @returns {boolean} if undo is possible.
         */
        isUndoEnabled: function () {
          if (undoStack.length < 1) {
            return false;
          }
          return true;
        },

        /**
         * @returns {boolean} if redo is possible.
         */
        isRedoEnabled: function () {
          if (redoStack.length < 1) {
            return false;
          }
          return true;
        },

        getUndoStepsCount: function () {
          return undoStack.length;
        },

        getRedoStepsCount: function () {
          return redoStack.length;
        }
      };


      function deSelectItemBoxOnNewState(lastState) {
        if (lastState.baseProduct) {
          var project = ProjectService.getProject();
          var designAreas = project.getDesignAreas();
          for (var i = 0; i < designAreas.length; i++) {
            var allItems = designAreas[i].getAllItems(false);
            for (var j = 0; j < allItems.length; j++) {
              allItems[j].setSelected(false);
            }
          }
        }
        else {
          var selectedDesignArea = ProjectService.getSelectedDesignArea();
          if (selectedDesignArea) {
            var selectedItemBox = selectedDesignArea.getSelectedItemBox();
            if (selectedItemBox) {
              $log.debug('SelectedItemBox', selectedItemBox);
              selectedItemBox.setSelected(false);
            }
          }
          var stateDesignArea = ProjectService.getDesignAreaById(lastState.id);
          if (stateDesignArea) {
            var allIStateItems = stateDesignArea.getAllItems(false);
            for (var l = 0; l < allIStateItems.length; l++) {
              allIStateItems[l].setSelected(false);
            }
          }
        }
      }

      return undoRedoService;
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A button that can save the current Project and inform about the progress of the save operation.
 *
 * @since 12.09.2014
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwSaveProjectButton', [
    '$log', '$rootScope', '$interval', '$location', '$modal', 'EventConstants', 'ProjectService', 'AuthenticationService', 'MessageService', 'NotificationService', 'BaseConfigService', 'LeaveEditorService', 'FileHandleService', 'UploadService',
    function ($log, $rootScope, $interval, $location, $modal, EventConstants, ProjectService, AuthenticationService, MessageService, NotificationService, BaseConfigService, LeaveEditorService, FileHandleService, UploadService) {
      var lastSaved;

      return {
        restrict: 'A',
        scope: {},
        transclude: false,
        replace: false,
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/project/cwSaveProjectButton.html.jsf',
        link: function (scope, element, attrs) {

          scope.minutesSinceLastSave = -1;
          scope.btnText = MessageService.getMessage('project.button.save');
          scope.btnStatusText = MessageService.getMessage('project.button.save.status.notSavedYet');
          scope.uploadProgressVisible = false;
          scope.saveWithUploadProgressFeedbackActive = false;

          /**
           * Set the button to one of its defined states.
           * @param newState 'saving', 'saved', 'saveFailed', 'unsavedChanges'
           */
          scope.setBtnState = function (newState) {
            if (!AuthenticationService.isLoggedIn() && !ProjectService.getProject().isUserRelated()) {
              scope.btnText = MessageService.getMessage('project.button.save');
              scope.btnStatusText = MessageService.getMessage('project.button.save.status.notSavedYet');
              scope.btnEnabled = true;
              return;
            }
            if (newState === 'saving') {

              scope.btnState = 'saving';
              scope.btnEnabled = false;
              scope.btnText = MessageService.getMessage('project.button.saveInProgress');

            } else if (newState === 'saved' && UploadService.getRemainingFileHandles().length === 0) {

              scope.minutesSinceLastSave = 0;
              lastSaved = new Date().getTime();
              scope.btnStatusText = MessageService.getMessage('project.button.save.status.lastSave.fewSeconds');

              // there are new unsaved changes since the save operation started
              if (scope.btnState === 'unsavedChanges') {
                return;
              }

              if (ProjectService.getProject().hasUnsavedChanges()) {
                scope.setBtnState('unsavedChanges');
                return;
              }
              scope.btnState = 'saved';
              scope.btnEnabled = false;
              scope.btnText = MessageService.getMessage('project.button.save');

            } else if (newState === 'unsavedChanges') {
              scope.btnEnabled = true;
              scope.btnState = 'unsavedChanges';
              scope.btnText = MessageService.getMessage('project.button.save');

            } else if (newState === 'saveFailed') {

              scope.setBtnState('unsavedChanges');

            }

          }
          ;
          scope.setBtnState('unsavedChanges');


          // toggle active status of the button according to whether there are changes on the undo/redo stack (i.e. the user made changes).
          scope.$watch(function watchUnsavedChanges() {
            return ProjectService.getProject() && ProjectService.getProject().hasUnsavedChanges();
          }, function (newValue, oldValue) {
            if (newValue === true) {
              scope.setBtnState('unsavedChanges');
            }
          });

          scope.$watch(function watchNumberOfRemainingFiles() {
            return scope.getNumberOfRemainingFiles();
          }, function (newValue, oldValue) {
            if (oldValue > 0 && newValue === 0 && scope.saveWithUploadProgressFeedbackActive) {
              scope.closeUploadProgressFlyout();
              ProjectService.saveProject();
            }
          });

          scope.$watch(function watchUploadProgress() {
            return scope.getNumberOfRemainingFiles() > 0;
          }, function (newValue, oldValue) {
            scope.hasUntransferredFiles = newValue ? newValue : false;
            if (!newValue) {
              scope.saveWithUploadProgressFeedbackActive = newValue;
            }
          });

          $interval(function updateSaveStatusText() {
            if (scope.hasProjectBeenSavedBefore()) {
              scope.minutesSinceLastSave = Math.round((new Date().getTime() - lastSaved) / 1000 / 60);
              if (scope.minutesSinceLastSave >= 1) {
                scope.btnStatusText = MessageService.getMessage('project.button.save.status.lastSave', [scope.minutesSinceLastSave]);
              }
            }
          }, 1000 * 60);


          scope.$on(EventConstants.PROJECT_SAVE_IN_PROGRESS, function onProjectSaveInProgress(project) {
            scope.setBtnState('saving');
          });

          scope.$on(EventConstants.PROJECT_SAVED, function onProjectSaved(project) {
            scope.setBtnState('saved');
          });

          scope.$on(EventConstants.PROJECT_SAVE_FAILED, function onProjectSaveFailed(project) {
            scope.setBtnState('saveFailed');
          });

          scope.hasProjectBeenSavedBefore = function () {
            return ProjectService.getProject() && ProjectService.getProject().getId() > 0 && scope.minutesSinceLastSave >= 0;
          };

          scope.openUploadProgressFlyout = function () {
            scope.uploadProgressVisible = true;
          };

          scope.closeUploadProgressFlyout = function () {
            scope.uploadProgressVisible = false;
          };

          scope.getRemainingTime = function () {
            var estimatedTimeMinutes = UploadService.getRemainingTimeMinutes();
            if (estimatedTimeMinutes) {
              return MessageService.getMessage('saveProgressFlyout.estimatedTime', [estimatedTimeMinutes]);
            }
            return MessageService.getMessage('saveProgressFlyout.calculatingTime');
          };

          scope.getRemainingFileHandles = function () {
            return UploadService.getRemainingFileHandles();
          };

          scope.getNumberOfRemainingFiles = function () {
            return scope.getRemainingFileHandles().length;
          };

          scope.getNumberOfUploadedFiles = function () {
            return UploadService.getNumberOfUploadedFiles();
          };

          scope.saveButtonClicked = function () {
            if (scope.btnState === 'saving' && scope.getNumberOfRemainingFiles() === 0) {
              $log.debug('Save in progress, ignoring subsequent request.');
              return;
            }

            AuthenticationService.ensureUserLoggedIn('loginRegister.failedSaving', null, null, true).then(function loggedIn() {
              ProjectService.saveProject().then(function projectSaved() {
                if (scope.getNumberOfRemainingFiles() > 0) {
                  scope.saveWithUploadProgressFeedbackActive = true;
                  scope.setBtnState('saving');
                  scope.openUploadProgressFlyout();
                }
              });
            }, function notLoggedIn(result) {
              if (BaseConfigService.isSSOSession() && result === 'sso') {
                ProjectService.saveCurrentProjectModal('saveStatus.finished.sso.redirectToLogin').then(function projectSaved() {
                  LeaveEditorService.handleSsoLogin(null, null);
                });
              }
            });
          };

        }
      };
    }
  ])
  ;
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * This class represents all hotkeys in Tatooine
 * @author Sascha Friedrich
 */
(function () {
  'use strict';

  angular.module('tatooine').factory('HotKeyService', [
    '$rootScope', '$log', '$q', '$modal', '$timeout', 'hotkeys', 'AppConstants', 'AppValues', 'ContextPanelAreaService', 'ImageItemFactory', 'TextItemFactory', 'DesignAreaFactory', 'TemplateBackgroundItemFactory', 'BackgroundItemTemplateFactory',
    'ProjectService', 'MessageService', 'UndoRedoService', 'LayoutService', 'DesignAreaService', 'FileHandleService', 'ProductService', 'AuthenticationService', 'NotificationService', 'BookPreviewService', 'ClipartItemFactory', 'ItemBoxPrototypeFactory',
    function ($rootScope, $log, $q, $modal, $timeout, hotkeys, AppConstants, AppValues, ContextPanelAreaService, ImageItemFactory, TextItemFactory, DesignAreaFactory, TemplateBackgroundItemFactory, BackgroundItemTemplateFactory,
              ProjectService, MessageService, UndoRedoService, LayoutService, DesignAreaService, FileHandleService, ProductService, AuthenticationService, NotificationService, BookPreviewService, ClipartItemFactory, ItemBoxPrototypeFactory) {

      var copyObject = null;
      var copyOnSameDesignAreaGap = 50;

      var hotKeyService = {

        initHotKeys: function () {
          // TODO Sascha 25.09.14 - this is not nice - > title through the rootScope object
          $rootScope.templateTitle = MessageService.getMessage('hotKey.title');
          hotkeys.del('?');
          hotkeys.add({
            combo: 'h',
            description: MessageService.getMessage('hotKey.description.cheatSheet'),
            callback: function () {
              hotkeys.toggleCheatSheet();
            }
          });


          /**
           * Just add the needed hotkey Combo below , if description is declared it will show up  (incl. key-icon) in the help menu
           *
           */

          /**
           * Save on 'ctrl +s'
           */
          hotkeys.add({
            combo: 'ctrl+s',
            description: MessageService.getMessage('hotKey.description.save'),
            callback: function (event) {
              event.preventDefault();
              $timeout(function () {
                angular.element('#ceweSaveButton').trigger('click');
              }, 100);
            }
          });

          /**
           * Undo on 'ctrl+z'
           */
          hotkeys.add({
            combo: 'ctrl+z',
            description: MessageService.getMessage('hotKey.description.undo'),
            callback: function (event) {
              event.preventDefault();
              UndoRedoService.undo();
            }
          });

          /**
           * Redo on 'ctrl+y'
           */
          hotkeys.add({
            combo: 'ctrl+y',
            description: MessageService.getMessage('hotKey.description.redo'),
            callback: function (event) {
              event.preventDefault();
              UndoRedoService.redo();
            }
          });

          /**
           * Copy itemBox or designArea on 'ctrl+c'
           */
          hotkeys.add({
            combo: 'ctrl+c',
            allowIn: ['TEXTAREA'],
            description: MessageService.getMessage('hotKey.description.copy'),
            callback: function (event) {
              $log.debug(event);
              //event.preventDefault();
              var selectedDesignArea = ProjectService.getProject().getSelectedDesignArea();
              if (selectedDesignArea) {
                var selectedItemBox = selectedDesignArea.getSelectedItemBox();
                if (selectedItemBox) {
                  copyObject = angular.copy(selectedItemBox);
                }
                else if (selectedDesignArea && ProjectService.getProject().isStoryBoardView()) {
                  copyObject = angular.copy(selectedDesignArea);
                }
              }
            }
          });

          /**
           * cut itemBox on 'ctrl+x'
           */
          hotkeys.add({
            combo: 'ctrl+x',
            allowIn: ['TEXTAREA'],
            description: MessageService.getMessage('hotKey.description.cut'),
            callback: function (event) {
              //event.preventDefault();
              var selectedDesignArea = ProjectService.getProject().getSelectedDesignArea();
              if (selectedDesignArea) {
                var undoHandle;
                var selectedItemBox = selectedDesignArea.getSelectedItemBox();
                if (selectedItemBox) {
                  undoHandle = UndoRedoService.pushModelData(selectedDesignArea);
                  copyObject = angular.copy(selectedItemBox);
                  selectedDesignArea.removeItemBox(selectedItemBox);
                  undoHandle.resolve();
                }
                else if (selectedDesignArea && ProjectService.getProject().isStoryBoardView()) {
                  undoHandle = UndoRedoService.pushModelData(selectedDesignArea);
                  copyObject = angular.copy(selectedDesignArea);
                  selectedDesignArea.getTemplateBackgroundItemLeft().setDesignElementId(AppConstants.BACKGROUND_DEFAULT_ID);
                  selectedDesignArea.getTemplateBackgroundItemRight().setDesignElementId(AppConstants.BACKGROUND_DEFAULT_ID);
                  selectedDesignArea.clearContent();
                  undoHandle.resolve();
                }
              }
            }
          });

          /**
           * paste itemBox or designArea on 'ctrl+v'
           */
          hotkeys.add({
            combo: 'ctrl+v',
            allowIn: ['TEXTAREA'],
            description: MessageService.getMessage('hotKey.description.paste'),
            callback: function (event) {
              var undoHandle;
              var selectedDesignArea = ProjectService.getProject().getSelectedDesignArea();
              if (selectedDesignArea) {
                var notChangedCopy = null;
                if (selectedDesignArea.getSelectedItemBox() instanceof  TextItemFactory.getClass() === false) {
                  event.preventDefault();
                  if (copyObject instanceof(ItemBoxPrototypeFactory.getClass())) {
                    undoHandle = UndoRedoService.pushModelData(selectedDesignArea);
                    copyObject.setSelected(false);
                    var imageTextOrClipArtItems = selectedDesignArea.getImageAndTextAndClipartItems();
                    imageTextOrClipArtItems.forEach(function (item) {
                      if (copyObject.getId() === item.getId() && copyObject.getCenterX() === item.getCenterX() && copyObject.getCenterY() === item.getCenterY() && item.getWidth() === copyObject.getWidth() && item.getHeight() === copyObject.getHeight()) {
                        notChangedCopy = angular.copy(copyObject);
                        copyObject.setCenterX(copyObject.getCenterX() + copyOnSameDesignAreaGap);
                        copyObject.setCenterY(copyObject.getCenterY() + copyOnSameDesignAreaGap);
                      }
                    });
                    copyObject.setLayerIndex(selectedDesignArea.getNextFreeLayerIndex());
                    if (copyObject instanceof ImageItemFactory.getClass()) {
                      selectedDesignArea.addImageItem(copyObject);
                      var fileHandle = FileHandleService.getFileHandleById(copyObject.getFileHandleId());
                      fileHandle.increaseUsageCount();
                    }
                    if (copyObject instanceof TextItemFactory.getClass()) {
                      selectedDesignArea.addTextItem(copyObject);
                    }
                    if (copyObject instanceof ClipartItemFactory.getClass()) {
                      selectedDesignArea.addClipartItem(copyObject);
                    }
                    copyObject = notChangedCopy ? notChangedCopy : angular.copy(copyObject);
                    notChangedCopy = null;
                    undoHandle.resolve();
                  }
                  else if (copyObject instanceof (DesignAreaFactory.getClass())) {
                    undoHandle = UndoRedoService.pushModelData(ProjectService.getProject());
                    var allImages = copyObject.getImageItems();
                    allImages.forEach(function (imageItem) {
                      var fileHandle = FileHandleService.getFileHandleById(imageItem.getFileHandleId());
                      fileHandle.increaseUsageCount();
                    });

                    selectedDesignArea.setImageItems(selectedDesignArea.getImageItems().concat(copyObject.getImageItems()));
                    selectedDesignArea.setTextItems(selectedDesignArea.getTextItems().concat(copyObject.getTextItems()));
                    selectedDesignArea.setTemplateBackgroundItemLeft(copyObject.getTemplateBackgroundItemLeft());
                    selectedDesignArea.setTemplateBackgroundItemRight(copyObject.getTemplateBackgroundItemRight());
                    selectedDesignArea.setClipartItems(copyObject.getClipartItems());
                    selectedDesignArea.setImageBackgroundItems(copyObject.getImageBackgroundItems());
                    copyObject = angular.copy(copyObject);
                    undoHandle.resolve();
                  }
                }
              }
            }
          });

          /**
           * Removes itemboxes on 'del'
           */
          hotkeys.add({
            combo: 'del',
            description: MessageService.getMessage('hotKey.description.delete'),
            callback: function () {
              var designArea = ProjectService.getSelectedDesignArea();
              if (designArea) {
                var undoHandle;
                var selectedItemBox = designArea.getSelectedItemBox();
                if (selectedItemBox) {
                  undoHandle = UndoRedoService.pushModelData(designArea);
                  designArea.removeItemBox(selectedItemBox);
                  undoHandle.resolve();
                }
                else if (ProjectService.getProject().isStoryBoardView()) {
                  undoHandle = UndoRedoService.pushModelData(designArea);
                  designArea.clearContent();
                  designArea.getTemplateBackgroundItemLeft().setDesignElementId(AppConstants.BACKGROUND_DEFAULT_ID);
                  designArea.getTemplateBackgroundItemRight().setDesignElementId(AppConstants.BACKGROUND_DEFAULT_ID);
                  undoHandle.resolve();
                }
              }
            }
          });


          /**
           *
           * Add Page Package on '+'
           */
          hotkeys.add({
            combo: '+',
            description: MessageService.getMessage('hotKey.description.addAdditionalPages',[AppValues.doublePagePackageSize * 2]),
            callback: function () {
              var project = ProjectService.getProject();
              var product = ProductService.getProductById(project.getProductId());
              if (project.getPagesCount() < product.getMaxNumberOfPages()) {
                var undoHandle = UndoRedoService.pushProject();
                ProjectService.addPagePackage();
                undoHandle.resolve();
              }
            }
          });


          /**
           *
           * Remove Page Package on '-'
           */
          hotkeys.add({
            combo: '-',
            description: MessageService.getMessage('hotKey.description.removeAdditionalPages',[AppValues.doublePagePackageSize * 2]),
            callback: function () {
              var project = ProjectService.getProject();
              var product = ProductService.getProductById(project.getProductId());
              if (project.getPagesCount() > product.getMinNumberOfPages()) {
                var undoHandle = UndoRedoService.pushProject();
                ProjectService.removePagePackage();
                undoHandle.resolve();
              }
            }
          });


          /**
           *
           * Enters detailView on 'enter'
           */
          hotkeys.add({
            combo: 'enter',
            callback: function (event) {
              event.preventDefault();
              if (ProjectService.getProject()) {
                var selectedDesignArea = ProjectService.getSelectedDesignArea();
                if (selectedDesignArea && ProjectService.getProject().isStoryBoardView()) {
                  ProjectService.toggleCanvasStoryBoardDetailView(AppValues.headAreaHeight + AppConstants.TOGGLE_HEAD_AREA_HEIGHT, selectedDesignArea);
                }
              } else {
                var startButton = angular.element('#startDesignButton');
                if (startButton) {
                  $timeout(function () {
                    angular.element('#startDesignButton').trigger('click');
                  }, 100);
                }
              }
            }
          });


          /**
           *
           * Leaves preview or detailview on 'esc'
           */
          hotkeys.add({
            combo: 'esc',
            callback: function (event) {
              event.preventDefault();
              if (ProjectService.getProject()) {
                if (ProjectService.getProject().isDetailView() && !BookPreviewService.isPreviewActive()) {
                  ProjectService.toggleCanvasStoryBoardDetailView(AppValues.headAreaHeight + AppConstants.TOGGLE_HEAD_AREA_HEIGHT);
                }
                else if (BookPreviewService.isPreviewActive()) {
                  BookPreviewService.setPreviewActive(false);
                }
              }
            }
          });

          /**
           * Shuffles selected designArea on 'space'
           */
          hotkeys.add({
            combo: 'space',
            description: MessageService.getMessage('hotKey.description.shuffle'),
            callback: function (event) {
              event.preventDefault();
              var designArea = ProjectService.getSelectedDesignArea();
              if (designArea) {
                var undoHandle = UndoRedoService.pushModelData(designArea);
                var designAreaOrientation = designArea.getPageHalfOrientation();
                var designAreaType = designArea.getType();

                var portraitImagesCountLeft = designArea.getPortraitImageItemsForHalfPage('left').length;
                var landscapeImagesCountLeft = designArea.getLandscapeImageItemsForHalfPage('left').length;
                var textsCountLeft = designArea.getTextItems('left', true).length;

                var portraitImagesCountRight = designArea.getPortraitImageItemsForHalfPage('right').length;
                var landscapeImagesCountRight = designArea.getLandscapeImageItemsForHalfPage('right').length;
                var textsCountRight = designArea.getTextItems('right', true).length;


                LayoutService.getRandomLayout(portraitImagesCountLeft, landscapeImagesCountLeft, textsCountLeft, designAreaOrientation, designAreaType, true, false).then(function (layout) {
                  if (layout) {
                    DesignAreaService.applyLayout(designArea, layout, 'left', false);
                  }
                });

                LayoutService.getRandomLayout(portraitImagesCountRight, landscapeImagesCountRight, textsCountRight, designAreaOrientation, designAreaType, true, false).then(function (layout) {
                  if (layout) {
                    DesignAreaService.applyLayout(designArea, layout, 'right', false);
                  }
                });
                undoHandle.resolve();
              }
            }
          });

          /**
           * Opens super secret information window
           *
           */
          hotkeys.add({
            combo: 'ctrl+shift+i',
            callback: function (event) {
              event.preventDefault();
              var designArea = ProjectService.getSelectedDesignArea();
              if (designArea.getId() === 'area_2') {
                var imagesCountRight = designArea.getImageItems('right').length;
                var imagesCountLeft = designArea.getImageItems('left').length;
                if (imagesCountLeft === 1 && imagesCountRight === 2) {
                  var modalInitialChoiceLightbox = $modal.open({
                    scope: $rootScope,
                    size: 'lg',
                    templateUrl: 'credits.html',
                    controller: 'CreditsLightboxController'
                  });
                }
              }
            }
          });

        }

      };

      return hotKeyService;
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 *
 * @since 12.09.2014
 * @author Frank Bruns (frank.bruns@cewe.de)
 * @author Christoph Suhren
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwMyProjects', [
    '$log', 'Utils', 'ProjectService', 'LeaveEditorService', 'AuthenticationService', 'ProductService',
    function ($log, Utils, ProjectService, LeaveEditorService, AuthenticationService, ProductService) {

      return {
        restrict: 'A',
        scope: {},
        transclude: false,
        replace: false,
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/project/cwMyProjects.html.jsf',
        link: function (scope, element, attrs) {

          scope.loadingProjects = AuthenticationService.isLoggedIn();
          scope.projects = [];

          var removeWatchLoginState = scope.$watch(function watchLoginState() {
            return AuthenticationService.isLoggedIn();
          }, function onLoginStateChanged(newValue) {
            if (newValue) {
              scope.loadingProjects = true;
              ProjectService.loadExternalProjects().then(function success(projects) {
                for (var i = 0; i < projects.length; i++) {

                  var date = new Date(projects[i].tsChanged);
                  projects[i].tsChangedTime = date.toLocaleTimeString();
                  projects[i].tsChangedDate = date.toLocaleDateString();

                  projects[i].previewUrl = 'photoBookRequest.do?operation=retrieveDoublePagePreview&photoBookId=' + projects[i].id + '&doublePageIndex=0&previewWidth=250&previewPageHalf=both';
                  if (ProjectService.getProject() && projects[i].id === ProjectService.getProject().getId()) {
                    projects[i].previewUrl += '&rnd=' + Utils.getRandomInt(0, 9999);
                  }
                }
                scope.projects = projects;
                scope.loadingProjects = false;
              });
            } else {
              scope.projects = [];
              scope.loadingProjects = false;
            }
          });

          scope.projectClicked = function (data) {
            if (data.id) {
              LeaveEditorService.reloadEditorWithProject(data.id);
            }
          };

          scope.isUserLoggedIn = function () {
            return AuthenticationService.isLoggedIn();
          };


          scope.getProductNameById = function (productId) {
            var product = ProductService.getProductById(productId);
            if (product) {
              return product.textResource || product.getName();
            } else {
              return  '';
            }
          };

        }
      };
    }
  ])
  ;
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Service for operatorProperties
 * @author Sascha Friedrich
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('OperatorService', [
    '$log', '$resource', 'OperatorRepository', 'BaseConfigService',
    function ($log, $resource, OperatorRepository, BaseConfigService) {

      // definition of the public service functions
      return {

        initOperator: function () {
          var photobookConfigUrl = 'config/photobook.rest';
          var PhotobookConfig = $resource(photobookConfigUrl);

          var operatorPhotobookConfig = PhotobookConfig.get(function () {
            $log.debug('photobook Configuration for operator: ', operatorPhotobookConfig);
            OperatorRepository.setOperatorConfig(operatorPhotobookConfig);
          });
          return operatorPhotobookConfig.$promise;
        },

        getSpineContentRotation: function () {
          var spineContentRotation = OperatorRepository.getConfigByKey('spineContentRotation');
          if (spineContentRotation === 'ccw') {
            return 270;
          } else {
            return 90;
          }
        },

        getLogoElementId: function () {
          return OperatorRepository.getConfigByKey('spineLogoElementId');
        },

        isSpineLogoEnabled: function () {
          return OperatorRepository.getConfigByKey('spineLogoEnabled');
        },

        /**
         *
         * @return {Boolean} is (general) tracking enabled at all?
         */
        isTrackingEnabled: function () {
          return OperatorRepository.getConfigByKey('trackingEnabled');
        },

        isUpsellingEnabled: function () {
          return OperatorRepository.getConfigByKey('upsellingEnabled');
        },

        isMyPhotosEnabled: function () {
          return OperatorRepository.getConfigByKey('myPhotosEnabled');
        },

        /**
         *
         * @returns the time delay (in seconds) until the save reminder should be shown.
         * A value <= 0 deactivates the save reminder.
         */
        getSaveReminderDelay: function () {
          return OperatorRepository.getConfigByKey('saveReminderDelay');
        },
        /**
         *
         * @return {Boolean} is detailed tracking enabled?
         */
        isDetailedTrackingEnabled: function () {
          return OperatorRepository.getConfigByKey('detailedTrackingEnabled');
        },

        getEditorCloseUrl: function () {
          return '/web/' + BaseConfigService.getOpId() + '/startup.do';
        },

        getOpenProjectUrl: function () {
          return '/web/' + BaseConfigService.getOpId() + '/showGalleryPhotobooks.do';
        },

        getDefaultDesignElementCategory: function (elementType) {
          var defaultCategories = OperatorRepository.getConfigByKey('defaultDesignElementCategories');
          return defaultCategories[elementType];
        },

        getPagePackageSize: function () {
          return OperatorRepository.getConfigByKey('photobookPageStep');
        },

        /**
         * @returns {Boolean} is upload of unused images enabled (if indexedDB is not available)?
         */
        isUploadUnusedImagesEnabled: function () {
          return OperatorRepository.getConfigByKey('uploadUnusedImagesEnabled');
        },

        getDesktopRecommendationLimit: function () {
          return OperatorRepository.getConfigByKey('desktopRecommendationLimit');
        },

        getDesktopRecommendationTargetUrl: function () {
          return OperatorRepository.getConfigByKey('desktopRecommendationTargetUrl');
        },

        getMinAgeForRegistration: function () {
          return OperatorRepository.getConfigByKey('minAgeForRegistration');
        },

        getPrivacyPageUrl: function () {
          return OperatorRepository.getConfigByKey('privacyPageUrl');
        },

        getSbcPageUrl: function() {
          return OperatorRepository.getConfigByKey('sbcPageUrl');
        }
      };

    }

  ]);
})();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * @author Christoph Suhren
 * @author Sascha Friedrich
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('OperatorRepository', [
    '$log',
    function ($log) {

      var repo = {
        // needs to be set.
        operatorConfig: undefined

      };
      // definition of the public repository functions
      return {

        getOperatorConfig: function () {
          return repo.operatorConfig;
        },

        setOperatorConfig: function (operatorConfig) {
          repo.operatorConfig = operatorConfig;
        },

        getConfigByKey: function (key) {
          return repo.operatorConfig[key];
        }

      };

    }
  ])
  ;

})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * Contains all text resources. Gets the text resources from 'window.tatooine.messageBundle'.
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('MessageRepository', [
    '$log', '$window',
    function ($log, $window) {

      // the code before the return block will be executed only once (as soon as angularJS tries to initially resolve the
      // service instance) and is not part of the created service instance itself.

      var repo = {
        messages: {}
      };

      if (!$window.tatooine || !$window.tatooine.messageBundle) {
        $log.error('No text resources found! Ensure that the `tatooine.messageBundle` exists as global (in window) variable.');
        return;
      }

      repo.messages = $window.tatooine.messageBundle;


      // definition of the public repository functions
      return {

        /**
         * Returns the text message with the given id, if found
         * @param key the key of the message to retrieve
         * @returns the found message
         */
        getMessage: function (key) {
          if(key === '') {
            $log.debug('Returning empty message for empty key');
            return '';
          }
          var message = repo.messages[key];

          if (message === undefined) {
            $log.debug('MessageRepository.getMessage(): No message found for text key: ' + key);
            message = '???' + key + '???';
          }

          return message;
        }
      };

    }
  ]);

})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A service to handle text resource messages based on the message repository.
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('MessageService', [
    '$log', 'MessageRepository',
    function ($log, MessageRepository) {

      var alertMessages = {};

      var replaceMsgArgs = function (message, replaceArgs) {

        // replaces possible markers of the form {i} in text resources with the corresponding arguments
        for (var i = 0; i < replaceArgs.length; i++) {
          message = message.replace('{' + i + '}', replaceArgs[i]);
        }

        // removes leftover markers; matches in case not enough arguments were given
        return message.replace(/\{\d+\}/g, '');
      };

      // definition of the public service functions
      return {

        /**
         *
         * @param key key of the text message to retrieve
         * @param {Array} replaceArgs optional array of arguments that will be inserted at defined places, e.g. "A text with arguments {0} and {1}."
         * @returns {String} the text message with inserted optional arguments
         */
        getMessage: function (key, replaceArgs) {
          var message = MessageRepository.getMessage(key);

          // replace arguments if necessary
          if (replaceArgs && replaceArgs.length > 0) {
            message = replaceMsgArgs(message, replaceArgs);
          }

          return message;
        }
      };

    }

  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 *
 * User: Silvia
 * Date: 29.07.13
 * Time: 18:34
 */

(function () {
  'use strict';

  angular.module('tatooine').filter('m', [
    '$log', 'MessageRepository',
    function ($log, MessageRepository) {
      return function (text) {

        if (text === undefined) {
          $log.error('Message filter (m): text key is undefined!');
          return '';
        }

        var m = MessageRepository.getMessage(text);

        // replaces possible markers of the form {i} in text resources with the corresponding arguments that were
        // given to the filter at parameter index i+1
        for (var i = 1; i < arguments.length; i++) {
          m = m.replace('{' + (i - 1) + '}', arguments[i]);
        }

        // removes leftover markers; matches in case not enough arguments were given
        m = m.replace(/\{\d+\}/g, '');

        return m;
      };
    }
  ]);
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A directive that is meant for tracking a button click and report it to a tracking service, such as Adobe Analytics.
 *
 * @since 30.03.2015
 * @author Frank Bruns (frank.bruns@cewe.de)
 * @author Sascha Friedrich (sascha.friedrich@cewe.de)
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwTrackButton', [
    '$log', 'TrackingService',
    function ($log, TrackingService) {

      return {
        restrict: 'A',
        scope: {
          trackingValue: '@trackingValue'
        },
        link: function(scope, element, attrs) {

          function onClick() {
            TrackingService.trackByContextData(TrackingService.TRACKING_KEY_BUTTONS, scope.trackingValue, scope.trackingValue);
          }


          element.bind('click', onClick);

          scope.$on('$destroy', function destroy() {
            element.unbind('click', onClick);
          });

        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 * A service to handle data tracking functionality, such as Omniture tracking.
 * (This file is called dontBlockTrackingService.js, because AdBlock blocked the name trackingService.js)
 *
 * @since 30.03.2015
 * @author Frank Bruns (frank.bruns@cewe.de)
 * @author Sascha Friedrich (sascha.friedrich@cewe.de)
 */

(function () {
  'use strict';

  angular.module('tatooine').factory('TrackingService', [
    '$log', '$window', 'OperatorService', 'BaseConfigService',
    function ($log, $window, OperatorService, BaseConfigService) {

      // definition of the public service functions
      var trackingService = {

        /**
         * Track data by the means of events
         * @param {String} eventId the event id (as defined in Adobe Analytics) to track
         * @param {String} trackingName the human readable tracking name to sent along with the tracking data
         */
        trackByEvent: function (eventId, trackingName) {
          // detailed tracking is done with contextData or events in Tatooine editor
          if (!$window.s || !OperatorService.isDetailedTrackingEnabled()) {
            return;
          }
          $window.s.events = eventId;
          $window.s.linkTrackVars = 'events';
          $window.s.linkTrackEvents = eventId;
          $window.s.events = eventId;
          $window.s.tl(true, 'o', trackingName);
          $log.debug('Tracking event data:', eventId, trackingName);
        },

        /**
         * Track data by the means of contextData.
         * @param {String} trackingKey use a value from this service's predefined constants
         * @param {String} trackingValue the value to track, a button click event name like 'buttonSaveClicked', for example. Will be prefixed automatically with 'tatooine.'.
         * @param {String} trackingName the human readable tracking name to sent along with the tracking data
         * @see https://marketing.adobe.com/resources/help/en_US/sc/implement/context_data_variables.html
         */
        trackByContextData: function (trackingKey, trackingValue, trackingName) {
          // detailed tracking is done with contextData or events in Tatooine editor
          if (!$window.s || !OperatorService.isDetailedTrackingEnabled()) {
            return;
          }

          if (BaseConfigService.isDevelopStatusActive()) {
            $log.debug('Skip contextData tracking:', trackingValue, '. Dev-status: ', BaseConfigService.isDevelopStatusActive());
            return;
          }

          $window.s.contextData[trackingKey] = 'tatooine.' + trackingValue;
          $window.s.linkTrackVars = 'contextData.' + trackingKey;
          $window.s.tl(true, 'o', trackingName);
          $log.debug('Tracking context data:', trackingKey, trackingValue, trackingName);
        },

        /**
         * Track data by the means of eVars.
         * @param {String} eVarKey
         * @param {String} eVarValue
         * @param {String} trackingName the human readable tracking name to sent along with the tracking data
         * @see https://marketing.adobe.com/resources/help/en_US/reference/insight_var.html
         */
        trackByEVar: function (eVarKey, eVarValue, trackingName) {
          // general tracking is done with eVars
          if (!$window.s || !OperatorService.isTrackingEnabled()) {
            return;
          }

          if (BaseConfigService.isDevelopStatusActive()) {
            $log.debug('Skip eVar tracking. Dev-status: ', BaseConfigService.isDevelopStatusActive());
            return;
          }
          $window.s[eVarKey] = eVarValue;
          $window.s.linkTrackVars = eVarKey;
          $window.s.tl(true, 'o', trackingName);
          $log.debug('Tracking eVar:', eVarKey, eVarValue, trackingName);
        }



      };

      /**
       * @type {string}
       */
      trackingService.TRACKING_KEY_BUTTONS = 'tatooineButtons';

      return trackingService;

    }

  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

(function () {
  'use strict';
  angular.module('tatooine').factory('AuthenticationService', [
    '$rootScope', '$log', '$http', '$window', '$timeout', '$location', '$q', 'AppConstants', 'EventConstants', '$modal', 'BaseConfigService', 'MessageService', 'NotificationService', 'LeaveEditorService', 'OperatorService',
    function ($rootScope, $log, $http, $window, $timeout, $location, $q, AppConstants, EventConstants, $modal, BaseConfigService, MessageService, NotificationService, LeaveEditorService, OperatorService) {

      var SERVICE_URL = 'cos/login.do';

      var userData = {
        isLoggedIn: false,
        firstName: null,
        middleName: null,
        lastName: null
      };

      if ($window.IPS) {
        userData.isLoggedIn = $window.IPS.isUserLoggedIn();
        var userName = $window.IPS.getUserName();
        userData.firstName = userName.firstName;
        userData.middleName = userName.middleName;
        userData.lastName = userName.lastName;
      } else {
        $log.error('Object IPS missing');
      }

      /* util functions */
      function empty(obj) {
        return obj === undefined || obj === '';
      }

      function loadUserInfoFromServer() {
        var deferred = $q.defer();
        var url = 'user/information.rest';
        $log.debug('Load user information from server:' + url);
        $http.get(url).success(function (userInfo) {
          $log.debug('User information loaded from server', userInfo);
          userData.isLoggedIn = userInfo.loggedIn;
          userData.firstName = userInfo.firstName;
          userData.middleName = userInfo.middleName;
          userData.lastName = userInfo.lastName;

          deferred.resolve();
        }).error(function () {
          $log.error('Loading user information from server failed.');
          NotificationService.addNotification('', MessageService.getMessage('notification.serverConnectionError'), 'warning', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
          deferred.reject();
        });
        return deferred.promise;
      }

      // definition of the public service functions
      var authenticationService = {

        /**
         *
         * @param additionalMessageKey messageKey that is used to show an additional message in the login/register dialog.
         *  If this is an SSO session, the login/register dialog is not used and therefore no additional message is shown.
         *  If the user is 'logged in on client side', a 'session timed out' message will be shown instead of the one defined by this key.
         * @param ssoAdditionalTargetPageParameters these parameters will be added to the targetPage used after (potential) SSO login
         * @param ssoAlternativeTargetPage allows to define an alternative targetPage that is used after (potential) SSO login,
         *  the default targetPage is the current (editor) page
         * @param ssoNoRedirect if set to true, the user will definitely not be redirected to the sso login page.
         * @returns {promise}
         */
        ensureUserLoggedIn: function (additionalMessageKey, ssoAdditionalTargetPageParameters, ssoAlternativeTargetPage, ssoNoRedirect) {
          if (authenticationService.isLoggedIn()) {
            additionalMessageKey = 'loginRegister.session.timeout';
          }
          var deferred = $q.defer();

          loadUserInfoFromServer().then(function userInfoLoaded() {
            if (authenticationService.isLoggedIn()) {
              deferred.resolve();
            } else {
              if (BaseConfigService.isSSOSession()) {
                // SSO
                $log.debug('The user is not logged in and this is an SSO session.');
                if (!ssoNoRedirect) {
                  LeaveEditorService.handleSsoLogin(ssoAdditionalTargetPageParameters, ssoAlternativeTargetPage);
                }
                deferred.reject('sso');
              } else {
                // *NO* SSO
                var additionalMessage = (additionalMessageKey ? MessageService.getMessage(additionalMessageKey) : '');

                var loginRegisterDialog = $modal.open({
                  templateUrl: 'loginRegisterDialog.html',
                  controller: 'LoginRegisterDialogController',
                  resolve: {
                    passThrough: function () {
                      return {additionalMessage: additionalMessage};
                    }
                  }
                });

                // Handle the result of the modal login/register dialog
                loginRegisterDialog.result.then(function ok(dialogData) {
                  if (authenticationService.isLoggedIn()) {
                    deferred.resolve();
                  }
                }, function dismissed() {
                  $log.debug('User dismissed login/register dialog.');
                  deferred.reject();
                });
              }
            }
          }, function loadUserInfoFailed() {
            deferred.reject();
          });
          return deferred.promise;
        },

        login: function (email, password) {
          if (empty(email)) {
            return $q.reject(MessageService.getMessage('loginRegister.invalidEmail'));
          }

          if (empty(password)) {
            return $q.reject(MessageService.getMessage('loginRegister.emptyPassword'));
          }

          return $http.get(SERVICE_URL, {
            params: {
              'ssl-login': email,
              'ssl-password': password,
              'skipSessionTimeout': true,
              'rnd': new Date().getTime()
            }

          }).then(
            function (response) {
              $log.debug(response);
              if (!response.data.loggedIn || response.data.status === 'failed') {
                return $q.reject(MessageService.getMessage('loginRegister.failedLogin'));
              }
              delete response.config.params;
              userData.isLoggedIn = true;
              userData.firstName = response.data.firstname;
              userData.middleName = response.data.middlename;
              userData.lastName = response.data.lastname;
              BaseConfigService.removeAccessCodeFromUrl();
              NotificationService.addNotification('', MessageService.getMessage('loginRegister.loginSuccessful'), 'info', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
            }, function (response) {
              // a failed login returns a normal http status, so this can only be an API/sever error
              NotificationService.addNotification('', MessageService.getMessage('notification.serverConnectionError'), 'danger', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
              $log.error('API error!', response);
              return $q.reject();
            });
        },

        register: function (email, password, passwordRepeat, privacyConditionsConfirmed, minAgeForRegistrationConfirmed) {
          if (empty(email)) {
            return $q.reject(MessageService.getMessage('loginRegister.invalidEmail'));
          }

          if (empty(password) || empty(passwordRepeat)) {
            return $q.reject(MessageService.getMessage('loginRegister.emptyPassword'));
          }

          if (password !== passwordRepeat) {
            return $q.reject(MessageService.getMessage('loginRegister.noPasswordMatch'));
          }

          if (!privacyConditionsConfirmed) {
            return $q.reject(MessageService.getMessage('loginRegister.privacy.error'));
          }

          if (!minAgeForRegistrationConfirmed && OperatorService.getMinAgeForRegistration()) {
            return $q.reject(MessageService.getMessage('loginRegister.minAgeForRegistration.error', [OperatorService.getMinAgeForRegistration()]));
          }

          return $http.get(SERVICE_URL, {
            params: {
              'ssl-login': email,
              'ssl-password': password,
              'register': true,
              'appId': 'tatooine',
              'skipSessionTimeout': true,
              'rnd': new Date().getTime()
            }
          }).then(function ok(response) {
            $log.debug(response.data);
            if (!response.data.loggedIn) {
              return $q.reject(MessageService.getMessage('loginRegister.failedRegister'));
            }
            userData.isLoggedIn = true;
            BaseConfigService.removeAccessCodeFromUrl();
            NotificationService.addNotification('', MessageService.getMessage('loginRegister.registerSuccessful'), 'info', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
          }, function failed(response) {
            // a failed register returns NOT a normal http status!
            if (response.data &&
              typeof response.data.loggedIn !== undefined &&
              response.data.status === 'failed') {
              return $q.reject(MessageService.getMessage('loginRegister.failedRegister'));
            }

            NotificationService.addNotification('', MessageService.getMessage('notification.serverConnectionError'), 'danger', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
            $log.error('API error!', response);
            return $q.reject();
          });
        },

        getUserName: function () {
          if (userData.firstName && userData.lastName) {
            return userData.firstName + ' ' + (userData.middleName ? userData.middleName + ' ' : '') + userData.lastName;
          }

          return '';
        },

        isLoggedIn: function () {
          return userData.isLoggedIn;
        }
      };

      return authenticationService;

    }

  ]);
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 *
 * @since 28.07.2015
 * @author Frank Bruns (frank.bruns@cewe.de)
 * @author Christoph Suhren
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwLoginRegisterForm', [
    '$log', 'ProjectService', 'AuthenticationService', 'IndexedDBService', 'OperatorService', 'MessageService',
    function ($log, ProjectService, AuthenticationService, IndexedDBService, OperatorService, MessageService) {

      return {
        restrict: 'A',
        scope: {
          onSuccess: '&onSuccess',
          onCancel: '&onCancel',
          additionalMessage: '@additionalMessage',
          showCancelButton: '=showCancelButton'
        },
        transclude: false,
        replace: false,
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/user/cwLoginRegisterForm.html.jsf',
        link: function (scope, element, attrs) {

          var updateIndexedDB = function () {
            if (IndexedDBService.isActive() && ProjectService.getProject() && ProjectService.getProject().getId() > 0) {
              IndexedDBService.makeImagesFilesUserRelated(ProjectService.getProject().getId());
            }
          };

          scope.data = {
            invalid: false,
            invalidMsg: '',
            loginMode: true,
            loginButtonDisabled: false,
            email: '',
            password: '',
            passwordRepeat: '',
            privacyConditionsUrl: OperatorService.getPrivacyPageUrl(),
            privacyConditionsConfirmed: false,
            minAgeForRegistration: OperatorService.getMinAgeForRegistration(),
            minAgeForRegistrationConfirmed: OperatorService.getMinAgeForRegistration() === null
          };

          scope.getPrivacyConditionsTextLine = function () {
            var anchorTagWithLink = '<a href="' + scope.data.privacyConditionsUrl + '" target="_blank">' + MessageService.getMessage('loginRegister.privacy') + '</a>';
            return MessageService.getMessage('loginRegister.privacy.label', [anchorTagWithLink]);
          };

          scope.submitClick = function () {
            scope.data.invalid = false;
            scope.data.invalidMsg = '';
            scope.data.loginButtonDisabled = true;
            var promise;
            if (scope.data.loginMode) {
              promise = AuthenticationService.login(scope.data.email, scope.data.password);
            } else {
              promise = AuthenticationService.register(scope.data.email, scope.data.password, scope.data.passwordRepeat, scope.data.privacyConditionsConfirmed, scope.data.minAgeForRegistrationConfirmed);
            }

            promise.then(function loggedIn() {
              updateIndexedDB();
              scope.onSuccess();
            }, function loginFailed(message) {
              scope.data.invalid = true;
              scope.data.invalidMsg = message;
            }).finally(function doFinally() {
              scope.data.loginButtonDisabled = false;
            });
          };

          scope.cancel = function () {
            scope.onCancel();
          };
        }
      };
    }
  ])
  ;
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 *
 * @since 29.07.2015
 * @author Christoph Suhren
 * @author Frank Bruns (frank.bruns@cewe.de)
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwLoginRegisterButton', [
    '$log', '$q', '$location', '$modal', 'ProjectService', 'LeaveEditorService', 'AuthenticationService', 'BaseConfigService',
    function ($log, $q, $location, $modal, ProjectService, LeaveEditorService, AuthenticationService, BaseConfigService) {

      return {
        restrict: 'A',
        scope: {
          showInputInplace: '=showInputInplace',
          onSuccess: '&onSuccess',
          onCancel: '&onCancel',
          additionalMessage: '@additionalMessage'
        },
        transclude: false,
        replace: false,
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/user/cwLoginRegisterButton.html.jsf',
        link: function (scope, element, attrs) {

          scope.loginRegisterFormVisible = !BaseConfigService.isSSOSession() && scope.showInputInplace;

          scope.isLoggedIn = function () {
            return AuthenticationService.isLoggedIn();
          };

          scope.getUserName = function () {
            return AuthenticationService.getUserName();
          };

          scope.loginClicked = function () {
            if (BaseConfigService.isSSOSession()) {
              if (ProjectService.getProject()) {
                ProjectService.saveCurrentProjectModal('saveStatus.finished.sso.redirectToLogin').then(function () {
                  LeaveEditorService.changeLocationTo(BaseConfigService.getLoginRegisterUrl() + '?targetpage=' + encodeURIComponent($location.absUrl()));
                });
              } else {
                LeaveEditorService.changeLocationTo(BaseConfigService.getLoginRegisterUrl() + '?targetpage=' + encodeURIComponent($location.absUrl()));
              }
            } else {
              var dialog = $modal.open({
                templateUrl: 'loginRegisterDialog.html',
                controller: 'LoginRegisterDialogController',
                resolve: {
                  passThrough: function () {
                    return {additionalMessage: ''};
                  }
                }
              });

            }
          };

          scope.logoutClicked = function () {
            var deferred = $q.defer();
            ProjectService.isSaveProjectNeeded().then(function ok(saveProjectNeeded) {
              if (saveProjectNeeded) {
                ProjectService.saveCurrentProjectModal('saveStatus.finished.logout').then(function ok() {
                  deferred.resolve();
                }, function dismissed() {
                  deferred.reject();
                });
              } else {
                deferred.resolve();
              }
            });
            deferred.promise.then(function ok() {
              LeaveEditorService.changeLocationTo(BaseConfigService.getLogoutUrl());
            });
          };

        }
      };
    }
  ])
  ;
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

(function () {
  'use strict';
  angular.module('tatooine').factory('AutoFillService', [
    '$rootScope', '$log', '$http', '$q', '$window', '$timeout', 'AppConstants', 'AppValues', 'EventConstants', '$modal', 'MessageService', 'NotificationService', 'FileHandleService',
    'ProjectService', 'LayoutService', 'ProductService', 'DesignAreaService', 'PhotoSourcesService', 'IpsAlbumService',
    function ($rootScope, $log, $http, $q, $window, $timeout, AppConstants, AppValues, EventConstants, $modal, MessageService, NotificationService, FileHandleService, ProjectService, LayoutService, ProductService, DesignAreaService, PhotoSourcesService, IpsAlbumService) {
      var itemBoxesReadyForLayout = false;
      var modalAutoFillProgress;

      function layoutToDesignAreas(designAreasLeft, designAreasRight) {

        var layoutPromises = [];

        designAreasLeft.forEach(function iterateDesignAreas(designArea) {
          var countLeftPortraits, countLeftLandscape;
          var designAreaOrientation = designArea.getPageHalfOrientation();
          var designAreaType = designArea.getType();
          countLeftPortraits = designArea.getPortraitImageItemsForHalfPage('left').length;
          countLeftLandscape = designArea.getLandscapeImageItemsForHalfPage('left').length;
          if ((countLeftLandscape + countLeftPortraits) > 0) {
            var layoutPromise = LayoutService.getRandomLayout(countLeftPortraits, countLeftLandscape, 0, designAreaOrientation, designAreaType, false, true).then(function ok(leftLayout) {
              if (leftLayout) {
                DesignAreaService.applyLayout(designArea, leftLayout, 'left', false);
              } else {
                // no layout found here, try again with no restrictions
                LayoutService.getRandomLayout(countLeftPortraits, countLeftLandscape, 0, designAreaOrientation, designAreaType, false, false).then(function ok(leftLayoutNoRestrictions) {
                  if (leftLayoutNoRestrictions) {
                    DesignAreaService.applyLayout(designArea, leftLayoutNoRestrictions, 'left', false);
                  }
                });
              }
            });

            layoutPromises.push(layoutPromise);
          }
        });

        designAreasRight.forEach(function iterateDesignAreas(designArea) {
          var countRightPortraits, countRightLandscape;
          var designAreaOrientation = designArea.getPageHalfOrientation();
          var designAreaType = designArea.getType();
          countRightPortraits = designArea.getPortraitImageItemsForHalfPage('right').length;
          countRightLandscape = designArea.getLandscapeImageItemsForHalfPage('right').length;
          if ((countRightLandscape + countRightPortraits) > 0) {
            var layoutPromise = LayoutService.getRandomLayout(countRightPortraits, countRightLandscape, 0, designAreaOrientation, designAreaType, false, true).then(function ok(rightLayout) {
              if (rightLayout) {
                DesignAreaService.applyLayout(designArea, rightLayout, 'right', false);
              }
              else {
                // no layout found here, try again with no restrictions
                LayoutService.getRandomLayout(countRightPortraits, countRightLandscape, 0, designAreaOrientation, designAreaType, false, false).then(function ok(rightLayoutNoRestrictions) {
                  if (rightLayoutNoRestrictions) {
                    DesignAreaService.applyLayout(designArea, rightLayoutNoRestrictions, 'right', false);
                  }
                });
              }
            });
            layoutPromises.push(layoutPromise);
          }
        });

        return $q.all(layoutPromises);

      }

      function convertCloudToServerFileHandle(fileHandle) {
        var deferred = $q.defer();
        PhotoSourcesService.makeAlbumItemFromCloudPicture(fileHandle.getMyPhotosEventId(), fileHandle.getMyPhotosPictureId()).then(function (data) {
          if (data.refCountId) {
            var fileHandles = FileHandleService.getFileHandles();
            var serverFileHandle = FileHandleService.createServerFileHandle(data.refCountId, fileHandle.getFileName(), null, null, fileHandles.indexOf(fileHandle));
            IpsAlbumService.createExifDataForRefCountId(data.refCountId).then(function (data) {
              serverFileHandle.setMyPhotosPictureId(fileHandle.getMyPhotosPictureId());
              serverFileHandle.setExif(data.exif);
              serverFileHandle.setMyPhotosEventName(data.myPhotosEventName);
              serverFileHandle.setMyPhotosEventId(fileHandle.getMyPhotosEventId());
              deferred.resolve(serverFileHandle);
            });
          }
        });
        return deferred.promise;
      }

      function checkIfDesignAreasReadyForLayouts(allLeftEmptyDesignAreas, allRightEmptyDesignAreas) {

        function checkItemBoxesContainingThumbnail() {
          var designAreasToCheck = ProjectService.getProject().getDesignAreas();
          if (!designAreasToCheck) {
            return false;
          }

          for (var i = 0; i < designAreasToCheck.length; i++) {
            var itemBoxesToCheck = designAreasToCheck[i].getImageItems();
            for (var j = 0; j < itemBoxesToCheck.length; j++) {
              if (!itemBoxesToCheck[j].isThumbKeyLoaded()) {
                return false;
              }
            }
          }
          return true;
        }

        itemBoxesReadyForLayout = checkItemBoxesContainingThumbnail();
        if (itemBoxesReadyForLayout) {
          $log.debug('Seems all itemBoxes contains an thumbnail now, lets start layouting them');
          allLeftEmptyDesignAreas.concat(allRightEmptyDesignAreas).forEach(function iterateDesignAreas(designArea) {
            DesignAreaService.bringClipartAndTextItemsToFront(designArea);
          });
          layoutToDesignAreas(allLeftEmptyDesignAreas, allRightEmptyDesignAreas).then(function layoutingDone() {
            $log.debug('Layouting done --> close autoFill dialog');
            modalAutoFillProgress.close();
            FileHandleService.setActiveFilter(FileHandleService.getActiveFilter());
          });
        }
        else {
          $timeout(function () {
            $log.debug('not every itemBox got a thumbnail now, lets wait a few seconds');
            checkIfDesignAreasReadyForLayouts(allLeftEmptyDesignAreas, allRightEmptyDesignAreas);
          }, 3000);
        }
      }

      function handleAutoFill(allPotentialFileHandles, designAreas, intendedAverage, addPagesAllowed, alsoFillCover, projectPagesToFill) {
        var sortByDateAsc = function (leftFileHandle, rightFileHandle) {
          return leftFileHandle.getDateTimeOriginal() > rightFileHandle.getDateTimeOriginal() ? 1 : leftFileHandle.getDateTimeOriginal() < rightFileHandle.getDateTimeOriginal() ? -1 : 0;
        };
        allPotentialFileHandles.sort(sortByDateAsc);

        // photosPerSite was a userChoice from the modal dialog

        // var intendedAverage = allProjectImagesArray.length / allPagesCount;
        var imageOnPage;
        var designAreaCounter = 0;
        var imageCounter = 0;
        var pageCounter = 0;

        // addPagesAllowed was a userChoice from the modal dialog, designAreas will added until the average * pages to Fill are bigger than the fileHandles
        if (addPagesAllowed) {
          while (allPotentialFileHandles.length > intendedAverage * projectPagesToFill) {
            if (ProjectService.getProject().getPagesCount() === ProductService.getProductById(ProjectService.getProject().getProductId()).getMaxNumberOfPages()) {
              break;
            }
            else {
              ProjectService.addPagePackage();
              projectPagesToFill = projectPagesToFill + AppValues.doublePagePackageSize * AppConstants.DESIGN_AREAS_ON_PAGE; // we should rename the second Constant
            }
          }
          designAreas = ProjectService.getProject().getDesignAreas();
        }

        var allLeftEmptyDesignAreas = [];
        var allRightEmptyDesignAreas = [];

        // alsoFillCover was a userChoice from the modal dialog, it will keep or override the cover
        if (alsoFillCover) {
          designAreas.forEach(function iterateDesignAreas(designArea) {
            if (!designArea.isLeftPageBlocked() && designArea.getImageItems('left').length === 0) {
              allLeftEmptyDesignAreas.push(designArea);
            }
            if (!designArea.isRightPageBlocked() && designArea.getImageItems('right').length === 0) {
              allRightEmptyDesignAreas.push(designArea);
            }
          });
        } else {
          designAreas.forEach(function iterateDesignAreas(designArea) {
            if (!designArea.isLeftPageBlocked() && designArea.getImageItems('left').length === 0 && !designArea.isCover()) {
              allLeftEmptyDesignAreas.push(designArea);
            }
            if (!designArea.isRightPageBlocked() && designArea.getImageItems('right').length === 0 && !designArea.isCover()) {
              allRightEmptyDesignAreas.push(designArea);
            }
          });
        }


        // create thumbnails in the size that will be used on the double pages later on
        var thumbnailCreationPromises = [];

        var fileHandleIterationIndex = 0;
        allPotentialFileHandles.forEach(function iterateFileHandles(fileHandle) {

          fileHandleIterationIndex++;

          // Only prepare the amount of thumbnails that will be distributed in the book
          if (fileHandleIterationIndex > intendedAverage * projectPagesToFill) {
            return;
          }

          var thumbnailCreationPromise = FileHandleService.createFileHandleThumbKey(fileHandle.getId(), AppConstants.EDITOR_IMAGE_TARGET_SIZE_PX)
            .then(function (thumbKey) {
              var maxSize = thumbKey.width >= thumbKey.height ? thumbKey.width : thumbKey.height;
              var fitTo = thumbKey.width >= thumbKey.height ? 'width' : 'height';
              return FileHandleService.getThumbnail(fileHandle.getId(), maxSize, fitTo, thumbKey.multiStepDownScaling).finally(function thumbHandled() {
                var eventData = {
                  fileHandle: fileHandle,
                  maxSize: maxSize,
                  fitTo: fitTo,
                  multiStepDownScaling: thumbKey.multiStepDownScaling
                };
                $rootScope.$broadcast(EventConstants.PHOTO_PREPARED_FOR_AUTO_FILL, eventData);
              });
            });

          thumbnailCreationPromises.push(thumbnailCreationPromise);
        });


        $q.all(thumbnailCreationPromises).finally(function allThumbsHandled() {

          while (allPotentialFileHandles.length > 0 && pageCounter !== projectPagesToFill && designAreaCounter < designAreas.length) {

            imageOnPage = imageCounter / pageCounter >= intendedAverage ? Math.floor(intendedAverage) : Math.ceil(intendedAverage);

            if (imageOnPage > allPotentialFileHandles.length) {
              imageOnPage = allPotentialFileHandles.length;
            }

            if (allRightEmptyDesignAreas[designAreaCounter] && allRightEmptyDesignAreas[designAreaCounter].getImageItems('right').length === 0) {
              for (var h = imageOnPage; h > 0; h--) {
                DesignAreaService.addImageItem(allPotentialFileHandles[0], allRightEmptyDesignAreas[designAreaCounter], allRightEmptyDesignAreas[designAreaCounter].getWidth() / 2 + 10, allRightEmptyDesignAreas[designAreaCounter].getHeight() / 2);
                imageCounter++;
                if (allPotentialFileHandles[1] && allPotentialFileHandles[1].getDateTimeOriginal() && allPotentialFileHandles[0].getDateTimeOriginal()) {
                  if (allPotentialFileHandles[0].getDateTimeOriginal() && allPotentialFileHandles[1].getDateTimeOriginal() && ((allPotentialFileHandles[1].getDateTimeOriginal().getTime() - allPotentialFileHandles[0].getDateTimeOriginal().getTime()) > 1000 * 60 * 10)) {
                    h = 0;
                  }
                }
                allPotentialFileHandles.shift();
              }
              pageCounter++;
            }

            imageOnPage = imageCounter / pageCounter >= intendedAverage ? Math.floor(intendedAverage) : Math.ceil(intendedAverage);

            if (imageOnPage > allPotentialFileHandles.length) {
              imageOnPage = allPotentialFileHandles.length;
            }

            if (allLeftEmptyDesignAreas[designAreaCounter] && allLeftEmptyDesignAreas[designAreaCounter].getImageItems('left').length === 0) {

              for (var j = imageOnPage; j > 0; j--) {
                DesignAreaService.addImageItem(allPotentialFileHandles[0], allLeftEmptyDesignAreas[designAreaCounter], allLeftEmptyDesignAreas[designAreaCounter].getWidth() / 2 - 10, allLeftEmptyDesignAreas[designAreaCounter].getHeight() / 2);
                imageCounter++;
                if (allPotentialFileHandles[1] && allPotentialFileHandles[1].getDateTimeOriginal() && allPotentialFileHandles[0].getDateTimeOriginal()) {
                  if (allPotentialFileHandles[0].getDateTimeOriginal() && allPotentialFileHandles[1].getDateTimeOriginal() && ((allPotentialFileHandles[1].getDateTimeOriginal().getTime() - allPotentialFileHandles[0].getDateTimeOriginal().getTime()) > 1000 * 60 * 10)) {
                    j = 0;
                  }
                }
                allPotentialFileHandles.shift();
              }
              pageCounter++;
            }

            designAreaCounter++;
          }
          $timeout(function () {
            checkIfDesignAreasReadyForLayouts(allLeftEmptyDesignAreas, allRightEmptyDesignAreas);
          }, 2000);

        });

      }


      // definition of the public service functions
      var autoFillService = {

          fillBookAutomatically: function (photosPerSite, keepCustomDesign, addPagesAllowed, alsoFillCover) {

            /*
             open the "inProcess" modal dialog, the user has no option to close it manually!
             */
            modalAutoFillProgress = $modal.open({
              size: 'lg',
              keyboard: false,
              backdrop: 'static',
              templateUrl: 'autoFillProgressLightbox',
              controller: 'AutoFillProgressLightBoxController'
            });


            var designAreas = ProjectService.getProject().getDesignAreas();

            var projectPagesToFill;

            // keepCustomDesign was a userChoice from the modalDialog, the user selects if the already designed areas will be skipped
            if (keepCustomDesign) {

              projectPagesToFill = 0;
              for (var p = 0; p < designAreas.length; p++) {
                if (designAreas[p].getImageItems('left').length === 0 && !designAreas[p].isLeftPageBlocked()) {
                  projectPagesToFill++;
                }
                if (designAreas[p].getImageItems('right').length === 0 && !designAreas[p].isRightPageBlocked()) {
                  projectPagesToFill++;
                }
              }

            } else { // remove the existing content from the DesignAreas
              for (var y = 0; y < designAreas.length; y++) {
                designAreas[y].clearContent();
              }

              projectPagesToFill = ProjectService.getProject().getPagesCount() + 2; // +2 are the coversites

            }


            // Lets get all the potential fileHandles that could be used in the book and put them in an array
            var allPotentialFileHandles = [];

            FileHandleService.getFileHandles().forEach(function iterateFileHandles(fileHandle) {
              if (fileHandle.getUsageCount() === 0 && fileHandle.isValid() && !fileHandle.isCloudFileHandle()) {
                allPotentialFileHandles.push(fileHandle);
              }
            });

            var intendedAverage = photosPerSite;
            var promises = [];
            if (allPotentialFileHandles.length < (Math.round(intendedAverage) * projectPagesToFill)) {
              var difference = (Math.round(intendedAverage) * projectPagesToFill) - allPotentialFileHandles.length;
              var cloudFilehandles = FileHandleService.getCloudFileHandles();
              for (var i = 0; i < difference; i++) {
                if (cloudFilehandles[i]) {
                  var promise = convertCloudToServerFileHandle(cloudFilehandles[i]);
                  promises.push(promise);
                }
              }

              var all = $q.all(promises);
              all.then(function success(serverFileHandlesFromCloud) {
                allPotentialFileHandles = allPotentialFileHandles.concat(serverFileHandlesFromCloud);
                handleAutoFill(allPotentialFileHandles, designAreas, intendedAverage, addPagesAllowed, alsoFillCover, projectPagesToFill);
              });

            } else {
              handleAutoFill(allPotentialFileHandles, designAreas, intendedAverage, addPagesAllowed, alsoFillCover, projectPagesToFill);
            }


          }

        }
        ;

      return autoFillService;

    }

  ])
  ;
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

(function () {
  'use strict';
  angular.module('tatooine').factory('ShoppingCartService', [
    '$rootScope', '$log', '$http', '$window', '$timeout', '$resource', 'AppConstants', 'LeaveEditorService', 'BaseConfigService', 'NotificationService', 'MessageService',
    function ($rootScope, $log, $http, $window, $timeout, $resource, AppConstants, LeaveEditorService, BaseConfigService, NotificationService, MessageService) {

      // definition of the public service functions
      var shoppingCartService = {
        addToShoppingCart: function (project,callback) {
          var addToCartUrl = 'photobook/shoppingcart/project/' + project.getId() + '.rest';

          var params = {
            quantity: 1,
            accessCode: project.getAccessCode()
          };
          var AddToCartResource = $resource(addToCartUrl, params);


          var addToCartResult = AddToCartResource.save(function addedToCart() {

            if (callback) {
              callback();
            }
          }, function failed(err) {
            $log.error(err.data);
            NotificationService.addNotification('', MessageService.getMessage('notification.addToShoppingCart.error'), 'danger', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
          });
        },

        redirectToShoppingCart: function () {
          $timeout(function redirectToCart() {
            LeaveEditorService.changeLocationTo(BaseConfigService.getShoppingCartUrl());
          }, 500);
        },


        addAndRedirectToShoppingCart: function (project) {
          shoppingCartService.addToShoppingCart(project,shoppingCartService.redirectToShoppingCart);

        }
      };

      return shoppingCartService;

    }

  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
/**
 *
 *
 * @since 26.10.2015
 * @author Frank Bruns
 * @author Sascha Friedrich
 */
(function () {
  'use strict';

  angular.module('tatooine').directive('cwUpsellingOptions', [
    '$log', 'ProjectService', 'ProductService', 'PriceService', 'ShoppingCartService', 'TrackingService',
    function ($log, ProjectService, ProductService, PriceService, ShoppingCartService, TrackingService) {

      return {
        restrict: 'A',
        scope: {},
        transclude: false,
        templateUrl: '/web/javax.faces.resource/app/tatooine/modules/shoppingcart/cwUpsellingOptions.html.jsf',
        link: function (scope, element, attrs) {

          var project = ProjectService.getProject();
          var upsellingPhotobookOptions = ProductService.getUpsellingOptions(project);

          scope.paperSelectionModel = {
            glossy: false,
            photopaperGlossy: false
          };

          scope.data = {
            paperType: upsellingPhotobookOptions[0].getPaper(),
            currentProductPrice: undefined,
            upsellingProductPrice: undefined,
            currentProduct: ProductService.getProductById(project.getProductId()),
            upsellingProduct: ProductService.getProductById(upsellingPhotobookOptions[0].getId()),
            upsellingPriceDifference: undefined,
            currentPagesCount: project.getPagesCount()
          };

          PriceService.calculatePriceDifference(project.getProductId(), upsellingPhotobookOptions[0].getId(), project.getPagesCount()).then(function (priceData) {
            scope.data.currentProductPrice = priceData.formattedSumProductA;
            scope.data.upsellingProductPrice = priceData.formattedSumProductB;
            scope.data.upsellingPriceDifference = priceData.formattedPriceDifference;

          });

          scope.togglePaperGlossySelection = function () {
            scope.paperSelectionModel.glossy = !scope.paperSelectionModel.glossy;
          };

          scope.togglePhotoPaperGlossySelection = function () {
            scope.paperSelectionModel.photopaperGlossy = !scope.paperSelectionModel.photopaperGlossy;
          };

          scope.addToShoppingCartClicked = function () {
            if (scope.paperSelectionModel.glossy || scope.paperSelectionModel.photopaperGlossy) {
              ProjectService.changeProjectProduct(upsellingPhotobookOptions[0].getId()).then(function ok() {
                ProjectService.saveProject().then(function () {
                  ShoppingCartService.addAndRedirectToShoppingCart(project);
                });
              });
              if (scope.paperSelectionModel.glossy) {
                TrackingService.trackByContextData(TrackingService.TRACKING_KEY_BUTTONS, 'button.upsellingGlossyPaperAccepted', 'button.upsellingGlossyPaperAccepted');
              }
              if (scope.paperSelectionModel.photopaperGlossy) {
                TrackingService.trackByContextData(TrackingService.TRACKING_KEY_BUTTONS, 'button.upsellingGlossyPhotoPaperAccepted', 'button.upsellingGlossyPhotoPaperAccepted');
              }
            } else if (upsellingPhotobookOptions[0].getPaper() === 'glossy') {
              ShoppingCartService.addAndRedirectToShoppingCart(project);
              TrackingService.trackByContextData(TrackingService.TRACKING_KEY_BUTTONS, 'button.upsellingGlossyPaperRejected', 'button.upsellingGlossyPaperRejected');
            } else if (upsellingPhotobookOptions[0].getPaper() === 'fotopaper-glossy'){
              ShoppingCartService.addAndRedirectToShoppingCart(project);
              TrackingService.trackByContextData(TrackingService.TRACKING_KEY_BUTTONS, 'button.upsellingGlossyPhotoPaperRejected', 'button.upsellingGlossyPhotoPaperRejected');
            }

          };

          scope.getPriceSum = function () {
            if (scope.paperSelectionModel.glossy || scope.paperSelectionModel.photopaperGlossy) {
              return scope.data.upsellingProductPrice;
            }
            return scope.data.currentProductPrice;
          };

          scope.$on('$destroy', function destroy() {
          });
        }
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';

  angular.module('tatooine').controller('MainController', [
    '$scope', '$log', '$window', '$timeout', '$modal', 'AppConstants', 'AppValues', 'hotkeys', 'MessageService', 'EventConstants', 'BaseConfigService', 'TrackingService', 'ProjectService', 'ProductService',
    'IpsAlbumService', 'FileHandleService', 'AuthenticationService', 'HotKeyService', 'UndoRedoService', 'LeaveEditorService', 'OperatorService', 'IndexedDBService', 'ContextPanelAreaService', 'PriceService', 'ShoppingCartService', 'NotificationService', 'PhotoSourcesService',
    function ($scope, $log, $window, $timeout, $modal, AppConstants, AppValues, hotkeys, MessageService, EventConstants, BaseConfigService, TrackingService, ProjectService, ProductService, IpsAlbumService, FileHandleService, AuthenticationService, HotKeyService, UndoRedoService, LeaveEditorService, OperatorService, IndexedDBService, ContextPanelAreaService, PriceService, ShoppingCartService, NotificationService, PhotoSourcesService) {


      $scope.mainData = {
        initialized: undefined,
        showOpenProjectOption: undefined,
        showUpsellingOptions: undefined
      };

      var upsellingProductId;
      var saveReminderNotification;
      angular.element('body').addClass('cewe-pre-editor-stage'); //IPS-15989: add class for special styling during the pre editor stage (e.g. projects dialog or product choice dialog)

      function loadAlbumItems(ipsAlbumId) {
        IpsAlbumService.getAlbumItems(ipsAlbumId).then(function ok(albumItems) {
          if (albumItems) {
            albumItems.forEach(function iterItems(albumItem) {
              FileHandleService.createServerFileHandle(albumItem.refCountId, albumItem.title, null, null);
            });
          }
        }).then(function ok() {
          IpsAlbumService.createExifDataForAlbum(ipsAlbumId);

        });
      }

      function checkForceLoginStatusForAlbumItems(ipsAlbumId) {
        if (BaseConfigService.hasForceLoginInUrl()) {
          AuthenticationService.ensureUserLoggedIn('loginRegister.loginToLoad', null, null, false).then(function loggedIn() {
            loadAlbumItems(ipsAlbumId);
            BaseConfigService.removeForceLoginParamFromUrl();
          });
        } else {
          loadAlbumItems(ipsAlbumId);
        }


      }


      function loadProject(projectId, accessCode) {
        ProjectService.loadProject(projectId, accessCode).then(function ok() {
          HotKeyService.initHotKeys();
          if (IndexedDBService.isActive()) {
            var parsedProjectId = parseInt(projectId, 10);
            if (AuthenticationService.isLoggedIn()) {
              IndexedDBService.makeImagesFilesUserRelated(parsedProjectId);
            }
            IndexedDBService.addToFileUpload(parsedProjectId);
          }
        });
      }

      $scope.isUserLoggedIn = function () {
        return AuthenticationService.isLoggedIn();
      };

      $scope.isHeadAreaVisible = function () {
        return AppValues.headAreaTop === 0;
      };

      $scope.getHeadAreaTop = function () {
        var top = AppValues.headAreaTop;

        if ($scope.isContextPanelAreaVisible()) {
          if ($scope.isHeadAreaVisible()) {
            top = -$scope.getFullHeadAreaHeight();
          } else {
            top = -(AppConstants.HEAD_AREA_HEIGHT + AppConstants.TOGGLE_HEAD_AREA_HEIGHT);
          }
        }

        return top;
      };

      $scope.getShowMainContainer = function () {
        return !$scope.mainData.showOpenProjectOption && $scope.mainData.initialized;
      };

      $scope.getHeadAreaHeight = function () {
        return AppValues.headAreaHeight;
      };

      $scope.getFullHeadAreaHeight = function () {
        return AppValues.headAreaHeight + AppConstants.TOGGLE_HEAD_AREA_HEIGHT;
      };

      $scope.getToggleHeadAreaWidth = function () {
        return AppConstants.TOGGLE_HEAD_AREA_WIDTH;
      };

      $scope.getToggleHeadAreaHeight = function () {
        return AppConstants.TOGGLE_HEAD_AREA_HEIGHT;
      };

      $scope.getDesignAreasContainerTop = function () {
        return $scope.isContextPanelAreaVisible() ? 0 : $scope.getHeadAreaHeight();
      };

      $scope.getContextPanelAreaHeight = function () {
        return $scope.isContextPanelAreaVisible() ? AppConstants.HEAD_AREA_HEIGHT : 0;
      };

      $scope.getContextPanelAreaZIndex = function () {
        return ContextPanelAreaService.getCssZIndex();
      };

      $scope.startInitialDialog = function () {
        openInitialChoiceDialog();
      };

      $scope.startMyProjectsDialog = function () {
        ProjectService.handleOpenMyProjects(false).then(function ok(response) {
          if (response) {
            LeaveEditorService.reloadEditorWithProject(response.id);
          }
        });
      };

      $scope.isDetailView = function () {
        var project = ProjectService.getProject();
        if (!project) {
          return false;
        }
        return project.isDetailView();
      };

      $scope.isContextPanelAreaVisible = function () {
        return ContextPanelAreaService.isContextPanelAreaVisible();
      };

      $window.onbeforeunload = function () {
        return LeaveEditorService.getWindowUnloadMessage(ProjectService.getProject());
      };

      $scope.$on(EventConstants.PROJECT_LOADED, function projectLoaded() {
        $scope.setEditorInitialized();
      });

      $scope.setEditorInitialized = function () {
        if ($scope.mainData.initialized === true) {
          $log.debug('The editor is already initialized.');
          return;
        }
        $scope.mainData.initialized = true;
        var body = angular.element('body');
        body.removeClass('cewe-pre-editor-stage');
        body.addClass('cewe-editor-initialized');

        var saveReminderDelay = OperatorService.getSaveReminderDelay();
        if (saveReminderDelay >= 0) {
          $log.info('Started save reminder timeout with a delay of ' + saveReminderDelay + ' sec.');
          $timeout(function delayedSaveReminder() {
            if (!$scope.isUserLoggedIn() || !ProjectService.getProject().getId() || ProjectService.getProject().getId() <= 0) {
              saveReminderNotification = NotificationService.addCustomIconNotification('toast-save-reminder', MessageService.getMessage('notification.save.reminder.title'),
                MessageService.getMessage('notification.save.reminder.text'), 'info', undefined);

              $scope.$on(EventConstants.PROJECT_SAVE_IN_PROGRESS, function onProjectSaveInProgress(project) {
                if (saveReminderNotification) {
                  NotificationService.removeNotification(saveReminderNotification);
                  saveReminderNotification = undefined;
                }
              });

            }
          }, saveReminderDelay * 1000);
        }

      };



      $scope.redirectToShoppingCart = function (option) {
        var project = ProjectService.getProject();
        if (AppValues.upsellingOptions.length > 0 && option === 'glossy') {
          ProjectService.changeProjectProduct(upsellingProductId).then(function changedSuccesfully() {
            ProjectService.saveProject().then(function () {
              ShoppingCartService.addAndRedirectToShoppingCart(project);
            });
          });
        } else {
          ShoppingCartService.addAndRedirectToShoppingCart(project);
        }
      };


      var removeWatchAppResourcesLoaded = $scope.$watch(function watchAppResourcesLoaded() {
        return AppValues.appResourcesLoaded;
      }, function onAppResourcesLoadedChanged(newValue) {
        if (newValue) {
          removeWatchAppResourcesLoaded();
          $scope.mainData.showOpenProjectOption = BaseConfigService.hasShowOpenProjectOptionParamInUrl();
          var self = this;
          FileHandleService.setActiveFilter('allPhotos');

          // watch the undo-redo stack to find out if the project model has changed
          $scope.$watchGroup([
            function watchUndoStackSize() {
              return UndoRedoService.getUndoStepsCount();
            },
            function watchRedoStackSize() {
              return UndoRedoService.getRedoStepsCount();
            }
          ], function (newValues, oldValues) {
            // undo or redo stack changed its size?
            if (oldValues[0] !== newValues[0] || oldValues[1] !== newValues[1]) {
              ProjectService.getProject().incrementModelStateVersion();
            }
          });

          if (!BaseConfigService.hasShowOpenProjectOptionParamInUrl() && !BaseConfigService.hasProjectIdInUrl() && !BaseConfigService.hasIpsAlbumIdInUrl()) {
            $scope.mainData.showOpenProjectOption = false;
            openInitialChoiceDialog();
          }

          if (BaseConfigService.hasIpsAlbumIdInUrl()) {
            checkForceLoginStatusForAlbumItems(BaseConfigService.getIpsAlbumIdFromUrl());
          }

          if (BaseConfigService.hasIpsAlbumIdInUrl() && !BaseConfigService.hasProjectIdInUrl()) {
            $scope.mainData.showOpenProjectOption = false;
            openInitialChoiceDialog();
          }

          var cartItemId = BaseConfigService.getShoppingCartItemIdFromUrl();
          if (cartItemId) {
            ProjectService.deleteProjectFromShoppingCart(cartItemId);
          }

          if (BaseConfigService.hasShowOpenProjectOptionParamInUrl() && BaseConfigService.getProductIdFromUrl()) {
            openInitialChoiceDialog();
          }

          if (BaseConfigService.hasProjectIdInUrl()) {
            $scope.mainData.showOpenProjectOption = false;
            loadProject(BaseConfigService.getProjectIdFromUrl(), BaseConfigService.getAccessCodeFromUrl());
          }

          if (BaseConfigService.hasOpenProjectDialogParamInUrl()) {
            BaseConfigService.removeOpenProjectDialogParamFromUrl();
            $scope.mainData.showOpenProjectOption = false;
            var myProjectsLightbox = $modal.open({
              size: 'lg',
              backdrop: 'static',
              templateUrl: 'myProjectsLightbox',
              controller: 'MyProjectsLightboxController'
            });

            myProjectsLightbox.result.then(function (response) {
              LeaveEditorService.reloadEditorWithProject(response.id);
            }, function (dimissed) {
              handleDismissedDialog();
            });
          }

          HotKeyService.initHotKeys();
        }
      });

      function handleDismissedDialog() {
        if (BaseConfigService.hasShowOpenProjectOptionParamInUrl()) {
          $scope.mainData.showOpenProjectOption = true;
        }
        else {
          var targetUrl = OperatorService.getEditorCloseUrl();
          LeaveEditorService.changeLocationTo(targetUrl);
        }
      }


      function openInitialChoiceDialog() {
        var productId = BaseConfigService.getProductIdFromUrl();
        var pagesCount = BaseConfigService.getPagesCountFromUrl();

        var dialogPassThroughDataForInit = {
          caller: 'mainController',
          productId: productId,
          pagesCount: pagesCount
        };

        // no parameter here, fire the dialog
        var modalInitialChoiceLightbox = $modal.open({
          scope: $scope,
          size: 'lg',
          backdrop: BaseConfigService.hasShowOpenProjectOptionParamInUrl(),
          templateUrl: 'initialChoiceLightbox.html',
          controller: 'InitialChoiceLightboxController',
          resolve: {
            passThrough: function () {
              return dialogPassThroughDataForInit;
            }
          }
        });

        /**
         *  Handle the result of the modal lightbox
         * */
        modalInitialChoiceLightbox.result.then(function (dialogData) {
          /*
           the modal dialog is closed here, we got the user choices in the dialogData object
           */

          var productId = null;
          var pagesCount = 26;
          var bookTitle = '';
          angular.forEach(dialogData, function (value, key) {
            if (key === 'productId') {
              productId = value;
            }
            if (key === 'pagesCount') {
              pagesCount = value;
            }
            if (key === 'bookTitle') {
              bookTitle = value;
            }
          });
          BaseConfigService.removeProductIdFromUrl();
          BaseConfigService.removeShowOpenProjectOptionParamFromUrl();
          // init project - an event will be fired when ready
          ProjectService.initProject(pagesCount, productId, bookTitle, true);
          $scope.setEditorInitialized();
          $scope.mainData.showOpenProjectOption = false;
          TrackingService.trackByEVar('eVar46', 'New unsaved project', 'Project id');

        }, function (dimissed) {
          BaseConfigService.removeProductIdFromUrl();
          handleDismissedDialog();
        });
      }


      var showUpsellingOptionsWatch = $scope.$watch(function watchUpsellingOptions() {
        return ProductService.getPossibleUpsellingProducts();
      }, function onProjectExistsChanged(newValue, oldValue) {
        if (newValue && newValue.length > 0) {
          $scope.mainData.showOpenProjectOption = false;
          $scope.mainData.initialized = false;
          $scope.mainData.showUpsellingOptions = true;
          upsellingProductId = newValue[0].getId();
          $scope.book = {};
          var project = ProjectService.getProject();

          PriceService.calculatePrice(newValue[0].getId(), project.getPagesCount()).then(
            function ok(priceData) {
              $scope.book.additionalPrice = priceData.totalSum;
            });

          PriceService.calculatePrice(project.getProductId(), project.getPagesCount()).then(
            function ok(priceData) {
              $log.debug(priceData);
              $scope.book.nonAdditionalPrice = priceData.totalSum;
            });
        }
      });


    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';
  angular.module('tatooine').controller('DesignElementSwitcherController', [
    '$scope', '$log', 'MessageService', 'ProjectService',
    function ($scope, $log, MessageService, ProjectService) {

      var TABS = [
        {
          name: 'photo',
          title: MessageService.getMessage('navigation.photos'),
          url: '/web/javax.faces.resource/app/tatooine/includes/photoSelection.html.jsf',
          active: true,
          disabled: false
        },
        {
          name: 'clipart',
          title: MessageService.getMessage('navigation.cliparts'),
          url: '/web/javax.faces.resource/app/tatooine/includes/clipartSelection.html.jsf',
          active: false
        },
        {
          name: 'background',
          title: MessageService.getMessage('navigation.backgrounds'),
          url: '/web/javax.faces.resource/app/tatooine/includes/backgroundSelection.html.jsf',
          active: false
        }

      ];
      $scope.tabList = TABS;
      $scope.navType = 'pills';


      var removeSelectedTabWatch = $scope.$watch(function watchSelectedTab() {
        return  ProjectService.getProject() ? ProjectService.getProject().getSelectedDesignElementTabIndex() : 0;
      }, function onWatchSelectedTabChanged(newValue, oldValue) {
        for (var i = 0; i < $scope.tabList.length; i++) {
          $scope.tabList[i].active = (i === newValue);
        }
      });

      $scope.tabSelected = function (tab) {
        if (!ProjectService.getProject()) {
          return;
        }
        ProjectService.getProject().setSelectedDesignElementTabIndex(TABS.indexOf(tab));
      };


    }
  ])
  ;
})
();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';

  angular.module('tatooine').controller('PhotoSelectionController', [
    '$scope', '$log', '$timeout', '$filter', 'SafeApply', '$modal', 'orderByFilter', 'Utils', 'EventConstants', 'FileHandleService', 'DesignAreaService', 'ProjectService', 'UndoRedoService', 'PhotoSourcesService', 'OperatorService',
    function ($scope, $log, $timeout, $filter, SafeApply, $modal, orderByFilter, Utils, EventConstants, FileHandleService, DesignAreaService, ProjectService, UndoRedoService, PhotoSourcesService, OperatorService) {


      var externalSourcesCounter = 0;
      if (OperatorService.isMyPhotosEnabled()) {
        $scope.myPhotosConfigValue = OperatorService.isMyPhotosEnabled();
        externalSourcesCounter++;
      }

      $scope.externalSourcesCounter = externalSourcesCounter;
      var MIN_ITEMS_TO_LOAD_UNTIL_RELYING_ON_SCROLL_EVENTS = 25;

      $scope.lazyLoadedFileHandles = [];
      $scope.selectedFileHandle = undefined;

      /**
       * Adds an image from a fileHandle to the currently selected design area.
       * @param fileHandle a FileHandle instance
       */
      $scope.addPhotoToSelectedDesignArea = function (fileHandle) {
        var selectedDesignArea = ProjectService.getSelectedDesignArea();

        var undoHandle = UndoRedoService.pushModelData(selectedDesignArea);
        DesignAreaService.addImageItem(fileHandle, selectedDesignArea, selectedDesignArea.getWidth() / 2, selectedDesignArea.getHeight() / 2)
          .then(undoHandle.resolve);

      };

      /**
       * Selects the thumbnail for the specified FileHandle, if it is not selected. Otherwise, opens it in the big dialog.
       * @param fileHandle
       */
      $scope.thumbClicked = function (fileHandle) {
        $scope.selectedFileHandle = fileHandle;
      };


      $scope.getLazyLoadedFileHandles = function () {
        if (FileHandleService.getActiveFilter() === 'localPhotos' || FileHandleService.getActiveFilter() === 'allPhotos') {
          return FileHandleService.filterFileHandles($scope.lazyLoadedFileHandles);
        }
        return FileHandleService.filterFileHandles(FileHandleService.getFileHandles());
      };


      $scope.loadMoreItems = function (itemsToFetch, forceRebuild) {
        $log.debug('lazily loading more FileHandles', itemsToFetch);

        if (forceRebuild) {
          $scope.lazyLoadedFileHandles = [];
        }
        var itemsFetched = 0;

        // load more items into the list of all FileHandles that are lazily loaded in chunks
        var allFileHandles = FileHandleService.getFileHandles();


        for (var i = 0; i < allFileHandles.length; i++) {
          var nextCandidate = allFileHandles[i];
          if (Utils.isInArray($scope.lazyLoadedFileHandles, nextCandidate)) {
            continue;
          }
          // would the next candidate be a visible item (i.e. not be filtered out)? --> only then fetch it successfully
          if (FileHandleService.filterFileHandles([nextCandidate]).length === 1) {
            $scope.lazyLoadedFileHandles[allFileHandles.indexOf(nextCandidate)] = nextCandidate;
            itemsFetched++;
          }
          if (itemsFetched === itemsToFetch) {
            break;
          }
        }
      };

      var filterCriteriaChangeWatch = $scope.$watchCollection(function watchFilterCriteriaChange() {
        return FileHandleService.getFilterCriteria();
      }, function onFilterCriteriaChange(newValue, oldValue) {
        fillUpToMinimumItems();
      });

      // React to increasing FileHandle counts and load more items into the GUI as long as there is no scroll bar yet (due to too little item counts)
      // and items can't be lazily loaded by listening to scrolling events.
      var fileHandleCountWatches = $scope.$watchGroup([
        function watchFileHandlesCount() {
          return FileHandleService.getFileHandlesCount();
        },
        function watchLazyLoadedFileHandlesCount() {
          return $scope.getLazyLoadedFileHandles().length;
        }
      ], function onFileHandlesCountChanged(newValues, oldValues) {
        fillUpToMinimumItems();
      });

      function fillUpToMinimumItems() {
        var currentItemCount = $scope.getLazyLoadedFileHandles().length;
        if (currentItemCount < MIN_ITEMS_TO_LOAD_UNTIL_RELYING_ON_SCROLL_EVENTS) {
          $scope.loadMoreItems(MIN_ITEMS_TO_LOAD_UNTIL_RELYING_ON_SCROLL_EVENTS - currentItemCount);
        }
      }

      /**
       * Opens the modal Lightbox for a big view of that photo
       * @param fileHandle
       */
      $scope.showInLightbox = function (fileHandle) {

        var modalInstance = $modal.open({
          templateUrl: 'photoLightbox',
          controller: 'PhotoLightboxController',
          scope: $scope,
          resolve: {
            fileHandle: function () {
              return fileHandle;
            }
          }
        });

        /**
         *  Handle the result of the modal lightbox
         * */
        modalInstance.result.then(function (fileHandle) {
          $scope.selectedFileHandle = fileHandle;
        }, function () {
          $log.debug('Modal photo lightbox dismissed at: ' + new Date());
        });

        $scope.$on('$destroy', function onDestroy() {
          fileHandleCountWatches();
        });
      };

    }
  ])
  ;


})
();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';

  angular.module('tatooine').controller('BackgroundSelectionController', [
    '$scope', '$log', '$timeout', 'AppConstants', 'AppValues', 'EventConstants', 'OperatorService', 'ProjectService', 'BackgroundTemplateService', 'BackgroundItemTemplateFactory',
    function ($scope, $log, $timeout, AppConstants, AppValues, EventConstants, OperatorService, ProjectService, BackgroundTemplateService, BackgroundItemTemplateFactory) {
      var MIN_ITEMS_TO_LOAD = 20;

      var initialize = function () {
        $scope.categorySelectionVisible = false;
        $scope.data = {
          backgroundItemTemplates: [],
          numberOfloadedBackgrounds: 0,
          defaultBackgroundItemTemplate: BackgroundItemTemplateFactory.createBackgroundItemTemplate(AppConstants.BACKGROUND_DEFAULT_ID),
          selectedBackgroundItemTemplate: null,
          itemWidth: 147,
          itemHeight: 105
        };

        $scope.categoryMap = {};
        BackgroundTemplateService.getBackgroundCategoryMap().then(function ok(categoryMap) {
          $scope.categoryMap = categoryMap;
        });

        var container = angular.element('#backgroundListContainer');
        container.on('scroll', function () {
          if (container.scrollLeft() > 100) {
            if (!allItemsLoaded()) {
              loadAllItemsRecursively();
            }
          }
        });

      };


      var removeWatchAppResourcesLoaded = $scope.$watch(function watchAppResourcesLoaded() {
        return AppValues.appResourcesLoaded;
      }, function onAppResourcesLoadedChanged(newValue) {
        if (newValue) {
          $scope.selectCategory(OperatorService.getDefaultDesignElementCategory('background'));
          removeWatchAppResourcesLoaded();
        }
      });

      var loadMoreItems = function (itemsToFetch) {
        for (var i = $scope.data.numberOfloadedBackgrounds;
             i < $scope.data.numberOfloadedBackgrounds + itemsToFetch && i < $scope.data.backgroundItemTemplates.length; i++) {
          $scope.data.backgroundItemTemplates[i].setInitialized(true);
        }
        $scope.data.numberOfloadedBackgrounds += itemsToFetch;
      };

      var loadAllItemsRecursively = function() {
        if (allItemsLoaded()) {
          return;
        }
        $timeout(function delayed() {
          loadMoreItems(20);
          loadAllItemsRecursively();
        }, 500);
      };

      var allItemsLoaded = function() {
        return $scope.data.numberOfloadedBackgrounds >= $scope.data.backgroundItemTemplates.length;
      };

      $scope.selectTemplate = function (backgroundItemTemplate) {
        if (backgroundItemTemplate === $scope.data.selectedBackgroundItemTemplate) {
          $scope.data.selectedBackgroundItemTemplate = null;
          return;
        }
        $scope.data.selectedBackgroundItemTemplate = backgroundItemTemplate;
      };

      $scope.toggleCategorySelection = function () {
        $scope.categorySelectionVisible = !$scope.categorySelectionVisible;
        if ($scope.categorySelectionVisible) {
          var selectedItembox = ProjectService.getSelectedDesignArea().getSelectedItemBox();
          if (selectedItembox) {
            selectedItembox.setSelected(false);
          }

        }
      };

      $scope.getBackgroundItemTemplates = function () {
        return $scope.data.backgroundItemTemplates;
      };

      $scope.selectCategory = function (categoryId) {
        BackgroundTemplateService.getBackgroundTemplatesByCategory(categoryId).then(
          function ok(backgroundItemTemplates) {
              $scope.data.backgroundItemTemplates = backgroundItemTemplates;
              $scope.data.numberOfloadedBackgrounds = 0;
              loadMoreItems(MIN_ITEMS_TO_LOAD);
              $scope.selectedCategory = categoryId;

              var backgroundListContainer = angular.element('#backgroundListContainer');
              if (backgroundListContainer) {
                backgroundListContainer.scrollLeft(0);
              }
            });
      };


      initialize();
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';

  angular.module('tatooine').controller('DesignAreasController', [
    '$scope', '$window', '$document', '$log', '$interval', '$timeout', '$location', '$anchorScroll', 'DeviceDetectionService', 'AppConstants', 'AppValues', 'EventConstants', 'ProjectService', 'DesignAreaService', 'LayoutService', 'ProductService', 'AuthenticationService', 'UndoRedoService', 'MessageService', 'NotificationService',
    function ($scope, $window, $document, $log, $interval, $timeout, $location, $anchorScroll, DeviceDetectionService, AppConstants, AppValues, EventConstants, ProjectService, DesignAreaService, LayoutService, ProductService, AuthenticationService, UndoRedoService, MessageService, NotificationService) {

      $scope.showBackgroundGradient = !DeviceDetectionService.isMacDevice();
      $scope.pagePackageSize = AppValues.doublePagePackageSize * 2;

      $scope.$on(EventConstants.PROJECT_TO_SCOPE_NEEDED, function onUndoRedo(e, project) {
        setProjectToScope(project);
      });

      var projectExistsWatch = $scope.$watch(function watchProjectExists() {
        return ProjectService.getProject() !== null;
      }, function onProjectExistsChanged(newValue, oldValue) {
        if (newValue) {
          setProjectToScope(ProjectService.getProject());
          projectExistsWatch();
        }
      });

      /**
       * Listens to the droppedOnDesignArea event that is emitted by a CanvasDesignArea in case a item was dropped on it
       */
      $scope.$on(EventConstants.DROPPED_ON_DESIGN_AREA, function (e, designArea) {
        $log.debug('droppedOnDesignArea', designArea);
        ProjectService.selectDesignArea(designArea);
        $scope.changeDesignAreasContainerBackground(designArea);
      });

      /**
       * Listens to the DesignAreaClicked event that is emitted by a CanvasDesignArea in case it was clicked
       */
      $scope.$on(EventConstants.DESIGN_AREA_CLICKED, function (e, designArea) {
        $log.debug('clickedOnDesignArea', designArea);
        if ($scope.selectedDesignArea === designArea && !designArea.isDetailInteractionMode() && !DesignAreaService.getDesignAreaToDrop()) {
          $scope.changeToDetailView(designArea);
        }
        if (!designArea.isSelected()) {
          ProjectService.selectDesignArea(designArea);
        }
      });


      /**
       * Listens to the DesignAreaClicked event that is emitted by a CanvasDesignArea in case it was clicked
       */
      $scope.$watch(function watchSelectedDesignAreaChanged() {
        return ProjectService.getSelectedDesignArea();
      }, function onSelectedDesignAreaChanged(newValue) {
        $scope.selectedDesignArea = newValue;
      });

      // if the number of design areas changes we would like to change to storyboard view
      $scope.$watch(function watchDesignAreasCount() {
        return $scope.project && $scope.project.getDesignAreas().length;
      }, function onDesignAreasCountChanged(newValue) {
        if (newValue && newValue > 0) {
          var project = ProjectService.getProject();
          var product = ProductService.getProductById(project.getProductId());

          var maxPages = product.getMaxNumberOfPages();
          var minPages = product.getMinNumberOfPages();

          var currentPages = project.getPagesCount();
          $scope.addPagePackageAllowed = currentPages !== maxPages;
          $scope.removePagePackageAllowed = currentPages !== minPages;

          $log.debug('Watch fired -> number of design areas changed to', newValue);
          $scope.changeToStoryboardView();
        }
      });


      $scope.containerBackgroundStyleLeft = null;
      $scope.containerBackgroundStyleRight = null;


      $scope.handleContainerResize = function (windowWidth, windowHeight) {
        // the variables are just for testing purposes currently
        var project = ProjectService.getProject();
        if (!project) {
          return;
        }
        if (project.isDetailView()) {
          $scope.selectedDesignArea.fitToDimensions(windowWidth - 2 * AppConstants.DESIGN_AREA_FLYOUT_WIDTH,
            windowHeight - $scope.getFullHeadAreaHeight() - 85);
        } else {
          project.getDesignAreas().forEach(function (designArea) {
            designArea.setToStoryboardSize();
          });
        }
      };

      $scope.deselectorClicked = function () {

        if ($scope.selectedDesignArea) {
          var itemBox = this.selectedDesignArea.getSelectedItemBox();
          if (itemBox) {
            itemBox.setSelected(false);
          }
        }
      };


      $scope.selectDesignArea = function (designArea) {
        if ($scope.selectedDesignArea) {
          $scope.selectedDesignArea.setSelected(false);
        }
        ProjectService.selectDesignArea(designArea);
        $scope.selectedDesignArea = designArea;
      };

      /**
       * Deletes the selected item box from data model from the currently selected design area model.
       */
      $scope.deleteSelectedItemBox = function () {
        var selectedDesignArea = ProjectService.getSelectedDesignArea();

        // TODO Frank Bruns 08.11.2013: As soon as this function is used again we have to have a look on what happens
        // if we remove elements from an array that is currently iterated
        selectedDesignArea.getImageItems().forEach(function iterImageItems(itemBoxModel) {
          if (itemBoxModel.isSelected()) {
            var index = selectedDesignArea.getImageItems().indexOf(itemBoxModel);
            selectedDesignArea.getImageItems().splice(index, 1);
          }
        });
      };

      /**
       * Display the next design area from data model in details view.
       */
      $scope.nextDesignArea = function () {

        var nextDesignAreaIndex = $scope.project.getDesignAreas().indexOf(ProjectService.getSelectedDesignArea()) + 1;
        nextDesignAreaIndex = Math.min(nextDesignAreaIndex, $scope.project.getDesignAreas().length - 1);

        var nextDesignArea = $scope.project.getDesignAreas()[nextDesignAreaIndex];

        // Deselect the itemBoxes on the old designArea.
        $scope.selectedDesignArea.setDetailInteractionMode(false);
        ProjectService.selectDesignArea(nextDesignArea);
        $scope.changeToDetailView(nextDesignArea);

        //saveProjectIfLoggedIn();
      };

      /**
       * Display the previous design area from data model in details view.
       */
      $scope.previousDesignArea = function () {

        var previousDesignAreaIndex = $scope.project.getDesignAreas().indexOf(ProjectService.getSelectedDesignArea()) - 1;
        previousDesignAreaIndex = Math.max(previousDesignAreaIndex, 0);

        var previousDesignArea = $scope.project.getDesignAreas()[previousDesignAreaIndex];

        // Deselect the itemBoxes on the old designArea.
        $scope.selectedDesignArea.setDetailInteractionMode(false);
        ProjectService.selectDesignArea(previousDesignArea);
        $scope.changeToDetailView(previousDesignArea);

        //saveProjectIfLoggedIn();
      };

      $scope.addPagePackage = function () {
        // Use the transaction-like mechanism of the undoRedoService to make this action undoable.
        var undoHandle = UndoRedoService.pushProject();
        ProjectService.addPagePackage();

        undoHandle.resolve();
      };

      $scope.removePagePackage = function () {
        // Use the transaction-like mechanism of the undoRedoService to make this action undoable.
        var undoHandle = UndoRedoService.pushProject();

        var project = ProjectService.getProject();
        var designAreas = project.getDesignAreas();
        var imagesOnRemovingDesignAreas = false;
        for (var i = designAreas.length - AppValues.doublePagePackageSize; i < designAreas.length; i++) {
          if (designAreas[i].getImageItems().length > 0) {
            imagesOnRemovingDesignAreas = true;
          }
        }
        if (imagesOnRemovingDesignAreas === true) {
          var okAction = function () {
            ProjectService.removePagePackage();
          };
          if (!$window.confirm(MessageService.getMessage('project.imageWillLost'))) {
            return;
          }
        }
        ProjectService.removePagePackage();

        if (!ProjectService.getSelectedDesignArea()) {
          designAreas[designAreas.length - 1].setSelected(true);
          ProjectService.selectDesignArea(designAreas[designAreas.length - 1]);
        }

        undoHandle.resolve();

      };


      $scope.changeDesignAreasContainerBackground = function (designArea) {


        var bgItemLeft = designArea.getTemplateBackgroundItemLeft();
        var bgItemRight = designArea.getTemplateBackgroundItemRight();

        var sameBackgroundOnBothPages = bgItemLeft.getDesignElementId() === bgItemRight.getDesignElementId();

        var bgTemplateUrlLeft = 'designElements/designElementImage.rest?imageSize=medium&elementId=' + bgItemLeft.getDesignElementId();
        var bgTemplateUrlRight = 'designElements/designElementImage.rest?imageSize=medium&elementId=' + bgItemRight.getDesignElementId();


        var blurFilterSupported = false;// DeviceDetectionService.isSupportedFilterBlur(); // Note: blur filter has a noticable performance impact
        var blur = blurFilterSupported ? 35 : 0;
        var grayscale = blurFilterSupported ? 30 : 0;
        var opacity = blurFilterSupported ? 0.35 : 0.225;

        $scope.containerBackgroundStyleLeft = {
          'background-image': 'url("' + bgTemplateUrlLeft + '")',
          '-webkit-filter': blurFilterSupported && bgItemLeft.getDesignElementId() !== AppConstants.BACKGROUND_DEFAULT_ID ? 'blur(' + blur + 'px) grayscale(' + grayscale + '%)' : '',
          '-moz-filter': blurFilterSupported && bgItemLeft.getDesignElementId() !== AppConstants.BACKGROUND_DEFAULT_ID ? 'blur(' + blur + 'px) grayscale(' + grayscale + '%)' : '',
          '-ms-filter': blurFilterSupported && bgItemLeft.getDesignElementId() !== AppConstants.BACKGROUND_DEFAULT_ID ? 'blur(' + blur + 'px) grayscale(' + grayscale + '%)' : '',
          'filter': blurFilterSupported && bgItemLeft.getDesignElementId() !== AppConstants.BACKGROUND_DEFAULT_ID ? 'blur(' + blur + 'px) grayscale(' + grayscale + '%)' : '',
          'opacity': opacity,
          'width': sameBackgroundOnBothPages ? '100%' : '50%',
          'height': '100%',
          'position': 'fixed',
          'background-size': 'cover',
          'top': '0px',
          'left': '0%',
          'z-index': '-1',
          'overflow': 'hidden'
        };

        $scope.containerBackgroundStyleRight = {
          'background-image': 'url("' + bgTemplateUrlRight + '")',
          '-webkit-filter': blurFilterSupported && bgItemRight.getDesignElementId() !== AppConstants.BACKGROUND_DEFAULT_ID ? 'blur(' + blur + 'px) grayscale(' + grayscale + '%)' : '',
          '-moz-filter': blurFilterSupported && bgItemRight.getDesignElementId() !== AppConstants.BACKGROUND_DEFAULT_ID ? 'blur(' + blur + 'px) grayscale(' + grayscale + '%)' : '',
          '-ms-filter': blurFilterSupported && bgItemRight.getDesignElementId() !== AppConstants.BACKGROUND_DEFAULT_ID ? 'blur(' + blur + 'px) grayscale(' + grayscale + '%)' : '',
          'filter': blurFilterSupported && bgItemRight.getDesignElementId() !== AppConstants.BACKGROUND_DEFAULT_ID ? 'blur(' + blur + 'px) grayscale(' + grayscale + '%)' : '',
          'opacity': opacity,
          'width': sameBackgroundOnBothPages ? '0%' : '50%',
          'height': '100%',
          'position': 'fixed',
          'background-size': 'cover',
          'top': '0px',
          'left': '50%',
          'z-index': '-1',
          'overflow': 'hidden'
        };


      };

      /**
       * Displays the specified design area from data model in details view.
       * @param designArea a design area from data model
       */
      $scope.changeToDetailView = function (designArea) {
        DesignAreaService.removeDesignAreaToDrop();
        ProjectService.toggleCanvasStoryBoardDetailView($scope.getFullHeadAreaHeight(), designArea);
        $scope.changeDesignAreasContainerBackground(designArea);
      };

      /**
       * Switch to the storyboard like overview of design areas.
       */
      $scope.changeToStoryboardView = function () {
        ProjectService.toggleCanvasStoryBoardDetailView($scope.getFullHeadAreaHeight());
      };

      $scope.isAddPagePackageAllowed = function () {
        var project = ProjectService.getProject();
        var product = ProductService.getProductById(project.getProductId());
        var maxPages = product.getMaxNumberOfPages();
        var currentPages = project.getPagesCount();
        return currentPages !== maxPages;
      };

      $scope.isRemovePagePackageAllowed = function () {
        var project = ProjectService.getProject();
        var product = ProductService.getProductById(project.getProductId());
        var minPages = product.getMinNumberOfPages();
        var currentPages = project.getPagesCount();
        return currentPages !== minPages;
      };

      var setProjectToScope = function (project) {
        $scope.project = project;
        var alreadySelectedDesignArea = ProjectService.getSelectedDesignArea();
        if (!alreadySelectedDesignArea) {
          ProjectService.selectDesignArea(project.getDesignAreas()[0]);
        }
        else {
          ProjectService.selectDesignArea(alreadySelectedDesignArea);
        }
        ProjectService.toggleCanvasStoryBoardDetailView($scope.getFullHeadAreaHeight());
      };

    }
  ])
  ;
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

(function () {
  'use strict';
  angular.module('tatooine').controller('StoryBoardDetailViewToggleController', [
    '$log', '$scope', 'ProjectService', 'LayoutService',
    function ($log, $scope, ProjectService, LayoutService) {

      $scope.project = ProjectService.getProject();

      $scope.isDetailView = function () {
        var project = ProjectService.getProject();
        if (project) {
          return project.isDetailView();
        }
      };

      $scope.changeToStoryboardView = function () {
        ProjectService.toggleCanvasStoryBoardDetailView($scope.getFullHeadAreaHeight());
      };

    }
  ]);
})();(function () {
  'use strict';
  angular.module('tatooine').controller('UndoRedoController', [
    '$log', '$scope', 'UndoRedoService', 'ProjectService',
    function ( $log, $scope,  UndoRedoService, ProjectService) {

      $scope.project = ProjectService.getProject();

      $scope.undo = function () {
        UndoRedoService.undo();
      };

      $scope.redo = function () {
        UndoRedoService.redo();
      };

      $scope.isUndoEnabled = function () {
        return UndoRedoService.isUndoEnabled();
      };

      $scope.isRedoEnabled = function () {
        return UndoRedoService.isRedoEnabled();
      };

    }
  ]);
})();(function () {
  'use strict';
  angular.module('tatooine').controller('ToggleHeadAreaController', [
    '$log', '$scope', 'AppValues', 'HeadAreaToggleService',
    function ($log, $scope, AppValues, HeadAreaToggleService) {

      $scope.isHeadAreaVisible = function () {
        return AppValues.headAreaTop === 0;
      };

      $scope.toggleHeadArea = function () {
        HeadAreaToggleService.toggleHeadArea();
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 * Controller for the shopping Cart.
 *
 * @author Holger Cremer
 * @author Sascha Friedrich
 */

(function () {
  'use strict';
  angular.module('tatooine').controller('ShoppingCartRedirectController', [
    '$log', '$scope', '$q', '$window', '$location', '$resource', '$timeout', 'AppConstants', 'AppValues', 'Utils', '$modal', 'BaseConfigService', 'PriceService', 'ProjectService', 'ProductService', 'NotificationService', 'MessageService', 'AuthenticationService', 'UploadService', 'ShoppingCartService', 'BookPreviewService', 'LeaveEditorService', 'OperatorService',
    function ($log, $scope, $q, $window, $location, $resource, $timeout, AppConstants, AppValues, Utils, $modal, BaseConfigService, PriceService, ProjectService, ProductService, NotificationService, MessageService, AuthenticationService, UploadService, ShoppingCartService, BookPreviewService, LeaveEditorService, OperatorService) {
      $scope.data = {};
      $scope.data.subLine = MessageService.getMessage('shoppingCart.button.addToShoppingCart.pricePrefix');
      $scope.data.buttonEnabled = true;
      $scope.data.buttonVisible = true;

      function calculate(productId, designAreasLength) {
        var pageCount = (designAreasLength - 2) * 2;
        PriceService.calculatePrice(productId, pageCount).then(
          function ok(priceData) {
            if (priceData) {
              $scope.priceData.totalSum = priceData.totalSum;
              $scope.priceData.pagePrice = priceData.pagePrice;
              $scope.data.subLine = MessageService.getMessage('shoppingCart.button.addToShoppingCart.pricePrefix') + ' ' + priceData.totalSum + '*';
            }
          });
      }

      function redirectToShoppingCart(project) {
        var upsellingPhotobookOptions = [];
        if (BaseConfigService.hasShowUpsellingParamInUrl()) {
          upsellingPhotobookOptions = ProductService.getUpsellingOptions(project);
        } else if (BaseConfigService.hasShowUpsellingParamInUrl() === null && OperatorService.isUpsellingEnabled()) {
          upsellingPhotobookOptions = ProductService.getUpsellingOptions(project);
        }

        var promises = [];
        upsellingPhotobookOptions.forEach(function (upsellingOption) {
          var promise = PriceService.calculatePriceDifference(project.getProductId(), upsellingOption.getId(), project.getPagesCount()).then(function (priceData) {
            if (priceData.sumProductA > priceData.sumProductB) {
              Utils.removeFromArray(upsellingPhotobookOptions, upsellingOption);
            }
          });
          promises.push(promise);
        });

        $q.all(promises).then(function ok() {
          ProductService.setPossibleUpsellingProducts(upsellingPhotobookOptions);
          if (upsellingPhotobookOptions.length <= 0) {
            ShoppingCartService.addAndRedirectToShoppingCart(project);
          } else {
            ProductService.setPossibleUpsellingProducts(upsellingPhotobookOptions);
          }
        });
      }

      $scope.priceData = {
        totalPrice: '?',
        pagePrice: '?'
      };

      $scope.$watch(function watchThis() {
        // the variables to watch are not defined on page load...
        var project = ProjectService.getProject();
        // we watch the productId AND designAreas length with the same watch
        return [
            project && project.baseProduct && project.baseProduct.productId,
            project && project.baseProduct && project.getDesignAreas() && project.getDesignAreas().length
          ];

      }, function onWatchThisChanged(newValue, oldValue) {
        // for any proper value, we calculate a new price
        if (newValue[0] && newValue[1]) {
          calculate(newValue[0], newValue[1]);
        }
      }, true);


      // TODO Frank Bruns 17.07.2015: Remove this whole preview active/button visible stuff. It's a workaround for a bug with
      // not hiding tooltips for disabled buttons in Angular UI Bootstrap.
      $scope.$watch(function watchPreviewActiveState() {
        return BookPreviewService.isPreviewActive();
      }, function onPreviewActiveStateChanged(newState) {
        $scope.data.buttonVisible = !newState;
      });


      $scope.openPreviewInShoppingCartMode = function () {

        $scope.data.buttonEnabled = false;

        ProjectService.saveProject(true).then(function () {
            if (ProjectService.getProject().isUserRelated()) {
              AuthenticationService.ensureUserLoggedIn('loginRegister.session.timeout', null, null, true).then(function loggedIn() {
                BookPreviewService.setPreviewActive(true, true);
              }, function notLoggedIn(result) {
                if (BaseConfigService.isSSOSession() && result === 'sso') {
                  ProjectService.saveCurrentProjectModal('saveStatus.finished.sso.redirectToLogin').then(function () {
                    LeaveEditorService.handleSsoLogin(null, null);
                  });
                }
              });
            } else {
              BookPreviewService.setPreviewActive(true, true);
            }
          }, function saveFailed(failedData) {
            NotificationService.addNotification('', MessageService.getMessage('notification.previewShoppingCart.error'), 'danger', AppConstants.NOTIFICATION_DEFAULT_TIMEOUT);
          }
        ).finally(function doFinally() {
            $scope.data.buttonEnabled = true;
          });
      };


      $scope.addToShoppingCartClicked = function () {

        var notYetTransferredImages = UploadService.getRemainingFileHandles();

        var project = ProjectService.getProject();
        var designAreas = project.getDesignAreas();

        var imagesInBook = 0;
        var emptyDoublePages = 0;
        var pagesWithBadImages = [];

        for (var designAreasIndex = 0; designAreasIndex < designAreas.length; designAreasIndex++) {
          var designArea = designAreas[designAreasIndex];

          // count non default template backgrounds on the design area
          var nonDefaultBackgrounds = 0;
          var allTemplateBackgrounds = designArea.getTemplateBackgroundItems();
          for (var backgroundsIndex = 0; backgroundsIndex < allTemplateBackgrounds.length; backgroundsIndex++) {
            if (AppConstants.BACKGROUND_DEFAULT_ID !== allTemplateBackgrounds[backgroundsIndex].getDesignElementId()) {
              nonDefaultBackgrounds++;
            }
          }

          // count text items with content
          var textItemsWithContent = 0;
          var allTextItems = designArea.getTextItems();
          for (var textsIndex = 0; textsIndex < allTextItems.length; textsIndex++) {
            var textItem = allTextItems[textsIndex];
            if (textItem.getText().length > 0 || textItem.getBackgroundColor() !== 'none') {
              textItemsWithContent++;
            }
          }

          // count clipart items
          var cliparts = designArea.getClipartItems().length;


          // count image items on the design area
          var imagesOnDoublePage = 0;
          var allDesignAreaImages = designArea.getImageItems().concat(designArea.getImageBackgroundItems());
          for (var imagesIndex = 0; imagesIndex < allDesignAreaImages.length; imagesIndex++) {
            var image = allDesignAreaImages[imagesIndex];
            // only consider imageItems as not empty if they have a thumbkey set to them
            if (image.getThumbKey()) {
              imagesOnDoublePage++;
              imagesInBook++;
            }

            if (image.calculateQuality() === 'red') {
              var pageNumber = designArea.getPageHalfFromItemBox(image) === 'left' ? designAreasIndex * 2 - 2 : designAreasIndex * 2 - 1;
              if (pagesWithBadImages.indexOf(pageNumber) === -1) {
                if (pageNumber === -2) {
                  pageNumber = MessageService.getMessage('designArea.coverBack');
                } else if (pageNumber === -1) {
                  pageNumber = MessageService.getMessage('designArea.coverFront');
                } else {
                  pageNumber = MessageService.getMessage('designArea.site') + ' ' + pageNumber;
                }
                pagesWithBadImages.push(pageNumber);
              }
            }
          }

          // is the design area considered empty? --> check conditions
          if (imagesOnDoublePage === 0 && nonDefaultBackgrounds === 0 && textItemsWithContent === 0 && cliparts === 0) {
            emptyDoublePages++;
          }
        }


        if (imagesInBook === 0 || notYetTransferredImages > 0 || pagesWithBadImages.length > 0 || emptyDoublePages > 0) {
          var dialogPassThroughData = {
            target: 'shoppingCart',
            title: 'shoppingCart.dialogTitle',
            confirmText: 'shoppingCart.confirmRedirect',
            imagesInBook: imagesInBook,
            notYetTransferredImages: notYetTransferredImages,
            pagesWithBadImages: pagesWithBadImages,
            emptyDoublePages: emptyDoublePages
          };

          var leaveEditorLightBox = $modal.open({
            scope: $scope,
            size: 'lg',
            templateUrl: 'leaveEditorLightBox',
            controller: 'LeaveEditorLightBoxController',
            resolve: {
              passThrough: function () {
                return dialogPassThroughData;
              }
            }
          });

          leaveEditorLightBox.result.then(function closed() {
            redirectToShoppingCart(project);
          }, function dismissed() {
            $log.debug('ShoppingCart redirect dismissed');
          });

        } else {
          redirectToShoppingCart(project);
        }

      };

    }
  ])
  ;
})
();
/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 * Controller for the auto FillUp.
 *
 * @author Sascha Friedrich
 */

(function () {
  'use strict';
  angular.module('tatooine').controller('AutoFillController', [
    '$log', '$scope', '$q', '$modal', '$location', '$resource', '$timeout', 'AppConstants', 'AppValues', 'EventConstants', 'SafeApply', 'DesignAreaService', 'ProjectService', 'UndoRedoService', 'LayoutService', 'NotificationService', 'MessageService', 'AuthenticationService', 'FileHandleService', 'AutoFillService',
    function ($log, $scope, $q, $modal, $location, $resource, $timeout, AppConstants, AppValues, EventConstants, SafeApply, DesignAreaService, ProjectService, UndoRedoService, LayoutService, NotificationService, MessageService, AuthenticationService, FileHandleService, AutoFillService) {
      $scope.autoFillUpActive = false;

      var removeFileHandlesAvailableWatch = $scope.$watch(function watchFileHandlesCount() {
        return FileHandleService.getFileHandlesCount() > 0;
      }, function onFileHandlesCountChanged(newValue) {
        $scope.autoFillUpActive = newValue;
      });


      $scope.$on('$destroy', function onDestroy() {
        removeFileHandlesAvailableWatch();
      });


      /**
       * starts the automaticFill
       * @params userChoices
       *
       */

      function automaticBookFillUp(photosPerSite, alsoFillCover, keepCustomDesign, addPagesAllowed) {

        UndoRedoService.pushProject().resolve();
        AutoFillService.fillBookAutomatically(photosPerSite, keepCustomDesign, addPagesAllowed, alsoFillCover);

      }

      $scope.isStoryBoardView = function () {
        var project = ProjectService.getProject();
        if (project) {
          return project.isStoryBoardView();
        }
      };

      /**
       * Opens the modalDialog to let the user choose the options
       */
      $scope.openAutomaticFillUpDialog = function () {
        ProjectService.getProject().setAutoFillUsed(true);

        var photosPerSite = 2.1, keepCustomDesign = true, alsoFillCover = false, addPagesAllowed = false;
        if (ProjectService.getProject().isDetailView()) {
          ProjectService.toggleCanvasStoryBoardDetailView(AppValues.headAreaHeight+AppConstants.TOGGLE_HEAD_AREA_HEIGHT);
        }
        automaticBookFillUp(photosPerSite, alsoFillCover, keepCustomDesign, addPagesAllowed);

        /*
         we start here, the modal dialog will appear here!
         */

        /* var modalAutoFillLightbox = $modal.open({
         templateUrl: 'autoFillSettingsLightbox',
         controller: 'AutoFillSettingsLightBoxController'
         });*/

        /**
         *  Handle the result of the modal lightbox
         * */
        /*modalAutoFillLightbox.result.then(function (resp) {

         /*
         the modal dialog is closed here, we got the user choices in the resp object

         var photosPerSite = 1.5, keepCustomDesign = true, alsoFillCover = true, addPagesAllowed = false;

         angular.forEach(resp, function (value, key) {
         if (key === 'photosPerSite') {
         photosPerSite = value;
         }
         if (key === 'keepCustomDesign') {
         keepCustomDesign = value;
         }
         if (key === 'alsoFillCover') {
         alsoFillCover = value;
         }
         if (key === 'addPagesAllowed') {
         addPagesAllowed = value;
         }
         });

         automaticBookFillUp(photosPerSite, alsoFillCover, keepCustomDesign, addPagesAllowed);

         }, function () {
         $log.info('Modal dismissed at: ' + new Date());
         });*/
      };

    }

  ])
  ;
})();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 *
 * @author Frank Bruns (frank.bruns@cewe.de)
 */

(function () {
  'use strict';
  angular.module('tatooine').controller('AutoFillProgressLightBoxController', [
    '$log', '$scope', 'EventConstants',
    function ($log, $scope, EventConstants) {

      $scope.preparedPhotos = [];

      $scope.$on(EventConstants.PHOTO_PREPARED_FOR_AUTO_FILL, function onPhotoPrepared(e, eventData) {
        $log.debug('Photo prepared for auto fill', eventData);
        $scope.preparedPhotos.push(eventData);
      });

      $scope.isLastInArray = function (preparedPhoto) {
        return $scope.preparedPhotos.indexOf(preparedPhoto) === $scope.preparedPhotos.length - 1;
      };

    }
  ]);
})
();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 * Settings dialog for tatooine autofill option
 *
 * @author Sascha Friedrich
 */

(function () {
  'use strict';
  angular.module('tatooine').controller('AutoFillSettingsLightBoxController', [
    '$scope', '$modalInstance', 'FileHandleService', 'ProjectService', 'ProductService', 'MessageService',
    function ($scope, $modalInstance, FileHandleService, ProjectService, ProductService, MessageService) {
      $scope.modal = {};
      var project = ProjectService.getProject();

      var designAreas = project.getDesignAreas();
      $scope.showKeepCustomDesign = false;

      for (var i = 0; i < designAreas.length; i++) {
        if (designAreas[i].getImageItems().length > 0) {
          $scope.showKeepCustomDesign = true;
          break;
        }
      }

      $scope.countingImages = FileHandleService.getFileHandlesCount();
      $scope.countingPages = project.getPagesCount();

      // TODO Sascha 01.07.14 - these are the same values from the modalInstance.result, maybe we can combine em, so we dont need double declarations
      $scope.modal.keepCustomDesign = true;
      $scope.modal.photosPerSite = 1.5;
      $scope.modal.alsoFillCover = true;
      $scope.modal.addPagesAllowed = false;


      $scope.neededPhotos = $scope.modal.photosPerSite * $scope.countingImages; // without Cover

      $scope.modal.withCoverText = MessageService.getMessage('autoFillUp.withCoversite');
      $scope.modal.withoutCoverText = MessageService.getMessage('autoFillUp.withoutCoversite');

      // TODO, sum nice sliders here?

      $scope.ok = function () {
        var response = {photosPerSite: $scope.modal.photosPerSite, keepCustomDesign: $scope.modal.keepCustomDesign, alsoFillCover: $scope.modal.alsoFillCover, addPagesAllowed: $scope.modal.addPagesAllowed};
        $modalInstance.close(response);
      };

      $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
      };


    }
  ]);
})
();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  /* global Caman */
  'use strict';
  angular.module('tatooine').controller('PhotoLightboxController', [
    '$window', '$scope', '$log', '$modalInstance', 'SafeApply', 'fileHandle', 'FileHandleService', 'UploadService', 'PhotoEffectService', 'NotificationService',
    function ($window, $scope, $log, $modalInstance, SafeApply, fileHandle, FileHandleService, UploadService, PhotoEffectService, NotificationService) {
      $scope.fileHandle = fileHandle;
      var URL = $window.URL || $window.webkitURL;
      var caman = Caman;


      var imageStore;
      $scope.effects = PhotoEffectService.getEffects();
      /**
       * The lightbox adjusts to browser window resize.
       */
      angular.element($window).bind('resize', function () {
        SafeApply.do(function applyLightBoxResize() {
          resizeLightbox($scope.fileHandle);
        }, $scope);
      });

      function resizeLightbox(fileHandle) {
        if (fileHandle) {
          calculateLightboxDimensions();
          calculateThumbProperties(fileHandle.getId()).then(
            function (thumbProperties) {
              FileHandleService.getThumbnail($scope.fileHandle.getId(), thumbProperties.height, 'height', thumbProperties.multiStepDownScaling).
                then(insertImage, insertError);

            }, function (error) {
              insertError(error);
            });
        }
      }

      /**
       * Computes the size and position (centered) of the lightbox.
       * The aspect ratio and distance from the edge can be specified.
       */
      function calculateLightboxDimensions() {

        // Save the information about window size and available space.
        var windowSize = {
          width: $window.innerWidth,
          height: $window.innerHeight
        };
        var minXOffset = 150;
        var minYOffset = 150;
        var targetSize = {
          width: windowSize.width - minXOffset,
          height: windowSize.height - minYOffset
        };
        var targetAspectRatio = targetSize.width / targetSize.height;
        var aspectRatio = 4 / 3;

        // Compute the values to fit the lightbox into the available space.
        var lightboxWidth, lightboxHeight, lightboxX, lightboxY;
        if (aspectRatio >= targetAspectRatio) {
          lightboxHeight = targetSize.width / aspectRatio;
          lightboxWidth = targetSize.width;
        } else {
          lightboxHeight = targetSize.height;
          lightboxWidth = targetSize.height * aspectRatio;
        }
        lightboxX = (windowSize.width - lightboxWidth) / 2;
        lightboxY = (windowSize.height - lightboxHeight) / 2;
        // Bind the values to the lightbox styling.
        $scope.lightboxDimensions = {
          'width': Math.round(lightboxWidth) + 'px',
          'height': Math.round(lightboxHeight) + 'px',
          'top': lightboxY + 'px',
          'left': lightboxX + 'px'
        };
      }

      /**
       *  Calculates the max dimensions of the image in the lightbox
       * @param fileHandleId
       * @returns {thumbProperties}
       */
      function calculateThumbProperties(fileHandleId) {
        var thumbProperties = {
          multiStepDownScaling: true
        };

        return FileHandleService.getImageDimension(fileHandleId)
          .then(function (dimensions) {

            // Save the aspect ratio of the photo and that of the available content area.
            var lightboxStyling = $scope.lightboxDimensions;
            // Header and footer take 44px off the content.
            var targetSize = {
              width: parseFloat(lightboxStyling.width) - 200,
              height: parseFloat(lightboxStyling.height) * 3 / 4
            };

            var targetAspectRatio = targetSize.width / targetSize.height;
            var photoAspectRatio = dimensions.width / dimensions.height;

            // Compute the values to fit the photo into the available space.
            if (photoAspectRatio >= targetAspectRatio) {
              thumbProperties.height = targetSize.width / photoAspectRatio;
              thumbProperties.width = targetSize.width;
            } else {
              thumbProperties.height = targetSize.height;
              thumbProperties.width = targetSize.height * photoAspectRatio;
            }

            $scope.contentImgHeight = Math.round(thumbProperties.height);

            return thumbProperties;
          }, function (error) {
            $log.error('Failed to create the canvas image for the photo lightbox.', error);
          });
      }

      /**
       * Adds the photo to the lightbox
       * @param imageObj
       */
      function insertImage(imageObj) {
        angular.element('.modal-dialog').css('width', $scope.lightboxDimensions.width);
        imageObj.data.style.height = $scope.contentImgHeight + 'px';
        angular.element('#enlargedImageCanvas').html('').append(imageObj.data);
        angular.element(imageObj.data).attr('class', 'img-rounded');

      }

      /**
       * Displays the error.
       * @param error
       */
      function insertError(error) {
        $log.error('Failed to create the image for the photo lightbox.', error);
        angular.element('#enlargedImageCanvas').html('<b>thumb error :(</b>');
      }


      var removeFileHandlesWatch = $scope.$watch(function watchSelectedFileHandle() {
        return $scope.fileHandle.getId();
      }, function onFileHandleChanged(newValue, oldValue) {
        if (newValue) {
          resizeLightbox($scope.fileHandle);
          $scope.previousNextButtonStatus = FileHandleService.getFileHandlesCount() <= 1;
        }
      });


      $scope.previousPhoto = function () {
        $scope.fileHandle = FileHandleService.getPreviousFileHandle($scope.fileHandle.getId());
        resizeLightbox($scope.fileHandle);
      };

      $scope.nextPhoto = function () {
        $scope.fileHandle = FileHandleService.getNextFileHandle($scope.fileHandle.getId());
        resizeLightbox($scope.fileHandle);
      };


      $scope.removeEffects = function () {
        caman(angular.element('#enlargedImageCanvas')[0].children[0], function () {
          this.revert();
        });
        $scope.selectedEffect = undefined;
        $scope.saveAvaiable = false;
      };
      $scope.addEffect = function (effectName) {
        PhotoEffectService.addEffectToCanvas(angular.element('#enlargedImageCanvas')[0].children[0], effectName).then(function () {
          SafeApply.do(function () {
            $scope.saveAvaiable = true;
          });
        });
        $scope.selectedEffectName = effectName;
      };

      $scope.savePhoto = function (effect, closeDialog) {
        PhotoEffectService.addEffectToCanvasAndStoreOriginalImage(angular.element('#enlargedImageCanvas')[0].children[0], $scope.fileHandle, effect).then(function (fileHandle) {
          NotificationService.addNotification(effect, 'auf Ihr Foto: ' + fileHandle.getFile().name + ' angewendet','info',5000);
          if (closeDialog) {
            $modalInstance.close($scope.fileHandle);
          }
        });
      };

      function blobToFile(theBlob, fileName) {
        //A Blob() is almost a File() - it's just missing the two properties below which we will add
        theBlob.lastModifiedDate = new Date();
        theBlob.name = fileName;
        return theBlob;
      }


      function dataURItoBlob(dataURI) {

        var byteString;

        if (dataURI.split(',')[0].indexOf('base64') >= 0) {
          byteString = atob(dataURI.split(',')[1]);
        } else {
          byteString = window.unescape(dataURI.split(',')[1]);

        }
        // separate out the mime component
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

        // write the bytes of the string to a typed array
        var ia = new Uint8Array(byteString.length);

        for (var i = 0; i < byteString.length; i++) {

          ia[i] = byteString.charCodeAt(i);

        }
        return new Blob([ia], {type: mimeString});
      }

      /**
       * Happens when the "close button from the lightbox is clicked
       * the photoSelection will handle the result in the modalInstance.result method
       */
      $scope.close = function () {
        $modalInstance.close($scope.fileHandle);
      };


    }
  ]);
})
();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 * Initial Dialog for title, format and cover
 * These are hardcoded  productIds just for PHOTOKINA Release, TODO might keep in mind that the productIds should not be hard-coded here
 *
 * @author Sascha Friedrich
 */


(function () {
  'use strict';
  angular.module('tatooine').controller('InitialChoiceLightboxController', [
    '$scope', '$log', '$modalInstance', '$timeout', '$modal', 'SafeApply', 'Utils', 'TrackingService', 'PriceService', 'passThrough', 'ProductService', 'BaseConfigService', 'ProjectService', 'UndoRedoService',
    function ($scope, $log, $modalInstance, $timeout, $modal, SafeApply, Utils, TrackingService, PriceService, passThrough, ProductService, BaseConfigService, ProjectService, UndoRedoService) {

      $scope.isInitDialog = function () {
        return passThrough.caller === 'mainController';
      };


      function getActiveScrollContainer() {
        var formatContainer = angular.element(document.getElementById('formatContainer'));
        var coverTypeContainer = angular.element(document.getElementById('coverTypeContainer'));
        var paperTypeContainer = angular.element(document.getElementById('paperTypeContainer'));
        return $scope.currentProductOptionStep === 'paperTypes' ? paperTypeContainer : $scope.currentProductOptionStep === 'coverTypes' ? coverTypeContainer : formatContainer;
      }

      function getCurrentScrollState(activeContainer) {
        if (!angular.element(activeContainer)[0]) {
          return 0;
        }
        return angular.element(activeContainer)[0].scrollWidth - angular.element(activeContainer)[0].scrollLeft;
      }

      function getMaxScrollWidth(activeContainer) {
        if (!angular.element(activeContainer)[0]) {
          return 0;
        }
        return angular.element(activeContainer)[0].clientWidth;
      }

      function scrollButtonsNeeded() {
        return getActiveScrollContainer()[0] ? getActiveScrollContainer()[0].scrollWidth > getActiveScrollContainer()[0].clientWidth : false;
      }

      $scope.book = {};
      $scope.scrollLeftActivated = false;
      $scope.scrollRightActivated = true;
      $scope.scrollButtonsNeeded = true;

      $scope.book.price = '';
      $scope.book.title = '';

      $scope.productOptionSteps = ['formats', 'coverTypes', 'paperTypes']; // the seqeuence in the array defines the order of appearance in the frontend

      var productOptionInUrl = BaseConfigService.getProductOptionStepFromUrl();
      if (productOptionInUrl && productOptionInUrl === 'formats' || productOptionInUrl === 'coverTypes' || productOptionInUrl === 'paperTypes') {
        $scope.currentProductOptionStep = $scope.productOptionSteps[$scope.productOptionSteps.indexOf(productOptionInUrl)];
        $scope.settingsVisible = true;
        BaseConfigService.removeProductOptionStepFromUrl();
      }
      else {
        $scope.currentProductOptionStep = $scope.productOptionSteps[0];
        $scope.settingsVisible = false;
      }


      var scrollDelayTime = 300;


      $scope.getPreviousProductOptionNavigationTextKey = function () {
        return 'productOption.button.' + $scope.productOptionSteps[Math.max(0, $scope.productOptionSteps.indexOf($scope.currentProductOptionStep) - 1)];
      };

      $scope.getNextProductOptionNavigationTextKey = function () {
        return 'productOption.button.' + $scope.productOptionSteps[Math.min($scope.productOptionSteps.length - 1, $scope.productOptionSteps.indexOf($scope.currentProductOptionStep) + 1)];
      };

      $scope.showPreviousProductOptionStep = function () {
        var goToStepIndex = Math.max(0, $scope.productOptionSteps.indexOf($scope.currentProductOptionStep) - 1);
        $scope.currentProductOptionStep = $scope.productOptionSteps[goToStepIndex];
      };

      $scope.showNextProductOptionStep = function () {
        var goToStepIndex = Math.min($scope.productOptionSteps.length - 1, $scope.productOptionSteps.indexOf($scope.currentProductOptionStep) + 1);
        $scope.currentProductOptionStep = $scope.productOptionSteps[goToStepIndex];
      };

      $scope.showProductOptionStep = function (stepName) {
        var goToStepIndex = $scope.productOptionSteps.indexOf(stepName);
        $scope.currentProductOptionStep = $scope.productOptionSteps[goToStepIndex];
      };


      $scope.scrollTo = function (direction) {
        var activeContainer = getActiveScrollContainer();
        if (activeContainer && direction === 'right') {
          activeContainer.duScrollLeftAnimated(activeContainer.scrollLeft() + getMaxScrollWidth(activeContainer) / 2, scrollDelayTime).then(function () {
            $scope.scrollLeftActivated = true;
            $scope.scrollRightActivated = getCurrentScrollState(activeContainer) !== getMaxScrollWidth(activeContainer);
          });
        }
        else if (activeContainer && direction === 'left') {
          activeContainer.duScrollLeftAnimated(Math.max(0, activeContainer.scrollLeft() - getMaxScrollWidth(activeContainer) / 2), scrollDelayTime).then(function () {
            $scope.scrollLeftActivated = activeContainer.scrollLeft() > 0;
            $scope.scrollRightActivated = true;
          });
        }
      };

      if ($scope.currentProductOptionStep === $scope.productOptionSteps[0]) {
        $timeout(function () {
          $scope.scrollTo('right');
        });
      }

      $scope.selectedProductFormat = null;
      $scope.selectedProductCoverType = null;
      $scope.selectedProductPaperType = null;
      $scope.supportedProducts = angular.copy(ProductService.getSupportedPhotobookProducts());

      var allProducts = ProductService.getProducts();

      if (passThrough.caller === 'productOptionButton') {
        var currentProduct = ProductService.getProductById(ProjectService.getProject().getProductId());
        var project = ProjectService.getProject();
        allProducts.forEach(function iterateProducts(product) {
          var productToCheck = ProductService.getProductById(product.getId());
          var isConversionAllowed = ProductService.isCompatibleForConversion(productToCheck, currentProduct);
          // remove product from list
          if (!isConversionAllowed) {
            angular.forEach($scope.supportedProducts, function (productFormat) {
              angular.forEach(productFormat.covers, function (productCoverType) {
                angular.forEach(productCoverType.papers, function (productPaperType) {
                  if (productPaperType.productId === productToCheck.getId()) {
                    var paperIndex = productCoverType.papers.indexOf(productPaperType);
                    if (paperIndex > -1) {
                      productCoverType.papers.splice(paperIndex, 1);
                    }
                    if (productCoverType.papers.length === 0) {
                      var coverIndex = productFormat.covers.indexOf(productCoverType);
                      if (coverIndex > -1) {
                        productFormat.covers.splice(coverIndex, 1);
                      }
                      if (productFormat.covers.length === 0) {
                        var productIndex = $scope.supportedProducts.indexOf(productFormat);
                        if (productIndex > -1) {
                          $scope.supportedProducts.splice(productIndex, 1);
                        }
                      }
                    }
                  }
                });
              });
            });
          }
        });

        $scope.productToChangeAvailable = 0;
        angular.forEach($scope.supportedProducts, function (productFormat) {
          angular.forEach(productFormat.covers, function (productCoverType) {
            angular.forEach(productCoverType.papers, function (productPaperType) {
              $scope.productToChangeAvailable++;
              PriceService.calculatePrice(productPaperType.productId, project.getPagesCount()).then(function (priceData) {
                productPaperType.price = priceData.totalSum;

              });
            });
          });
        });
      }


      $scope.selectProductFormat = function (productFormat) {
        $scope.selectedProductFormat = productFormat;
        $scope.selectProductCoverType($scope.selectedProductCoverType);
      };


      $scope.selectProductCoverType = function (productCoverType) {
        var newlySelectedCoverType = null;
        $scope.selectedProductFormat.covers.forEach(function iterateCoverTypesOfSelectedFormat(coverType) {
          if (coverType.type === productCoverType.type) {
            newlySelectedCoverType = coverType;
          }
        });

        // the current cover type is not available with the new selection? --> set to the first available one
        if (newlySelectedCoverType) {
          $scope.selectedProductCoverType = newlySelectedCoverType;
        } else {
          $scope.selectedProductCoverType = $scope.selectedProductFormat.covers[0];
        }

        $scope.selectProductPaperType($scope.selectedProductPaperType);
      };


      $scope.selectProductPaperType = function (productPaperType) {
        var newlySelectedPaperType = null;
        $scope.selectedProductCoverType.papers.forEach(function iteratePaperTypesOfSelectedCoverType(paperType) {
          if (paperType.type === productPaperType.type) {
            newlySelectedPaperType = paperType;
          }
        });

        // the current paper type is not available with the new selection? --> set to the first available one
        if (newlySelectedPaperType) {
          $scope.selectedProductPaperType = newlySelectedPaperType;
        } else {
          $scope.selectedProductPaperType = $scope.selectedProductCoverType.papers[0];
        }

      };

      $scope.getMinPriceForProductFormat = function (productFormat) {
        var product = ProductService.getProductById(productFormat.covers[0].papers[0].productId);
        return product.formattedPrice;
      };

      $scope.getMinPriceForProductCoverType = function (productCoverType) {

        var product = ProductService.getProductById(productCoverType.papers[0].productId);
        return product.formattedPrice;
      };

      $scope.getPriceForProductPaperType = function (productPaperType) {
        var product = ProductService.getProductById(productPaperType.productId);
        return product.formattedPrice;
      };


      $scope.setSettingsVisible = function (trueOrFalse) {
        $scope.settingsVisible = trueOrFalse;
      };


      if (passThrough.caller === 'mainController' && !passThrough.productId) {
        passThrough.productId = 10141; // A4 hardcover as a fallback
        $scope.settingsVisible = true;
      } else {
        $scope.settingsVisible = true;
      }

      var chosenProduct = ProductService.getProductById(passThrough.productId);
      if (chosenProduct) {
        $scope.productName = chosenProduct.textResource;
      }
      // find  product with that id in the supported products object
      angular.forEach($scope.supportedProducts, function (productFormat) {
        angular.forEach(productFormat.covers, function (productCoverType) {
          angular.forEach(productCoverType.papers, function (productPaperType) {
            if (productPaperType.productId === passThrough.productId) {
              $scope.selectedProductFormat = productFormat;
              $scope.selectedProductCoverType = productCoverType;
              $scope.selectedProductPaperType = productPaperType;
            }
          });
        });
      });

      if (passThrough.pagesCount) {
        $scope.pagesCount = passThrough.pagesCount;
      }

      function updateProductName(productId) {
        var chosenProduct = ProductService.getProductById(productId);
        if (chosenProduct) {
          $scope.productName = chosenProduct.name || chosenProduct.textResource;
        } else {
          $scope.productName = 'n./a.';
        }
      }

      function calculatePrice(productId, pagesCount) {
        PriceService.calculatePrice(productId, pagesCount).then(
          function ok(priceData) {
            $scope.book.price = priceData.totalSum;
          });
      }

      calculatePrice(passThrough.productId, $scope.pagesCount);

      // if the number of design areas changes we would like to change to storyboard view
      $scope.$watch(function watchProductId() {
        return $scope.selectedProductPaperType.productId;
      }, function onProductIdChanged(newValue) {
        updateProductName(newValue);

        // cut down page count since the newly selected product has a lesser maximum page count or put the page count back to the one the dialog
        // was opened with
        var newProduct = ProductService.getProductById(newValue);

        var a = Math.min($scope.pagesCount, newProduct.getMaxNumberOfPages()); // cut down pages count due to new product limits
        var b = Math.min(passThrough.pagesCount, newProduct.getMaxNumberOfPages()); // original dialog pages count or new product limits
        $scope.pagesCount = Math.max(a, b);

        calculatePrice(newValue, $scope.pagesCount);
      }, true);

      var watchContainerChanged = $scope.$watchCollection(function watchContainer() {
        return [$scope.currentProductOptionStep, $scope.settingsVisible];
      }, function currentProductOptionStepSwitched(newValue) {
        if (newValue) {
          $timeout(function () {
            var activeContainer = getActiveScrollContainer();
            $scope.scrollButtonsNeeded = scrollButtonsNeeded();
            $scope.scrollLeftActivated = activeContainer.scrollLeft() > 0;
            $scope.scrollRightActivated = getCurrentScrollState(activeContainer) !== getMaxScrollWidth(activeContainer);

            activeContainer.on('scroll', function () {
              SafeApply.do(function () {
                $scope.scrollLeftActivated = activeContainer.scrollLeft() > 0;
                $scope.scrollRightActivated = getCurrentScrollState(activeContainer) !== getMaxScrollWidth(activeContainer);

              }, $scope);
            });

          }, scrollDelayTime);
        }
      });


      $scope.ok = function () {
        watchContainerChanged();
        var response = {productId: $scope.selectedProductPaperType.productId, pagesCount: $scope.pagesCount, bookTitle: $scope.book.title};

        if (passThrough.caller === 'mainController') {
          var trackingValue = $scope.selectedProductFormat.type + '/' + $scope.selectedProductCoverType.type + '/' + $scope.selectedProductPaperType.type;
          TrackingService.trackByEVar('eVar28', trackingValue, 'Changed product');
          $modalInstance.close(response);
        } else {
          var calledProduct = ProductService.getProductById($scope.selectedProductPaperType.productId);
          var currentProject = ProjectService.getProject();
          var currentProduct = ProductService.getProductById(currentProject.getProductId());

          var numberOfPagesChanged = ProjectService.getProject().getPagesCount() > calledProduct.getMaxNumberOfPages();
          var productDimensionsChanged = !ProductService.hasSameDimensionsForPages(calledProduct, currentProduct, currentProject.getPagesCount());

          if (numberOfPagesChanged || productDimensionsChanged) {
            var modalElement = document.getElementsByClassName('product-options-dialog')[0];
            modalElement.style.display = 'none';
            var productChangeConfirmDialog = $modal.open({
              templateUrl: 'productChangeConfirmDialog',
              controller: 'ProductChangeConfirmDialogController',
              resolve: {
                passThrough: function () {
                  return{
                    currentPagesCount: currentProject.getPagesCount(),
                    newMaxNumberOfPages: calledProduct.getMaxNumberOfPages(),
                    numberOfPagesChanged: numberOfPagesChanged,
                    productDimensionsChanged: productDimensionsChanged,
                    onlyFullBackgroundOnEachPage: calledProduct.getFullBackgroundOnEachPage()
                  };
                }
              }
            });

            productChangeConfirmDialog.result.then(function () {
              $log.debug('Accepted product change');
              var trackingValue = $scope.selectedProductFormat.type + '/' + $scope.selectedProductCoverType.type + '/' + $scope.selectedProductPaperType.type;
              TrackingService.trackByEVar('eVar28', trackingValue, 'Changed product');
              $modalInstance.close(response);
            }, function (dimissed) {
              var modalElement = document.getElementsByClassName('product-options-dialog')[0];
              modalElement.style.display = 'block';
              $log.debug('DISMISSED');
            });

          } else {
            $modalInstance.close(response);
          }
        }
      };

      $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
      };


    }
  ])
  ;
})
();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

(function () {
  'use strict';
  angular.module('tatooine').controller('CreditsLightboxController', [
    '$scope', '$modalInstance', 'ProjectService',
    function ($scope, $modalInstance, ProjectService) {
      $scope.modal = {};
      $scope.modal.tatooineRelease = ProjectService.getProject().getClientVersion();
      $scope.ok = function () {
        $modalInstance.close();
      };

    }
  ]);
})
();(function () {
  'use strict';
  angular.module('tatooine').controller('LeaveEditorController', [
    '$log', '$scope', 'OperatorService', 'ProjectService', 'LeaveEditorService', 'BaseConfigService', 'AuthenticationService',
    function ($log, $scope, OperatorService, ProjectService, LeaveEditorService, BaseConfigService, AuthenticationService) {

      var exitEditor = function () {
        $log.debug('exitEditor called');
        ProjectService.isSaveProjectNeeded().then(function ok(saveProject) {
          var targetUrl = OperatorService.getEditorCloseUrl();
          LeaveEditorService.setLeaveActive();

          if (!saveProject) {
            LeaveEditorService.changeLocationTo(targetUrl);
            return;
          }

          // The user decided to keep/save current project
          if (BaseConfigService.isSSOSession()) {
            // SSO: save before (potential) login
            ProjectService.saveCurrentProjectModal().then(function projectSaved() {
              if (!ProjectService.getProject().isUserRelated()) {
                // the project is still anonymous
                // use 'startup.do' as targetPage, because the user needs to request an IPS URL after login to enable the IPS to assign the project to the user
                AuthenticationService.ensureUserLoggedIn('loginRegister.failedSaving', null, 'startup.do', false).then(function loggedIn() {
                  LeaveEditorService.changeLocationTo(targetUrl);
                });
              } else {
                LeaveEditorService.changeLocationTo(targetUrl);
              }
            });
          } else {
            // *NO* SSO: save after (potential) login
            AuthenticationService.ensureUserLoggedIn('loginRegister.failedSaving', null, null, false).then(function loggedIn() {
              ProjectService.saveCurrentProjectModal().then(function projectSaved() {
                LeaveEditorService.changeLocationTo(targetUrl);
              });
            });
          }
        });
      };

      $scope.closeEditorClicked = function () {
        exitEditor();
      };

      $scope.headerLogoClicked = function () {
        //exitEditor(); // <-- Frank Bruns 01.04.2015: Commented out by request of Kruidvat
      };
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 *
 * @author Sascha Friedrich
 * @author Christoph Suhren
 */

(function () {
  'use strict';
  angular.module('tatooine').controller('LeaveEditorLightBoxController', [
    '$scope', '$log', '$modalInstance', '$window', '$timeout', 'passThrough', 'UploadService', 'MessageService', 'ProjectService', 'AuthenticationService',
    function ($scope, $log, $modalInstance, $window, $timeout, passThrough, UploadService, MessageService, ProjectService, AuthenticationService) {
      if (passThrough) {
        $scope.title = MessageService.getMessage(passThrough.title);
        $scope.confirmText = MessageService.getMessage(passThrough.confirmText);
        $scope.additionalMessage = passThrough.additionalMessageKey ? MessageService.getMessage(passThrough.additionalMessageKey) : '';
      }

      var addToShoppingCartAllowed = true;
      var saveAfterUploadNeeded = true;

      var initialize = function () {
        var messages = [];

        var initialNumberOfUntransferredFiles = UploadService.getRemainingFileHandles().length;
        $scope.maxUntransferredFiles = initialNumberOfUntransferredFiles;

        saveAfterUploadNeeded = initialNumberOfUntransferredFiles > 0 &&
          (passThrough.target === 'externalLogin' || passThrough.target === 'shoppingCart');

        if (passThrough.target === 'leave') {
          $scope.labelButtonLeave = MessageService.getMessage('button.leave');
          if (!AuthenticationService.isLoggedIn()) {
            messages.push({ severity: 'info', text: MessageService.getMessage('leaveEditor.hintNotLoggedIn')});
          }
        } else if (passThrough.target === 'externalLogin') {
          $scope.labelButtonLeave = MessageService.getMessage('button.externalLogin');
        } else if (passThrough.target === 'logout') {
          $scope.labelButtonLeave = MessageService.getMessage('button.logoutAndQuit');
        } else if (passThrough.target === 'shoppingCart') {
          if (passThrough.imagesInBook === 0) {
            messages.push({ severity: 'danger', text: MessageService.getMessage('shoppingCart.empty.book')});
            addToShoppingCartAllowed = false;
          }

          if (passThrough.pagesWithBadImages.length > 0) {
            messages.push({ severity: 'info', text: MessageService.getMessage('shoppingCart.badImages', [passThrough.pagesWithBadImages.join(', ')])});
          }

          if (passThrough.emptyDoublePages > 0 && passThrough.imagesInBook > 0) {
            messages.push({ severity: 'info', text: MessageService.getMessage('shoppingCart.empty.pages')});
          }

          if (addToShoppingCartAllowed) {
            $scope.labelButtonLeave = MessageService.getMessage('shoppingCart.button.addToShoppingCart');
          }
        } else {
          $scope.labelButtonLeave = MessageService.getMessage('shoppingCart.button.addToShoppingCart');
        }

        $scope.hintMessages = messages;
        if (!addToShoppingCartAllowed) {
          $scope.confirmText = '';
        }

        if ($scope.hasUnsavedChanges()) {
          // delay saving because otherwise the show up animation of the modal dialog stutters.
          $timeout(function delayed() {
            ProjectService.saveProject();
          }, 1000);
        }

      };

      $scope.getTotalFilesToTransfer = function () {
        return $scope.getNumberOfTransferredFiles() + $scope.getNumberOfRemainingFiles();
      };

      $scope.getNumberOfRemainingFiles = function () {
        return UploadService.getRemainingFileHandles().length;
      };

      $scope.getNumberOfTransferredFiles = function () {
        return UploadService.getNumberOfUploadedFiles();
      };

      $scope.showUploadInProgress = function () {
        if (passThrough.target === 'leave' && !AuthenticationService.isLoggedIn()) {
          return false;
        }
        return $scope.isUploadInProgress();
      };

      $scope.isUploadInProgress = function () {
        return UploadService.getRemainingFileHandles().length > 0;
      };

      $scope.hasUnsavedChanges = function () {
        return ProjectService.getProject().hasUnsavedChanges() && !saveAfterUploadNeeded;
      };

      $scope.getUploadInProgressMessage = function () {
        var numberOfRemainingFiles = $scope.getNumberOfRemainingFiles();

        if (numberOfRemainingFiles > 0) {
          return MessageService.getMessage('leaveEditor.hintUploadInProgress', [numberOfRemainingFiles]);
        }
        return '';
      };

      $scope.isLeaveAllowed = function () {
        return addToShoppingCartAllowed && !saveAfterUploadNeeded && !((passThrough.target === 'externalLogin' || passThrough.target === 'shoppingCart') && ProjectService.getProject().hasUnsavedChanges());
      };

      var removeWatchUploadInProgress = $scope.$watch(function watchUploadInProgress() {
        return $scope.isUploadInProgress();
      }, function uploadInProgressChanged(newValue, oldValue) {
        if (newValue === false && oldValue === true) {
          ProjectService.saveProject().finally(function doFinally() {
            saveAfterUploadNeeded = false;
          });
        }
      });

      $scope.ok = function () {
        $modalInstance.close();
      };

      $scope.cancel = function () {
        $modalInstance.dismiss();
      };

      initialize();
    }

  ]);
})
();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';
  angular.module('tatooine').controller('LoginRegisterDialogController', [
    '$scope', '$log', '$timeout', '$modalInstance', 'passThrough',
    function ($scope, $log, $timeout, $modalInstance, passThrough) {
      $scope.additionalMessage = passThrough.additionalMessage;

      $scope.onCancel = function () {
        $modalInstance.dismiss('cancel');
      };

      $scope.onSuccess = function () {
        $modalInstance.close();
      };

    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 * @author Sascha Friedrich
 * @author Christoph Suhren
 */

(function () {
  'use strict';
  angular.module('tatooine').controller('MyProjectsLightboxController', [
    '$scope', '$log', '$modalInstance', 'Utils', 'FileHandleService', 'ProjectService', 'ProductService', 'MessageService',
    function ($scope, $log, $modalInstance, Utils, FileHandleService, ProjectService, ProductService, MessageService) {
      $scope.modal = {};
      $scope.modal.header = MessageService.getMessage('myProjects.dialog.header');
      $scope.modal.text = MessageService.getMessage('myProjects.dialog.description');

      $scope.close = function () {
        $modalInstance.dismiss('cancel');
      };

    }
  ]);
})
();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 *
 * @author Sascha Friedrich
 * @author Christoph Suhren
 */

(function () {
  'use strict';
  angular.module('tatooine').controller('SaveProjectChoiceLightboxController', [
    '$scope', '$log', '$modalInstance', 'passThrough',
    function ($scope, $log, $modalInstance, passThrough) {

      $scope.modal = {};
      $scope.modal.header = passThrough.header;
      $scope.modal.text = passThrough.text;

      $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
      };

      $scope.setSaveProject = function (trueOrFalse) {
        var response = {keepProject: trueOrFalse};
        $log.debug('dialog response', response);
        $modalInstance.close(response);
      };
    }
  ]);
})
();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 * @author Sascha Friedrich
 * @author Christoph Suhren
 */

(function () {
  'use strict';
  angular.module('tatooine').controller('SaveProjectStatusLightboxController', [
    '$scope', '$log', '$modalInstance', 'passThrough', 'Utils', 'FileHandleService', 'NotificationService', 'ProjectService', 'MessageService', 'UploadService',
    function ($scope, $log, $modalInstance, passThrough, Utils, FileHandleService, NotificationService, ProjectService, MessageService, UploadService) {

      $scope.modal = {};
      $scope.modal.header = MessageService.getMessage('saveStatus.header');
      $scope.modal.text = MessageService.getMessage('saveStatus.waitInfo');
      $scope.modal.infoText = passThrough.infoText;

      $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
      };

      $scope.getTotalFilesToTransfer = function () {
        return $scope.getNumberOfTransferredFiles() + $scope.getNumberOfRemainingFiles();
      };

      $scope.getNumberOfRemainingFiles = function () {
        return UploadService.getRemainingFileHandles().length;
      };

      $scope.getNumberOfTransferredFiles = function () {
        return UploadService.getNumberOfUploadedFiles();
      };

      $scope.getUploadInProgressMessage = function () {
        var untransferredFileHandles = $scope.getNumberOfRemainingFiles();

        if (untransferredFileHandles > 0) {
          return MessageService.getMessage('leaveEditor.hintUploadInProgress', [untransferredFileHandles]);
        }
        return '';
      };

      var removeWatchUploadInProgress = $scope.$watch(function watchUploadInProgress() {
        return UploadService.getRemainingFileHandles().length > 0;
      }, function uploadInProgressChanged(newValue) {
        if (!newValue) {
          ProjectService.saveProject().then(function saveOk() {
              $modalInstance.close();
            }, function saveFailed() {
              $log.debug('save project failed');
              $scope.cancel();
            });
        }
      });
    }
  ]);
})
();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */
(function () {
  'use strict';
  angular.module('tatooine').controller('ClipartSelectionController', [
    '$scope', '$log', '$timeout', 'AppConstants', 'AppValues', 'EventConstants', 'OperatorService', 'ClipartService', 'BackgroundItemTemplateFactory', 'ProjectService', 'DeviceDetectionService',
    function ($scope, $log, $timeout, AppConstants, AppValues, EventConstants, OperatorService, ClipartService, BackgroundItemTemplateFactory, ProjectService, DeviceDetectionService) {

      var MIN_ITEMS_TO_LOAD = 20;

      var initialize = function () {
        $scope.categorySelectionVisible = false;
        $scope.data = {
          clipartItemTemplates: [],
          numberOfLoadedCliparts: 0,
          selectedClipartItemTemplate: null,
          itemWidth: 105,
          itemHeight: 105
        };

        $scope.categoryMap = {};
        ClipartService.getClipartCategoryMap().then(function ok(categoryMap) {
          $scope.categoryMap = categoryMap;
        });

        var container = angular.element('#clipartListContainer');
        container.on('scroll', function () {
          if (container.scrollLeft() > 100) {
            if (!allItemsLoaded()) {
              loadAllItemsRecursively();
            }
          }
        });

      };


      var removeWatchAppResourcesLoaded = $scope.$watch(function watchAppResourcesLoaded() {
        return AppValues.appResourcesLoaded;
      }, function onAppResourcesLoadedChanged(newValue) {
        if (newValue) {
          $scope.selectCategory(OperatorService.getDefaultDesignElementCategory('clipart'));
          removeWatchAppResourcesLoaded();
        }
      });

      var loadMoreItems = function (itemsToFetch) {
        for (var i = $scope.data.numberOfLoadedCliparts;
             i < $scope.data.numberOfLoadedCliparts + itemsToFetch && i < $scope.data.clipartItemTemplates.length; i++) {
          $scope.data.clipartItemTemplates[i].setInitialized(true);
        }
        $scope.data.numberOfLoadedCliparts += itemsToFetch;
      };

      var loadAllItemsRecursively = function () {
        if (allItemsLoaded()) {
          return;
        }
        $timeout(function delayed() {
          loadMoreItems(20);
          loadAllItemsRecursively();
        }, 500);
      };

      var allItemsLoaded = function() {
        return $scope.data.numberOfLoadedCliparts >= $scope.data.clipartItemTemplates.length;
      };

      $scope.selectTemplate = function (clipartItemTemplate) {
        if (clipartItemTemplate === $scope.data.selectedClipartItemTemplate) {
          $scope.data.selectedClipartItemTemplate = null;
          return;
        }
        $scope.data.selectedClipartItemTemplate = clipartItemTemplate;
      };

      $scope.toggleCategorySelection = function () {
        $scope.categorySelectionVisible = !$scope.categorySelectionVisible;
        if ($scope.categorySelectionVisible) {
          var selectedItembox = ProjectService.getSelectedDesignArea().getSelectedItemBox();
          if (selectedItembox) {
            selectedItembox.setSelected(false);
          }

        }
      };

      $scope.getClipartItemTemplates = function () {
        return $scope.data.clipartItemTemplates;
      };

      $scope.selectCategory = function (categoryId) {
        ClipartService.getClipartTemplatesByCategory(categoryId).then(
          function ok(clipartItemTemplates) {
            $scope.data.clipartItemTemplates = clipartItemTemplates;
            $scope.data.numberOfLoadedCliparts = 0;
            loadMoreItems(MIN_ITEMS_TO_LOAD);
            $scope.selectedCategory = categoryId;

            var clipartListContainer = angular.element('#clipartListContainer');
            if (clipartListContainer) {
              clipartListContainer.scrollLeft(0);
            }
          });
      };

      $scope.isIE = function () {
        return DeviceDetectionService.isBrowserIE();
      };

      initialize();
    }
  ]);
})();/*
 * Copyright (C) 2014, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 *
 * @author Sascha Friedrich
 * @author Frank Bruns
 */

(function () {
  'use strict';
  angular.module('tatooine').controller('ProductChangeConfirmDialogController', [
    '$scope', '$log', '$modalInstance', 'passThrough',
    function ($scope, $log, $modalInstance, passThrough) {

      $scope.data = {};
      $scope.data.currentPagesCount = passThrough.currentPagesCount;
      $scope.data.newMaxNumberOfPages = passThrough.newMaxNumberOfPages;
      $scope.data.numberOfPagesChanged = passThrough.numberOfPagesChanged;
      $scope.data.productDimensionsChanged = passThrough.productDimensionsChanged;
      $scope.data.onlyFullBackgroundOnEachPage = passThrough.onlyFullBackgroundOnEachPage;

      $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
      };

      $scope.confirmChangeProduct = function () {
        $modalInstance.close();
      };
    }
  ]);
})
();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */

/**
 *
 * @author Frank Bruns
 * @author Christoph Suhren
 */

(function () {
  'use strict';
  angular.module('tatooine').controller('ConfirmApplyColoredBorderSettingsController', [
    '$scope', '$log', '$modalInstance', 'dialogSettings',
    function ($scope, $log, $modalInstance, dialogSettings) {

      $scope.settings = {
        applyBorderWidth: dialogSettings.applyBorderWidth !== undefined ? dialogSettings.applyBorderWidth : true,
        applyBorderColor: dialogSettings.applyBorderColor !== undefined ? dialogSettings.applyBorderColor : true,
        borderColor: dialogSettings.borderColor,
        borderWidthMm: dialogSettings.borderWidthMm
      };

      $scope.cancel = function () {
        $modalInstance.dismiss();
      };

      $scope.apply = function () {
        $modalInstance.close($scope.settings);
      };
    }
  ]);
})
();/*
 * Copyright (C) 2015, CEWE Stiftung & Co. KGaA / Oldenburg / Germany
 *
 * This document contains trade secret data which is the property of CEWE Stiftung & Co. KGaA Information
 * contained herein may not be used, copied or disclosed in whole or part except as permitted by
 * written agreement from CEWE Stiftung & Co. KGaA.
 */


(function () {
  'use strict';
  /* global Caman */
  angular.module('tatooine').controller('PhotoEffectProgressLightboxController', [
    '$log', '$scope', '$modalInstance', 'PhotoEffectService', 'FileHandleService',
    function ($log, $scope, $modalInstance, PhotoEffectService, FileHandleService) {
      var caman = Caman;

      $scope.currentCamanJob = undefined;
      $scope.progress = undefined;
      $scope.totalJobs = undefined;
      $scope.jobsFinished = 0;


      $scope.effectsAndFilehandle = [];
      angular.forEach(PhotoEffectService.getEffectStore(), function (effect, fileHandleId) {
        $scope.effectsAndFilehandle.push({
          effect: effect,
          fileHandle: FileHandleService.getFileHandle(fileHandleId)
        });
      });
      PhotoEffectService.clearEffectStore();
      // Listen to all CamanJS instances
      caman.Event.listen('processStart', function (job) {
        if (job.totalJobs) {
          $scope.currentCamanJob = job.name + '(' + job.index + ' of ' + job.totalJobs + ')';
          $scope.totalJobs = job.totalJobs;
        }
      });

      caman.Event.listen('processComplete', function (job) {
        if ($scope.totalJobs) {
          $scope.jobsFinished++;
        }
      });

      caman.Event.listen('blockFinished', function (block) {
        if ($scope.totalJobs) {
          //SafeApply.do(function doApply() {
          $scope.progress = Math.round(($scope.jobsFinished * block.totalBlocks + block.blocksFinished) / (block.totalBlocks * $scope.totalJobs) * 100);
          //});
        }
      });

      $scope.getProgress = function () {
        return $scope.progress;
      };

      $scope.preparedPhotos = [];

    }
  ]);
})
();/*
 * $Id: KeepAlive.js 251110 2018-01-02 09:53:38Z mmoeller $
 * Copyright (C) 2005 Klaus Reimer <k.reimer@iplabs.de)
 * All rights reserved.
 */

/**
 * Keep Alive.
 * 
 * @author Klaus Reimer (k@ailis.de)
 * @version $Revision: 251110 $
 * 
 * @param interval
 *          The interval in seconds to send keep alive pings
 * @param count
 *          The number of pings to send
 * @param url
 *          The keep alive url
 */
function KeepAlive(interval, count, url) {
  this.interval = interval;
  this.count = count;
  this.url = url;
  this.iteration = 0;
//  this.callbackIteration = 'undefined';
//  this.iteration = 'undefined';

  // Prepare static access to this object to allow timeout events
  this.prepareStatic();

  // Start keep alive timer
  window.setTimeout("KeepAlive.handleTimeout(\"" + url + "\")", interval * 1000);
}

/**
 * Prepares the static access to this object. Because events like ontimeout() cannot handle object references it's needed to
 * access an object by an identifier (In this case the keep alive url).
 */
KeepAlive.prototype.prepareStatic = function() {
  // Initialize static cache if not already done
  if (!KeepAlive.instances) {
    KeepAlive.instances = new Object();
  }

  // Put current instance in cache. Using url as key
  KeepAlive.instances[this.url] = this;
};

/**
 * Sends the keep alive ping, decreases the ping counter and returns true if there are still pings left or false if no more pings
 * should be send.
 * 
 * @return If more pings must be send
 */
KeepAlive.prototype.ping = function() {
  if (this.script) {
    this.script.parentNode.removeChild(this.script);
  }
  this.script = document.createElement('script');
  this.script.src = this.url + '?t=' + new Date().getTime();
  document.body.appendChild(this.script);
  this.count--;
  return this.count > 0;
};

/**
 * Set a callback method called after a successful keep alive request, e.g. for handling a tracking session
 */
KeepAlive.prototype.setCallback = function(callback, callEveryNthKeepAlive) {
  this.callback = callback;
  this.callbackIteration = callEveryNthKeepAlive;
};

/**
 * Static timeout handler. This handler is responsible for sending the keep alive requests.
 */
KeepAlive.handleTimeout = function(url) {
  var o;

  o = KeepAlive.instances[url];
  if (!o)
    return;
  if (o.ping()) {
    try {
      o.iteration++;
      if (typeof (o.callback) !== 'undefined') {
        if (typeof(o.callbackIteration) === 'undefined' || (o.iteration % o.callbackIteration == 0)) {          
          o.callback();
        }
      }
    } catch (ex) {
      if (console && console.log) {
        console.log(ex);
      }
    }
    window.setTimeout("KeepAlive.handleTimeout(\"" + url + "\")", o.interval * 1000);
  }
};/* $Id: */
/**
 * enable "no portlet mode" for MyFaces so that all viewState hidden input fields will be updated
 * see http://werpublogs.blogspot.de/2011/11/jsf-ajax-and-multiple-forms.html
 * 
 * Author: Michael Möller
 */
window.myfaces = window.myfaces || {};
myfaces.config = myfaces.config || {};
//set the config part
myfaces.config.no_portlet_env = true; 
