/*! * jQuery JavaScript Library v1.11.1 * 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: 2014-05-01T17:42Z */ (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.1", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // 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 return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 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 ) { var length = 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 v1.10.19 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-04-18 */ (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" + -(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 strundefined = typeof undefined, 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 if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[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 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 ); }; // 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 || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (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 && context.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 === 9 && 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 !== strundefined && 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, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // 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; // Support tests documentIsHTML = !isXML( doc ); // 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", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* 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; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // 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 !== strundefined && 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 !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && 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 div.innerHTML = "<select msallowclip=''><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("[msallowclip^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // 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"); } }); 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.call( sortInput, a ) - indexOf.call( 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.call( sortInput, a ) - indexOf.call( 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 !== strundefined && 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 + " " ).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.call( 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 ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { 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.call( 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.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; 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 // 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 ) { return elem.ownerDocument.defaultView.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 ); } // 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 fireGlobals = 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 }); }; }); // 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._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) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", 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; }; 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 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/ */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { // $.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/ */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { 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(); }); } }; }); return $.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/ */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./widget" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { var mouseHandled = false; $( document ).mouseup( function() { mouseHandled = false; }); return $.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 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/ */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./mouse", "./widget" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.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> </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 }; } }); })); /* Copyright (C) 2011 by Yehuda Katz 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. */ // lib/handlebars/browser-prefix.js var Handlebars = {}; (function(Handlebars, undefined) { ; // lib/handlebars/base.js Handlebars.VERSION = "1.0.0-rc.4"; Handlebars.COMPILER_REVISION = 3; Handlebars.REVISION_CHANGES = { 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it 2: '== 1.0.0-rc.3', 3: '>= 1.0.0-rc.4' }; Handlebars.helpers = {}; Handlebars.partials = {}; var toString = Object.prototype.toString, functionType = '[object Function]', objectType = '[object Object]'; Handlebars.registerHelper = function(name, fn, inverse) { if (toString.call(name) === objectType) { if (inverse || fn) { throw new Handlebars.Exception('Arg not supported with multiple helpers'); } Handlebars.Utils.extend(this.helpers, name); } else { if (inverse) { fn.not = inverse; } this.helpers[name] = fn; } }; Handlebars.registerPartial = function(name, str) { if (toString.call(name) === objectType) { Handlebars.Utils.extend(this.partials, name); } else { this.partials[name] = str; } }; Handlebars.registerHelper('helperMissing', function(arg) { if(arguments.length === 2) { return undefined; } else { throw new Error("Could not find property '" + arg + "'"); } }); Handlebars.registerHelper('blockHelperMissing', function(context, options) { var inverse = options.inverse || function() {}, fn = options.fn; var type = toString.call(context); if(type === functionType) { context = context.call(this); } if(context === true) { return fn(this); } else if(context === false || context == null) { return inverse(this); } else if(type === "[object Array]") { if(context.length > 0) { return Handlebars.helpers.each(context, options); } else { return inverse(this); } } else { return fn(context); } }); Handlebars.K = function() {}; Handlebars.createFrame = Object.create || function(object) { Handlebars.K.prototype = object; var obj = new Handlebars.K(); Handlebars.K.prototype = null; return obj; }; Handlebars.logger = { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, level: 3, methodMap: {0: 'debug', 1: 'info', 2: 'warn', 3: 'error'}, // can be overridden in the host environment log: function(level, obj) { if (Handlebars.logger.level <= level) { var method = Handlebars.logger.methodMap[level]; if (typeof console !== 'undefined' && console[method]) { console[method].call(console, obj); } } } }; Handlebars.log = function(level, obj) { Handlebars.logger.log(level, obj); }; Handlebars.registerHelper('each', function(context, options) { var fn = options.fn, inverse = options.inverse; var i = 0, ret = "", data; if (options.data) { data = Handlebars.createFrame(options.data); } if(context && typeof context === 'object') { if(context instanceof Array){ for(var j = context.length; i<j; i++) { if (data) { data.index = i; } ret = ret + fn(context[i], { data: data }); } } else { for(var key in context) { if(context.hasOwnProperty(key)) { if(data) { data.key = key; } ret = ret + fn(context[key], {data: data}); i++; } } } } if(i === 0){ ret = inverse(this); } return ret; }); Handlebars.registerHelper('if', function(context, options) { var type = toString.call(context); if(type === functionType) { context = context.call(this); } if(!context || Handlebars.Utils.isEmpty(context)) { return options.inverse(this); } else { return options.fn(this); } }); Handlebars.registerHelper('unless', function(context, options) { return Handlebars.helpers['if'].call(this, context, {fn: options.inverse, inverse: options.fn}); }); Handlebars.registerHelper('with', function(context, options) { if (!Handlebars.Utils.isEmpty(context)) return options.fn(context); }); Handlebars.registerHelper('log', function(context, options) { var level = options.data && options.data.level != null ? parseInt(options.data.level, 10) : 1; Handlebars.log(level, context); }); ; // lib/handlebars/utils.js var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; Handlebars.Exception = function(message) { var tmp = Error.prototype.constructor.apply(this, arguments); // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. for (var idx = 0; idx < errorProps.length; idx++) { this[errorProps[idx]] = tmp[errorProps[idx]]; } }; Handlebars.Exception.prototype = new Error(); // Build out our basic SafeString type Handlebars.SafeString = function(string) { this.string = string; }; Handlebars.SafeString.prototype.toString = function() { return this.string.toString(); }; var escape = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'", "`": "`" }; var badChars = /[&<>"'`]/g; var possible = /[&<>"'`]/; var escapeChar = function(chr) { return escape[chr] || "&"; }; Handlebars.Utils = { extend: function(obj, value) { for(var key in value) { if(value.hasOwnProperty(key)) { obj[key] = value[key]; } } }, escapeExpression: function(string) { // don't escape SafeStrings, since they're already safe if (string instanceof Handlebars.SafeString) { return string.toString(); } else if (string == null || string === false) { return ""; } // Force a string conversion as this will be done by the append regardless and // the regex test will do this transparently behind the scenes, causing issues if // an object's to string has escaped characters in it. string = string.toString(); if(!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); }, isEmpty: function(value) { if (!value && value !== 0) { return true; } else if(toString.call(value) === "[object Array]" && value.length === 0) { return true; } else { return false; } } }; ; // lib/handlebars/runtime.js Handlebars.VM = { template: function(templateSpec) { // Just add water var container = { escapeExpression: Handlebars.Utils.escapeExpression, invokePartial: Handlebars.VM.invokePartial, programs: [], program: function(i, fn, data) { var programWrapper = this.programs[i]; if(data) { programWrapper = Handlebars.VM.program(i, fn, data); } else if (!programWrapper) { programWrapper = this.programs[i] = Handlebars.VM.program(i, fn); } return programWrapper; }, programWithDepth: Handlebars.VM.programWithDepth, noop: Handlebars.VM.noop, compilerInfo: null }; return function(context, options) { options = options || {}; var result = templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data); var compilerInfo = container.compilerInfo || [], compilerRevision = compilerInfo[0] || 1, currentRevision = Handlebars.COMPILER_REVISION; if (compilerRevision !== currentRevision) { if (compilerRevision < currentRevision) { var runtimeVersions = Handlebars.REVISION_CHANGES[currentRevision], compilerVersions = Handlebars.REVISION_CHANGES[compilerRevision]; throw "Template was precompiled with an older version of Handlebars than the current runtime. "+ "Please update your precompiler to a newer version ("+runtimeVersions+") or downgrade your runtime to an older version ("+compilerVersions+")."; } else { // Use the embedded version info since the runtime doesn't know about this revision yet throw "Template was precompiled with a newer version of Handlebars than the current runtime. "+ "Please update your runtime to a newer version ("+compilerInfo[1]+")."; } } return result; }; }, programWithDepth: function(i, fn, data /*, $depth */) { var args = Array.prototype.slice.call(arguments, 3); var program = function(context, options) { options = options || {}; return fn.apply(this, [context, options.data || data].concat(args)); }; program.program = i; program.depth = args.length; return program; }, program: function(i, fn, data) { var program = function(context, options) { options = options || {}; return fn(context, options.data || data); }; program.program = i; program.depth = 0; return program; }, noop: function() { return ""; }, invokePartial: function(partial, name, context, helpers, partials, data) { var options = { helpers: helpers, partials: partials, data: data }; if(partial === undefined) { throw new Handlebars.Exception("The partial " + name + " could not be found"); } else if(partial instanceof Function) { return partial(context, options); } else if (!Handlebars.compile) { throw new Handlebars.Exception("The partial " + name + " could not be compiled when running in runtime-only mode"); } else { partials[name] = Handlebars.compile(partial, {data: data !== undefined}); return partials[name](context, options); } } }; Handlebars.template = Handlebars.VM.template; ; // lib/handlebars/browser-suffix.js })(Handlebars); ; /*! * jQuery Cookie Plugin v1.3.1 * https://github.com/carhartl/jquery-cookie * * Copyright 2013 Klaus Hartl * Released under the MIT license */ (function (factory) { if (typeof define === 'function' && define.amd && define.amd.jQuery) { // AMD. Register as anonymous module. define(['jquery'], factory); } else { // Browser globals. factory(jQuery); } }(function ($) { var pluses = /\+/g; function raw(s) { return s; } function decoded(s) { return decodeURIComponent(s.replace(pluses, ' ')); } function converted(s) { if (s.indexOf('"') === 0) { // This is a quoted cookie as according to RFC2068, unescape s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\'); } try { return config.json ? JSON.parse(s) : s; } catch(er) {} } var config = $.cookie = function (key, value, options) { // write if (value !== undefined) { options = $.extend({}, config.defaults, options); if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } value = config.json ? JSON.stringify(value) : String(value); return (document.cookie = [ encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // read var decode = config.raw ? raw : decoded; var cookies = document.cookie.split('; '); var result = key ? undefined : {}; for (var i = 0, l = cookies.length; i < l; i++) { var parts = cookies[i].split('='); var name = decode(parts.shift()); var cookie = decode(parts.join('=')); if (key && key === name) { result = converted(cookie); break; } if (!key) { result[name] = converted(cookie); } } return result; }; config.defaults = {}; $.removeCookie = function (key, options) { if ($.cookie(key) !== undefined) { $.cookie(key, '', $.extend(options, { expires: -1 })); return true; } return false; }; })); /** * jQuery Internationalization library * * Copyright (C) 2012 Santhosh Thottingal * * jquery.i18n is dual licensed GPLv2 or later and MIT. You don't have to do * anything special to choose one license or the other and you don't have to * notify anyone which license you are using. You are free to use * UniversalLanguageSelector in commercial projects as long as the copyright * header is left intact. See files GPL-LICENSE and MIT-LICENSE for details. * * @licence GNU General Public Licence 2.0 or later * @licence MIT License */ ( function ( $ ) { 'use strict'; var nav, slice = Array.prototype.slice; /** * @constructor * @param {Object} options */ var I18N = function ( options ) { // Load defaults this.options = $.extend( {}, I18N.defaults, options ); this.parser = this.options.parser; this.locale = this.options.locale; this.messageStore = this.options.messageStore; this.languages = {}; this.init(); }; I18N.prototype = { /** * Initialize by loading locales and setting up * String.prototype.toLocaleString and String.locale. */ init: function () { var i18n; i18n = this; i18n.messageStore.init( i18n.locale ); // Set locale of String environment String.locale = i18n.locale; // Override String.localeString method String.prototype.toLocaleString = function () { var localeParts, messageLocation, localePartIndex, value, locale, fallbackIndex; value = this.valueOf(); locale = i18n.locale; fallbackIndex = 0; while ( locale ) { // Iterate through locales starting at most-specific until // localization is found. As in fi-Latn-FI, fi-Latn and fi. localeParts = locale.toLowerCase().split( '-' ); localePartIndex = localeParts.length; do { var _locale = localeParts.slice( 0, localePartIndex ).join( '-' ); if ( i18n.options.messageLocationResolver ) { messageLocation = i18n.options.messageLocationResolver( _locale, value ); if ( messageLocation && ( !i18n.messageStore.isLoaded( _locale ,messageLocation ) ) ) { i18n.messageStore.load( messageLocation, _locale ); } } var message = i18n.messageStore.get( _locale, value ); if ( message ) { return message; } localePartIndex--; } while ( localePartIndex ); if ( locale === 'en' ) { break; } locale = ( $.i18n.fallbacks[i18n.locale] && $.i18n.fallbacks[i18n.locale][fallbackIndex] ) || i18n.options.fallbackLocale; i18n.log( 'Trying fallback locale for ' + i18n.locale + ': ' + locale ); fallbackIndex++; } // key not found return ''; }; }, /* * Destroy the i18n instance. */ destroy: function () { $.removeData( document, 'i18n' ); }, /** * General message loading API This can take a URL string for * the json formatted messages. * <code>load('path/to/all_localizations.json');</code> * * This can also load a localization file for a locale <code> * load('path/to/de-messages.json', 'de' ); * </code> * A data object containing message key- message translation mappings * can also be passed Eg: * <code> * load( { 'hello' : 'Hello' }, optionalLocale ); * </code> If the data argument is * null/undefined/false, * all cached messages for the i18n instance will get reset. * * @param {String|Object|null} data * @param {String} locale Language tag */ load: function ( data, locale ) { this.messageStore.load( data, locale ); }, log: function ( /* arguments */ ) { if ( window.console && $.i18n.debug ) { window.console.log.apply( window.console, arguments ); } }, /** * Does parameter and magic word substitution. * * @param {string} key Message key * @param {Array} parameters Message parameters * @return {string} */ parse: function ( key, parameters ) { var message = key.toLocaleString(); // FIXME: This changes the state of the I18N object, // should probably not change the 'this.parser' but just // pass it to the parser. this.parser.language = $.i18n.languages[$.i18n().locale] || $.i18n.languages['default']; if( message === '' ) { message = key; } return this.parser.parse( message, parameters ); } }; /** * Process a message from the $.I18N instance * for the current document, stored in jQuery.data(document). * * @param {string} key Key of the message. * @param {string} param1 [param...] Variadic list of parameters for {key}. * @return {string|$.I18N} Parsed message, or if no key was given * the instance of $.I18N is returned. */ $.i18n = function ( key, param1 ) { var parameters, i18n = $.data( document, 'i18n' ), options = typeof key === 'object' && key; // If the locale option for this call is different then the setup so far, // update it automatically. This doesn't just change the context for this // call but for all future call as well. // If there is no i18n setup yet, don't do this. It will be taken care of // by the `new I18N` construction below. // NOTE: It should only change language for this one call. // Then cache instances of I18N somewhere. if ( options && options.locale && i18n && i18n.locale !== options.locale ) { String.locale = i18n.locale = options.locale; } if ( !i18n ) { i18n = new I18N( options ); $.data( document, 'i18n', i18n ); } if ( typeof key === 'string' ) { if ( param1 !== undefined ) { parameters = slice.call( arguments, 1 ); } else { parameters = []; } return i18n.parse( key, parameters ); } else { // FIXME: remove this feature/bug. return i18n; } }; $.fn.i18n = function () { var i18n = $.data( document, 'i18n' ); String.locale = i18n.locale; if ( !i18n ) { i18n = new I18N( ); $.data( document, 'i18n', i18n ); } return this.each( function () { var $this = $( this ); if ( $this.data( 'i18n' ) ) { var messageKey = $this.data( 'i18n' ), message = messageKey.toLocaleString(); if ( message !== '' ) { $this.text( message ); } } else { $this.find( '[data-i18n]' ).i18n(); } } ); }; String.locale = String.locale || $( 'html' ).attr( 'lang' ); if ( !String.locale ) { if ( typeof window.navigator !== undefined ) { nav = window.navigator; String.locale = nav.language || nav.userLanguage || ''; } else { String.locale = ''; } } $.i18n.languages = {}; $.i18n.messageStore = $.i18n.messageStore || {}; $.i18n.parser = { // The default parser only handles variable substitution parse: function ( message, parameters ) { return message.replace( /\$(\d+)/g, function ( str, match ) { var index = parseInt( match, 10 ) - 1; return parameters[index] !== undefined ? parameters[index] : '$' + match; } ); }, emitter: {} }; $.i18n.debug = false; /* Static members */ I18N.defaults = { locale: String.locale, fallbackLocale: 'en', parser: $.i18n.parser, messageStore: $.i18n.messageStore, /* messageLocationResolver - should be a function taking language code as argument and * returning absolute or relative path to the localization file */ messageLocationResolver: null }; // Expose constructor $.I18N = I18N; }( jQuery ) ); /** * jQuery Internationalization library Message loading , parsing, retrieving utilities * * Copyright (C) 2012 Santhosh Thottingal * * jquery.i18n is dual licensed GPLv2 or later and MIT. You don't have to do anything special to * choose one license or the other and you don't have to notify anyone which license you are using. * You are free to use UniversalLanguageSelector in commercial projects as long as the copyright * header is left intact. See files GPL-LICENSE and MIT-LICENSE for details. * * @licence GNU General Public Licence 2.0 or later * @licence MIT License */ ( function ( $, window, undefined ) { 'use strict'; var MessageStore = function () { this.messages = {}; this.sources = {}; this.locale = String.locale; }; MessageStore.prototype = { /** * See https://github.com/wikimedia/jquery.i18n/wiki/Specification#wiki-Message_File_Loading * * @param locale */ init: function ( locale ) { var messageStore = this; messageStore.locale = locale; messageStore.log( 'initializing for ' + locale ); $( 'link' ).each( function ( index, element ) { var $link = $( element ), rel = ( $link.attr( 'rel' ) || '' ).toLowerCase().split( /\s+/ ); if ( $.inArray( 'localizations', rel ) !== -1 ) { // multiple localizations messageStore.load( $link.attr( 'href' ) ); } else if ( $.inArray( 'localization', rel ) !== -1 ) { // single localization messageStore.queue( ( $link.attr( 'hreflang' ) || '' ).toLowerCase(), $link.attr( 'href' ) ); } } ); }, /** * General message loading API This can take a URL string for * the json formatted messages. * <code>load('path/to/all_localizations.json');</code> * * This can also load a localization file for a locale <code> * load('path/to/de-messages.json', 'de' ); * </code> * A data object containing message key- message translation mappings * can also be passed Eg: * <code> * load( { 'hello' : 'Hello' }, optionalLocale ); * </code> If the data argument is * null/undefined/false, * all cached messages for the i18n instance will get reset. * * @param {String|Object|null} data * @param {String} locale Language tag */ load: function ( data, locale ) { var key = null, messageStore = this, hasOwn = Object.prototype.hasOwnProperty; if ( !data ) { // reset all localizations messageStore.log( 'Resetting for locale ' + locale ); messageStore.messages = {}; return; } if ( typeof data === 'string' ) { // This is a URL to the messages file. messageStore.log( 'Loading messages from: ' + data ); messageStore.jsonMessageLoader( data ).done( function ( localization, textStatus ) { messageStore.load( localization, locale ); messageStore.queue( locale, data ); messageStore.markLoaded( locale, data ); } ); } else { // Data is either a group of messages for {locale}, // or a group of languages with groups of messages inside. for ( key in data ) { if ( hasOwn.call( data, key ) ) { if ( locale ) { // Lazy-init the object if ( !messageStore.messages[locale] ) { messageStore.messages[locale] = {}; } // Update message object keys, // don't overwrite the entire object. messageStore.messages[locale][key] = data[key]; messageStore.log( '[' + locale + '][' + key + '] : ' + data[key] ); // No {locale} given, assume data is a group of languages, // call this function again for each langauge. } else { messageStore.load( data[key], key ); } } } } }, log: function ( /* arguments */ ) { if ( window.console && $.i18n.debug ) { window.console.log.apply( window.console, arguments ); } }, /** * Mark a message Location for a locale loaded * * @param locale * @param messageLocation */ markLoaded: function ( locale, messageLocation ) { var i, queue = this.sources[locale]; if ( !queue ) { this.queue( locale, messageLocation ); queue = this.sources[locale]; } this.sources[locale] = this.sources[locale] || []; for ( i = 0; i < queue.length; i++ ) { if ( queue[i].source.url === messageLocation ) { queue[i].source.loaded = true; return; } } }, /** * Register the message location for a locale, will be loaded when required * * @param locale * @param messageLocation */ queue: function ( locale, messageLocation ) { var i, queue = this.sources[locale]; this.sources[locale] = this.sources[locale] || []; if ( queue ) { for ( i = 0; i < queue.length; i++ ) { if ( queue[i].source.url === messageLocation ) { return; } } } this.log( 'Source for: ' + locale + ' is ' + messageLocation + ' registered' ); this.sources[locale].push( { source: { url: messageLocation, loaded: false } } ); }, /** * Load the messages from the source queue for the locale * * @param {String} locale */ loadFromQueue: function ( locale ) { var i, queue = this.sources[locale]; if ( queue ) { for ( i = 0; i < queue.length; i++ ) { if ( !queue[i].source.loaded ) { this.load( queue[i].source.url, locale ); this.sources[locale][i].source.loaded = true; } } } }, isLoaded: function ( locale, messageLocation ) { var i, sources = this.sources[locale], result = false; if ( sources ) { for ( i = 0; i < sources.length; i++ ) { if ( sources[i].source.url === messageLocation ) { result = true; } } } return result; }, jsonMessageLoader: function ( url ) { var messageStore = this; return $.ajax( { url: url, dataType: 'json', async: false // This is unfortunate. } ).fail( function ( jqxhr, settings, exception ) { messageStore.log( 'Error in loading messages from ' + url + ' Exception: ' + exception ); } ); }, /** * * @param locale * @param messageKey * @returns {Boolean} */ get: function ( locale, messageKey ) { // load locale if not loaded if ( !this.messages[locale] ) { this.loadFromQueue( locale ); } return this.messages[locale] && this.messages[locale][messageKey]; } }; $.extend( $.i18n.messageStore, new MessageStore() ); }( jQuery, window ) ); /** * jQuery Internationalization library * * Copyright (C) 2012 Santhosh Thottingal * * jquery.i18n is dual licensed GPLv2 or later and MIT. You don't have to do anything special to * choose one license or the other and you don't have to notify anyone which license you are using. * You are free to use UniversalLanguageSelector in commercial projects as long as the copyright * header is left intact. See files GPL-LICENSE and MIT-LICENSE for details. * * @licence GNU General Public Licence 2.0 or later * @licence MIT License */ ( function ( $, undefined ) { 'use strict'; $.i18n = $.i18n || {}; $.i18n.fallbacks = { 'ab': ['ru'], 'ace': ['id'], 'aln': ['sq'], // Not so standard - als is supposed to be Tosk Albanian, // but in Wikipedia it's used for a Germanic language. 'als': ['gsw', 'de'], 'an': ['es'], 'anp': ['hi'], 'arn': ['es'], 'arz': ['ar'], 'av': ['ru'], 'ay': ['es'], 'ba': ['ru'], 'bar': ['de'], 'bat-smg': ['sgs', 'lt'], 'bcc': ['fa'], 'be-x-old': ['be-tarask'], 'bh': ['bho'], 'bjn': ['id'], 'bm': ['fr'], 'bpy': ['bn'], 'bqi': ['fa'], 'bug': ['id'], 'cbk-zam': ['es'], 'ce': ['ru'], 'crh': ['crh-latn'], 'crh-cyrl': ['ru'], 'csb': ['pl'], 'cv': ['ru'], 'de-at': ['de'], 'de-ch': ['de'], 'de-formal': ['de'], 'dsb': ['de'], 'dtp': ['ms'], 'egl': ['it'], 'eml': ['it'], 'ff': ['fr'], 'fit': ['fi'], 'fiu-vro': ['vro', 'et'], 'frc': ['fr'], 'frp': ['fr'], 'frr': ['de'], 'fur': ['it'], 'gag': ['tr'], 'gan': ['gan-hant', 'zh-hant', 'zh-hans'], 'gan-hans': ['zh-hans'], 'gan-hant': ['zh-hant', 'zh-hans'], 'gl': ['pt'], 'glk': ['fa'], 'gn': ['es'], 'gsw': ['de'], 'hif': ['hif-latn'], 'hsb': ['de'], 'ht': ['fr'], 'ii': ['zh-cn', 'zh-hans'], 'inh': ['ru'], 'iu': ['ike-cans'], 'jut': ['da'], 'jv': ['id'], 'kaa': ['kk-latn', 'kk-cyrl'], 'kbd': ['kbd-cyrl'], 'khw': ['ur'], 'kiu': ['tr'], 'kk': ['kk-cyrl'], 'kk-arab': ['kk-cyrl'], 'kk-latn': ['kk-cyrl'], 'kk-cn': ['kk-arab', 'kk-cyrl'], 'kk-kz': ['kk-cyrl'], 'kk-tr': ['kk-latn', 'kk-cyrl'], 'kl': ['da'], 'ko-kp': ['ko'], 'koi': ['ru'], 'krc': ['ru'], 'ks': ['ks-arab'], 'ksh': ['de'], 'ku': ['ku-latn'], 'ku-arab': ['ckb'], 'kv': ['ru'], 'lad': ['es'], 'lb': ['de'], 'lbe': ['ru'], 'lez': ['ru'], 'li': ['nl'], 'lij': ['it'], 'liv': ['et'], 'lmo': ['it'], 'ln': ['fr'], 'ltg': ['lv'], 'lzz': ['tr'], 'mai': ['hi'], 'map-bms': ['jv', 'id'], 'mg': ['fr'], 'mhr': ['ru'], 'min': ['id'], 'mo': ['ro'], 'mrj': ['ru'], 'mwl': ['pt'], 'myv': ['ru'], 'mzn': ['fa'], 'nah': ['es'], 'nap': ['it'], 'nds': ['de'], 'nds-nl': ['nl'], 'nl-informal': ['nl'], 'no': ['nb'], 'os': ['ru'], 'pcd': ['fr'], 'pdc': ['de'], 'pdt': ['de'], 'pfl': ['de'], 'pms': ['it'], 'pt': ['pt-br'], 'pt-br': ['pt'], 'qu': ['es'], 'qug': ['qu', 'es'], 'rgn': ['it'], 'rmy': ['ro'], 'roa-rup': ['rup'], 'rue': ['uk', 'ru'], 'ruq': ['ruq-latn', 'ro'], 'ruq-cyrl': ['mk'], 'ruq-latn': ['ro'], 'sa': ['hi'], 'sah': ['ru'], 'scn': ['it'], 'sg': ['fr'], 'sgs': ['lt'], 'sli': ['de'], 'sr': ['sr-ec'], 'srn': ['nl'], 'stq': ['de'], 'su': ['id'], 'szl': ['pl'], 'tcy': ['kn'], 'tg': ['tg-cyrl'], 'tt': ['tt-cyrl', 'ru'], 'tt-cyrl': ['ru'], 'ty': ['fr'], 'udm': ['ru'], 'ug': ['ug-arab'], 'uk': ['ru'], 'vec': ['it'], 'vep': ['et'], 'vls': ['nl'], 'vmf': ['de'], 'vot': ['fi'], 'vro': ['et'], 'wa': ['fr'], 'wo': ['fr'], 'wuu': ['zh-hans'], 'xal': ['ru'], 'xmf': ['ka'], 'yi': ['he'], 'za': ['zh-hans'], 'zea': ['nl'], 'zh': ['zh-hans'], 'zh-classical': ['lzh'], 'zh-cn': ['zh-hans'], 'zh-hant': ['zh-hans'], 'zh-hk': ['zh-hant', 'zh-hans'], 'zh-min-nan': ['nan'], 'zh-mo': ['zh-hk', 'zh-hant', 'zh-hans'], 'zh-my': ['zh-sg', 'zh-hans'], 'zh-sg': ['zh-hans'], 'zh-tw': ['zh-hant', 'zh-hans'], 'zh-yue': ['yue'] }; }( jQuery ) ); /** * jQuery Internationalization library * * Copyright (C) 2012 Santhosh Thottingal * * jquery.i18n is dual licensed GPLv2 or later and MIT. You don't have to do * anything special to choose one license or the other and you don't have to * notify anyone which license you are using. You are free to use * UniversalLanguageSelector in commercial projects as long as the copyright * header is left intact. See files GPL-LICENSE and MIT-LICENSE for details. * * @licence GNU General Public Licence 2.0 or later * @licence MIT License */ ( function ( $ ) { 'use strict'; var MessageParser = function ( options ) { this.options = $.extend( {}, $.i18n.parser.defaults, options ); this.language = $.i18n.languages[String.locale] || $.i18n.languages['default']; this.emitter = $.i18n.parser.emitter; }; MessageParser.prototype = { constructor: MessageParser, simpleParse: function ( message, parameters ) { return message.replace( /\$(\d+)/g, function ( str, match ) { var index = parseInt( match, 10 ) - 1; return parameters[index] !== undefined ? parameters[index] : '$' + match; } ); }, parse: function ( message, replacements ) { if ( message.indexOf( '{{' ) < 0 ) { return this.simpleParse( message, replacements ); } this.emitter.language = $.i18n.languages[$.i18n().locale] || $.i18n.languages['default']; return this.emitter.emit( this.ast( message ), replacements ); }, ast: function ( message ) { var pos = 0; // Try parsers until one works, if none work return null function choice ( parserSyntax ) { return function () { var i, result; for ( i = 0; i < parserSyntax.length; i++ ) { result = parserSyntax[i](); if ( result !== null ) { return result; } } return null; }; } // Try several parserSyntax-es in a row. // All must succeed; otherwise, return null. // This is the only eager one. function sequence ( parserSyntax ) { var i, res, originalPos = pos, result = []; for ( i = 0; i < parserSyntax.length; i++ ) { res = parserSyntax[i](); if ( res === null ) { pos = originalPos; return null; } result.push( res ); } return result; } // Run the same parser over and over until it fails. // Must succeed a minimum of n times; otherwise, return null. function nOrMore ( n, p ) { return function () { var originalPos = pos, result = [], parsed = p(); while ( parsed !== null ) { result.push( parsed ); parsed = p(); } if ( result.length < n ) { pos = originalPos; return null; } return result; }; } // Helpers -- just make parserSyntax out of simpler JS builtin types function makeStringParser ( s ) { var len = s.length; return function () { var result = null; if ( message.substr( pos, len ) === s ) { result = s; pos += len; } return result; }; } function makeRegexParser ( regex ) { return function () { var matches = message.substr( pos ).match( regex ); if ( matches === null ) { return null; } pos += matches[0].length; return matches[0]; }; } var pipe = makeStringParser( '|' ); var colon = makeStringParser( ':' ); var backslash = makeStringParser( '\\' ); var anyCharacter = makeRegexParser( /^./ ); var dollar = makeStringParser( '$' ); var digits = makeRegexParser( /^\d+/ ); var regularLiteral = makeRegexParser( /^[^{}\[\]$\\]/ ); var regularLiteralWithoutBar = makeRegexParser( /^[^{}\[\]$\\|]/ ); var regularLiteralWithoutSpace = makeRegexParser( /^[^{}\[\]$\s]/ ); // There is a general pattern: // parse a thing; // if it worked, apply transform, // otherwise return null. // But using this as a combinator seems to cause problems // when combined with nOrMore(). // May be some scoping issue. function transform ( p, fn ) { return function () { var result = p(); return result === null ? null : fn( result ); }; } // Used to define "literals" within template parameters. The pipe // character is the parameter delimeter, so by default // it is not a literal in the parameter function literalWithoutBar () { var result = nOrMore( 1, escapedOrLiteralWithoutBar )(); return result === null ? null : result.join( '' ); } function literal () { var result = nOrMore( 1, escapedOrRegularLiteral )(); return result === null ? null : result.join( '' ); } function escapedLiteral () { var result = sequence( [ backslash, anyCharacter ] ); return result === null ? null : result[1]; } choice( [ escapedLiteral, regularLiteralWithoutSpace ] ); var escapedOrLiteralWithoutBar = choice( [ escapedLiteral, regularLiteralWithoutBar ] ); var escapedOrRegularLiteral = choice( [ escapedLiteral, regularLiteral ] ); function replacement () { var result = sequence( [ dollar, digits ] ); if ( result === null ) { return null; } return [ 'REPLACE', parseInt( result[1], 10 ) - 1 ]; } var templateName = transform( // see $wgLegalTitleChars // not allowing : due to the need to catch "PLURAL:$1" makeRegexParser( /^[ !"$&'()*,.\/0-9;=?@A-Z\^_`a-z~\x80-\xFF+\-]+/ ), function ( result ) { return result.toString(); } ); function templateParam () { var result = sequence( [ pipe, nOrMore( 0, paramExpression ) ] ); if ( result === null ) { return null; } var expr = result[1]; // use a "CONCAT" operator if there are multiple nodes, // otherwise return the first node, raw. return expr.length > 1 ? [ 'CONCAT' ].concat( expr ) : expr[0]; } function templateWithReplacement () { var result = sequence( [ templateName, colon, replacement ] ); return result === null ? null : [ result[0], result[2] ]; } function templateWithOutReplacement () { var result = sequence( [ templateName, colon, paramExpression ] ); return result === null ? null : [ result[0], result[2] ]; } var templateContents = choice( [ function () { var res = sequence( [ // templates can have placeholders for dynamic // replacement eg: {{PLURAL:$1|one car|$1 cars}} // or no placeholders eg: // {{GRAMMAR:genitive|{{SITENAME}}} choice( [ templateWithReplacement, templateWithOutReplacement ] ), nOrMore( 0, templateParam ) ] ); return res === null ? null : res[0].concat( res[1] ); }, function () { var res = sequence( [ templateName, nOrMore( 0, templateParam ) ] ); if ( res === null ) { return null; } return [ res[0] ].concat( res[1] ); } ] ); var openTemplate = makeStringParser( '{{' ); var closeTemplate = makeStringParser( '}}' ); function template () { var result = sequence( [ openTemplate, templateContents, closeTemplate ] ); return result === null ? null : result[1]; } var expression = choice( [ template, replacement, literal ] ); var paramExpression = choice( [ template, replacement, literalWithoutBar ] ); function start () { var result = nOrMore( 0, expression )(); if ( result === null ) { return null; } return [ 'CONCAT' ].concat( result ); } var result = start(); /* * For success, the pos must have gotten to the end of the input * and returned a non-null. * n.b. This is part of language infrastructure, so we do not throw an internationalizable message. */ if ( result === null || pos !== message.length ) { throw new Error( 'Parse error at position ' + pos.toString() + ' in input: ' + message ); } return result; } }; $.extend( $.i18n.parser, new MessageParser() ); }( jQuery ) ); /** * jQuery Internationalization library * * Copyright (C) 2012 Santhosh Thottingal * * jquery.i18n is dual licensed GPLv2 or later and MIT. You don't have to do * anything special to choose one license or the other and you don't have to * notify anyone which license you are using. You are free to use * UniversalLanguageSelector in commercial projects as long as the copyright * header is left intact. See files GPL-LICENSE and MIT-LICENSE for details. * * @licence GNU General Public Licence 2.0 or later * @licence MIT License */ ( function ( $ ) { 'use strict'; var MessageParserEmitter = function () { this.language = $.i18n.languages[String.locale] || $.i18n.languages['default']; }; MessageParserEmitter.prototype = { constructor: MessageParserEmitter, /** * (We put this method definition here, and not in prototype, to make * sure it's not overwritten by any magic.) Walk entire node structure, * applying replacements and template functions when appropriate * * @param {Mixed} node abstract syntax tree (top node or subnode) * @param {Array} replacements for $1, $2, ... $n * @return {Mixed} single-string node or array of nodes suitable for * jQuery appending. */ emit: function ( node, replacements ) { var ret, subnodes, operation, messageParserEmitter = this; switch ( typeof node ) { case 'string': case 'number': ret = node; break; case 'object': // node is an array of nodes subnodes = $.map( node.slice( 1 ), function ( n ) { return messageParserEmitter.emit( n, replacements ); } ); operation = node[0].toLowerCase(); if ( typeof messageParserEmitter[operation] === 'function' ) { ret = messageParserEmitter[operation]( subnodes, replacements ); } else { throw new Error( 'unknown operation "' + operation + '"' ); } break; case 'undefined': // Parsing the empty string (as an entire expression, or as a // paramExpression in a template) results in undefined // Perhaps a more clever parser can detect this, and return the // empty string? Or is that useful information? // The logical thing is probably to return the empty string here // when we encounter undefined. ret = ''; break; default: throw new Error( 'unexpected type in AST: ' + typeof node ); } return ret; }, /** * Parsing has been applied depth-first we can assume that all nodes * here are single nodes Must return a single node to parents -- a * jQuery with synthetic span However, unwrap any other synthetic spans * in our children and pass them upwards * * @param {Array} nodes Mixed, some single nodes, some arrays of nodes. * @return String */ concat: function ( nodes ) { var result = ''; $.each( nodes, function ( i, node ) { // strings, integers, anything else result += node; } ); return result; }, /** * Return escaped replacement of correct index, or string if * unavailable. Note that we expect the parsed parameter to be * zero-based. i.e. $1 should have become [ 0 ]. if the specified * parameter is not found return the same string (e.g. "$99" -> * parameter 98 -> not found -> return "$99" ) TODO throw error if * nodes.length > 1 ? * * @param {Array} nodes One element, integer, n >= 0 * @param {Array} replacements for $1, $2, ... $n * @return {string} replacement */ replace: function ( nodes, replacements ) { var index = parseInt( nodes[0], 10 ); if ( index < replacements.length ) { // replacement is not a string, don't touch! return replacements[index]; } else { // index not found, fallback to displaying variable return '$' + ( index + 1 ); } }, /** * Transform parsed structure into pluralization n.b. The first node may * be a non-integer (for instance, a string representing an Arabic * number). So convert it back with the current language's * convertNumber. * * @param {Array} nodes List [ {String|Number}, {String}, {String} ... ] * @return {String} selected pluralized form according to current * language. */ plural: function ( nodes ) { var count = parseFloat( this.language.convertNumber( nodes[0], 10 ) ), forms = nodes.slice( 1 ); return forms.length ? this.language.convertPlural( count, forms ) : ''; }, /** * Transform parsed structure into gender Usage * {{gender:gender|masculine|feminine|neutral}}. * * @param {Array} nodes List [ {String}, {String}, {String} , {String} ] * @return {String} selected gender form according to current language */ gender: function ( nodes ) { var gender = nodes[0], forms = nodes.slice( 1 ); return this.language.gender( gender, forms ); }, /** * Transform parsed structure into grammar conversion. Invoked by * putting {{grammar:form|word}} in a message * * @param {Array} nodes List [{Grammar case eg: genitive}, {String word}] * @return {String} selected grammatical form according to current * language. */ grammar: function ( nodes ) { var form = nodes[0], word = nodes[1]; return word && form && this.language.convertGrammar( word, form ); } }; $.extend( $.i18n.parser.emitter, new MessageParserEmitter() ); }( jQuery ) ); /*global pluralRuleParser */ ( function ( $ ) { 'use strict'; var language = { // CLDR plural rules generated using // http://i18ndata.appspot.com/cldr/tags/unconfirmed/supplemental/plurals?action=browse&depth=-1 // and compressed pluralRules: { gv: { one: 'n mod 10 in 1..2 or n mod 20 is 0' }, gu: { one: 'n is 1' }, rof: { one: 'n is 1' }, ga: { few: 'n in 3..6', many: 'n in 7..10', two: 'n is 2', one: 'n is 1' }, gl: { one: 'n is 1' }, lg: { one: 'n is 1' }, lb: { one: 'n is 1' }, xog: { one: 'n is 1' }, ln: { one: 'n in 0..1' }, lo: '', brx: { one: 'n is 1' }, tr: '', ts: { one: 'n is 1' }, tn: { one: 'n is 1' }, to: '', lt: { few: 'n mod 10 in 2..9 and n mod 100 not in 11..19', one: 'n mod 10 is 1 and n mod 100 not in 11..19' }, tk: { one: 'n is 1' }, th: '', ksb: { one: 'n is 1' }, te: { one: 'n is 1' }, ksh: { zero: 'n is 0', one: 'n is 1' }, fil: { one: 'n in 0..1' }, haw: { one: 'n is 1' }, kcg: { one: 'n is 1' }, ssy: { one: 'n is 1' }, yo: '', de: { one: 'n is 1' }, ko: '', da: { one: 'n is 1' }, dz: '', dv: { one: 'n is 1' }, guw: { one: 'n in 0..1' }, shi: { few: 'n in 2..10', one: 'n within 0..1' }, el: { one: 'n is 1' }, eo: { one: 'n is 1' }, en: { one: 'n is 1' }, ses: '', teo: { one: 'n is 1' }, ee: { one: 'n is 1' }, kde: '', fr: { one: 'n within 0..2 and n is not 2' }, eu: { one: 'n is 1' }, et: { one: 'n is 1' }, es: { one: 'n is 1' }, seh: { one: 'n is 1' }, ru: { few: 'n mod 10 in 2..4 and n mod 100 not in 12..14', many: 'n mod 10 is 0 or n mod 10 in 5..9 or n mod 100 in 11..14', one: 'n mod 10 is 1 and n mod 100 is not 11' }, kl: { one: 'n is 1' }, sms: { two: 'n is 2', one: 'n is 1' }, smn: { two: 'n is 2', one: 'n is 1' }, smj: { two: 'n is 2', one: 'n is 1' }, smi: { two: 'n is 2', one: 'n is 1' }, fy: { one: 'n is 1' }, rm: { one: 'n is 1' }, ro: { few: 'n is 0 OR n is not 1 AND n mod 100 in 1..19', one: 'n is 1' }, bn: { one: 'n is 1' }, sma: { two: 'n is 2', one: 'n is 1' }, be: { few: 'n mod 10 in 2..4 and n mod 100 not in 12..14', many: 'n mod 10 is 0 or n mod 10 in 5..9 or n mod 100 in 11..14', one: 'n mod 10 is 1 and n mod 100 is not 11' }, bg: { one: 'n is 1' }, ms: '', wa: { one: 'n in 0..1' }, ps: { one: 'n is 1' }, wo: '', bm: '', jv: '', bo: '', bh: { one: 'n in 0..1' }, kea: '', asa: { one: 'n is 1' }, cgg: { one: 'n is 1' }, br: { few: 'n mod 10 in 3..4,9 and n mod 100 not in 10..19,70..79,90..99', many: 'n mod 1000000 is 0 and n is not 0', two: 'n mod 10 is 2 and n mod 100 not in 12,72,92', one: 'n mod 10 is 1 and n mod 100 not in 11,71,91' }, bs: { few: 'n mod 10 in 2..4 and n mod 100 not in 12..14', many: 'n mod 10 is 0 or n mod 10 in 5..9 or n mod 100 in 11..14', one: 'n mod 10 is 1 and n mod 100 is not 11' }, ja: '', om: { one: 'n is 1' }, fa: '', vun: { one: 'n is 1' }, or: { one: 'n is 1' }, xh: { one: 'n is 1' }, nso: { one: 'n in 0..1' }, ca: { one: 'n is 1' }, cy: { few: 'n is 3', zero: 'n is 0', many: 'n is 6', two: 'n is 2', one: 'n is 1' }, cs: { few: 'n in 2..4', one: 'n is 1' }, zh: '', lv: { zero: 'n is 0', one: 'n mod 10 is 1 and n mod 100 is not 11' }, pt: { one: 'n is 1' }, wae: { one: 'n is 1' }, tl: { one: 'n in 0..1' }, chr: { one: 'n is 1' }, pa: { one: 'n is 1' }, ak: { one: 'n in 0..1' }, pl: { few: 'n mod 10 in 2..4 and n mod 100 not in 12..14', many: 'n is not 1 and n mod 10 in 0..1 or n mod 10 in 5..9 or n mod 100 in 12..14', one: 'n is 1' }, hr: { few: 'n mod 10 in 2..4 and n mod 100 not in 12..14', many: 'n mod 10 is 0 or n mod 10 in 5..9 or n mod 100 in 11..14', one: 'n mod 10 is 1 and n mod 100 is not 11' }, am: { one: 'n in 0..1' }, ti: { one: 'n in 0..1' }, hu: '', hi: { one: 'n in 0..1' }, jmc: { one: 'n is 1' }, ha: { one: 'n is 1' }, he: { one: 'n is 1' }, mg: { one: 'n in 0..1' }, fur: { one: 'n is 1' }, bem: { one: 'n is 1' }, ml: { one: 'n is 1' }, mo: { few: 'n is 0 OR n is not 1 AND n mod 100 in 1..19', one: 'n is 1' }, mn: { one: 'n is 1' }, mk: { one: 'n mod 10 is 1 and n is not 11' }, ur: { one: 'n is 1' }, bez: { one: 'n is 1' }, mt: { few: 'n is 0 or n mod 100 in 2..10', many: 'n mod 100 in 11..19', one: 'n is 1' }, uk: { few: 'n mod 10 in 2..4 and n mod 100 not in 12..14', many: 'n mod 10 is 0 or n mod 10 in 5..9 or n mod 100 in 11..14', one: 'n mod 10 is 1 and n mod 100 is not 11' }, mr: { one: 'n is 1' }, ta: { one: 'n is 1' }, my: '', sah: '', ve: { one: 'n is 1' }, af: { one: 'n is 1' }, vi: '', is: { one: 'n is 1' }, iu: { two: 'n is 2', one: 'n is 1' }, it: { one: 'n is 1' }, kn: '', ii: '', ar: { few: 'n mod 100 in 3..10', zero: 'n is 0', many: 'n mod 100 in 11..99', two: 'n is 2', one: 'n is 1' }, zu: { one: 'n is 1' }, saq: { one: 'n is 1' }, az: '', tzm: { one: 'n in 0..1 or n in 11..99' }, id: '', ig: '', pap: { one: 'n is 1' }, nl: { one: 'n is 1' }, nn: { one: 'n is 1' }, no: { one: 'n is 1' }, nah: { one: 'n is 1' }, nd: { one: 'n is 1' }, ne: { one: 'n is 1' }, ny: { one: 'n is 1' }, naq: { two: 'n is 2', one: 'n is 1' }, nyn: { one: 'n is 1' }, kw: { two: 'n is 2', one: 'n is 1' }, nr: { one: 'n is 1' }, tig: { one: 'n is 1' }, kab: { one: 'n within 0..2 and n is not 2' }, mas: { one: 'n is 1' }, rwk: { one: 'n is 1' }, kaj: { one: 'n is 1' }, lag: { zero: 'n is 0', one: 'n within 0..2 and n is not 0 and n is not 2' }, syr: { one: 'n is 1' }, kk: { one: 'n is 1' }, ff: { one: 'n within 0..2 and n is not 2' }, fi: { one: 'n is 1' }, fo: { one: 'n is 1' }, ka: '', gsw: { one: 'n is 1' }, ckb: { one: 'n is 1' }, ss: { one: 'n is 1' }, sr: { few: 'n mod 10 in 2..4 and n mod 100 not in 12..14', many: 'n mod 10 is 0 or n mod 10 in 5..9 or n mod 100 in 11..14', one: 'n mod 10 is 1 and n mod 100 is not 11' }, sq: { one: 'n is 1' }, sw: { one: 'n is 1' }, sv: { one: 'n is 1' }, km: '', st: { one: 'n is 1' }, sk: { few: 'n in 2..4', one: 'n is 1' }, sh: { few: 'n mod 10 in 2..4 and n mod 100 not in 12..14', many: 'n mod 10 is 0 or n mod 10 in 5..9 or n mod 100 in 11..14', one: 'n mod 10 is 1 and n mod 100 is not 11' }, so: { one: 'n is 1' }, sn: { one: 'n is 1' }, ku: { one: 'n is 1' }, sl: { few: 'n mod 100 in 3..4', two: 'n mod 100 is 2', one: 'n mod 100 is 1' }, sg: '', nb: { one: 'n is 1' }, se: { two: 'n is 2', one: 'n is 1' } }, /** * Plural form transformations, needed for some languages. * * @param count * integer Non-localized quantifier * @param forms * array List of plural forms * @return string Correct form for quantifier in this language */ convertPlural: function ( count, forms ) { var pluralRules, pluralFormIndex = 0; if ( !forms || forms.length === 0 ) { return ''; } pluralRules = this.pluralRules[$.i18n().locale]; if ( !pluralRules ) { // default fallback. return ( count === 1 ) ? forms[0] : forms[1]; } pluralFormIndex = this.getPluralForm( count, pluralRules ); pluralFormIndex = Math.min( pluralFormIndex, forms.length - 1 ); return forms[pluralFormIndex]; }, /** * For the number, get the plural for index * * @param number * @param pluralRules * @return plural form index */ getPluralForm: function ( number, pluralRules ) { var i, pluralForms = [ 'zero', 'one', 'two', 'few', 'many', 'other' ], pluralFormIndex = 0; for ( i = 0; i < pluralForms.length; i++ ) { if ( pluralRules[pluralForms[i]] ) { if ( pluralRuleParser( pluralRules[pluralForms[i]], number ) ) { return pluralFormIndex; } pluralFormIndex++; } } return pluralFormIndex; }, /** * Converts a number using digitTransformTable. * * @param {number} num Value to be converted * @param {boolean} integer Convert the return value to an integer */ 'convertNumber': function ( num, integer ) { var tmp, item, i, transformTable, numberString, convertedNumber; // Set the target Transform table: transformTable = this.digitTransformTable( $.i18n().locale ); numberString = '' + num; convertedNumber = ''; if ( !transformTable ) { return num; } // Check if the restore to Latin number flag is set: if ( integer ) { if ( parseFloat( num, 10 ) === num ) { return num; } tmp = []; for ( item in transformTable ) { tmp[transformTable[item]] = item; } transformTable = tmp; } for ( i = 0; i < numberString.length; i++ ) { if ( transformTable[numberString[i]] ) { convertedNumber += transformTable[numberString[i]]; } else { convertedNumber += numberString[i]; } } return integer ? parseFloat( convertedNumber, 10 ) : convertedNumber; }, /** * Grammatical transformations, needed for inflected languages. * Invoked by putting {{grammar:form|word}} in a message. * Override this method for languages that need special grammar rules * applied dynamically. * * @param word {String} * @param form {String} * @return {String} */ convertGrammar: function ( word, form ) { return word; }, /** * Provides an alternative text depending on specified gender. Usage * {{gender:[gender|user object]|masculine|feminine|neutral}}. If second * or third parameter are not specified, masculine is used. * * These details may be overriden per language. * * @param gender * string male, female, or anything else for neutral. * @param forms * array List of gender forms * * @return string */ 'gender': function ( gender, forms ) { if ( !forms || forms.length === 0 ) { return ''; } while ( forms.length < 2 ) { forms.push( forms[forms.length - 1] ); } if ( gender === 'male' ) { return forms[0]; } if ( gender === 'female' ) { return forms[1]; } return ( forms.length === 3 ) ? forms[2] : forms[0]; }, /** * Get the digit transform table for the given language * See http://cldr.unicode.org/translation/numbering-systems * @param language * @returns {Array|boolean} List of digits in the passed language or false * representation, or boolean false if there is no information. */ digitTransformTable: function ( language ) { var tables = { ar: '٠١٢٣٤٥٦٧٨٩', fa: '۰۱۲۳۴۵۶۷۸۹', ml: '൦൧൨൩൪൫൬൭൮൯', kn: '೦೧೨೩೪೫೬೭೮೯', lo: '໐໑໒໓໔໕໖໗໘໙', or: '୦୧୨୩୪୫୬୭୮୯', kh: '០១២៣៤៥៦៧៨៩', pa: '੦੧੨੩੪੫੬੭੮੯', gu: '૦૧૨૩૪૫૬૭૮૯', hi: '०१२३४५६७८९', my: '၀၁၂၃၄၅၆၇၈၉', ta: '௦௧௨௩௪௫௬௭௮௯', te: '౦౧౨౩౪౫౬౭౮౯', th: '๐๑๒๓๔๕๖๗๘๙', //FIXME use iso 639 codes bo: '༠༡༢༣༤༥༦༧༨༩' //FIXME use iso 639 codes }; if ( !tables[language] ) { return false; } return tables[language].split( '' ); } }; $.extend( $.i18n.languages, { 'default': language } ); }( jQuery ) ); /** * Bosnian (bosanski) language functions */ ( function ( $ ) { 'use strict'; $.i18n.languages.bs = $.extend( {}, $.i18n.languages['default'], { convertGrammar: function ( word, form ) { switch ( form ) { case 'instrumental': // instrumental word = 's ' + word; break; case 'lokativ': // locative word = 'o ' + word; break; } return word; } } ); }( jQuery ) ); /** * Lower Sorbian (Dolnoserbski) language functions */ ( function ( $ ) { 'use strict'; $.i18n.languages.dsb = $.extend( {}, $.i18n.languages['default'], { convertGrammar: function ( word, form ) { switch ( form ) { case 'instrumental': // instrumental word = 'z ' + word; break; case 'lokatiw': // lokatiw word = 'wo ' + word; break; } return word; } } ); }( jQuery ) ); /** * Finnish (Suomi) language functions * * @author Santhosh Thottingal */ ( function ( $ ) { 'use strict'; $.i18n.languages.fi = $.extend( {}, $.i18n.languages['default'], { convertGrammar: function ( word, form ) { // vowel harmony flag var aou = word.match( /[aou][^äöy]*$/i ), origWord = word; if ( word.match( /wiki$/i ) ) { aou = false; } // append i after final consonant if ( word.match( /[bcdfghjklmnpqrstvwxz]$/i ) ) { word += 'i'; } switch ( form ) { case 'genitive': word += 'n'; break; case 'elative': word += ( aou ? 'sta' : 'stä' ); break; case 'partitive': word += ( aou ? 'a' : 'ä' ); break; case 'illative': // Double the last letter and add 'n' word += word.substr( word.length - 1 ) + 'n'; break; case 'inessive': word += ( aou ? 'ssa' : 'ssä' ); break; default: word = origWord; break; } return word; } } ); }( jQuery ) ); /** * Irish (Gaeilge) language functions */ ( function ( $ ) { 'use strict'; $.i18n.languages.ga = $.extend( {}, $.i18n.languages['default'], { convertGrammar: function ( word, form ) { if ( form === 'ainmlae' ) { switch ( word ) { case 'an Domhnach': word = 'Dé Domhnaigh'; break; case 'an Luan': word = 'Dé Luain'; break; case 'an Mháirt': word = 'Dé Mháirt'; break; case 'an Chéadaoin': word = 'Dé Chéadaoin'; break; case 'an Déardaoin': word = 'Déardaoin'; break; case 'an Aoine': word = 'Dé hAoine'; break; case 'an Satharn': word = 'Dé Sathairn'; break; } } return word; } } ); }( jQuery ) ); /** * Hebrew (עברית) language functions */ ( function ( $ ) { 'use strict'; $.i18n.languages.he = $.extend( {}, $.i18n.languages['default'], { convertGrammar: function ( word, form ) { switch ( form ) { case 'prefixed': case 'תחילית': // the same word in Hebrew // Duplicate prefixed "Waw", but only if it's not already double if ( word.substr( 0, 1 ) === 'ו' && word.substr( 0, 2 ) !== 'וו' ) { word = 'ו' + word; } // Remove the "He" if prefixed if ( word.substr( 0, 1 ) === 'ה' ) { word = word.substr( 1, word.length ); } // Add a hyphen (maqaf) before numbers and non-Hebrew letters if ( word.substr( 0, 1 ) < 'א' || word.substr( 0, 1 ) > 'ת' ) { word = '־' + word; } } return word; } } ); }( jQuery ) ); /** * Upper Sorbian (Hornjoserbsce) language functions */ ( function ( $ ) { 'use strict'; $.i18n.languages.hsb = $.extend( {}, $.i18n.languages['default'], { convertGrammar: function ( word, form ) { switch ( form ) { case 'instrumental': // instrumental word = 'z ' + word; break; case 'lokatiw': // lokatiw word = 'wo ' + word; break; } return word; } } ); }( jQuery ) ); /** * Hungarian language functions * * @author Santhosh Thottingal */ ( function ( $ ) { 'use strict'; $.i18n.languages.hu = $.extend( {}, $.i18n.languages['default'], { convertGrammar: function ( word, form ) { switch ( form ) { case 'rol': word += 'ról'; break; case 'ba': word += 'ba'; break; case 'k': word += 'k'; break; } return word; } } ); }( jQuery ) ); /** * Armenian (Հայերեն) language functions */ ( function ( $ ) { 'use strict'; $.i18n.languages.hy = $.extend( {}, $.i18n.languages['default'], { convertGrammar: function ( word, form ) { if ( form === 'genitive' ) { // սեռական հոլով if ( word.substr( -1 ) === 'ա' ) { word = word.substr( 0, word.length - 1 ) + 'այի'; } else if ( word.substr( -1 ) === 'ո' ) { word = word.substr( 0, word.length - 1 ) + 'ոյի'; } else if ( word.substr( -4 ) === 'գիրք' ) { word = word.substr( 0, word.length - 4 ) + 'գրքի'; } else { word = word + 'ի'; } } return word; } } ); }( jQuery ) ); /** * Latin (lingua Latina) language functions * * @author Santhosh Thottingal */ ( function ( $ ) { 'use strict'; $.i18n.languages.la = $.extend( {}, $.i18n.languages['default'], { convertGrammar: function ( word, form ) { switch ( form ) { case 'genitive': // only a few declensions, and even for those mostly the singular only word = word.replace( /u[ms]$/i, 'i' ); // 2nd declension singular word = word.replace( /ommunia$/i, 'ommunium' ); // 3rd declension neuter plural (partly) word = word.replace( /a$/i, 'ae' ); // 1st declension singular word = word.replace( /libri$/i, 'librorum' ); // 2nd declension plural (partly) word = word.replace( /nuntii$/i, 'nuntiorum' ); // 2nd declension plural (partly) word = word.replace( /tio$/i, 'tionis' ); // 3rd declension singular (partly) word = word.replace( /ns$/i, 'ntis' ); word = word.replace( /as$/i, 'atis' ); word = word.replace( /es$/i, 'ei' ); // 5th declension singular break; case 'accusative': // only a few declensions, and even for those mostly the singular only word = word.replace( /u[ms]$/i, 'um' ); // 2nd declension singular word = word.replace( /ommunia$/i, 'am' ); // 3rd declension neuter plural (partly) word = word.replace( /a$/i, 'ommunia' ); // 1st declension singular word = word.replace( /libri$/i, 'libros' ); // 2nd declension plural (partly) word = word.replace( /nuntii$/i, 'nuntios' );// 2nd declension plural (partly) word = word.replace( /tio$/i, 'tionem' ); // 3rd declension singular (partly) word = word.replace( /ns$/i, 'ntem' ); word = word.replace( /as$/i, 'atem' ); word = word.replace( /es$/i, 'em' ); // 5th declension singular break; case 'ablative': // only a few declensions, and even for those mostly the singular only word = word.replace( /u[ms]$/i, 'o' ); // 2nd declension singular word = word.replace( /ommunia$/i, 'ommunibus' ); // 3rd declension neuter plural (partly) word = word.replace( /a$/i, 'a' ); // 1st declension singular word = word.replace( /libri$/i, 'libris' ); // 2nd declension plural (partly) word = word.replace( /nuntii$/i, 'nuntiis' ); // 2nd declension plural (partly) word = word.replace( /tio$/i, 'tione' ); // 3rd declension singular (partly) word = word.replace( /ns$/i, 'nte' ); word = word.replace( /as$/i, 'ate' ); word = word.replace( /es$/i, 'e' ); // 5th declension singular break; } return word; } } ); }( jQuery ) ); /** * Ossetian (Ирон) language functions * * @author Santhosh Thottingal */ ( function ( $ ) { 'use strict'; $.i18n.languages.os = $.extend( {}, $.i18n.languages['default'], { convertGrammar: function ( word, form ) { // Ending for allative case var endAllative = 'мæ'; // Variable for 'j' beetwen vowels var jot = ''; // Variable for "-" for not Ossetic words var hyphen = ''; // Variable for ending var ending = ''; // Checking if the $word is in plural form if ( word.match( /тæ$/i ) ) { word = word.substring( 0, word.length - 1 ); endAllative = 'æм'; } // Works if word is in singular form. // Checking if word ends on one of the vowels: е, ё, и, о, ы, э, ю, // я. else if ( word.match( /[аæеёиоыэюя]$/i ) ) { jot = 'й'; } // Checking if word ends on 'у'. 'У' can be either consonant 'W' or // vowel 'U' in cyrillic Ossetic. // Examples: {{grammar:genitive|аунеу}} = аунеуы, // {{grammar:genitive|лæппу}} = лæппуйы. else if ( word.match( /у$/i ) ) { if ( !word.substring( word.length - 2, word.length - 1 ) .match( /[аæеёиоыэюя]$/i ) ) { jot = 'й'; } } else if ( !word.match( /[бвгджзйклмнопрстфхцчшщьъ]$/i ) ) { hyphen = '-'; } switch ( form ) { case 'genitive': ending = hyphen + jot + 'ы'; break; case 'dative': ending = hyphen + jot + 'æн'; break; case 'allative': ending = hyphen + endAllative; break; case 'ablative': if ( jot === 'й' ) { ending = hyphen + jot + 'æ'; } else { ending = hyphen + jot + 'æй'; } break; case 'superessive': ending = hyphen + jot + 'ыл'; break; case 'equative': ending = hyphen + jot + 'ау'; break; case 'comitative': ending = hyphen + 'имæ'; break; } return word + ending; } } ); }( jQuery ) ); /** * Russian (Русский) language functions */ ( function ( $ ) { 'use strict'; $.i18n.languages.ru = $.extend( {}, $.i18n.languages['default'], { convertGrammar: function ( word, form ) { if ( form === 'genitive' ) { // родительный падеж if ( ( word.substr( word.length - 4 ) === 'вики' ) || ( word.substr( word.length - 4 ) === 'Вики' ) ) { // ... } else if ( word.substr( word.length - 1 ) === 'ь' ) { word = word.substr( 0, word.length - 1 ) + 'я'; } else if ( word.substr( word.length - 2 ) === 'ия' ) { word = word.substr( 0, word.length - 2 ) + 'ии'; } else if ( word.substr( word.length - 2 ) === 'ка' ) { word = word.substr( 0, word.length - 2 ) + 'ки'; } else if ( word.substr( word.length - 2 ) === 'ти' ) { word = word.substr( 0, word.length - 2 ) + 'тей'; } else if ( word.substr( word.length - 2 ) === 'ды' ) { word = word.substr( 0, word.length - 2 ) + 'дов'; } else if ( word.substr( word.length - 3 ) === 'ник' ) { word = word.substr( 0, word.length - 3 ) + 'ника'; } } return word; } } ); }( jQuery ) ); /** * Slovenian (Slovenščina) language functions */ ( function ( $ ) { 'use strict'; $.i18n.languages.sl = $.extend( {}, $.i18n.languages['default'], { convertGrammar: function ( word, form ) { switch ( form ) { // locative case 'mestnik': word = 'o ' + word; break; // instrumental case 'orodnik': word = 'z ' + word; break; } return word; } } ); }( jQuery ) ); /** * Ukrainian (Українська) language functions */ ( function ( $ ) { 'use strict'; $.i18n.languages.uk = $.extend( {}, $.i18n.languages['default'], { convertGrammar: function ( word, form ) { switch ( form ) { case 'genitive': // родовий відмінок if ( ( word.substr( word.length - 4 ) === 'вікі' ) || ( word.substr( word.length - 4 ) === 'Вікі' ) ) { // ... } else if ( word.substr( word.length - 1 ) === 'ь' ) { word = word.substr( 0, word.length - 1 ) + 'я'; } else if ( word.substr( word.length - 2 ) === 'ія' ) { word = word.substr( 0, word.length - 2 ) + 'ії'; } else if ( word.substr( word.length - 2 ) === 'ка' ) { word = word.substr( 0, word.length - 2 ) + 'ки'; } else if ( word.substr( word.length - 2 ) === 'ти' ) { word = word.substr( 0, word.length - 2 ) + 'тей'; } else if ( word.substr( word.length - 2 ) === 'ды' ) { word = word.substr( 0, word.length - 2 ) + 'дов'; } else if ( word.substr( word.length - 3 ) === 'ник' ) { word = word.substr( 0, word.length - 3 ) + 'ника'; } break; case 'accusative': // знахідний відмінок if ( ( word.substr( word.length - 4 ) === 'вікі' ) || ( word.substr( word.length - 4 ) === 'Вікі' ) ) { // ... } else if ( word.substr( word.length - 2 ) === 'ія' ) { word = word.substr( 0, word.length - 2 ) + 'ію'; } break; } return word; } } ); }( jQuery ) ); /** * cldrpluralparser.js * A parser engine for CLDR plural rules. * * Copyright 2012 GPLV3+, Santhosh Thottingal * * @version 0.1.0-alpha * @source https://github.com/santhoshtr/CLDRPluralRuleParser * @author Santhosh Thottingal <santhosh.thottingal@gmail.com> * @author Timo Tijhof * @author Amir Aharoni */ /** * Evaluates a plural rule in CLDR syntax for a number * @param rule * @param number * @return true|false|null */ function pluralRuleParser(rule, number) { /* Syntax: see http://unicode.org/reports/tr35/#Language_Plural_Rules ----------------------------------------------------------------- condition = and_condition ('or' and_condition)* and_condition = relation ('and' relation)* relation = is_relation | in_relation | within_relation | 'n' <EOL> is_relation = expr 'is' ('not')? value in_relation = expr ('not')? 'in' range_list within_relation = expr ('not')? 'within' range_list expr = 'n' ('mod' value)? range_list = (range | value) (',' range_list)* value = digit+ digit = 0|1|2|3|4|5|6|7|8|9 range = value'..'value */ // Indicates current position in the rule as we parse through it. // Shared among all parsing functions below. var pos = 0; var whitespace = makeRegexParser(/^\s+/); var digits = makeRegexParser(/^\d+/); var _n_ = makeStringParser('n'); var _is_ = makeStringParser('is'); var _mod_ = makeStringParser('mod'); var _not_ = makeStringParser('not'); var _in_ = makeStringParser('in'); var _within_ = makeStringParser('within'); var _range_ = makeStringParser('..'); var _comma_ = makeStringParser(','); var _or_ = makeStringParser('or'); var _and_ = makeStringParser('and'); function debug() { /* console.log.apply(console, arguments);*/ } debug('pluralRuleParser', rule, number); // Try parsers until one works, if none work return null function choice(parserSyntax) { return function () { for (var i = 0; i < parserSyntax.length; i++) { var result = parserSyntax[i](); if (result !== null) { return result; } } return null; }; } // Try several parserSyntax-es in a row. // All must succeed; otherwise, return null. // This is the only eager one. function sequence(parserSyntax) { var originalPos = pos; var result = []; for (var i = 0; i < parserSyntax.length; i++) { var res = parserSyntax[i](); if (res === null) { pos = originalPos; return null; } result.push(res); } return result; } // Run the same parser over and over until it fails. // Must succeed a minimum of n times; otherwise, return null. function nOrMore(n, p) { return function () { var originalPos = pos; var result = []; var parsed = p(); while (parsed !== null) { result.push(parsed); parsed = p(); } if (result.length < n) { pos = originalPos; return null; } return result; }; } // Helpers -- just make parserSyntax out of simpler JS builtin types function makeStringParser(s) { var len = s.length; return function () { var result = null; if (rule.substr(pos, len) === s) { result = s; pos += len; } return result; }; } function makeRegexParser(regex) { return function () { var matches = rule.substr(pos).match(regex); if (matches === null) { return null; } pos += matches[0].length; return matches[0]; }; } function n() { var result = _n_(); if (result === null) { debug(" -- failed n"); return result; } result = parseInt(number, 10); debug(" -- passed n ", result); return result; } var expression = choice([mod, n]); function mod() { var result = sequence([n, whitespace, _mod_, whitespace, digits]); if (result === null) { debug(" -- failed mod"); return null; } debug(" -- passed mod"); return parseInt(result[0], 10) % parseInt(result[4], 10); } function not() { var result = sequence([whitespace, _not_]); if (result === null) { debug(" -- failed not"); return null; } else { return result[1]; } } function is() { var result = sequence([expression, whitespace, _is_, nOrMore(0, not), whitespace, digits]); if (result !== null) { debug(" -- passed is"); if (result[3][0] === 'not') { return result[0] !== parseInt(result[5], 10); } else { return result[0] === parseInt(result[5], 10); } } debug(" -- failed is"); return null; } function rangeList() { // range_list = (range | value) (',' range_list)* var result = sequence([choice([range, digits]), nOrMore(0, rangeTail)]); var resultList = []; if (result !== null) { resultList = resultList.concat(result[0], result[1][0]); return resultList; } debug(" -- failed rangeList"); return null; } function rangeTail() { // ',' range_list var result = sequence([_comma_, rangeList]); if (result !== null) { return result[1]; } debug(" -- failed rangeTail"); return null; } function range() { var result = sequence([digits, _range_, digits]); if (result !== null) { debug(" -- passed range"); var array = []; var left = parseInt(result[0], 10); var right = parseInt(result[2], 10); for ( i = left; i <= right; i++) { array.push(i); } return array; } debug(" -- failed range"); return null; } function _in() { // in_relation = expr ('not')? 'in' range_list var result = sequence([expression, nOrMore(0, not), whitespace, _in_, whitespace, rangeList]); if (result !== null) { debug(" -- passed _in"); var range_list = result[5]; for (var i = 0; i < range_list.length; i++) { if (parseInt(range_list[i], 10) === result[0]) { return (result[1][0] !== 'not'); } } return (result[1][0] === 'not'); } debug(" -- failed _in "); return null; } function within() { var result = sequence([expression, whitespace, _within_, whitespace, rangeList]); if (result !== null) { debug(" -- passed within "); var range_list = result[4]; return (parseInt( range_list[0],10 )<= result[0] && result[0] <= parseInt( range_list[1], 10)); } debug(" -- failed within "); return null; } var relation = choice([is, _in, within]); function and() { var result = sequence([relation, whitespace, _and_, whitespace, condition]); if (result) { debug(" -- passed and"); return result[0] && result[4]; } debug(" -- failed and"); return null; } function or() { var result = sequence([relation, whitespace, _or_, whitespace, condition]); if (result) { debug(" -- passed or"); return result[0] || result[4]; } debug(" -- failed or"); return null; } var condition = choice([and, or, relation]); function isInt(n) { return parseFloat(n) % 1 === 0; } function start() { if (!isInt(number)) { return false; } var result = condition(); return result; } var result = start(); /* * For success, the pos must have gotten to the end of the rule * and returned a non-null. * n.b. This is part of language infrastructure, so we do not throw an internationalizable message. */ if (result === null || pos !== rule.length) { // throw new Error("Parse error at position " + pos.toString() + " in input: " + rule + " result is " + result); } return result; } /* For module loaders, e.g. NodeJS, NPM */ if (typeof module !== 'undefined' && module.exports) { module.exports = pluralRuleParser; } ; // Underscore.js 1.8.2 // http://underscorejs.org // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind, nativeCreate = Object.create; // Naked function reference for surrogate-prototype-swapping. var Ctor = function(){}; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.8.2'; // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. var optimizeCb = function(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; case 2: return function(value, other) { return func.call(context, value, other); }; case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; }; // A mostly-internal function to generate callbacks that can be applied // to each element in a collection, returning the desired result — either // identity, an arbitrary callback, a property matcher, or a property accessor. var cb = function(value, context, argCount) { if (value == null) return _.identity; if (_.isFunction(value)) return optimizeCb(value, context, argCount); if (_.isObject(value)) return _.matcher(value); return _.property(value); }; _.iteratee = function(value, context) { return cb(value, context, Infinity); }; // An internal function for creating assigner functions. var createAssigner = function(keysFunc, undefinedOnly) { return function(obj) { var length = arguments.length; if (length < 2 || obj == null) return obj; for (var index = 1; index < length; index++) { var source = arguments[index], keys = keysFunc(source), l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; } } return obj; }; }; // An internal function for creating a new object that inherits from another. var baseCreate = function(prototype) { if (!_.isObject(prototype)) return {}; if (nativeCreate) return nativeCreate(prototype); Ctor.prototype = prototype; var result = new Ctor; Ctor.prototype = null; return result; }; // Helper for collection methods to determine whether a collection // should be iterated as an array or as an object // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; var isArrayLike = function(collection) { var length = collection && collection.length; return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; }; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. _.each = _.forEach = function(obj, iteratee, context) { iteratee = optimizeCb(iteratee, context); var i, length; if (isArrayLike(obj)) { for (i = 0, length = obj.length; i < length; i++) { iteratee(obj[i], i, obj); } } else { var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj; }; // Return the results of applying the iteratee to each element. _.map = _.collect = function(obj, iteratee, context) { iteratee = cb(iteratee, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, results = Array(length); for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; }; // Create a reducing function iterating left or right. function createReduce(dir) { // Optimized iterator function as using arguments.length // in the main function will deoptimize the, see #1991. function iterator(obj, iteratee, memo, keys, index, length) { for (; index >= 0 && index < length; index += dir) { var currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; } return function(obj, iteratee, memo, context) { iteratee = optimizeCb(iteratee, context, 4); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, index = dir > 0 ? 0 : length - 1; // Determine the initial value if none is provided. if (arguments.length < 3) { memo = obj[keys ? keys[index] : index]; index += dir; } return iterator(obj, iteratee, memo, keys, index, length); }; } // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. _.reduce = _.foldl = _.inject = createReduce(1); // The right-associative version of reduce, also known as `foldr`. _.reduceRight = _.foldr = createReduce(-1); // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var key; if (isArrayLike(obj)) { key = _.findIndex(obj, predicate, context); } else { key = _.findKey(obj, predicate, context); } if (key !== void 0 && key !== -1) return obj[key]; }; // Return all the elements that pass a truth test. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; predicate = cb(predicate, context); _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(cb(predicate)), context); }; // Determine whether all of the elements match a truth test. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; }; // Determine if at least one element in the object matches a truth test. // Aliased as `any`. _.some = _.any = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `includes` and `include`. _.contains = _.includes = _.include = function(obj, target, fromIndex) { if (!isArrayLike(obj)) obj = _.values(obj); return _.indexOf(obj, target, typeof fromIndex == 'number' && fromIndex) >= 0; }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { var func = isFunc ? method : value[method]; return func == null ? func : func.apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matcher(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matcher(attrs)); }; // Return the maximum element (or element-based computation). _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value > result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value < result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Shuffle a collection, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). _.shuffle = function(obj) { var set = isArrayLike(obj) ? obj : _.values(obj); var length = set.length; var shuffled = Array(length); for (var index = 0, rand; index < length; index++) { rand = _.random(0, index); if (rand !== index) shuffled[index] = shuffled[rand]; shuffled[rand] = set[index]; } return shuffled; }; // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (!isArrayLike(obj)) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; // Sort the object's values by a criterion produced by an iteratee. _.sortBy = function(obj, iteratee, context) { iteratee = cb(iteratee, context); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iteratee(value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, iteratee, context) { var result = {}; iteratee = cb(iteratee, context); _.each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, value, key) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, value, key) { if (_.has(result, key)) result[key]++; else result[key] = 1; }); // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (isArrayLike(obj)) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return isArrayLike(obj) ? obj.length : _.keys(obj).length; }; // Split a collection into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = function(obj, predicate, context) { predicate = cb(predicate, context); var pass = [], fail = []; _.each(obj, function(value, key, obj) { (predicate(value, key, obj) ? pass : fail).push(value); }); return [pass, fail]; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[0]; return _.initial(array, array.length - n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. _.last = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[array.length - 1]; return _.rest(array, Math.max(0, array.length - n)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, strict, startIndex) { var output = [], idx = 0; for (var i = startIndex || 0, length = input && input.length; i < length; i++) { var value = input[i]; if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { //flatten current level of array or arguments object if (!shallow) value = flatten(value, shallow, strict); var j = 0, len = value.length; output.length += len; while (j < len) { output[idx++] = value[j++]; } } else if (!strict) { output[idx++] = value; } } return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, false); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iteratee, context) { if (array == null) return []; if (!_.isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = cb(iteratee, context); var result = []; var seen = []; for (var i = 0, length = array.length; i < length; i++) { var value = array[i], computed = iteratee ? iteratee(value, i, array) : value; if (isSorted) { if (!i || seen !== computed) result.push(value); seen = computed; } else if (iteratee) { if (!_.contains(seen, computed)) { seen.push(computed); result.push(value); } } else if (!_.contains(result, value)) { result.push(value); } } return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(flatten(arguments, true, true)); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { if (array == null) return []; var result = []; var argsLength = arguments.length; for (var i = 0, length = array.length; i < length; i++) { var item = array[i]; if (_.contains(result, item)) continue; for (var j = 1; j < argsLength; j++) { if (!_.contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = flatten(arguments, true, true, 1); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function() { return _.unzip(arguments); }; // Complement of _.zip. Unzip accepts an array of arrays and groups // each array's elements on shared indices _.unzip = function(array) { var length = array && _.max(array, 'length').length || 0; var result = Array(length); for (var index = 0; index < length; index++) { result[index] = _.pluck(array, index); } return result; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { var result = {}; for (var i = 0, length = list && list.length; i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { var i = 0, length = array && array.length; if (typeof isSorted == 'number') { i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted; } else if (isSorted && length) { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } if (item !== item) { return _.findIndex(slice.call(array, i), _.isNaN); } for (; i < length; i++) if (array[i] === item) return i; return -1; }; _.lastIndexOf = function(array, item, from) { var idx = array ? array.length : 0; if (typeof from == 'number') { idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1); } if (item !== item) { return _.findLastIndex(slice.call(array, 0, idx), _.isNaN); } while (--idx >= 0) if (array[idx] === item) return idx; return -1; }; // Generator function to create the findIndex and findLastIndex functions function createIndexFinder(dir) { return function(array, predicate, context) { predicate = cb(predicate, context); var length = array != null && array.length; var index = dir > 0 ? 0 : length - 1; for (; index >= 0 && index < length; index += dir) { if (predicate(array[index], index, array)) return index; } return -1; }; } // Returns the first index on an array-like that passes a predicate test _.findIndex = createIndexFinder(1); _.findLastIndex = createIndexFinder(-1); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iteratee, context) { iteratee = cb(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = array.length; while (low < high) { var mid = Math.floor((low + high) / 2); if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = step || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }; // Function (ahem) Functions // ------------------ // Determines whether to execute a function as a constructor // or a normal function with the provided arguments var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); var self = baseCreate(sourceFunc.prototype); var result = sourceFunc.apply(self, args); if (_.isObject(result)) return result; return self; }; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); var args = slice.call(arguments, 2); var bound = function() { return executeBound(func, bound, context, this, args.concat(slice.call(arguments))); }; return bound; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder, allowing any combination of arguments to be pre-filled. _.partial = function(func) { var boundArgs = slice.call(arguments, 1); var bound = function() { var position = 0, length = boundArgs.length; var args = Array(length); for (var i = 0; i < length; i++) { args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i]; } while (position < arguments.length) args.push(arguments[position++]); return executeBound(func, bound, this, this, args); }; return bound; }; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = function(obj) { var i, length = arguments.length, key; if (length <= 1) throw new Error('bindAll must be passed function names'); for (i = 1; i < length; i++) { key = arguments[i]; obj[key] = _.bind(obj[key], obj); } return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = '' + (hasher ? hasher.apply(this, arguments) : key); if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = _.partial(_.delay, _, 1); // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a negated version of the passed-in predicate. _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; }; // Returns a function that will only be executed on and after the Nth call. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Returns a function that will only be executed up to (but not including) the Nth call. _.before = function(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } if (times <= 1) func = null; return memo; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = _.partial(_.before, 2); // Object Functions // ---------------- // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; function collectNonEnumProps(obj, keys) { var nonEnumIdx = nonEnumerableProps.length; var constructor = obj.constructor; var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto; // Constructor is a special case. var prop = 'constructor'; if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); while (nonEnumIdx--) { prop = nonEnumerableProps[nonEnumIdx]; if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { keys.push(prop); } } } // Retrieve the names of an object's own properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; // Retrieve all the property names of an object. _.allKeys = function(obj) { if (!_.isObject(obj)) return []; var keys = []; for (var key in obj) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Returns the results of applying the iteratee to each element of the object // In contrast to _.map it returns an object _.mapObject = function(obj, iteratee, context) { iteratee = cb(iteratee, context); var keys = _.keys(obj), length = keys.length, results = {}, currentKey; for (var index = 0; index < length; index++) { currentKey = keys[index]; results[currentKey] = iteratee(obj[currentKey], currentKey, obj); } return results; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = createAssigner(_.allKeys); // Assigns a given object with all the own properties in the passed-in object(s) // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) _.extendOwn = _.assign = createAssigner(_.keys); // Returns the first key on an object that passes a predicate test _.findKey = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = _.keys(obj), key; for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; if (predicate(obj[key], key, obj)) return key; } }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(object, oiteratee, context) { var result = {}, obj = object, iteratee, keys; if (obj == null) return result; if (_.isFunction(oiteratee)) { keys = _.allKeys(obj); iteratee = optimizeCb(oiteratee, context); } else { keys = flatten(arguments, false, false, 1); iteratee = function(value, key, obj) { return key in obj; }; obj = Object(obj); } for (var i = 0, length = keys.length; i < length; i++) { var key = keys[i]; var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } return result; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj, iteratee, context) { if (_.isFunction(iteratee)) { iteratee = _.negate(iteratee); } else { var keys = _.map(flatten(arguments, false, false, 1), String); iteratee = function(value, key) { return !_.contains(keys, key); }; } return _.pick(obj, iteratee, context); }; // Fill in a given object with default properties. _.defaults = createAssigner(_.allKeys, true); // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Returns whether an object has a given set of `key:value` pairs. _.isMatch = function(object, attrs) { var keys = _.keys(attrs), length = keys.length; if (object == null) return !length; var obj = Object(object); for (var i = 0; i < length; i++) { var key = keys[i]; if (attrs[key] !== obj[key] || !(key in obj)) return false; } return true; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return '' + a === '' + b; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; } var areArrays = className === '[object Array]'; if (!areArrays) { if (typeof a != 'object' || typeof b != 'object') return false; // Objects with different constructors are not equivalent, but `Object`s or `Array`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) && ('constructor' in a && 'constructor' in b)) { return false; } } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. // Initializing stack of traversed objects. // It's done here since we only need them for objects and arrays comparison. aStack = aStack || []; bStack = bStack || []; var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); // Recursively compare objects and arrays. if (areArrays) { // Compare array lengths to determine if a deep comparison is necessary. length = a.length; if (length !== b.length) return false; // Deep compare the contents, ignoring non-numeric properties. while (length--) { if (!eq(a[length], b[length], aStack, bStack)) return false; } } else { // Deep compare objects. var keys = _.keys(a), key; length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. if (_.keys(b).length !== length) return false; while (length--) { // Deep compare each member key = keys[length]; if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return true; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; return _.keys(obj).length === 0; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE < 9), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return _.has(obj, 'callee'); }; } // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, // IE 11 (#1621), and in Safari 8 (#1929). if (typeof /./ != 'function' && typeof Int8Array != 'object') { _.isFunction = function(obj) { return typeof obj == 'function' || false; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj !== +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iteratees. _.identity = function(value) { return value; }; // Predicate-generating functions. Often useful outside of Underscore. _.constant = function(value) { return function() { return value; }; }; _.noop = function(){}; _.property = function(key) { return function(obj) { return obj == null ? void 0 : obj[key]; }; }; // Generates a function for a given object that returns a given property. _.propertyOf = function(obj) { return obj == null ? function(){} : function(key) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of // `key:value` pairs. _.matcher = _.matches = function(attrs) { attrs = _.extendOwn({}, attrs); return function(obj) { return _.isMatch(obj, attrs); }; }; // Run a function **n** times. _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = optimizeCb(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var escapeMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`' }; var unescapeMap = _.invert(escapeMap); // Functions for escaping and unescaping strings to/from HTML interpolation. var createEscaper = function(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped var source = '(?:' + _.keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; _.escape = createEscaper(escapeMap); _.unescape = createEscaper(unescapeMap); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property, fallback) { var value = object == null ? void 0 : object[property]; if (value === void 0) { value = fallback; } return _.isFunction(value) ? value.call(object) : value; }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\u2028|\u2029/g; var escapeChar = function(match) { return '\\' + escapes[match]; }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. _.template = function(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escaper, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offest. return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; try { var render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; return template; }; // Add a "chain" function. Start chaining a wrapped Underscore object. _.chain = function(obj) { var instance = _(obj); instance._chain = true; return instance; }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(instance, obj) { return instance._chain ? _(obj).chain() : obj; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { _.each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result(this, func.apply(_, args)); }; }); }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; return result(this, obj); }; }); // Add all accessor Array functions to the wrapper. _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result(this, method.apply(this._wrapped, arguments)); }; }); // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; // Provide unwrapping proxy for some methods used in engine operations // such as arithmetic and JSON stringification. _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; _.prototype.toString = function() { return '' + this._wrapped; }; // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (typeof define === 'function' && define.amd) { define('underscore', [], function() { return _; }); } }.call(this)); //! moment.js //! version : 2.9.0 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = '2.9.0', // the global-scope this is NOT the global object in Node.js globalScope = (typeof global !== 'undefined' && (typeof window === 'undefined' || window === global.window)) ? global : this, oldGlobalMoment, round = Math.round, hasOwnProperty = Object.prototype.hasOwnProperty, i, YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, // internal storage for locale config files locales = {}, // extra moment internal properties (plugins register props here) momentProperties = [], // check for nodeJS hasModule = (typeof module !== 'undefined' && module && module.exports), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenDigits = /\d+/, // nonzero number of digits parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO separator) parseTokenOffsetMs = /[\+\-]?\d+/, // 1234567890123 parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 //strict parsing regexes parseTokenOneDigit = /\d/, // 0 - 9 parseTokenTwoDigits = /\d\d/, // 00 - 99 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{4}/, // 0000 - 9999 parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999 parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], ['GGGG-[W]WW', /\d{4}-W\d{2}/], ['YYYY-DDD', /\d{4}-\d{3}/] ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker '+10:00' > ['10', '00'] or '-1530' > ['-', '15', '30'] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', D : 'date', w : 'week', W : 'isoWeek', M : 'month', Q : 'quarter', y : 'year', DDD : 'dayOfYear', e : 'weekday', E : 'isoWeekday', gg: 'weekYear', GG: 'isoWeekYear' }, camelFunctions = { dayofyear : 'dayOfYear', isoweekday : 'isoWeekday', isoweek : 'isoWeek', weekyear : 'weekYear', isoweekyear : 'isoWeekYear' }, // format function strings formatFunctions = {}, // default relative time thresholds relativeTimeThresholds = { s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month M: 11 // months to year }, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.localeData().monthsShort(this, format); }, MMMM : function (format) { return this.localeData().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.localeData().weekdaysMin(this, format); }, ddd : function (format) { return this.localeData().weekdaysShort(this, format); }, dddd : function (format) { return this.localeData().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, YYYYYY : function () { var y = this.year(), sign = y >= 0 ? '+' : '-'; return sign + leftZeroFill(Math.abs(y), 6); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return leftZeroFill(this.weekYear(), 4); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return leftZeroFill(this.isoWeekYear(), 4); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.localeData().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.localeData().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return toInt(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(toInt(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, SSSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = this.utcOffset(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + ':' + leftZeroFill(toInt(a) % 60, 2); }, ZZ : function () { var a = this.utcOffset(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, x : function () { return this.valueOf(); }, X : function () { return this.unix(); }, Q : function () { return this.quarter(); } }, deprecations = {}, lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'], updateInProgress = false; // Pick the first defined of two or three arguments. dfl comes from // default. function dfl(a, b, c) { switch (arguments.length) { case 2: return a != null ? a : b; case 3: return a != null ? a : b != null ? b : c; default: throw new Error('Implement me'); } } function hasOwnProp(a, b) { return hasOwnProperty.call(a, b); } function defaultParsingFlags() { // We need to deep clone this object, and es5 standard is not very // helpful. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso: false }; } function printMsg(msg) { if (moment.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { console.warn('Deprecation warning: ' + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (firstTime) { printMsg(msg); firstTime = false; } return fn.apply(this, arguments); }, fn); } function deprecateSimple(name, msg) { if (!deprecations[name]) { printMsg(msg); deprecations[name] = true; } } function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.localeData().ordinal(func.call(this, a), period); }; } function monthDiff(a, b) { // difference in months var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), // b is in (anchor - 1 month, anchor + 1 month) anchor = a.clone().add(wholeMonthDiff, 'months'), anchor2, adjust; if (b - anchor < 0) { anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor - anchor2); } else { anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor2 - anchor); } return -(wholeMonthDiff + adjust); } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); function meridiemFixWrap(locale, hour, meridiem) { var isPm; if (meridiem == null) { // nothing to do return hour; } if (locale.meridiemHour != null) { return locale.meridiemHour(hour, meridiem); } else if (locale.isPM != null) { // Fallback isPm = locale.isPM(meridiem); if (isPm && hour < 12) { hour += 12; } if (!isPm && hour === 12) { hour = 0; } return hour; } else { // thie is not supposed to happen return hour; } } /************************************ Constructors ************************************/ function Locale() { } // Moment prototype object function Moment(config, skipOverflow) { if (skipOverflow !== false) { checkOverflow(config); } copyConfig(this, config); this._d = new Date(+config._d); // Prevent infinite loop in case updateOffset creates new moment // objects. if (updateInProgress === false) { updateInProgress = true; moment.updateOffset(this); updateInProgress = false; } } // Duration Constructor function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = moment.localeData(); this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (hasOwnProp(b, i)) { a[i] = b[i]; } } if (hasOwnProp(b, 'toString')) { a.toString = b.toString; } if (hasOwnProp(b, 'valueOf')) { a.valueOf = b.valueOf; } return a; } function copyConfig(to, from) { var i, prop, val; if (typeof from._isAMomentObject !== 'undefined') { to._isAMomentObject = from._isAMomentObject; } if (typeof from._i !== 'undefined') { to._i = from._i; } if (typeof from._f !== 'undefined') { to._f = from._f; } if (typeof from._l !== 'undefined') { to._l = from._l; } if (typeof from._strict !== 'undefined') { to._strict = from._strict; } if (typeof from._tzm !== 'undefined') { to._tzm = from._tzm; } if (typeof from._isUTC !== 'undefined') { to._isUTC = from._isUTC; } if (typeof from._offset !== 'undefined') { to._offset = from._offset; } if (typeof from._pf !== 'undefined') { to._pf = from._pf; } if (typeof from._locale !== 'undefined') { to._locale = from._locale; } if (momentProperties.length > 0) { for (i in momentProperties) { prop = momentProperties[i]; val = from[prop]; if (typeof val !== 'undefined') { to[prop] = val; } } } return to; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength, forceSign) { var output = '' + Math.abs(number), sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } return (sign ? (forceSign ? '+' : '') : '-') + output; } function positiveMomentsDifference(base, other) { var res = {milliseconds: 0, months: 0}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; other = makeAs(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).'); tmp = val; val = period; period = tmp; } val = typeof val === 'string' ? +val : val; dur = moment.duration(val, period); addOrSubtractDurationFromMoment(this, dur, direction); return this; }; } function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months; updateOffset = updateOffset == null ? true : updateOffset; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } if (days) { rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding); } if (months) { rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding); } if (updateOffset) { moment.updateOffset(mom, days || months); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase().replace(/(.)s$/, '$1'); units = unitAliases[units] || camelFunctions[lowered] || lowered; } return units; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (hasOwnProp(inputObject, prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeList(field) { var count, setter; if (field.indexOf('week') === 0) { count = 7; setter = 'day'; } else if (field.indexOf('month') === 0) { count = 12; setter = 'month'; } else { return; } moment[field] = function (format, index) { var i, getter, method = moment._locale[field], results = []; if (typeof format === 'number') { index = format; format = undefined; } getter = function (i) { var m = moment().utc().set(setter, i); return method.call(moment._locale, m, format || ''); }; if (index != null) { return getter(index); } else { for (i = 0; i < count; i++) { results.push(getter(i)); } return results; } }; } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } function weeksInYear(year, dow, doy) { return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week; } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function checkOverflow(m) { var overflow; if (m._a && m._pf.overflow === -2) { overflow = m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH : m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE : m._a[HOUR] < 0 || m._a[HOUR] > 24 || (m._a[HOUR] === 24 && (m._a[MINUTE] !== 0 || m._a[SECOND] !== 0 || m._a[MILLISECOND] !== 0)) ? HOUR : m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE : m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND : m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } } function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0 && m._pf.bigHour === undefined; } } return m._isValid; } function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return null; } function loadLocale(name) { var oldLocale = null; if (!locales[name] && hasModule) { try { oldLocale = moment.locale(); require('./locale/' + name); // because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales moment.locale(oldLocale); } catch (e) { } } return locales[name]; } // Return a moment from input, that is local/utc/utcOffset equivalent to // model. function makeAs(input, model) { var res, diff; if (model._isUTC) { res = model.clone(); diff = (moment.isMoment(input) || isDate(input) ? +input : +moment(input)) - (+res); // Use low-level api, because this fn is low-level api. res._d.setTime(+res._d + diff); moment.updateOffset(res, false); return res; } else { return moment(input).local(); } } /************************************ Locale ************************************/ extend(Locale.prototype, { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } // Lenient ordinal parsing accepts just a number in addition to // number + (possibly) stuff coming from _ordinalParseLenient. this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + /\d{1,2}/.source); }, _months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), months : function (m) { return this._months[m.month()]; }, _monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName, format, strict) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = moment.utc([2000, i]); if (strict && !this._longMonthsParse[i]) { this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); } if (!strict && !this._monthsParse[i]) { regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { return i; } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { return i; } else if (!strict && this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LTS : 'h:mm:ss A', LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY LT', LLLL : 'dddd, MMMM D, YYYY LT' }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom, now) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom, [now]) : output; }, _relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace('%d', number); }, _ordinal : '%d', _ordinalParse : /\d{1,2}/, preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }, firstDayOfWeek : function () { return this._week.dow; }, firstDayOfYear : function () { return this._week.doy; }, _invalidDate: 'Invalid date', invalidDate: function () { return this._invalidDate; } }); /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ''; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { var a, strict = config._strict; switch (token) { case 'Q': return parseTokenOneDigit; case 'DDDD': return parseTokenThreeDigits; case 'YYYY': case 'GGGG': case 'gggg': return strict ? parseTokenFourDigits : parseTokenOneToFourDigits; case 'Y': case 'G': case 'g': return parseTokenSignedNumber; case 'YYYYYY': case 'YYYYY': case 'GGGGG': case 'ggggg': return strict ? parseTokenSixDigits : parseTokenOneToSixDigits; case 'S': if (strict) { return parseTokenOneDigit; } /* falls through */ case 'SS': if (strict) { return parseTokenTwoDigits; } /* falls through */ case 'SSS': if (strict) { return parseTokenThreeDigits; } /* falls through */ case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord; case 'a': case 'A': return config._locale._meridiemParse; case 'x': return parseTokenOffsetMs; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'SSSS': return parseTokenDigits; case 'MM': case 'DD': case 'YY': case 'GG': case 'gg': case 'HH': case 'hh': case 'mm': case 'ss': case 'ww': case 'WW': return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits; case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': case 'w': case 'W': case 'e': case 'E': return parseTokenOneOrTwoDigits; case 'Do': return strict ? config._locale._ordinalParse : config._locale._ordinalParseLenient; default : a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i')); return a; } } function utcOffsetFromString(string) { string = string || ''; var possibleTzMatches = (string.match(parseTokenTimezone) || []), tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [], parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? minutes : -minutes; } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, datePartArray = config._a; switch (token) { // QUARTER case 'Q': if (input != null) { datePartArray[MONTH] = (toInt(input) - 1) * 3; } break; // MONTH case 'M' : // fall through to MM case 'MM' : if (input != null) { datePartArray[MONTH] = toInt(input) - 1; } break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = config._locale.monthsParse(input, token, config._strict); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[MONTH] = a; } else { config._pf.invalidMonth = input; } break; // DAY OF MONTH case 'D' : // fall through to DD case 'DD' : if (input != null) { datePartArray[DATE] = toInt(input); } break; case 'Do' : if (input != null) { datePartArray[DATE] = toInt(parseInt( input.match(/\d{1,2}/)[0], 10)); } break; // DAY OF YEAR case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { config._dayOfYear = toInt(input); } break; // YEAR case 'YY' : datePartArray[YEAR] = moment.parseTwoDigitYear(input); break; case 'YYYY' : case 'YYYYY' : case 'YYYYYY' : datePartArray[YEAR] = toInt(input); break; // AM / PM case 'a' : // fall through to A case 'A' : config._meridiem = input; // config._isPm = config._locale.isPM(input); break; // HOUR case 'h' : // fall through to hh case 'hh' : config._pf.bigHour = true; /* falls through */ case 'H' : // fall through to HH case 'HH' : datePartArray[HOUR] = toInt(input); break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[MINUTE] = toInt(input); break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[SECOND] = toInt(input); break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : case 'SSSS' : datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000); break; // UNIX OFFSET (MILLISECONDS) case 'x': config._d = new Date(toInt(input)); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; config._tzm = utcOffsetFromString(input); break; // WEEKDAY - human case 'dd': case 'ddd': case 'dddd': a = config._locale.weekdaysParse(input); // if we didn't get a weekday name, mark the date as invalid if (a != null) { config._w = config._w || {}; config._w['d'] = a; } else { config._pf.invalidWeekday = input; } break; // WEEK, WEEK DAY - numeric case 'w': case 'ww': case 'W': case 'WW': case 'd': case 'e': case 'E': token = token.substr(0, 1); /* falls through */ case 'gggg': case 'GGGG': case 'GGGGG': token = token.substr(0, 2); if (input) { config._w = config._w || {}; config._w[token] = toInt(input); } break; case 'gg': case 'GG': config._w = config._w || {}; config._w[token] = moment.parseTwoDigitYear(input); } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year); week = dfl(w.W, 1); weekday = dfl(w.E, 1); } else { dow = config._locale._week.dow; doy = config._locale._week.doy; weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year); week = dfl(w.w, 1); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < dow) { ++week; } } else if (w.e != null) { // local weekday -- counting starts from begining of week weekday = w.e + dow; } else { // default to begining of week weekday = dow; } } temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromConfig(config) { var i, date, input = [], currentDate, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = dfl(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse)) { config._pf._overflowDayOfYear = true; } date = makeUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } // Check for 24:00:00.000 if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) { config._nextDay = true; config._a[HOUR] = 0; } config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input); // Apply timezone offset from input. The actual utcOffset can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); } if (config._nextDay) { config._a[HOUR] = 24; } } function dateFromObject(config) { var normalizedInput; if (config._d) { return; } normalizedInput = normalizeObjectUnits(config._i); config._a = [ normalizedInput.year, normalizedInput.month, normalizedInput.day || normalizedInput.date, normalizedInput.hour, normalizedInput.minute, normalizedInput.second, normalizedInput.millisecond ]; dateFromConfig(config); } function currentDateArray(config) { var now = new Date(); if (config._useUTC) { return [ now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ]; } else { return [now.getFullYear(), now.getMonth(), now.getDate()]; } } // date from string and format string function makeDateFromStringAndFormat(config) { if (config._f === moment.ISO_8601) { parseISO(config); return; } config._a = []; config._pf.empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { config._pf.unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { config._pf.empty = false; } else { config._pf.unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { config._pf.unusedTokens.push(token); } } // add remaining unparsed input length to the string config._pf.charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { config._pf.unusedInput.push(string); } // clear _12h flag if hour is <= 12 if (config._pf.bigHour === true && config._a[HOUR] <= 12) { config._pf.bigHour = undefined; } // handle meridiem config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); dateFromConfig(config); checkOverflow(config); } function unescapeFormat(s) { return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; }); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function regexpEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { config._pf.invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = copyConfig({}, config); if (config._useUTC != null) { tempConfig._useUTC = config._useUTC; } tempConfig._pf = defaultParsingFlags(); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += tempConfig._pf.charsLeftOver; //or tokens currentScore += tempConfig._pf.unusedTokens.length * 10; tempConfig._pf.score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } // date from iso format function parseISO(config) { var i, l, string = config._i, match = isoRegex.exec(string); if (match) { config._pf.iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(string)) { // match[5] should be 'T' or undefined config._f = isoDates[i][0] + (match[6] || ' '); break; } } for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (string.match(parseTokenTimezone)) { config._f += 'Z'; } makeDateFromStringAndFormat(config); } else { config._isValid = false; } } // date from iso format or fallback function makeDateFromString(config) { parseISO(config); if (config._isValid === false) { delete config._isValid; moment.createFromInputFallback(config); } } function map(arr, fn) { var res = [], i; for (i = 0; i < arr.length; ++i) { res.push(fn(arr[i], i)); } return res; } function makeDateFromInput(config) { var input = config._i, matched; if (input === undefined) { config._d = new Date(); } else if (isDate(input)) { config._d = new Date(+input); } else if ((matched = aspNetJsonRegex.exec(input)) !== null) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = map(input.slice(0), function (obj) { return parseInt(obj, 10); }); dateFromConfig(config); } else if (typeof(input) === 'object') { dateFromObject(config); } else if (typeof(input) === 'number') { // from milliseconds config._d = new Date(input); } else { moment.createFromInputFallback(config); } } function makeDate(y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor doesn't accept years < 1970 if (y < 1970) { date.setFullYear(y); } return date; } function makeUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); if (y < 1970) { date.setUTCFullYear(y); } return date; } function parseWeekday(input, locale) { if (typeof input === 'string') { if (!isNaN(input)) { input = parseInt(input, 10); } else { input = locale.weekdaysParse(input); if (typeof input !== 'number') { return null; } } } return input; } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(posNegDuration, withoutSuffix, locale) { var duration = moment.duration(posNegDuration).abs(), seconds = round(duration.as('s')), minutes = round(duration.as('m')), hours = round(duration.as('h')), days = round(duration.as('d')), months = round(duration.as('M')), years = round(duration.as('y')), args = seconds < relativeTimeThresholds.s && ['s', seconds] || minutes === 1 && ['m'] || minutes < relativeTimeThresholds.m && ['mm', minutes] || hours === 1 && ['h'] || hours < relativeTimeThresholds.h && ['hh', hours] || days === 1 && ['d'] || days < relativeTimeThresholds.d && ['dd', days] || months === 1 && ['M'] || months < relativeTimeThresholds.M && ['MM', months] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = +posNegDuration > 0; args[4] = locale; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = moment(mom).add(daysToDayOfWeek, 'd'); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear; d = d === 0 ? 7 : d; weekday = weekday != null ? weekday : firstDayOfWeek; daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; return { year: dayOfYear > 0 ? year : year - 1, dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f, res; config._locale = config._locale || moment.localeData(config._l); if (input === null || (format === undefined && input === '')) { return moment.invalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (moment.isMoment(input)) { return new Moment(input, true); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } res = new Moment(config); if (res._nextDay) { // Adding is smart enough around DST res.add(1, 'd'); res._nextDay = undefined; } return res; } moment = function (input, format, locale, strict) { var c; if (typeof(locale) === 'boolean') { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._i = input; c._f = format; c._l = locale; c._strict = strict; c._isUTC = false; c._pf = defaultParsingFlags(); return makeMoment(c); }; moment.suppressDeprecationWarnings = false; moment.createFromInputFallback = deprecate( 'moment construction falls back to js Date. This is ' + 'discouraged and will be removed in upcoming major ' + 'release. Please refer to ' + 'https://github.com/moment/moment/issues/1407 for more info.', function (config) { config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return moment(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (moments[i][fn](res)) { res = moments[i]; } } return res; } moment.min = function () { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); }; moment.max = function () { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); }; // creating with utc moment.utc = function (input, format, locale, strict) { var c; if (typeof(locale) === 'boolean') { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._useUTC = true; c._isUTC = true; c._l = locale; c._i = input; c._f = format; c._strict = strict; c._pf = defaultParsingFlags(); return makeMoment(c).utc(); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, parseIso, diffRes; if (moment.isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoDurationRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; parseIso = function (inp) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; }; duration = { y: parseIso(match[2]), M: parseIso(match[3]), d: parseIso(match[4]), h: parseIso(match[5]), m: parseIso(match[6]), s: parseIso(match[7]), w: parseIso(match[8]) }; } else if (duration == null) {// checks for null or undefined duration = {}; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(moment(duration.from), moment(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (moment.isDuration(input) && hasOwnProp(input, '_locale')) { ret._locale = input._locale; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // constant that refers to the ISO standard moment.ISO_8601 = function () {}; // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. moment.momentProperties = momentProperties; // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. moment.updateOffset = function () {}; // This function allows you to set a threshold for relative time strings moment.relativeTimeThreshold = function (threshold, limit) { if (relativeTimeThresholds[threshold] === undefined) { return false; } if (limit === undefined) { return relativeTimeThresholds[threshold]; } relativeTimeThresholds[threshold] = limit; return true; }; moment.lang = deprecate( 'moment.lang is deprecated. Use moment.locale instead.', function (key, value) { return moment.locale(key, value); } ); // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. moment.locale = function (key, values) { var data; if (key) { if (typeof(values) !== 'undefined') { data = moment.defineLocale(key, values); } else { data = moment.localeData(key); } if (data) { moment.duration._locale = moment._locale = data; } } return moment._locale._abbr; }; moment.defineLocale = function (name, values) { if (values !== null) { values.abbr = name; if (!locales[name]) { locales[name] = new Locale(); } locales[name].set(values); // backwards compat for now: also set the locale moment.locale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } }; moment.langData = deprecate( 'moment.langData is deprecated. Use moment.localeData instead.', function (key) { return moment.localeData(key); } ); // returns locale data moment.localeData = function (key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return moment._locale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment || (obj != null && hasOwnProp(obj, '_isAMomentObject')); }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; for (i = lists.length - 1; i >= 0; --i) { makeList(lists[i]); } moment.normalizeUnits = function (units) { return normalizeUnits(units); }; moment.invalid = function (flags) { var m = moment.utc(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; }; moment.parseZone = function () { return moment.apply(null, arguments).parseZone(); }; moment.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; moment.isDate = isDate; /************************************ Moment Prototype ************************************/ extend(moment.fn = Moment.prototype, { clone : function () { return moment(this); }, valueOf : function () { return +this._d - ((this._offset || 0) * 60000); }, unix : function () { return Math.floor(+this / 1000); }, toString : function () { return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); }, toDate : function () { return this._offset ? new Date(+this) : this._d; }, toISOString : function () { var m = moment(this).utc(); if (0 < m.year() && m.year() <= 9999) { if ('function' === typeof Date.prototype.toISOString) { // native implementation is ~50x faster, use it when we can return this.toDate().toISOString(); } else { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { return isValid(this); }, isDSTShifted : function () { if (this._a) { return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0; } return false; }, parsingFlags : function () { return extend({}, this._pf); }, invalidAt: function () { return this._pf.overflow; }, utc : function (keepLocalTime) { return this.utcOffset(0, keepLocalTime); }, local : function (keepLocalTime) { if (this._isUTC) { this.utcOffset(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.subtract(this._dateUtcOffset(), 'm'); } } return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.localeData().postformat(output); }, add : createAdder(1, 'add'), subtract : createAdder(-1, 'subtract'), diff : function (input, units, asFloat) { var that = makeAs(input, this), zoneDiff = (that.utcOffset() - this.utcOffset()) * 6e4, anchor, diff, output, daysAdjust; units = normalizeUnits(units); if (units === 'year' || units === 'month' || units === 'quarter') { output = monthDiff(this, that); if (units === 'quarter') { output = output / 3; } else if (units === 'year') { output = output / 12; } } else { diff = this - that; output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function (time) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're locat/utc/offset // or not. var now = time || moment(), sod = makeAs(now, this).startOf('day'), diff = this.diff(sod, 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.localeData().calendar(format, this, moment(now))); }, isLeapYear : function () { return isLeapYear(this.year()); }, isDST : function () { return (this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } }, month : makeAccessor('Month', true), startOf : function (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.weekday(0); } else if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; }, endOf: function (units) { units = normalizeUnits(units); if (units === undefined || units === 'millisecond') { return this; } return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); }, isAfter: function (input, units) { var inputMs; units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); if (units === 'millisecond') { input = moment.isMoment(input) ? input : moment(input); return +this > +input; } else { inputMs = moment.isMoment(input) ? +input : +moment(input); return inputMs < +this.clone().startOf(units); } }, isBefore: function (input, units) { var inputMs; units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); if (units === 'millisecond') { input = moment.isMoment(input) ? input : moment(input); return +this < +input; } else { inputMs = moment.isMoment(input) ? +input : +moment(input); return +this.clone().endOf(units) < inputMs; } }, isBetween: function (from, to, units) { return this.isAfter(from, units) && this.isBefore(to, units); }, isSame: function (input, units) { var inputMs; units = normalizeUnits(units || 'millisecond'); if (units === 'millisecond') { input = moment.isMoment(input) ? input : moment(input); return +this === +input; } else { inputMs = +moment(input); return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units)); } }, min: deprecate( 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other < this ? this : other; } ), max: deprecate( 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other > this ? this : other; } ), zone : deprecate( 'moment().zone is deprecated, use moment().utcOffset instead. ' + 'https://github.com/moment/moment/issues/1779', function (input, keepLocalTime) { if (input != null) { if (typeof input !== 'string') { input = -input; } this.utcOffset(input, keepLocalTime); return this; } else { return -this.utcOffset(); } } ), // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. utcOffset : function (input, keepLocalTime) { var offset = this._offset || 0, localAdjust; if (input != null) { if (typeof input === 'string') { input = utcOffsetFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = this._dateUtcOffset(); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.add(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { addOrSubtractDurationFromMoment(this, moment.duration(input - offset, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; moment.updateOffset(this, true); this._changeInProgress = null; } } return this; } else { return this._isUTC ? offset : this._dateUtcOffset(); } }, isLocal : function () { return !this._isUTC; }, isUtcOffset : function () { return this._isUTC; }, isUtc : function () { return this._isUTC && this._offset === 0; }, zoneAbbr : function () { return this._isUTC ? 'UTC' : ''; }, zoneName : function () { return this._isUTC ? 'Coordinated Universal Time' : ''; }, parseZone : function () { if (this._tzm) { this.utcOffset(this._tzm); } else if (typeof this._i === 'string') { this.utcOffset(utcOffsetFromString(this._i)); } return this; }, hasAlignedHourOffset : function (input) { if (!input) { input = 0; } else { input = moment(input).utcOffset(); } return (this.utcOffset() - input) % 60 === 0; }, daysInMonth : function () { return daysInMonth(this.year(), this.month()); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); }, quarter : function (input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); }, weekYear : function (input) { var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year; return input == null ? year : this.add((input - year), 'y'); }, isoWeekYear : function (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add((input - year), 'y'); }, week : function (input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); }, weekday : function (input) { var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); }, isoWeekday : function (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, isoWeeksInYear : function () { return weeksInYear(this.year(), 1, 4); }, weeksInYear : function () { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); }, get : function (units) { units = normalizeUnits(units); return this[units](); }, set : function (units, value) { var unit; if (typeof units === 'object') { for (unit in units) { this.set(unit, units[unit]); } } else { units = normalizeUnits(units); if (typeof this[units] === 'function') { this[units](value); } } return this; }, // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. locale : function (key) { var newLocaleData; if (key === undefined) { return this._locale._abbr; } else { newLocaleData = moment.localeData(key); if (newLocaleData != null) { this._locale = newLocaleData; } return this; } }, lang : deprecate( 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) { if (key === undefined) { return this.localeData(); } else { return this.locale(key); } } ), localeData : function () { return this._locale; }, _dateUtcOffset : function () { // On Firefox.24 Date#getTimezoneOffset returns a floating point. // https://github.com/moment/moment/pull/1871 return -Math.round(this._d.getTimezoneOffset() / 15) * 15; } }); function rawMonthSetter(mom, value) { var dayOfMonth; // TODO: Move this out of here! if (typeof value === 'string') { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (typeof value !== 'number') { return mom; } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function rawGetter(mom, unit) { return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); } function rawSetter(mom, unit, value) { if (unit === 'Month') { return rawMonthSetter(mom, value); } else { return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } function makeAccessor(unit, keepTime) { return function (value) { if (value != null) { rawSetter(this, unit, value); moment.updateOffset(this, keepTime); return this; } else { return rawGetter(this, unit); } }; } moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false); moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false); moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false); // Setting the hour should keep the time, because the user explicitly // specified which hour he wants. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true); // moment.fn.month is defined separately moment.fn.date = makeAccessor('Date', true); moment.fn.dates = deprecate('dates accessor is deprecated. Use date instead.', makeAccessor('Date', true)); moment.fn.year = makeAccessor('FullYear', true); moment.fn.years = deprecate('years accessor is deprecated. Use year instead.', makeAccessor('FullYear', true)); // add plural methods moment.fn.days = moment.fn.day; moment.fn.months = moment.fn.month; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; moment.fn.quarters = moment.fn.quarter; // add aliased format methods moment.fn.toJSON = moment.fn.toISOString; // alias isUtc for dev-friendliness moment.fn.isUTC = moment.fn.isUtc; /************************************ Duration Prototype ************************************/ function daysToYears (days) { // 400 years have 146097 days (taking into account leap year rules) return days * 400 / 146097; } function yearsToDays (years) { // years * 365 + absRound(years / 4) - // absRound(years / 100) + absRound(years / 400); return years * 146097 / 400; } extend(moment.duration.fn = Duration.prototype, { _bubble : function () { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years = 0; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes = absRound(seconds / 60); data.minutes = minutes % 60; hours = absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); // Accurately convert days to years, assume start from year 0. years = absRound(daysToYears(days)); days -= absRound(yearsToDays(years)); // 30 days to a month // TODO (iskren): Use anchor date (like 1st Jan) to compute this. months += absRound(days / 30); days %= 30; // 12 months -> 1 year years += absRound(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; }, abs : function () { this._milliseconds = Math.abs(this._milliseconds); this._days = Math.abs(this._days); this._months = Math.abs(this._months); this._data.milliseconds = Math.abs(this._data.milliseconds); this._data.seconds = Math.abs(this._data.seconds); this._data.minutes = Math.abs(this._data.minutes); this._data.hours = Math.abs(this._data.hours); this._data.months = Math.abs(this._data.months); this._data.years = Math.abs(this._data.years); return this; }, weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6; }, humanize : function (withSuffix) { var output = relativeTime(this, !withSuffix, this.localeData()); if (withSuffix) { output = this.localeData().pastFuture(+this, output); } return this.localeData().postformat(output); }, add : function (input, val) { // supports only 2.0-style add(1, 's') or add(moment) var dur = moment.duration(input, val); this._milliseconds += dur._milliseconds; this._days += dur._days; this._months += dur._months; this._bubble(); return this; }, subtract : function (input, val) { var dur = moment.duration(input, val); this._milliseconds -= dur._milliseconds; this._days -= dur._days; this._months -= dur._months; this._bubble(); return this; }, get : function (units) { units = normalizeUnits(units); return this[units.toLowerCase() + 's'](); }, as : function (units) { var days, months; units = normalizeUnits(units); if (units === 'month' || units === 'year') { days = this._days + this._milliseconds / 864e5; months = this._months + daysToYears(days) * 12; return units === 'month' ? months : months / 12; } else { // handle milliseconds separately because of floating point math errors (issue #1867) days = this._days + Math.round(yearsToDays(this._months / 12)); switch (units) { case 'week': return days / 7 + this._milliseconds / 6048e5; case 'day': return days + this._milliseconds / 864e5; case 'hour': return days * 24 + this._milliseconds / 36e5; case 'minute': return days * 24 * 60 + this._milliseconds / 6e4; case 'second': return days * 24 * 60 * 60 + this._milliseconds / 1000; // Math.floor prevents floating point math errors here case 'millisecond': return Math.floor(days * 24 * 60 * 60 * 1000) + this._milliseconds; default: throw new Error('Unknown unit ' + units); } } }, lang : moment.fn.lang, locale : moment.fn.locale, toIsoString : deprecate( 'toIsoString() is deprecated. Please use toISOString() instead ' + '(notice the capitals)', function () { return this.toISOString(); } ), toISOString : function () { // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var years = Math.abs(this.years()), months = Math.abs(this.months()), days = Math.abs(this.days()), hours = Math.abs(this.hours()), minutes = Math.abs(this.minutes()), seconds = Math.abs(this.seconds() + this.milliseconds() / 1000); if (!this.asSeconds()) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (this.asSeconds() < 0 ? '-' : '') + 'P' + (years ? years + 'Y' : '') + (months ? months + 'M' : '') + (days ? days + 'D' : '') + ((hours || minutes || seconds) ? 'T' : '') + (hours ? hours + 'H' : '') + (minutes ? minutes + 'M' : '') + (seconds ? seconds + 'S' : ''); }, localeData : function () { return this._locale; }, toJSON : function () { return this.toISOString(); } }); moment.duration.fn.toString = moment.duration.fn.toISOString; function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } for (i in unitMillisecondFactors) { if (hasOwnProp(unitMillisecondFactors, i)) { makeDurationGetter(i.toLowerCase()); } } moment.duration.fn.asMilliseconds = function () { return this.as('ms'); }; moment.duration.fn.asSeconds = function () { return this.as('s'); }; moment.duration.fn.asMinutes = function () { return this.as('m'); }; moment.duration.fn.asHours = function () { return this.as('h'); }; moment.duration.fn.asDays = function () { return this.as('d'); }; moment.duration.fn.asWeeks = function () { return this.as('weeks'); }; moment.duration.fn.asMonths = function () { return this.as('M'); }; moment.duration.fn.asYears = function () { return this.as('y'); }; /************************************ Default Locale ************************************/ // Set default locale, other locale will inherit from English. moment.locale('en', { ordinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); /* EMBED_LOCALES */ /************************************ Exposing Moment ************************************/ function makeGlobal(shouldDeprecate) { /*global ender:false */ if (typeof ender !== 'undefined') { return; } oldGlobalMoment = globalScope.moment; if (shouldDeprecate) { globalScope.moment = deprecate( 'Accessing Moment through the global scope is ' + 'deprecated, and will be removed in an upcoming ' + 'release.', moment); } else { globalScope.moment = moment; } } // CommonJS module is defined if (hasModule) { module.exports = moment; } else if (typeof define === 'function' && define.amd) { define(function (require, exports, module) { if (module.config && module.config() && module.config().noGlobal === true) { // release the global variable globalScope.moment = oldGlobalMoment; } return moment; }); makeGlobal(true); } else { makeGlobal(); } }).call(this); // moment.js locale configuration // locale : german (de) // author : lluchs : https://github.com/lluchs // author: Menelion Elensúle: https://github.com/Oire (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory((typeof global !== 'undefined' ? global : this).moment); // node or other global } }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } return moment.defineLocale('de', { months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), monthsShort : 'Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), weekdaysShort : 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), longDateFormat : { LT: 'HH:mm', LTS: 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY LT', LLLL : 'dddd, D. MMMM YYYY LT' }, calendar : { sameDay: '[Heute um] LT [Uhr]', sameElse: 'L', nextDay: '[Morgen um] LT [Uhr]', nextWeek: 'dddd [um] LT [Uhr]', lastDay: '[Gestern um] LT [Uhr]', lastWeek: '[letzten] dddd [um] LT [Uhr]' }, relativeTime : { future : 'in %s', past : 'vor %s', s : 'ein paar Sekunden', m : processRelativeTime, mm : '%d Minuten', h : processRelativeTime, hh : '%d Stunden', d : processRelativeTime, dd : processRelativeTime, M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, ordinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); /* Copyright 2012 Igor Vaynberg Version: 3.5.0 Timestamp: Mon Jun 16 19:29:44 EDT 2014 This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU General Public License version 2 (the "GPL License"). You may choose either license to govern your use of this software only upon the condition that you accept all of the terms of either the Apache License or the GPL License. You may obtain a copy of the Apache License and the GPL License at: http://www.apache.org/licenses/LICENSE-2.0 http://www.gnu.org/licenses/gpl-2.0.html Unless required by applicable law or agreed to in writing, software distributed under the Apache License or the GPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Apache License and the GPL License for the specific language governing permissions and limitations under the Apache License and the GPL License. */ (function ($) { if(typeof $.fn.each2 == "undefined") { $.extend($.fn, { /* * 4-10 times faster .each replacement * use it carefully, as it overrides jQuery context of element on each iteration */ each2 : function (c) { var j = $([0]), i = -1, l = this.length; while ( ++i < l && (j.context = j[0] = this[i]) && c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object ); return this; } }); } })(jQuery); (function ($, undefined) { "use strict"; /*global document, window, jQuery, console */ if (window.Select2 !== undefined) { return; } var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer, lastMousePosition={x:0,y:0}, $document, scrollBarDimensions, KEY = { TAB: 9, ENTER: 13, ESC: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, SHIFT: 16, CTRL: 17, ALT: 18, PAGE_UP: 33, PAGE_DOWN: 34, HOME: 36, END: 35, BACKSPACE: 8, DELETE: 46, isArrow: function (k) { k = k.which ? k.which : k; switch (k) { case KEY.LEFT: case KEY.RIGHT: case KEY.UP: case KEY.DOWN: return true; } return false; }, isControl: function (e) { var k = e.which; switch (k) { case KEY.SHIFT: case KEY.CTRL: case KEY.ALT: return true; } if (e.metaKey) return true; return false; }, isFunctionKey: function (k) { k = k.which ? k.which : k; return k >= 112 && k <= 123; } }, MEASURE_SCROLLBAR_TEMPLATE = "<div class='select2-measure-scrollbar'></div>", DIACRITICS = {"\u24B6":"A","\uFF21":"A","\u00C0":"A","\u00C1":"A","\u00C2":"A","\u1EA6":"A","\u1EA4":"A","\u1EAA":"A","\u1EA8":"A","\u00C3":"A","\u0100":"A","\u0102":"A","\u1EB0":"A","\u1EAE":"A","\u1EB4":"A","\u1EB2":"A","\u0226":"A","\u01E0":"A","\u00C4":"A","\u01DE":"A","\u1EA2":"A","\u00C5":"A","\u01FA":"A","\u01CD":"A","\u0200":"A","\u0202":"A","\u1EA0":"A","\u1EAC":"A","\u1EB6":"A","\u1E00":"A","\u0104":"A","\u023A":"A","\u2C6F":"A","\uA732":"AA","\u00C6":"AE","\u01FC":"AE","\u01E2":"AE","\uA734":"AO","\uA736":"AU","\uA738":"AV","\uA73A":"AV","\uA73C":"AY","\u24B7":"B","\uFF22":"B","\u1E02":"B","\u1E04":"B","\u1E06":"B","\u0243":"B","\u0182":"B","\u0181":"B","\u24B8":"C","\uFF23":"C","\u0106":"C","\u0108":"C","\u010A":"C","\u010C":"C","\u00C7":"C","\u1E08":"C","\u0187":"C","\u023B":"C","\uA73E":"C","\u24B9":"D","\uFF24":"D","\u1E0A":"D","\u010E":"D","\u1E0C":"D","\u1E10":"D","\u1E12":"D","\u1E0E":"D","\u0110":"D","\u018B":"D","\u018A":"D","\u0189":"D","\uA779":"D","\u01F1":"DZ","\u01C4":"DZ","\u01F2":"Dz","\u01C5":"Dz","\u24BA":"E","\uFF25":"E","\u00C8":"E","\u00C9":"E","\u00CA":"E","\u1EC0":"E","\u1EBE":"E","\u1EC4":"E","\u1EC2":"E","\u1EBC":"E","\u0112":"E","\u1E14":"E","\u1E16":"E","\u0114":"E","\u0116":"E","\u00CB":"E","\u1EBA":"E","\u011A":"E","\u0204":"E","\u0206":"E","\u1EB8":"E","\u1EC6":"E","\u0228":"E","\u1E1C":"E","\u0118":"E","\u1E18":"E","\u1E1A":"E","\u0190":"E","\u018E":"E","\u24BB":"F","\uFF26":"F","\u1E1E":"F","\u0191":"F","\uA77B":"F","\u24BC":"G","\uFF27":"G","\u01F4":"G","\u011C":"G","\u1E20":"G","\u011E":"G","\u0120":"G","\u01E6":"G","\u0122":"G","\u01E4":"G","\u0193":"G","\uA7A0":"G","\uA77D":"G","\uA77E":"G","\u24BD":"H","\uFF28":"H","\u0124":"H","\u1E22":"H","\u1E26":"H","\u021E":"H","\u1E24":"H","\u1E28":"H","\u1E2A":"H","\u0126":"H","\u2C67":"H","\u2C75":"H","\uA78D":"H","\u24BE":"I","\uFF29":"I","\u00CC":"I","\u00CD":"I","\u00CE":"I","\u0128":"I","\u012A":"I","\u012C":"I","\u0130":"I","\u00CF":"I","\u1E2E":"I","\u1EC8":"I","\u01CF":"I","\u0208":"I","\u020A":"I","\u1ECA":"I","\u012E":"I","\u1E2C":"I","\u0197":"I","\u24BF":"J","\uFF2A":"J","\u0134":"J","\u0248":"J","\u24C0":"K","\uFF2B":"K","\u1E30":"K","\u01E8":"K","\u1E32":"K","\u0136":"K","\u1E34":"K","\u0198":"K","\u2C69":"K","\uA740":"K","\uA742":"K","\uA744":"K","\uA7A2":"K","\u24C1":"L","\uFF2C":"L","\u013F":"L","\u0139":"L","\u013D":"L","\u1E36":"L","\u1E38":"L","\u013B":"L","\u1E3C":"L","\u1E3A":"L","\u0141":"L","\u023D":"L","\u2C62":"L","\u2C60":"L","\uA748":"L","\uA746":"L","\uA780":"L","\u01C7":"LJ","\u01C8":"Lj","\u24C2":"M","\uFF2D":"M","\u1E3E":"M","\u1E40":"M","\u1E42":"M","\u2C6E":"M","\u019C":"M","\u24C3":"N","\uFF2E":"N","\u01F8":"N","\u0143":"N","\u00D1":"N","\u1E44":"N","\u0147":"N","\u1E46":"N","\u0145":"N","\u1E4A":"N","\u1E48":"N","\u0220":"N","\u019D":"N","\uA790":"N","\uA7A4":"N","\u01CA":"NJ","\u01CB":"Nj","\u24C4":"O","\uFF2F":"O","\u00D2":"O","\u00D3":"O","\u00D4":"O","\u1ED2":"O","\u1ED0":"O","\u1ED6":"O","\u1ED4":"O","\u00D5":"O","\u1E4C":"O","\u022C":"O","\u1E4E":"O","\u014C":"O","\u1E50":"O","\u1E52":"O","\u014E":"O","\u022E":"O","\u0230":"O","\u00D6":"O","\u022A":"O","\u1ECE":"O","\u0150":"O","\u01D1":"O","\u020C":"O","\u020E":"O","\u01A0":"O","\u1EDC":"O","\u1EDA":"O","\u1EE0":"O","\u1EDE":"O","\u1EE2":"O","\u1ECC":"O","\u1ED8":"O","\u01EA":"O","\u01EC":"O","\u00D8":"O","\u01FE":"O","\u0186":"O","\u019F":"O","\uA74A":"O","\uA74C":"O","\u01A2":"OI","\uA74E":"OO","\u0222":"OU","\u24C5":"P","\uFF30":"P","\u1E54":"P","\u1E56":"P","\u01A4":"P","\u2C63":"P","\uA750":"P","\uA752":"P","\uA754":"P","\u24C6":"Q","\uFF31":"Q","\uA756":"Q","\uA758":"Q","\u024A":"Q","\u24C7":"R","\uFF32":"R","\u0154":"R","\u1E58":"R","\u0158":"R","\u0210":"R","\u0212":"R","\u1E5A":"R","\u1E5C":"R","\u0156":"R","\u1E5E":"R","\u024C":"R","\u2C64":"R","\uA75A":"R","\uA7A6":"R","\uA782":"R","\u24C8":"S","\uFF33":"S","\u1E9E":"S","\u015A":"S","\u1E64":"S","\u015C":"S","\u1E60":"S","\u0160":"S","\u1E66":"S","\u1E62":"S","\u1E68":"S","\u0218":"S","\u015E":"S","\u2C7E":"S","\uA7A8":"S","\uA784":"S","\u24C9":"T","\uFF34":"T","\u1E6A":"T","\u0164":"T","\u1E6C":"T","\u021A":"T","\u0162":"T","\u1E70":"T","\u1E6E":"T","\u0166":"T","\u01AC":"T","\u01AE":"T","\u023E":"T","\uA786":"T","\uA728":"TZ","\u24CA":"U","\uFF35":"U","\u00D9":"U","\u00DA":"U","\u00DB":"U","\u0168":"U","\u1E78":"U","\u016A":"U","\u1E7A":"U","\u016C":"U","\u00DC":"U","\u01DB":"U","\u01D7":"U","\u01D5":"U","\u01D9":"U","\u1EE6":"U","\u016E":"U","\u0170":"U","\u01D3":"U","\u0214":"U","\u0216":"U","\u01AF":"U","\u1EEA":"U","\u1EE8":"U","\u1EEE":"U","\u1EEC":"U","\u1EF0":"U","\u1EE4":"U","\u1E72":"U","\u0172":"U","\u1E76":"U","\u1E74":"U","\u0244":"U","\u24CB":"V","\uFF36":"V","\u1E7C":"V","\u1E7E":"V","\u01B2":"V","\uA75E":"V","\u0245":"V","\uA760":"VY","\u24CC":"W","\uFF37":"W","\u1E80":"W","\u1E82":"W","\u0174":"W","\u1E86":"W","\u1E84":"W","\u1E88":"W","\u2C72":"W","\u24CD":"X","\uFF38":"X","\u1E8A":"X","\u1E8C":"X","\u24CE":"Y","\uFF39":"Y","\u1EF2":"Y","\u00DD":"Y","\u0176":"Y","\u1EF8":"Y","\u0232":"Y","\u1E8E":"Y","\u0178":"Y","\u1EF6":"Y","\u1EF4":"Y","\u01B3":"Y","\u024E":"Y","\u1EFE":"Y","\u24CF":"Z","\uFF3A":"Z","\u0179":"Z","\u1E90":"Z","\u017B":"Z","\u017D":"Z","\u1E92":"Z","\u1E94":"Z","\u01B5":"Z","\u0224":"Z","\u2C7F":"Z","\u2C6B":"Z","\uA762":"Z","\u24D0":"a","\uFF41":"a","\u1E9A":"a","\u00E0":"a","\u00E1":"a","\u00E2":"a","\u1EA7":"a","\u1EA5":"a","\u1EAB":"a","\u1EA9":"a","\u00E3":"a","\u0101":"a","\u0103":"a","\u1EB1":"a","\u1EAF":"a","\u1EB5":"a","\u1EB3":"a","\u0227":"a","\u01E1":"a","\u00E4":"a","\u01DF":"a","\u1EA3":"a","\u00E5":"a","\u01FB":"a","\u01CE":"a","\u0201":"a","\u0203":"a","\u1EA1":"a","\u1EAD":"a","\u1EB7":"a","\u1E01":"a","\u0105":"a","\u2C65":"a","\u0250":"a","\uA733":"aa","\u00E6":"ae","\u01FD":"ae","\u01E3":"ae","\uA735":"ao","\uA737":"au","\uA739":"av","\uA73B":"av","\uA73D":"ay","\u24D1":"b","\uFF42":"b","\u1E03":"b","\u1E05":"b","\u1E07":"b","\u0180":"b","\u0183":"b","\u0253":"b","\u24D2":"c","\uFF43":"c","\u0107":"c","\u0109":"c","\u010B":"c","\u010D":"c","\u00E7":"c","\u1E09":"c","\u0188":"c","\u023C":"c","\uA73F":"c","\u2184":"c","\u24D3":"d","\uFF44":"d","\u1E0B":"d","\u010F":"d","\u1E0D":"d","\u1E11":"d","\u1E13":"d","\u1E0F":"d","\u0111":"d","\u018C":"d","\u0256":"d","\u0257":"d","\uA77A":"d","\u01F3":"dz","\u01C6":"dz","\u24D4":"e","\uFF45":"e","\u00E8":"e","\u00E9":"e","\u00EA":"e","\u1EC1":"e","\u1EBF":"e","\u1EC5":"e","\u1EC3":"e","\u1EBD":"e","\u0113":"e","\u1E15":"e","\u1E17":"e","\u0115":"e","\u0117":"e","\u00EB":"e","\u1EBB":"e","\u011B":"e","\u0205":"e","\u0207":"e","\u1EB9":"e","\u1EC7":"e","\u0229":"e","\u1E1D":"e","\u0119":"e","\u1E19":"e","\u1E1B":"e","\u0247":"e","\u025B":"e","\u01DD":"e","\u24D5":"f","\uFF46":"f","\u1E1F":"f","\u0192":"f","\uA77C":"f","\u24D6":"g","\uFF47":"g","\u01F5":"g","\u011D":"g","\u1E21":"g","\u011F":"g","\u0121":"g","\u01E7":"g","\u0123":"g","\u01E5":"g","\u0260":"g","\uA7A1":"g","\u1D79":"g","\uA77F":"g","\u24D7":"h","\uFF48":"h","\u0125":"h","\u1E23":"h","\u1E27":"h","\u021F":"h","\u1E25":"h","\u1E29":"h","\u1E2B":"h","\u1E96":"h","\u0127":"h","\u2C68":"h","\u2C76":"h","\u0265":"h","\u0195":"hv","\u24D8":"i","\uFF49":"i","\u00EC":"i","\u00ED":"i","\u00EE":"i","\u0129":"i","\u012B":"i","\u012D":"i","\u00EF":"i","\u1E2F":"i","\u1EC9":"i","\u01D0":"i","\u0209":"i","\u020B":"i","\u1ECB":"i","\u012F":"i","\u1E2D":"i","\u0268":"i","\u0131":"i","\u24D9":"j","\uFF4A":"j","\u0135":"j","\u01F0":"j","\u0249":"j","\u24DA":"k","\uFF4B":"k","\u1E31":"k","\u01E9":"k","\u1E33":"k","\u0137":"k","\u1E35":"k","\u0199":"k","\u2C6A":"k","\uA741":"k","\uA743":"k","\uA745":"k","\uA7A3":"k","\u24DB":"l","\uFF4C":"l","\u0140":"l","\u013A":"l","\u013E":"l","\u1E37":"l","\u1E39":"l","\u013C":"l","\u1E3D":"l","\u1E3B":"l","\u017F":"l","\u0142":"l","\u019A":"l","\u026B":"l","\u2C61":"l","\uA749":"l","\uA781":"l","\uA747":"l","\u01C9":"lj","\u24DC":"m","\uFF4D":"m","\u1E3F":"m","\u1E41":"m","\u1E43":"m","\u0271":"m","\u026F":"m","\u24DD":"n","\uFF4E":"n","\u01F9":"n","\u0144":"n","\u00F1":"n","\u1E45":"n","\u0148":"n","\u1E47":"n","\u0146":"n","\u1E4B":"n","\u1E49":"n","\u019E":"n","\u0272":"n","\u0149":"n","\uA791":"n","\uA7A5":"n","\u01CC":"nj","\u24DE":"o","\uFF4F":"o","\u00F2":"o","\u00F3":"o","\u00F4":"o","\u1ED3":"o","\u1ED1":"o","\u1ED7":"o","\u1ED5":"o","\u00F5":"o","\u1E4D":"o","\u022D":"o","\u1E4F":"o","\u014D":"o","\u1E51":"o","\u1E53":"o","\u014F":"o","\u022F":"o","\u0231":"o","\u00F6":"o","\u022B":"o","\u1ECF":"o","\u0151":"o","\u01D2":"o","\u020D":"o","\u020F":"o","\u01A1":"o","\u1EDD":"o","\u1EDB":"o","\u1EE1":"o","\u1EDF":"o","\u1EE3":"o","\u1ECD":"o","\u1ED9":"o","\u01EB":"o","\u01ED":"o","\u00F8":"o","\u01FF":"o","\u0254":"o","\uA74B":"o","\uA74D":"o","\u0275":"o","\u01A3":"oi","\u0223":"ou","\uA74F":"oo","\u24DF":"p","\uFF50":"p","\u1E55":"p","\u1E57":"p","\u01A5":"p","\u1D7D":"p","\uA751":"p","\uA753":"p","\uA755":"p","\u24E0":"q","\uFF51":"q","\u024B":"q","\uA757":"q","\uA759":"q","\u24E1":"r","\uFF52":"r","\u0155":"r","\u1E59":"r","\u0159":"r","\u0211":"r","\u0213":"r","\u1E5B":"r","\u1E5D":"r","\u0157":"r","\u1E5F":"r","\u024D":"r","\u027D":"r","\uA75B":"r","\uA7A7":"r","\uA783":"r","\u24E2":"s","\uFF53":"s","\u00DF":"s","\u015B":"s","\u1E65":"s","\u015D":"s","\u1E61":"s","\u0161":"s","\u1E67":"s","\u1E63":"s","\u1E69":"s","\u0219":"s","\u015F":"s","\u023F":"s","\uA7A9":"s","\uA785":"s","\u1E9B":"s","\u24E3":"t","\uFF54":"t","\u1E6B":"t","\u1E97":"t","\u0165":"t","\u1E6D":"t","\u021B":"t","\u0163":"t","\u1E71":"t","\u1E6F":"t","\u0167":"t","\u01AD":"t","\u0288":"t","\u2C66":"t","\uA787":"t","\uA729":"tz","\u24E4":"u","\uFF55":"u","\u00F9":"u","\u00FA":"u","\u00FB":"u","\u0169":"u","\u1E79":"u","\u016B":"u","\u1E7B":"u","\u016D":"u","\u00FC":"u","\u01DC":"u","\u01D8":"u","\u01D6":"u","\u01DA":"u","\u1EE7":"u","\u016F":"u","\u0171":"u","\u01D4":"u","\u0215":"u","\u0217":"u","\u01B0":"u","\u1EEB":"u","\u1EE9":"u","\u1EEF":"u","\u1EED":"u","\u1EF1":"u","\u1EE5":"u","\u1E73":"u","\u0173":"u","\u1E77":"u","\u1E75":"u","\u0289":"u","\u24E5":"v","\uFF56":"v","\u1E7D":"v","\u1E7F":"v","\u028B":"v","\uA75F":"v","\u028C":"v","\uA761":"vy","\u24E6":"w","\uFF57":"w","\u1E81":"w","\u1E83":"w","\u0175":"w","\u1E87":"w","\u1E85":"w","\u1E98":"w","\u1E89":"w","\u2C73":"w","\u24E7":"x","\uFF58":"x","\u1E8B":"x","\u1E8D":"x","\u24E8":"y","\uFF59":"y","\u1EF3":"y","\u00FD":"y","\u0177":"y","\u1EF9":"y","\u0233":"y","\u1E8F":"y","\u00FF":"y","\u1EF7":"y","\u1E99":"y","\u1EF5":"y","\u01B4":"y","\u024F":"y","\u1EFF":"y","\u24E9":"z","\uFF5A":"z","\u017A":"z","\u1E91":"z","\u017C":"z","\u017E":"z","\u1E93":"z","\u1E95":"z","\u01B6":"z","\u0225":"z","\u0240":"z","\u2C6C":"z","\uA763":"z","\u0386":"\u0391","\u0388":"\u0395","\u0389":"\u0397","\u038A":"\u0399","\u03AA":"\u0399","\u038C":"\u039F","\u038E":"\u03A5","\u03AB":"\u03A5","\u038F":"\u03A9","\u03AC":"\u03B1","\u03AD":"\u03B5","\u03AE":"\u03B7","\u03AF":"\u03B9","\u03CA":"\u03B9","\u0390":"\u03B9","\u03CC":"\u03BF","\u03CD":"\u03C5","\u03CB":"\u03C5","\u03B0":"\u03C5","\u03C9":"\u03C9","\u03C2":"\u03C3"}; $document = $(document); nextUid=(function() { var counter=1; return function() { return counter++; }; }()); function reinsertElement(element) { var placeholder = $(document.createTextNode('')); element.before(placeholder); placeholder.before(element); placeholder.remove(); } function stripDiacritics(str) { // Used 'uni range + named function' from http://jsperf.com/diacritics/18 function match(a) { return DIACRITICS[a] || a; } return str.replace(/[^\u0000-\u007E]/g, match); } function indexOf(value, array) { var i = 0, l = array.length; for (; i < l; i = i + 1) { if (equal(value, array[i])) return i; } return -1; } function measureScrollbar () { var $template = $( MEASURE_SCROLLBAR_TEMPLATE ); $template.appendTo('body'); var dim = { width: $template.width() - $template[0].clientWidth, height: $template.height() - $template[0].clientHeight }; $template.remove(); return dim; } /** * Compares equality of a and b * @param a * @param b */ function equal(a, b) { if (a === b) return true; if (a === undefined || b === undefined) return false; if (a === null || b === null) return false; // Check whether 'a' or 'b' is a string (primitive or object). // The concatenation of an empty string (+'') converts its argument to a string's primitive. if (a.constructor === String) return a+'' === b+''; // a+'' - in case 'a' is a String object if (b.constructor === String) return b+'' === a+''; // b+'' - in case 'b' is a String object return false; } /** * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty * strings * @param string * @param separator */ function splitVal(string, separator) { var val, i, l; if (string === null || string.length < 1) return []; val = string.split(separator); for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]); return val; } function getSideBorderPadding(element) { return element.outerWidth(false) - element.width(); } function installKeyUpChangeEvent(element) { var key="keyup-change-value"; element.on("keydown", function () { if ($.data(element, key) === undefined) { $.data(element, key, element.val()); } }); element.on("keyup", function () { var val= $.data(element, key); if (val !== undefined && element.val() !== val) { $.removeData(element, key); element.trigger("keyup-change"); } }); } /** * filters mouse events so an event is fired only if the mouse moved. * * filters out mouse events that occur when mouse is stationary but * the elements under the pointer are scrolled. */ function installFilteredMouseMove(element) { element.on("mousemove", function (e) { var lastpos = lastMousePosition; if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) { $(e.target).trigger("mousemove-filtered", e); } }); } /** * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made * within the last quietMillis milliseconds. * * @param quietMillis number of milliseconds to wait before invoking fn * @param fn function to be debounced * @param ctx object to be used as this reference within fn * @return debounced version of fn */ function debounce(quietMillis, fn, ctx) { ctx = ctx || undefined; var timeout; return function () { var args = arguments; window.clearTimeout(timeout); timeout = window.setTimeout(function() { fn.apply(ctx, args); }, quietMillis); }; } function installDebouncedScroll(threshold, element) { var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);}); element.on("scroll", function (e) { if (indexOf(e.target, element.get()) >= 0) notify(e); }); } function focus($el) { if ($el[0] === document.activeElement) return; /* set the focus in a 0 timeout - that way the focus is set after the processing of the current event has finished - which seems like the only reliable way to set focus */ window.setTimeout(function() { var el=$el[0], pos=$el.val().length, range; $el.focus(); /* make sure el received focus so we do not error out when trying to manipulate the caret. sometimes modals or others listeners may steal it after its set */ var isVisible = (el.offsetWidth > 0 || el.offsetHeight > 0); if (isVisible && el === document.activeElement) { /* after the focus is set move the caret to the end, necessary when we val() just before setting focus */ if(el.setSelectionRange) { el.setSelectionRange(pos, pos); } else if (el.createTextRange) { range = el.createTextRange(); range.collapse(false); range.select(); } } }, 0); } function getCursorInfo(el) { el = $(el)[0]; var offset = 0; var length = 0; if ('selectionStart' in el) { offset = el.selectionStart; length = el.selectionEnd - offset; } else if ('selection' in document) { el.focus(); var sel = document.selection.createRange(); length = document.selection.createRange().text.length; sel.moveStart('character', -el.value.length); offset = sel.text.length - length; } return { offset: offset, length: length }; } function killEvent(event) { event.preventDefault(); event.stopPropagation(); } function killEventImmediately(event) { event.preventDefault(); event.stopImmediatePropagation(); } function measureTextWidth(e) { if (!sizer){ var style = e[0].currentStyle || window.getComputedStyle(e[0], null); sizer = $(document.createElement("div")).css({ position: "absolute", left: "-10000px", top: "-10000px", display: "none", fontSize: style.fontSize, fontFamily: style.fontFamily, fontStyle: style.fontStyle, fontWeight: style.fontWeight, letterSpacing: style.letterSpacing, textTransform: style.textTransform, whiteSpace: "nowrap" }); sizer.attr("class","select2-sizer"); $("body").append(sizer); } sizer.text(e.val()); return sizer.width(); } function syncCssClasses(dest, src, adapter) { var classes, replacements = [], adapted; classes = $.trim(dest.attr("class")); if (classes) { classes = '' + classes; // for IE which returns object $(classes.split(/\s+/)).each2(function() { if (this.indexOf("select2-") === 0) { replacements.push(this); } }); } classes = $.trim(src.attr("class")); if (classes) { classes = '' + classes; // for IE which returns object $(classes.split(/\s+/)).each2(function() { if (this.indexOf("select2-") !== 0) { adapted = adapter(this); if (adapted) { replacements.push(adapted); } } }); } dest.attr("class", replacements.join(" ")); } function markMatch(text, term, markup, escapeMarkup) { var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())), tl=term.length; if (match<0) { markup.push(escapeMarkup(text)); return; } markup.push(escapeMarkup(text.substring(0, match))); markup.push("<span class='select2-match'>"); markup.push(escapeMarkup(text.substring(match, match + tl))); markup.push("</span>"); markup.push(escapeMarkup(text.substring(match + tl, text.length))); } function defaultEscapeMarkup(markup) { var replace_map = { '\\': '\', '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', "/": '/' }; return String(markup).replace(/[&<>"'\/\\]/g, function (match) { return replace_map[match]; }); } /** * Produces an ajax-based query function * * @param options object containing configuration parameters * @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax * @param options.url url for the data * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url. * @param options.dataType request data type: ajax, jsonp, other datatypes supported by jQuery's $.ajax function or the transport function if specified * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often * @param options.results a function(remoteData, pageNumber, query) that converts data returned form the remote request to the format expected by Select2. * The expected format is an object containing the following keys: * results array of objects that will be used as choices * more (optional) boolean indicating whether there are more results available * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true} */ function ajax(options) { var timeout, // current scheduled but not yet executed request handler = null, quietMillis = options.quietMillis || 100, ajaxUrl = options.url, self = this; return function (query) { window.clearTimeout(timeout); timeout = window.setTimeout(function () { var data = options.data, // ajax data function url = ajaxUrl, // ajax url string or function transport = options.transport || $.fn.select2.ajaxDefaults.transport, // deprecated - to be removed in 4.0 - use params instead deprecated = { type: options.type || 'GET', // set type of request (GET or POST) cache: options.cache || false, jsonpCallback: options.jsonpCallback||undefined, dataType: options.dataType||"json" }, params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated); data = data ? data.call(self, query.term, query.page, query.context) : null; url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url; if (handler && typeof handler.abort === "function") { handler.abort(); } if (options.params) { if ($.isFunction(options.params)) { $.extend(params, options.params.call(self)); } else { $.extend(params, options.params); } } $.extend(params, { url: url, dataType: options.dataType, data: data, success: function (data) { // TODO - replace query.page with query so users have access to term, page, etc. // added query as third paramter to keep backwards compatibility var results = options.results(data, query.page, query); query.callback(results); } }); handler = transport.call(self, params); }, quietMillis); }; } /** * Produces a query function that works with a local array * * @param options object containing configuration parameters. The options parameter can either be an array or an * object. * * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys. * * If the object form is used it is assumed that it contains 'data' and 'text' keys. The 'data' key should contain * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text' * key can either be a String in which case it is expected that each element in the 'data' array has a key with the * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract * the text. */ function local(options) { var data = options, // data elements dataText, tmp, text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search if ($.isArray(data)) { tmp = data; data = { results: tmp }; } if ($.isFunction(data) === false) { tmp = data; data = function() { return tmp; }; } var dataItem = data(); if (dataItem.text) { text = dataItem.text; // if text is not a function we assume it to be a key name if (!$.isFunction(text)) { dataText = dataItem.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available text = function (item) { return item[dataText]; }; } } return function (query) { var t = query.term, filtered = { results: [] }, process; if (t === "") { query.callback(data()); return; } process = function(datum, collection) { var group, attr; datum = datum[0]; if (datum.children) { group = {}; for (attr in datum) { if (datum.hasOwnProperty(attr)) group[attr]=datum[attr]; } group.children=[]; $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); }); if (group.children.length || query.matcher(t, text(group), datum)) { collection.push(group); } } else { if (query.matcher(t, text(datum), datum)) { collection.push(datum); } } }; $(data().results).each2(function(i, datum) { process(datum, filtered.results); }); query.callback(filtered); }; } // TODO javadoc function tags(data) { var isFunc = $.isFunction(data); return function (query) { var t = query.term, filtered = {results: []}; var result = isFunc ? data(query) : data; if ($.isArray(result)) { $(result).each(function () { var isObject = this.text !== undefined, text = isObject ? this.text : this; if (t === "" || query.matcher(t, text)) { filtered.results.push(isObject ? this : {id: this, text: this}); } }); query.callback(filtered); } }; } /** * Checks if the formatter function should be used. * * Throws an error if it is not a function. Returns true if it should be used, * false if no formatting should be performed. * * @param formatter */ function checkFormatter(formatter, formatterName) { if ($.isFunction(formatter)) return true; if (!formatter) return false; if (typeof(formatter) === 'string') return true; throw new Error(formatterName +" must be a string, function, or falsy value"); } /** * Returns a given value * If given a function, returns its output * * @param val string|function * @param context value of "this" to be passed to function * @returns {*} */ function evaluate(val, context) { if ($.isFunction(val)) { var args = Array.prototype.slice.call(arguments, 2); return val.apply(context, args); } return val; } function countResults(results) { var count = 0; $.each(results, function(i, item) { if (item.children) { count += countResults(item.children); } else { count++; } }); return count; } /** * Default tokenizer. This function uses breaks the input on substring match of any string from the * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those * two options have to be defined in order for the tokenizer to work. * * @param input text user has typed so far or pasted into the search field * @param selection currently selected choices * @param selectCallback function(choice) callback tho add the choice to selection * @param opts select2's opts * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value */ function defaultTokenizer(input, selection, selectCallback, opts) { var original = input, // store the original so we can compare and know if we need to tell the search to update its text dupe = false, // check for whether a token we extracted represents a duplicate selected choice token, // token index, // position at which the separator was found i, l, // looping variables separator; // the matched separator if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined; while (true) { index = -1; for (i = 0, l = opts.tokenSeparators.length; i < l; i++) { separator = opts.tokenSeparators[i]; index = input.indexOf(separator); if (index >= 0) break; } if (index < 0) break; // did not find any token separator in the input string, bail token = input.substring(0, index); input = input.substring(index + separator.length); if (token.length > 0) { token = opts.createSearchChoice.call(this, token, selection); if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) { dupe = false; for (i = 0, l = selection.length; i < l; i++) { if (equal(opts.id(token), opts.id(selection[i]))) { dupe = true; break; } } if (!dupe) selectCallback(token); } } } if (original!==input) return input; } function cleanupJQueryElements() { var self = this; $.each(arguments, function (i, element) { self[element].remove(); self[element] = null; }); } /** * Creates a new class * * @param superClass * @param methods */ function clazz(SuperClass, methods) { var constructor = function () {}; constructor.prototype = new SuperClass; constructor.prototype.constructor = constructor; constructor.prototype.parent = SuperClass.prototype; constructor.prototype = $.extend(constructor.prototype, methods); return constructor; } AbstractSelect2 = clazz(Object, { // abstract bind: function (func) { var self = this; return function () { func.apply(self, arguments); }; }, // abstract init: function (opts) { var results, search, resultsSelector = ".select2-results"; // prepare options this.opts = opts = this.prepareOpts(opts); this.id=opts.id; // destroy if called on an existing component if (opts.element.data("select2") !== undefined && opts.element.data("select2") !== null) { opts.element.data("select2").destroy(); } this.container = this.createContainer(); this.liveRegion = $("<span>", { role: "status", "aria-live": "polite" }) .addClass("select2-hidden-accessible") .appendTo(document.body); this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid()); this.containerEventName= this.containerId .replace(/([.])/g, '_') .replace(/([;&,\-\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); this.container.attr("id", this.containerId); this.container.attr("title", opts.element.attr("title")); this.body = $("body"); syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass); this.container.attr("style", opts.element.attr("style")); this.container.css(evaluate(opts.containerCss, this.opts.element)); this.container.addClass(evaluate(opts.containerCssClass, this.opts.element)); this.elementTabIndex = this.opts.element.attr("tabindex"); // swap container for the element this.opts.element .data("select2", this) .attr("tabindex", "-1") .before(this.container) .on("click.select2", killEvent); // do not leak click events this.container.data("select2", this); this.dropdown = this.container.find(".select2-drop"); syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass); this.dropdown.addClass(evaluate(opts.dropdownCssClass, this.opts.element)); this.dropdown.data("select2", this); this.dropdown.on("click", killEvent); this.results = results = this.container.find(resultsSelector); this.search = search = this.container.find("input.select2-input"); this.queryCount = 0; this.resultsPage = 0; this.context = null; // initialize the container this.initContainer(); this.container.on("click", killEvent); installFilteredMouseMove(this.results); this.dropdown.on("mousemove-filtered", resultsSelector, this.bind(this.highlightUnderEvent)); this.dropdown.on("touchstart touchmove touchend", resultsSelector, this.bind(function (event) { this._touchEvent = true; this.highlightUnderEvent(event); })); this.dropdown.on("touchmove", resultsSelector, this.bind(this.touchMoved)); this.dropdown.on("touchstart touchend", resultsSelector, this.bind(this.clearTouchMoved)); // Waiting for a click event on touch devices to select option and hide dropdown // otherwise click will be triggered on an underlying element this.dropdown.on('click', this.bind(function (event) { if (this._touchEvent) { this._touchEvent = false; this.selectHighlighted(); } })); installDebouncedScroll(80, this.results); this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded)); // do not propagate change event from the search field out of the component $(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();}); $(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();}); // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel if ($.fn.mousewheel) { results.mousewheel(function (e, delta, deltaX, deltaY) { var top = results.scrollTop(); if (deltaY > 0 && top - deltaY <= 0) { results.scrollTop(0); killEvent(e); } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) { results.scrollTop(results.get(0).scrollHeight - results.height()); killEvent(e); } }); } installKeyUpChangeEvent(search); search.on("keyup-change input paste", this.bind(this.updateResults)); search.on("focus", function () { search.addClass("select2-focused"); }); search.on("blur", function () { search.removeClass("select2-focused");}); this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) { if ($(e.target).closest(".select2-result-selectable").length > 0) { this.highlightUnderEvent(e); this.selectHighlighted(e); } })); // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's // dom it will trigger the popup close, which is not what we want // focusin can cause focus wars between modals and select2 since the dropdown is outside the modal. this.dropdown.on("click mouseup mousedown touchstart touchend focusin", function (e) { e.stopPropagation(); }); this.nextSearchTerm = undefined; if ($.isFunction(this.opts.initSelection)) { // initialize selection based on the current value of the source element this.initSelection(); // if the user has provided a function that can set selection based on the value of the source element // we monitor the change event on the element and trigger it, allowing for two way synchronization this.monitorSource(); } if (opts.maximumInputLength !== null) { this.search.attr("maxlength", opts.maximumInputLength); } var disabled = opts.element.prop("disabled"); if (disabled === undefined) disabled = false; this.enable(!disabled); var readonly = opts.element.prop("readonly"); if (readonly === undefined) readonly = false; this.readonly(readonly); // Calculate size of scrollbar scrollBarDimensions = scrollBarDimensions || measureScrollbar(); this.autofocus = opts.element.prop("autofocus"); opts.element.prop("autofocus", false); if (this.autofocus) this.focus(); this.search.attr("placeholder", opts.searchInputPlaceholder); }, // abstract destroy: function () { var element=this.opts.element, select2 = element.data("select2"); this.close(); if (element.length && element[0].detachEvent) { element.each(function () { this.detachEvent("onpropertychange", this._sync); }); } if (this.propertyObserver) { this.propertyObserver.disconnect(); this.propertyObserver = null; } this._sync = null; if (select2 !== undefined) { select2.container.remove(); select2.liveRegion.remove(); select2.dropdown.remove(); element .removeClass("select2-offscreen") .removeData("select2") .off(".select2") .prop("autofocus", this.autofocus || false); if (this.elementTabIndex) { element.attr({tabindex: this.elementTabIndex}); } else { element.removeAttr("tabindex"); } element.show(); } cleanupJQueryElements.call(this, "container", "liveRegion", "dropdown", "results", "search" ); }, // abstract optionToData: function(element) { if (element.is("option")) { return { id:element.prop("value"), text:element.text(), element: element.get(), css: element.attr("class"), disabled: element.prop("disabled"), locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true) }; } else if (element.is("optgroup")) { return { text:element.attr("label"), children:[], element: element.get(), css: element.attr("class") }; } }, // abstract prepareOpts: function (opts) { var element, select, idKey, ajaxUrl, self = this; element = opts.element; if (element.get(0).tagName.toLowerCase() === "select") { this.select = select = opts.element; } if (select) { // these options are not allowed when attached to a select because they are picked up off the element itself $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () { if (this in opts) { throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element."); } }); } opts = $.extend({}, { populateResults: function(container, results, query) { var populate, id=this.opts.id, liveRegion=this.liveRegion; populate=function(results, container, depth) { var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted; results = opts.sortResults(results, container, query); // collect the created nodes for bulk append var nodes = []; for (i = 0, l = results.length; i < l; i = i + 1) { result=results[i]; disabled = (result.disabled === true); selectable = (!disabled) && (id(result) !== undefined); compound=result.children && result.children.length > 0; node=$("<li></li>"); node.addClass("select2-results-dept-"+depth); node.addClass("select2-result"); node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable"); if (disabled) { node.addClass("select2-disabled"); } if (compound) { node.addClass("select2-result-with-children"); } node.addClass(self.opts.formatResultCssClass(result)); node.attr("role", "presentation"); label=$(document.createElement("div")); label.addClass("select2-result-label"); label.attr("id", "select2-result-label-" + nextUid()); label.attr("role", "option"); formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup); if (formatted!==undefined) { label.html(formatted); node.append(label); } if (compound) { innerContainer=$("<ul></ul>"); innerContainer.addClass("select2-result-sub"); populate(result.children, innerContainer, depth+1); node.append(innerContainer); } node.data("select2-data", result); nodes.push(node[0]); } // bulk append the created nodes container.append(nodes); liveRegion.text(opts.formatMatches(results.length)); }; populate(results, container, 0); } }, $.fn.select2.defaults, opts); if (typeof(opts.id) !== "function") { idKey = opts.id; opts.id = function (e) { return e[idKey]; }; } if ($.isArray(opts.element.data("select2Tags"))) { if ("tags" in opts) { throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id"); } opts.tags=opts.element.data("select2Tags"); } if (select) { opts.query = this.bind(function (query) { var data = { results: [], more: false }, term = query.term, children, placeholderOption, process; process=function(element, collection) { var group; if (element.is("option")) { if (query.matcher(term, element.text(), element)) { collection.push(self.optionToData(element)); } } else if (element.is("optgroup")) { group=self.optionToData(element); element.children().each2(function(i, elm) { process(elm, group.children); }); if (group.children.length>0) { collection.push(group); } } }; children=element.children(); // ignore the placeholder option if there is one if (this.getPlaceholder() !== undefined && children.length > 0) { placeholderOption = this.getPlaceholderOption(); if (placeholderOption) { children=children.not(placeholderOption); } } children.each2(function(i, elm) { process(elm, data.results); }); query.callback(data); }); // this is needed because inside val() we construct choices from options and there id is hardcoded opts.id=function(e) { return e.id; }; } else { if (!("query" in opts)) { if ("ajax" in opts) { ajaxUrl = opts.element.data("ajax-url"); if (ajaxUrl && ajaxUrl.length > 0) { opts.ajax.url = ajaxUrl; } opts.query = ajax.call(opts.element, opts.ajax); } else if ("data" in opts) { opts.query = local(opts.data); } else if ("tags" in opts) { opts.query = tags(opts.tags); if (opts.createSearchChoice === undefined) { opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; }; } if (opts.initSelection === undefined) { opts.initSelection = function (element, callback) { var data = []; $(splitVal(element.val(), opts.separator)).each(function () { var obj = { id: this, text: this }, tags = opts.tags; if ($.isFunction(tags)) tags=tags(); $(tags).each(function() { if (equal(this.id, obj.id)) { obj = this; return false; } }); data.push(obj); }); callback(data); }; } } } } if (typeof(opts.query) !== "function") { throw "query function not defined for Select2 " + opts.element.attr("id"); } if (opts.createSearchChoicePosition === 'top') { opts.createSearchChoicePosition = function(list, item) { list.unshift(item); }; } else if (opts.createSearchChoicePosition === 'bottom') { opts.createSearchChoicePosition = function(list, item) { list.push(item); }; } else if (typeof(opts.createSearchChoicePosition) !== "function") { throw "invalid createSearchChoicePosition option must be 'top', 'bottom' or a custom function"; } return opts; }, /** * Monitor the original element for changes and update select2 accordingly */ // abstract monitorSource: function () { var el = this.opts.element, observer, self = this; el.on("change.select2", this.bind(function (e) { if (this.opts.element.data("select2-change-triggered") !== true) { this.initSelection(); } })); this._sync = this.bind(function () { // sync enabled state var disabled = el.prop("disabled"); if (disabled === undefined) disabled = false; this.enable(!disabled); var readonly = el.prop("readonly"); if (readonly === undefined) readonly = false; this.readonly(readonly); syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass); this.container.addClass(evaluate(this.opts.containerCssClass, this.opts.element)); syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass); this.dropdown.addClass(evaluate(this.opts.dropdownCssClass, this.opts.element)); }); // IE8-10 (IE9/10 won't fire propertyChange via attachEventListener) if (el.length && el[0].attachEvent) { el.each(function() { this.attachEvent("onpropertychange", self._sync); }); } // safari, chrome, firefox, IE11 observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver; if (observer !== undefined) { if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; } this.propertyObserver = new observer(function (mutations) { $.each(mutations, self._sync); }); this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false }); } }, // abstract triggerSelect: function(data) { var evt = $.Event("select2-selecting", { val: this.id(data), object: data, choice: data }); this.opts.element.trigger(evt); return !evt.isDefaultPrevented(); }, /** * Triggers the change event on the source element */ // abstract triggerChange: function (details) { details = details || {}; details= $.extend({}, details, { type: "change", val: this.val() }); // prevents recursive triggering this.opts.element.data("select2-change-triggered", true); this.opts.element.trigger(details); this.opts.element.data("select2-change-triggered", false); // some validation frameworks ignore the change event and listen instead to keyup, click for selects // so here we trigger the click event manually this.opts.element.click(); // ValidationEngine ignores the change event and listens instead to blur // so here we trigger the blur event manually if so desired if (this.opts.blurOnChange) this.opts.element.blur(); }, //abstract isInterfaceEnabled: function() { return this.enabledInterface === true; }, // abstract enableInterface: function() { var enabled = this._enabled && !this._readonly, disabled = !enabled; if (enabled === this.enabledInterface) return false; this.container.toggleClass("select2-container-disabled", disabled); this.close(); this.enabledInterface = enabled; return true; }, // abstract enable: function(enabled) { if (enabled === undefined) enabled = true; if (this._enabled === enabled) return; this._enabled = enabled; this.opts.element.prop("disabled", !enabled); this.enableInterface(); }, // abstract disable: function() { this.enable(false); }, // abstract readonly: function(enabled) { if (enabled === undefined) enabled = false; if (this._readonly === enabled) return; this._readonly = enabled; this.opts.element.prop("readonly", enabled); this.enableInterface(); }, // abstract opened: function () { return (this.container) ? this.container.hasClass("select2-dropdown-open") : false; }, // abstract positionDropdown: function() { var $dropdown = this.dropdown, offset = this.container.offset(), height = this.container.outerHeight(false), width = this.container.outerWidth(false), dropHeight = $dropdown.outerHeight(false), $window = $(window), windowWidth = $window.width(), windowHeight = $window.height(), viewPortRight = $window.scrollLeft() + windowWidth, viewportBottom = $window.scrollTop() + windowHeight, dropTop = offset.top + height, dropLeft = offset.left, enoughRoomBelow = dropTop + dropHeight <= viewportBottom, enoughRoomAbove = (offset.top - dropHeight) >= $window.scrollTop(), dropWidth = $dropdown.outerWidth(false), enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight, aboveNow = $dropdown.hasClass("select2-drop-above"), bodyOffset, above, changeDirection, css, resultsListNode; // always prefer the current above/below alignment, unless there is not enough room if (aboveNow) { above = true; if (!enoughRoomAbove && enoughRoomBelow) { changeDirection = true; above = false; } } else { above = false; if (!enoughRoomBelow && enoughRoomAbove) { changeDirection = true; above = true; } } //if we are changing direction we need to get positions when dropdown is hidden; if (changeDirection) { $dropdown.hide(); offset = this.container.offset(); height = this.container.outerHeight(false); width = this.container.outerWidth(false); dropHeight = $dropdown.outerHeight(false); viewPortRight = $window.scrollLeft() + windowWidth; viewportBottom = $window.scrollTop() + windowHeight; dropTop = offset.top + height; dropLeft = offset.left; dropWidth = $dropdown.outerWidth(false); enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight; $dropdown.show(); // fix so the cursor does not move to the left within the search-textbox in IE this.focusSearch(); } if (this.opts.dropdownAutoWidth) { resultsListNode = $('.select2-results', $dropdown)[0]; $dropdown.addClass('select2-drop-auto-width'); $dropdown.css('width', ''); // Add scrollbar width to dropdown if vertical scrollbar is present dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width); dropWidth > width ? width = dropWidth : dropWidth = width; dropHeight = $dropdown.outerHeight(false); enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight; } else { this.container.removeClass('select2-drop-auto-width'); } //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow); //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body.scrollTop(), "enough?", enoughRoomAbove); // fix positioning when body has an offset and is not position: static if (this.body.css('position') !== 'static') { bodyOffset = this.body.offset(); dropTop -= bodyOffset.top; dropLeft -= bodyOffset.left; } if (!enoughRoomOnRight) { dropLeft = offset.left + this.container.outerWidth(false) - dropWidth; } css = { left: dropLeft, width: width }; if (above) { css.top = offset.top - dropHeight; css.bottom = 'auto'; this.container.addClass("select2-drop-above"); $dropdown.addClass("select2-drop-above"); } else { css.top = dropTop; css.bottom = 'auto'; this.container.removeClass("select2-drop-above"); $dropdown.removeClass("select2-drop-above"); } css = $.extend(css, evaluate(this.opts.dropdownCss, this.opts.element)); $dropdown.css(css); }, // abstract shouldOpen: function() { var event; if (this.opened()) return false; if (this._enabled === false || this._readonly === true) return false; event = $.Event("select2-opening"); this.opts.element.trigger(event); return !event.isDefaultPrevented(); }, // abstract clearDropdownAlignmentPreference: function() { // clear the classes used to figure out the preference of where the dropdown should be opened this.container.removeClass("select2-drop-above"); this.dropdown.removeClass("select2-drop-above"); }, /** * Opens the dropdown * * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example, * the dropdown is already open, or if the 'open' event listener on the element called preventDefault(). */ // abstract open: function () { if (!this.shouldOpen()) return false; this.opening(); // Only bind the document mousemove when the dropdown is visible $document.on("mousemove.select2Event", function (e) { lastMousePosition.x = e.pageX; lastMousePosition.y = e.pageY; }); return true; }, /** * Performs the opening of the dropdown */ // abstract opening: function() { var cid = this.containerEventName, scroll = "scroll." + cid, resize = "resize."+cid, orient = "orientationchange."+cid, mask; this.container.addClass("select2-dropdown-open").addClass("select2-container-active"); this.clearDropdownAlignmentPreference(); if(this.dropdown[0] !== this.body.children().last()[0]) { this.dropdown.detach().appendTo(this.body); } // create the dropdown mask if doesn't already exist mask = $("#select2-drop-mask"); if (mask.length == 0) { mask = $(document.createElement("div")); mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask"); mask.hide(); mask.appendTo(this.body); mask.on("mousedown touchstart click", function (e) { // Prevent IE from generating a click event on the body reinsertElement(mask); var dropdown = $("#select2-drop"), self; if (dropdown.length > 0) { self=dropdown.data("select2"); if (self.opts.selectOnBlur) { self.selectHighlighted({noFocus: true}); } self.close(); e.preventDefault(); e.stopPropagation(); } }); } // ensure the mask is always right before the dropdown if (this.dropdown.prev()[0] !== mask[0]) { this.dropdown.before(mask); } // move the global id to the correct dropdown $("#select2-drop").removeAttr("id"); this.dropdown.attr("id", "select2-drop"); // show the elements mask.show(); this.positionDropdown(); this.dropdown.show(); this.positionDropdown(); this.dropdown.addClass("select2-drop-active"); // attach listeners to events that can change the position of the container and thus require // the position of the dropdown to be updated as well so it does not come unglued from the container var that = this; this.container.parents().add(window).each(function () { $(this).on(resize+" "+scroll+" "+orient, function (e) { if (that.opened()) that.positionDropdown(); }); }); }, // abstract close: function () { if (!this.opened()) return; var cid = this.containerEventName, scroll = "scroll." + cid, resize = "resize."+cid, orient = "orientationchange."+cid; // unbind event listeners this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); }); this.clearDropdownAlignmentPreference(); $("#select2-drop-mask").hide(); this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id this.dropdown.hide(); this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active"); this.results.empty(); // Now that the dropdown is closed, unbind the global document mousemove event $document.off("mousemove.select2Event"); this.clearSearch(); this.search.removeClass("select2-active"); this.opts.element.trigger($.Event("select2-close")); }, /** * Opens control, sets input value, and updates results. */ // abstract externalSearch: function (term) { this.open(); this.search.val(term); this.updateResults(false); }, // abstract clearSearch: function () { }, //abstract getMaximumSelectionSize: function() { return evaluate(this.opts.maximumSelectionSize, this.opts.element); }, // abstract ensureHighlightVisible: function () { var results = this.results, children, index, child, hb, rb, y, more, topOffset; index = this.highlight(); if (index < 0) return; if (index == 0) { // if the first element is highlighted scroll all the way to the top, // that way any unselectable headers above it will also be scrolled // into view results.scrollTop(0); return; } children = this.findHighlightableChoices().find('.select2-result-label'); child = $(children[index]); topOffset = (child.offset() || {}).top || 0; hb = topOffset + child.outerHeight(true); // if this is the last child lets also make sure select2-more-results is visible if (index === children.length - 1) { more = results.find("li.select2-more-results"); if (more.length > 0) { hb = more.offset().top + more.outerHeight(true); } } rb = results.offset().top + results.outerHeight(true); if (hb > rb) { results.scrollTop(results.scrollTop() + (hb - rb)); } y = topOffset - results.offset().top; // make sure the top of the element is visible if (y < 0 && child.css('display') != 'none' ) { results.scrollTop(results.scrollTop() + y); // y is negative } }, // abstract findHighlightableChoices: function() { return this.results.find(".select2-result-selectable:not(.select2-disabled):not(.select2-selected)"); }, // abstract moveHighlight: function (delta) { var choices = this.findHighlightableChoices(), index = this.highlight(); while (index > -1 && index < choices.length) { index += delta; var choice = $(choices[index]); if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) { this.highlight(index); break; } } }, // abstract highlight: function (index) { var choices = this.findHighlightableChoices(), choice, data; if (arguments.length === 0) { return indexOf(choices.filter(".select2-highlighted")[0], choices.get()); } if (index >= choices.length) index = choices.length - 1; if (index < 0) index = 0; this.removeHighlight(); choice = $(choices[index]); choice.addClass("select2-highlighted"); // ensure assistive technology can determine the active choice this.search.attr("aria-activedescendant", choice.find(".select2-result-label").attr("id")); this.ensureHighlightVisible(); this.liveRegion.text(choice.text()); data = choice.data("select2-data"); if (data) { this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data }); } }, removeHighlight: function() { this.results.find(".select2-highlighted").removeClass("select2-highlighted"); }, touchMoved: function() { this._touchMoved = true; }, clearTouchMoved: function() { this._touchMoved = false; }, // abstract countSelectableResults: function() { return this.findHighlightableChoices().length; }, // abstract highlightUnderEvent: function (event) { var el = $(event.target).closest(".select2-result-selectable"); if (el.length > 0 && !el.is(".select2-highlighted")) { var choices = this.findHighlightableChoices(); this.highlight(choices.index(el)); } else if (el.length == 0) { // if we are over an unselectable item remove all highlights this.removeHighlight(); } }, // abstract loadMoreIfNeeded: function () { var results = this.results, more = results.find("li.select2-more-results"), below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible page = this.resultsPage + 1, self=this, term=this.search.val(), context=this.context; if (more.length === 0) return; below = more.offset().top - results.offset().top - results.height(); if (below <= this.opts.loadMorePadding) { more.addClass("select2-active"); this.opts.query({ element: this.opts.element, term: term, page: page, context: context, matcher: this.opts.matcher, callback: this.bind(function (data) { // ignore a response if the select2 has been closed before it was received if (!self.opened()) return; self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context}); self.postprocessResults(data, false, false); if (data.more===true) { more.detach().appendTo(results).text(evaluate(self.opts.formatLoadMore, self.opts.element, page+1)); window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10); } else { more.remove(); } self.positionDropdown(); self.resultsPage = page; self.context = data.context; this.opts.element.trigger({ type: "select2-loaded", items: data }); })}); } }, /** * Default tokenizer function which does nothing */ tokenize: function() { }, /** * @param initial whether or not this is the call to this method right after the dropdown has been opened */ // abstract updateResults: function (initial) { var search = this.search, results = this.results, opts = this.opts, data, self = this, input, term = search.val(), lastTerm = $.data(this.container, "select2-last-term"), // sequence number used to drop out-of-order responses queryNumber; // prevent duplicate queries against the same term if (initial !== true && lastTerm && equal(term, lastTerm)) return; $.data(this.container, "select2-last-term", term); // if the search is currently hidden we do not alter the results if (initial !== true && (this.showSearchInput === false || !this.opened())) { return; } function postRender() { search.removeClass("select2-active"); self.positionDropdown(); if (results.find('.select2-no-results,.select2-selection-limit,.select2-searching').length) { self.liveRegion.text(results.text()); } else { self.liveRegion.text(self.opts.formatMatches(results.find('.select2-result-selectable').length)); } } function render(html) { results.html(html); postRender(); } queryNumber = ++this.queryCount; var maxSelSize = this.getMaximumSelectionSize(); if (maxSelSize >=1) { data = this.data(); if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) { render("<li class='select2-selection-limit'>" + evaluate(opts.formatSelectionTooBig, opts.element, maxSelSize) + "</li>"); return; } } if (search.val().length < opts.minimumInputLength) { if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) { render("<li class='select2-no-results'>" + evaluate(opts.formatInputTooShort, opts.element, search.val(), opts.minimumInputLength) + "</li>"); } else { render(""); } if (initial && this.showSearch) this.showSearch(true); return; } if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) { if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) { render("<li class='select2-no-results'>" + evaluate(opts.formatInputTooLong, opts.element, search.val(), opts.maximumInputLength) + "</li>"); } else { render(""); } return; } if (opts.formatSearching && this.findHighlightableChoices().length === 0) { render("<li class='select2-searching'>" + evaluate(opts.formatSearching, opts.element) + "</li>"); } search.addClass("select2-active"); this.removeHighlight(); // give the tokenizer a chance to pre-process the input input = this.tokenize(); if (input != undefined && input != null) { search.val(input); } this.resultsPage = 1; opts.query({ element: opts.element, term: search.val(), page: this.resultsPage, context: null, matcher: opts.matcher, callback: this.bind(function (data) { var def; // default choice // ignore old responses if (queryNumber != this.queryCount) { return; } // ignore a response if the select2 has been closed before it was received if (!this.opened()) { this.search.removeClass("select2-active"); return; } // save context, if any this.context = (data.context===undefined) ? null : data.context; // create a default choice and prepend it to the list if (this.opts.createSearchChoice && search.val() !== "") { def = this.opts.createSearchChoice.call(self, search.val(), data.results); if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) { if ($(data.results).filter( function () { return equal(self.id(this), self.id(def)); }).length === 0) { this.opts.createSearchChoicePosition(data.results, def); } } } if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) { render("<li class='select2-no-results'>" + evaluate(opts.formatNoMatches, opts.element, search.val()) + "</li>"); return; } results.empty(); self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null}); if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) { results.append("<li class='select2-more-results'>" + opts.escapeMarkup(evaluate(opts.formatLoadMore, opts.element, this.resultsPage)) + "</li>"); window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10); } this.postprocessResults(data, initial); postRender(); this.opts.element.trigger({ type: "select2-loaded", items: data }); })}); }, // abstract cancel: function () { this.close(); }, // abstract blur: function () { // if selectOnBlur == true, select the currently highlighted option if (this.opts.selectOnBlur) this.selectHighlighted({noFocus: true}); this.close(); this.container.removeClass("select2-container-active"); // synonymous to .is(':focus'), which is available in jquery >= 1.6 if (this.search[0] === document.activeElement) { this.search.blur(); } this.clearSearch(); this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"); }, // abstract focusSearch: function () { focus(this.search); }, // abstract selectHighlighted: function (options) { if (this._touchMoved) { this.clearTouchMoved(); return; } var index=this.highlight(), highlighted=this.results.find(".select2-highlighted"), data = highlighted.closest('.select2-result').data("select2-data"); if (data) { this.highlight(index); this.onSelect(data, options); } else if (options && options.noFocus) { this.close(); } }, // abstract getPlaceholder: function () { var placeholderOption; return this.opts.element.attr("placeholder") || this.opts.element.attr("data-placeholder") || // jquery 1.4 compat this.opts.element.data("placeholder") || this.opts.placeholder || ((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined); }, // abstract getPlaceholderOption: function() { if (this.select) { var firstOption = this.select.children('option').first(); if (this.opts.placeholderOption !== undefined ) { //Determine the placeholder option based on the specified placeholderOption setting return (this.opts.placeholderOption === "first" && firstOption) || (typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select)); } else if ($.trim(firstOption.text()) === "" && firstOption.val() === "") { //No explicit placeholder option specified, use the first if it's blank return firstOption; } } }, /** * Get the desired width for the container element. This is * derived first from option `width` passed to select2, then * the inline 'style' on the original element, and finally * falls back to the jQuery calculated element width. */ // abstract initContainerWidth: function () { function resolveContainerWidth() { var style, attrs, matches, i, l, attr; if (this.opts.width === "off") { return null; } else if (this.opts.width === "element"){ return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px'; } else if (this.opts.width === "copy" || this.opts.width === "resolve") { // check if there is inline style on the element that contains width style = this.opts.element.attr('style'); if (style !== undefined) { attrs = style.split(';'); for (i = 0, l = attrs.length; i < l; i = i + 1) { attr = attrs[i].replace(/\s/g, ''); matches = attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i); if (matches !== null && matches.length >= 1) return matches[1]; } } if (this.opts.width === "resolve") { // next check if css('width') can resolve a width that is percent based, this is sometimes possible // when attached to input type=hidden or elements hidden via css style = this.opts.element.css('width'); if (style.indexOf("%") > 0) return style; // finally, fallback on the calculated width of the element return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px'); } return null; } else if ($.isFunction(this.opts.width)) { return this.opts.width(); } else { return this.opts.width; } }; var width = resolveContainerWidth.call(this); if (width !== null) { this.container.css("width", width); } } }); SingleSelect2 = clazz(AbstractSelect2, { // single createContainer: function () { var container = $(document.createElement("div")).attr({ "class": "select2-container" }).html([ "<a href='javascript:void(0)' class='select2-choice' tabindex='-1'>", " <span class='select2-chosen'> </span><abbr class='select2-search-choice-close'></abbr>", " <span class='select2-arrow' role='presentation'><b role='presentation'></b></span>", "</a>", "<label for='' class='select2-offscreen'></label>", "<input class='select2-focusser select2-offscreen' type='text' aria-haspopup='true' role='button' />", "<div class='select2-drop select2-display-none'>", " <div class='select2-search'>", " <label for='' class='select2-offscreen'></label>", " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input' role='combobox' aria-expanded='true'", " aria-autocomplete='list' />", " </div>", " <ul class='select2-results' role='listbox'>", " </ul>", "</div>"].join("")); return container; }, // single enableInterface: function() { if (this.parent.enableInterface.apply(this, arguments)) { this.focusser.prop("disabled", !this.isInterfaceEnabled()); } }, // single opening: function () { var el, range, len; if (this.opts.minimumResultsForSearch >= 0) { this.showSearch(true); } this.parent.opening.apply(this, arguments); if (this.showSearchInput !== false) { // IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range // all other browsers handle this just fine this.search.val(this.focusser.val()); } if (this.opts.shouldFocusInput(this)) { this.search.focus(); // move the cursor to the end after focussing, otherwise it will be at the beginning and // new text will appear *before* focusser.val() el = this.search.get(0); if (el.createTextRange) { range = el.createTextRange(); range.collapse(false); range.select(); } else if (el.setSelectionRange) { len = this.search.val().length; el.setSelectionRange(len, len); } } // initializes search's value with nextSearchTerm (if defined by user) // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter if(this.search.val() === "") { if(this.nextSearchTerm != undefined){ this.search.val(this.nextSearchTerm); this.search.select(); } } this.focusser.prop("disabled", true).val(""); this.updateResults(true); this.opts.element.trigger($.Event("select2-open")); }, // single close: function () { if (!this.opened()) return; this.parent.close.apply(this, arguments); this.focusser.prop("disabled", false); if (this.opts.shouldFocusInput(this)) { this.focusser.focus(); } }, // single focus: function () { if (this.opened()) { this.close(); } else { this.focusser.prop("disabled", false); if (this.opts.shouldFocusInput(this)) { this.focusser.focus(); } } }, // single isFocused: function () { return this.container.hasClass("select2-container-active"); }, // single cancel: function () { this.parent.cancel.apply(this, arguments); this.focusser.prop("disabled", false); if (this.opts.shouldFocusInput(this)) { this.focusser.focus(); } }, // single destroy: function() { $("label[for='" + this.focusser.attr('id') + "']") .attr('for', this.opts.element.attr("id")); this.parent.destroy.apply(this, arguments); cleanupJQueryElements.call(this, "selection", "focusser" ); }, // single initContainer: function () { var selection, container = this.container, dropdown = this.dropdown, idSuffix = nextUid(), elementLabel; if (this.opts.minimumResultsForSearch < 0) { this.showSearch(false); } else { this.showSearch(true); } this.selection = selection = container.find(".select2-choice"); this.focusser = container.find(".select2-focusser"); // add aria associations selection.find(".select2-chosen").attr("id", "select2-chosen-"+idSuffix); this.focusser.attr("aria-labelledby", "select2-chosen-"+idSuffix); this.results.attr("id", "select2-results-"+idSuffix); this.search.attr("aria-owns", "select2-results-"+idSuffix); // rewrite labels from original element to focusser this.focusser.attr("id", "s2id_autogen"+idSuffix); elementLabel = $("label[for='" + this.opts.element.attr("id") + "']"); this.focusser.prev() .text(elementLabel.text()) .attr('for', this.focusser.attr('id')); // Ensure the original element retains an accessible name var originalTitle = this.opts.element.attr("title"); this.opts.element.attr("title", (originalTitle || elementLabel.text())); this.focusser.attr("tabindex", this.elementTabIndex); // write label for search field using the label from the focusser element this.search.attr("id", this.focusser.attr('id') + '_search'); this.search.prev() .text($("label[for='" + this.focusser.attr('id') + "']").text()) .attr('for', this.search.attr('id')); this.search.on("keydown", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) { // prevent the page from scrolling killEvent(e); return; } switch (e.which) { case KEY.UP: case KEY.DOWN: this.moveHighlight((e.which === KEY.UP) ? -1 : 1); killEvent(e); return; case KEY.ENTER: this.selectHighlighted(); killEvent(e); return; case KEY.TAB: this.selectHighlighted({noFocus: true}); return; case KEY.ESC: this.cancel(e); killEvent(e); return; } })); this.search.on("blur", this.bind(function(e) { // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown. // without this the search field loses focus which is annoying if (document.activeElement === this.body.get(0)) { window.setTimeout(this.bind(function() { if (this.opened()) { this.search.focus(); } }), 0); } })); this.focusser.on("keydown", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) { return; } if (this.opts.openOnEnter === false && e.which === KEY.ENTER) { killEvent(e); return; } if (e.which == KEY.DOWN || e.which == KEY.UP || (e.which == KEY.ENTER && this.opts.openOnEnter)) { if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return; this.open(); killEvent(e); return; } if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) { if (this.opts.allowClear) { this.clear(); } killEvent(e); return; } })); installKeyUpChangeEvent(this.focusser); this.focusser.on("keyup-change input", this.bind(function(e) { if (this.opts.minimumResultsForSearch >= 0) { e.stopPropagation(); if (this.opened()) return; this.open(); } })); selection.on("mousedown touchstart", "abbr", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; this.clear(); killEventImmediately(e); this.close(); this.selection.focus(); })); selection.on("mousedown touchstart", this.bind(function (e) { // Prevent IE from generating a click event on the body reinsertElement(selection); if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } if (this.opened()) { this.close(); } else if (this.isInterfaceEnabled()) { this.open(); } killEvent(e); })); dropdown.on("mousedown touchstart", this.bind(function() { if (this.opts.shouldFocusInput(this)) { this.search.focus(); } })); selection.on("focus", this.bind(function(e) { killEvent(e); })); this.focusser.on("focus", this.bind(function(){ if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.container.addClass("select2-container-active"); })).on("blur", this.bind(function() { if (!this.opened()) { this.container.removeClass("select2-container-active"); this.opts.element.trigger($.Event("select2-blur")); } })); this.search.on("focus", this.bind(function(){ if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.container.addClass("select2-container-active"); })); this.initContainerWidth(); this.opts.element.addClass("select2-offscreen"); this.setPlaceholder(); }, // single clear: function(triggerChange) { var data=this.selection.data("select2-data"); if (data) { // guard against queued quick consecutive clicks var evt = $.Event("select2-clearing"); this.opts.element.trigger(evt); if (evt.isDefaultPrevented()) { return; } var placeholderOption = this.getPlaceholderOption(); this.opts.element.val(placeholderOption ? placeholderOption.val() : ""); this.selection.find(".select2-chosen").empty(); this.selection.removeData("select2-data"); this.setPlaceholder(); if (triggerChange !== false){ this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data }); this.triggerChange({removed:data}); } } }, /** * Sets selection based on source element's value */ // single initSelection: function () { var selected; if (this.isPlaceholderOptionSelected()) { this.updateSelection(null); this.close(); this.setPlaceholder(); } else { var self = this; this.opts.initSelection.call(null, this.opts.element, function(selected){ if (selected !== undefined && selected !== null) { self.updateSelection(selected); self.close(); self.setPlaceholder(); self.nextSearchTerm = self.opts.nextSearchTerm(selected, self.search.val()); } }); } }, isPlaceholderOptionSelected: function() { var placeholderOption; if (this.getPlaceholder() === undefined) return false; // no placeholder specified so no option should be considered return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.prop("selected")) || (this.opts.element.val() === "") || (this.opts.element.val() === undefined) || (this.opts.element.val() === null); }, // single prepareOpts: function () { var opts = this.parent.prepareOpts.apply(this, arguments), self=this; if (opts.element.get(0).tagName.toLowerCase() === "select") { // install the selection initializer opts.initSelection = function (element, callback) { var selected = element.find("option").filter(function() { return this.selected && !this.disabled }); // a single select box always has a value, no need to null check 'selected' callback(self.optionToData(selected)); }; } else if ("data" in opts) { // install default initSelection when applied to hidden input and data is local opts.initSelection = opts.initSelection || function (element, callback) { var id = element.val(); //search in data by id, storing the actual matching item var match = null; opts.query({ matcher: function(term, text, el){ var is_match = equal(id, opts.id(el)); if (is_match) { match = el; } return is_match; }, callback: !$.isFunction(callback) ? $.noop : function() { callback(match); } }); }; } return opts; }, // single getPlaceholder: function() { // if a placeholder is specified on a single select without a valid placeholder option ignore it if (this.select) { if (this.getPlaceholderOption() === undefined) { return undefined; } } return this.parent.getPlaceholder.apply(this, arguments); }, // single setPlaceholder: function () { var placeholder = this.getPlaceholder(); if (this.isPlaceholderOptionSelected() && placeholder !== undefined) { // check for a placeholder option if attached to a select if (this.select && this.getPlaceholderOption() === undefined) return; this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder)); this.selection.addClass("select2-default"); this.container.removeClass("select2-allowclear"); } }, // single postprocessResults: function (data, initial, noHighlightUpdate) { var selected = 0, self = this, showSearchInput = true; // find the selected element in the result list this.findHighlightableChoices().each2(function (i, elm) { if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) { selected = i; return false; } }); // and highlight it if (noHighlightUpdate !== false) { if (initial === true && selected >= 0) { this.highlight(selected); } else { this.highlight(0); } } // hide the search box if this is the first we got the results and there are enough of them for search if (initial === true) { var min = this.opts.minimumResultsForSearch; if (min >= 0) { this.showSearch(countResults(data.results) >= min); } } }, // single showSearch: function(showSearchInput) { if (this.showSearchInput === showSearchInput) return; this.showSearchInput = showSearchInput; this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput); this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput); //add "select2-with-searchbox" to the container if search box is shown $(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput); }, // single onSelect: function (data, options) { if (!this.triggerSelect(data)) { return; } var old = this.opts.element.val(), oldData = this.data(); this.opts.element.val(this.id(data)); this.updateSelection(data); this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data }); this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val()); this.close(); if ((!options || !options.noFocus) && this.opts.shouldFocusInput(this)) { this.focusser.focus(); } if (!equal(old, this.id(data))) { this.triggerChange({ added: data, removed: oldData }); } }, // single updateSelection: function (data) { var container=this.selection.find(".select2-chosen"), formatted, cssClass; this.selection.data("select2-data", data); container.empty(); if (data !== null) { formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup); } if (formatted !== undefined) { container.append(formatted); } cssClass=this.opts.formatSelectionCssClass(data, container); if (cssClass !== undefined) { container.addClass(cssClass); } this.selection.removeClass("select2-default"); if (this.opts.allowClear && this.getPlaceholder() !== undefined) { this.container.addClass("select2-allowclear"); } }, // single val: function () { var val, triggerChange = false, data = null, self = this, oldData = this.data(); if (arguments.length === 0) { return this.opts.element.val(); } val = arguments[0]; if (arguments.length > 1) { triggerChange = arguments[1]; } if (this.select) { this.select .val(val) .find("option").filter(function() { return this.selected }).each2(function (i, elm) { data = self.optionToData(elm); return false; }); this.updateSelection(data); this.setPlaceholder(); if (triggerChange) { this.triggerChange({added: data, removed:oldData}); } } else { // val is an id. !val is true for [undefined,null,'',0] - 0 is legal if (!val && val !== 0) { this.clear(triggerChange); return; } if (this.opts.initSelection === undefined) { throw new Error("cannot call val() if initSelection() is not defined"); } this.opts.element.val(val); this.opts.initSelection(this.opts.element, function(data){ self.opts.element.val(!data ? "" : self.id(data)); self.updateSelection(data); self.setPlaceholder(); if (triggerChange) { self.triggerChange({added: data, removed:oldData}); } }); } }, // single clearSearch: function () { this.search.val(""); this.focusser.val(""); }, // single data: function(value) { var data, triggerChange = false; if (arguments.length === 0) { data = this.selection.data("select2-data"); if (data == undefined) data = null; return data; } else { if (arguments.length > 1) { triggerChange = arguments[1]; } if (!value) { this.clear(triggerChange); } else { data = this.data(); this.opts.element.val(!value ? "" : this.id(value)); this.updateSelection(value); if (triggerChange) { this.triggerChange({added: value, removed:data}); } } } } }); MultiSelect2 = clazz(AbstractSelect2, { // multi createContainer: function () { var container = $(document.createElement("div")).attr({ "class": "select2-container select2-container-multi" }).html([ "<ul class='select2-choices'>", " <li class='select2-search-field'>", " <label for='' class='select2-offscreen'></label>", " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>", " </li>", "</ul>", "<div class='select2-drop select2-drop-multi select2-display-none'>", " <ul class='select2-results'>", " </ul>", "</div>"].join("")); return container; }, // multi prepareOpts: function () { var opts = this.parent.prepareOpts.apply(this, arguments), self=this; // TODO validate placeholder is a string if specified if (opts.element.get(0).tagName.toLowerCase() === "select") { // install the selection initializer opts.initSelection = function (element, callback) { var data = []; element.find("option").filter(function() { return this.selected && !this.disabled }).each2(function (i, elm) { data.push(self.optionToData(elm)); }); callback(data); }; } else if ("data" in opts) { // install default initSelection when applied to hidden input and data is local opts.initSelection = opts.initSelection || function (element, callback) { var ids = splitVal(element.val(), opts.separator); //search in data by array of ids, storing matching items in a list var matches = []; opts.query({ matcher: function(term, text, el){ var is_match = $.grep(ids, function(id) { return equal(id, opts.id(el)); }).length; if (is_match) { matches.push(el); } return is_match; }, callback: !$.isFunction(callback) ? $.noop : function() { // reorder matches based on the order they appear in the ids array because right now // they are in the order in which they appear in data array var ordered = []; for (var i = 0; i < ids.length; i++) { var id = ids[i]; for (var j = 0; j < matches.length; j++) { var match = matches[j]; if (equal(id, opts.id(match))) { ordered.push(match); matches.splice(j, 1); break; } } } callback(ordered); } }); }; } return opts; }, // multi selectChoice: function (choice) { var selected = this.container.find(".select2-search-choice-focus"); if (selected.length && choice && choice[0] == selected[0]) { } else { if (selected.length) { this.opts.element.trigger("choice-deselected", selected); } selected.removeClass("select2-search-choice-focus"); if (choice && choice.length) { this.close(); choice.addClass("select2-search-choice-focus"); this.opts.element.trigger("choice-selected", choice); } } }, // multi destroy: function() { $("label[for='" + this.search.attr('id') + "']") .attr('for', this.opts.element.attr("id")); this.parent.destroy.apply(this, arguments); cleanupJQueryElements.call(this, "searchContainer", "selection" ); }, // multi initContainer: function () { var selector = ".select2-choices", selection; this.searchContainer = this.container.find(".select2-search-field"); this.selection = selection = this.container.find(selector); var _this = this; this.selection.on("click", ".select2-search-choice:not(.select2-locked)", function (e) { //killEvent(e); _this.search[0].focus(); _this.selectChoice($(this)); }); // rewrite labels from original element to focusser this.search.attr("id", "s2id_autogen"+nextUid()); this.search.prev() .text($("label[for='" + this.opts.element.attr("id") + "']").text()) .attr('for', this.search.attr('id')); this.search.on("input paste", this.bind(function() { if (this.search.attr('placeholder') && this.search.val().length == 0) return; if (!this.isInterfaceEnabled()) return; if (!this.opened()) { this.open(); } })); this.search.attr("tabindex", this.elementTabIndex); this.keydowns = 0; this.search.on("keydown", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; ++this.keydowns; var selected = selection.find(".select2-search-choice-focus"); var prev = selected.prev(".select2-search-choice:not(.select2-locked)"); var next = selected.next(".select2-search-choice:not(.select2-locked)"); var pos = getCursorInfo(this.search); if (selected.length && (e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) { var selectedChoice = selected; if (e.which == KEY.LEFT && prev.length) { selectedChoice = prev; } else if (e.which == KEY.RIGHT) { selectedChoice = next.length ? next : null; } else if (e.which === KEY.BACKSPACE) { if (this.unselect(selected.first())) { this.search.width(10); selectedChoice = prev.length ? prev : next; } } else if (e.which == KEY.DELETE) { if (this.unselect(selected.first())) { this.search.width(10); selectedChoice = next.length ? next : null; } } else if (e.which == KEY.ENTER) { selectedChoice = null; } this.selectChoice(selectedChoice); killEvent(e); if (!selectedChoice || !selectedChoice.length) { this.open(); } return; } else if (((e.which === KEY.BACKSPACE && this.keydowns == 1) || e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) { this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last()); killEvent(e); return; } else { this.selectChoice(null); } if (this.opened()) { switch (e.which) { case KEY.UP: case KEY.DOWN: this.moveHighlight((e.which === KEY.UP) ? -1 : 1); killEvent(e); return; case KEY.ENTER: this.selectHighlighted(); killEvent(e); return; case KEY.TAB: this.selectHighlighted({noFocus:true}); this.close(); return; case KEY.ESC: this.cancel(e); killEvent(e); return; } } if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) { return; } if (e.which === KEY.ENTER) { if (this.opts.openOnEnter === false) { return; } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) { return; } } this.open(); if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) { // prevent the page from scrolling killEvent(e); } if (e.which === KEY.ENTER) { // prevent form from being submitted killEvent(e); } })); this.search.on("keyup", this.bind(function (e) { this.keydowns = 0; this.resizeSearch(); }) ); this.search.on("blur", this.bind(function(e) { this.container.removeClass("select2-container-active"); this.search.removeClass("select2-focused"); this.selectChoice(null); if (!this.opened()) this.clearSearch(); e.stopImmediatePropagation(); this.opts.element.trigger($.Event("select2-blur")); })); this.container.on("click", selector, this.bind(function (e) { if (!this.isInterfaceEnabled()) return; if ($(e.target).closest(".select2-search-choice").length > 0) { // clicked inside a select2 search choice, do not open return; } this.selectChoice(null); this.clearPlaceholder(); if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.open(); this.focusSearch(); e.preventDefault(); })); this.container.on("focus", selector, this.bind(function () { if (!this.isInterfaceEnabled()) return; if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.container.addClass("select2-container-active"); this.dropdown.addClass("select2-drop-active"); this.clearPlaceholder(); })); this.initContainerWidth(); this.opts.element.addClass("select2-offscreen"); // set the placeholder if necessary this.clearSearch(); }, // multi enableInterface: function() { if (this.parent.enableInterface.apply(this, arguments)) { this.search.prop("disabled", !this.isInterfaceEnabled()); } }, // multi initSelection: function () { var data; if (this.opts.element.val() === "" && this.opts.element.text() === "") { this.updateSelection([]); this.close(); // set the placeholder if necessary this.clearSearch(); } if (this.select || this.opts.element.val() !== "") { var self = this; this.opts.initSelection.call(null, this.opts.element, function(data){ if (data !== undefined && data !== null) { self.updateSelection(data); self.close(); // set the placeholder if necessary self.clearSearch(); } }); } }, // multi clearSearch: function () { var placeholder = this.getPlaceholder(), maxWidth = this.getMaxSearchWidth(); if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) { this.search.val(placeholder).addClass("select2-default"); // stretch the search box to full width of the container so as much of the placeholder is visible as possible // we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944 this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width")); } else { this.search.val("").width(10); } }, // multi clearPlaceholder: function () { if (this.search.hasClass("select2-default")) { this.search.val("").removeClass("select2-default"); } }, // multi opening: function () { this.clearPlaceholder(); // should be done before super so placeholder is not used to search this.resizeSearch(); this.parent.opening.apply(this, arguments); this.focusSearch(); // initializes search's value with nextSearchTerm (if defined by user) // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter if(this.search.val() === "") { if(this.nextSearchTerm != undefined){ this.search.val(this.nextSearchTerm); this.search.select(); } } this.updateResults(true); if (this.opts.shouldFocusInput(this)) { this.search.focus(); } this.opts.element.trigger($.Event("select2-open")); }, // multi close: function () { if (!this.opened()) return; this.parent.close.apply(this, arguments); }, // multi focus: function () { this.close(); this.search.focus(); }, // multi isFocused: function () { return this.search.hasClass("select2-focused"); }, // multi updateSelection: function (data) { var ids = [], filtered = [], self = this; // filter out duplicates $(data).each(function () { if (indexOf(self.id(this), ids) < 0) { ids.push(self.id(this)); filtered.push(this); } }); data = filtered; this.selection.find(".select2-search-choice").remove(); $(data).each(function () { self.addSelectedChoice(this); }); self.postprocessResults(); }, // multi tokenize: function() { var input = this.search.val(); input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts); if (input != null && input != undefined) { this.search.val(input); if (input.length > 0) { this.open(); } } }, // multi onSelect: function (data, options) { if (!this.triggerSelect(data)) { return; } this.addSelectedChoice(data); this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data }); // keep track of the search's value before it gets cleared this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val()); this.clearSearch(); this.updateResults(); if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true); if (this.opts.closeOnSelect) { this.close(); this.search.width(10); } else { if (this.countSelectableResults()>0) { this.search.width(10); this.resizeSearch(); if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) { // if we reached max selection size repaint the results so choices // are replaced with the max selection reached message this.updateResults(true); } else { // initializes search's value with nextSearchTerm and update search result if(this.nextSearchTerm != undefined){ this.search.val(this.nextSearchTerm); this.updateResults(); this.search.select(); } } this.positionDropdown(); } else { // if nothing left to select close this.close(); this.search.width(10); } } // since its not possible to select an element that has already been // added we do not need to check if this is a new element before firing change this.triggerChange({ added: data }); if (!options || !options.noFocus) this.focusSearch(); }, // multi cancel: function () { this.close(); this.focusSearch(); }, addSelectedChoice: function (data) { var enableChoice = !data.locked, enabledItem = $( "<li class='select2-search-choice'>" + " <div></div>" + " <a href='#' class='select2-search-choice-close' tabindex='-1'></a>" + "</li>"), disabledItem = $( "<li class='select2-search-choice select2-locked'>" + "<div></div>" + "</li>"); var choice = enableChoice ? enabledItem : disabledItem, id = this.id(data), val = this.getVal(), formatted, cssClass; formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup); if (formatted != undefined) { choice.find("div").replaceWith("<div>"+formatted+"</div>"); } cssClass=this.opts.formatSelectionCssClass(data, choice.find("div")); if (cssClass != undefined) { choice.addClass(cssClass); } if(enableChoice){ choice.find(".select2-search-choice-close") .on("mousedown", killEvent) .on("click dblclick", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; this.unselect($(e.target)); this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"); killEvent(e); this.close(); this.focusSearch(); })).on("focus", this.bind(function () { if (!this.isInterfaceEnabled()) return; this.container.addClass("select2-container-active"); this.dropdown.addClass("select2-drop-active"); })); } choice.data("select2-data", data); choice.insertBefore(this.searchContainer); val.push(id); this.setVal(val); }, // multi unselect: function (selected) { var val = this.getVal(), data, index; selected = selected.closest(".select2-search-choice"); if (selected.length === 0) { throw "Invalid argument: " + selected + ". Must be .select2-search-choice"; } data = selected.data("select2-data"); if (!data) { // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued // and invoked on an element already removed return; } var evt = $.Event("select2-removing"); evt.val = this.id(data); evt.choice = data; this.opts.element.trigger(evt); if (evt.isDefaultPrevented()) { return false; } while((index = indexOf(this.id(data), val)) >= 0) { val.splice(index, 1); this.setVal(val); if (this.select) this.postprocessResults(); } selected.remove(); this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data }); this.triggerChange({ removed: data }); return true; }, // multi postprocessResults: function (data, initial, noHighlightUpdate) { var val = this.getVal(), choices = this.results.find(".select2-result"), compound = this.results.find(".select2-result-with-children"), self = this; choices.each2(function (i, choice) { var id = self.id(choice.data("select2-data")); if (indexOf(id, val) >= 0) { choice.addClass("select2-selected"); // mark all children of the selected parent as selected choice.find(".select2-result-selectable").addClass("select2-selected"); } }); compound.each2(function(i, choice) { // hide an optgroup if it doesn't have any selectable children if (!choice.is('.select2-result-selectable') && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) { choice.addClass("select2-selected"); } }); if (this.highlight() == -1 && noHighlightUpdate !== false){ self.highlight(0); } //If all results are chosen render formatNoMatches if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){ if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) { if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) { this.results.append("<li class='select2-no-results'>" + evaluate(self.opts.formatNoMatches, self.opts.element, self.search.val()) + "</li>"); } } } }, // multi getMaxSearchWidth: function() { return this.selection.width() - getSideBorderPadding(this.search); }, // multi resizeSearch: function () { var minimumWidth, left, maxWidth, containerLeft, searchWidth, sideBorderPadding = getSideBorderPadding(this.search); minimumWidth = measureTextWidth(this.search) + 10; left = this.search.offset().left; maxWidth = this.selection.width(); containerLeft = this.selection.offset().left; searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding; if (searchWidth < minimumWidth) { searchWidth = maxWidth - sideBorderPadding; } if (searchWidth < 40) { searchWidth = maxWidth - sideBorderPadding; } if (searchWidth <= 0) { searchWidth = minimumWidth; } this.search.width(Math.floor(searchWidth)); }, // multi getVal: function () { var val; if (this.select) { val = this.select.val(); return val === null ? [] : val; } else { val = this.opts.element.val(); return splitVal(val, this.opts.separator); } }, // multi setVal: function (val) { var unique; if (this.select) { this.select.val(val); } else { unique = []; // filter out duplicates $(val).each(function () { if (indexOf(this, unique) < 0) unique.push(this); }); this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator)); } }, // multi buildChangeDetails: function (old, current) { var current = current.slice(0), old = old.slice(0); // remove intersection from each array for (var i = 0; i < current.length; i++) { for (var j = 0; j < old.length; j++) { if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) { current.splice(i, 1); if(i>0){ i--; } old.splice(j, 1); j--; } } } return {added: current, removed: old}; }, // multi val: function (val, triggerChange) { var oldData, self=this; if (arguments.length === 0) { return this.getVal(); } oldData=this.data(); if (!oldData.length) oldData=[]; // val is an id. !val is true for [undefined,null,'',0] - 0 is legal if (!val && val !== 0) { this.opts.element.val(""); this.updateSelection([]); this.clearSearch(); if (triggerChange) { this.triggerChange({added: this.data(), removed: oldData}); } return; } // val is a list of ids this.setVal(val); if (this.select) { this.opts.initSelection(this.select, this.bind(this.updateSelection)); if (triggerChange) { this.triggerChange(this.buildChangeDetails(oldData, this.data())); } } else { if (this.opts.initSelection === undefined) { throw new Error("val() cannot be called if initSelection() is not defined"); } this.opts.initSelection(this.opts.element, function(data){ var ids=$.map(data, self.id); self.setVal(ids); self.updateSelection(data); self.clearSearch(); if (triggerChange) { self.triggerChange(self.buildChangeDetails(oldData, self.data())); } }); } this.clearSearch(); }, // multi onSortStart: function() { if (this.select) { throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead."); } // collapse search field into 0 width so its container can be collapsed as well this.search.width(0); // hide the container this.searchContainer.hide(); }, // multi onSortEnd:function() { var val=[], self=this; // show search and move it to the end of the list this.searchContainer.show(); // make sure the search container is the last item in the list this.searchContainer.appendTo(this.searchContainer.parent()); // since we collapsed the width in dragStarted, we resize it here this.resizeSearch(); // update selection this.selection.find(".select2-search-choice").each(function() { val.push(self.opts.id($(this).data("select2-data"))); }); this.setVal(val); this.triggerChange(); }, // multi data: function(values, triggerChange) { var self=this, ids, old; if (arguments.length === 0) { return this.selection .children(".select2-search-choice") .map(function() { return $(this).data("select2-data"); }) .get(); } else { old = this.data(); if (!values) { values = []; } ids = $.map(values, function(e) { return self.opts.id(e); }); this.setVal(ids); this.updateSelection(values); this.clearSearch(); if (triggerChange) { this.triggerChange(this.buildChangeDetails(old, this.data())); } } } }); $.fn.select2 = function () { var args = Array.prototype.slice.call(arguments, 0), opts, select2, method, value, multiple, allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"], valueMethods = ["opened", "isFocused", "container", "dropdown"], propertyMethods = ["val", "data"], methodsMap = { search: "externalSearch" }; this.each(function () { if (args.length === 0 || typeof(args[0]) === "object") { opts = args.length === 0 ? {} : $.extend({}, args[0]); opts.element = $(this); if (opts.element.get(0).tagName.toLowerCase() === "select") { multiple = opts.element.prop("multiple"); } else { multiple = opts.multiple || false; if ("tags" in opts) {opts.multiple = multiple = true;} } select2 = multiple ? new window.Select2["class"].multi() : new window.Select2["class"].single(); select2.init(opts); } else if (typeof(args[0]) === "string") { if (indexOf(args[0], allowedMethods) < 0) { throw "Unknown method: " + args[0]; } value = undefined; select2 = $(this).data("select2"); if (select2 === undefined) return; method=args[0]; if (method === "container") { value = select2.container; } else if (method === "dropdown") { value = select2.dropdown; } else { if (methodsMap[method]) method = methodsMap[method]; value = select2[method].apply(select2, args.slice(1)); } if (indexOf(args[0], valueMethods) >= 0 || (indexOf(args[0], propertyMethods) >= 0 && args.length == 1)) { return false; // abort the iteration, ready to return first matched value } } else { throw "Invalid arguments to select2 plugin: " + args; } }); return (value === undefined) ? this : value; }; // plugin defaults, accessible to users $.fn.select2.defaults = { width: "copy", loadMorePadding: 0, closeOnSelect: true, openOnEnter: true, containerCss: {}, dropdownCss: {}, containerCssClass: "", dropdownCssClass: "", formatResult: function(result, container, query, escapeMarkup) { var markup=[]; markMatch(result.text, query.term, markup, escapeMarkup); return markup.join(""); }, formatSelection: function (data, container, escapeMarkup) { return data ? escapeMarkup(data.text) : undefined; }, sortResults: function (results, container, query) { return results; }, formatResultCssClass: function(data) {return data.css;}, formatSelectionCssClass: function(data, container) {return undefined;}, formatMatches: function (matches) { if (matches === 1) { return "One result is available, press enter to select it."; } return matches + " results are available, use up and down arrow keys to navigate."; }, formatNoMatches: function () { return "No matches found"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " or more character" + (n == 1? "" : "s"); }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); }, formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); }, formatLoadMore: function (pageNumber) { return "Loading more results…"; }, formatSearching: function () { return "Searching…"; }, minimumResultsForSearch: 0, minimumInputLength: 0, maximumInputLength: null, maximumSelectionSize: 0, id: function (e) { return e == undefined ? null : e.id; }, matcher: function(term, text) { return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0; }, separator: ",", tokenSeparators: [], tokenizer: defaultTokenizer, escapeMarkup: defaultEscapeMarkup, blurOnChange: false, selectOnBlur: false, adaptContainerCssClass: function(c) { return c; }, adaptDropdownCssClass: function(c) { return null; }, nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; }, searchInputPlaceholder: '', createSearchChoicePosition: 'top', shouldFocusInput: function (instance) { // Attempt to detect touch devices var supportsTouchEvents = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0)); // Only devices which support touch events should be special cased if (!supportsTouchEvents) { return true; } // Never focus the input if search is disabled if (instance.opts.minimumResultsForSearch < 0) { return false; } return true; } }; $.fn.select2.ajaxDefaults = { transport: $.ajax, params: { type: "GET", cache: false, dataType: "json" } }; // exports window.Select2 = { query: { ajax: ajax, local: local, tags: tags }, util: { debounce: debounce, markMatch: markMatch, escapeMarkup: defaultEscapeMarkup, stripDiacritics: stripDiacritics }, "class": { "abstract": AbstractSelect2, "single": SingleSelect2, "multi": MultiSelect2 } }; }(jQuery)); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["alert_dialog"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing; buffer += "<div class=\"scrivito_alert_dialog scrivito_modal_prompt scrivito_center_dialog scrivito_"; if (stack1 = helpers.color) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.color; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\">\n <div class=\"scrivito_modal_header\">\n <i class=\"scrivito_icon\">"; if (stack1 = helpers.icon) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.icon; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</i><h3 class=\"scrivito_title\">"; if (stack1 = helpers.message) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.message; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</h3>\n </div>\n <div class=\"scrivito_modal_footer\">\n <a href=\"#\" class=\"scrivito_button scrivito_close\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "ok", options) : helperMissing.call(depth0, "translate", "ok", options))) + "</a>\n </div>\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["alert_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["changes_dialog"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; buffer += "<div class=\"scrivito_changes_overview scrivito_modal_large scrivito_adjust_dialog\" >\n\n <div class=\"scrivito_modal_header\">\n <h3>\n <i class=\"scrivito_icon\"></i>\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "changes_dialog.title", depth0.selected_workspace_title, options) : helperMissing.call(depth0, "translate", "changes_dialog.title", depth0.selected_workspace_title, options))) + "\n <span id=\"scrivito_obj_count\" class=\"scrivito_hidden\">\n (<span id=\"scrivito_loaded_obj_count\"></span> / <span id=\"scrivito_total_obj_count\"></span>)\n </span>\n </h3>\n </div>\n <div class=\"scrivito_modal_body scrivito_auto_height\">\n\n <table class=\"scrivito_changes_table\">\n <thead>\n <tr>\n <th><span class=\"scrivito_sortable\" data-scrivito-private-sort-by=\"modification\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "changes_dialog.row.change", options) : helperMissing.call(depth0, "translate", "changes_dialog.row.change", options))) + "</span></th>\n <th><span class=\"scrivito_sortable\" data-scrivito-private-sort-by=\"rights\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "changes_dialog.row.rights", options) : helperMissing.call(depth0, "translate", "changes_dialog.row.rights", options))) + "</span></th>\n <th><span>"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "changes_dialog.row.description_for_editor", options) : helperMissing.call(depth0, "translate", "changes_dialog.row.description_for_editor", options))) + "</span></th>\n <th><span class=\"scrivito_sortable\" data-scrivito-private-sort-by=\"obj_class_name\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "changes_dialog.row.type", options) : helperMissing.call(depth0, "translate", "changes_dialog.row.type", options))) + "</span></th>\n <th><span class=\"scrivito_sortable sort_down\" data-scrivito-private-sort-by=\"last_changed\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "changes_dialog.row.last_changed", options) : helperMissing.call(depth0, "translate", "changes_dialog.row.last_changed", options))) + "</span></th>\n </tr>\n </thead>\n <tbody id=\"scrivito_changes_table_loaded\">\n </tbody>\n <tbody id=\"scrivito_changes_table_empty_result\" class=\"scrivito_hidden\">\n <tr>\n <td colspan=\"5\">\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "changes_dialog.empty_result", options) : helperMissing.call(depth0, "translate", "changes_dialog.empty_result", options))) + "\n </td>\n </tr>\n </tbody>\n <tbody id=\"scrivito_changes_table_loading\">\n <tr>\n <td colspan=\"5\">\n <i class=\"scrivito_icon scrivito_spinning\"></i>\n </td>\n </tr>\n </tbody>\n\n </table>\n\n <span class=\"scrivito_load_more scrivito_hidden\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "changes_dialog.more", options) : helperMissing.call(depth0, "translate", "changes_dialog.more", options))) + "</span>\n\n </div>\n <div class=\"scrivito_modal_footer\">\n <a class=\"scrivito_button scrivito_cancel scrivito_green\" href=\"#\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "done", options) : helperMissing.call(depth0, "translate", "done", options))) + "</a>\n </div>\n\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["changes_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["changes_dialog/row"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, helperMissing=helpers.helperMissing, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { return "conflict"; } function program3(depth0,data) { var buffer = "", stack1, stack2, options; buffer += "\n <span class=\"scrivito_restriction\" title=\""; options = {hash:{},data:data}; stack2 = ((stack1 = helpers.array_to_title),stack1 ? stack1.call(depth0, depth0.restriction_messages, options) : helperMissing.call(depth0, "array_to_title", depth0.restriction_messages, options)); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\"></span>\n "; return buffer; } function program5(depth0,data) { return "\n <span></span>\n "; } function program7(depth0,data) { var buffer = "", stack1, options; buffer += "\n <span><time datetime=\""; if (stack1 = helpers.last_changed) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.last_changed; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\" title=\""; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.localize_date),stack1 ? stack1.call(depth0, depth0.last_changed, options) : helperMissing.call(depth0, "localize_date", depth0.last_changed, options))) + "\">\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.localize_date_relative),stack1 ? stack1.call(depth0, depth0.last_changed, options) : helperMissing.call(depth0, "localize_date_relative", depth0.last_changed, options))) + "\n </time></span>\n "; return buffer; } buffer += "<tr class=\"scrivito_link_to_obj\" title=\""; if (stack1 = helpers.tooltip) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.tooltip; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\"\n data-scrivito-private-changes-list-obj-id=\""; if (stack1 = helpers.id) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.id; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\"\n data-scrivito-private-changes-list-obj-modification=\""; if (stack1 = helpers.modification) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.modification; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\"\n data-scrivito-private-changes-list-obj-is-binary=\""; if (stack1 = helpers.is_binary) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.is_binary; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\">\n <td><span class=\"scrivito_changes_state "; if (stack1 = helpers.modification) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.modification; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + " "; stack1 = helpers['if'].call(depth0, depth0.has_conflict, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\"></span></td>\n <td>\n "; stack1 = helpers['if'].call(depth0, depth0.has_restriction, {hash:{},inverse:self.program(5, program5, data),fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </td>\n <td><span class=\"scrivito_title\">"; if (stack1 = helpers.description_for_editor) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.description_for_editor; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</span>\n <td><span class=\"scrivito_obj_class\">"; if (stack1 = helpers.obj_class_name) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.obj_class_name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</span></td>\n <td>\n "; stack1 = helpers.unless.call(depth0, depth0.is_deleted, {hash:{},inverse:self.noop,fn:self.program(7, program7, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </td>\n</tr>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["changes_dialog/row"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["choose_obj_class_dialog"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing; buffer += "<div class=\"scrivito_choose_obj_class_dialog scrivito_modal_large scrivito_adjust_dialog\">\n\n <div class=\"scrivito_modal_header\">\n <h3><i class=\"scrivito_icon\"></i>"; if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</h3>\n </div>\n\n <div class=\"scrivito_modal_body scrivito_auto_height\">\n <div id=\"scrivito_replace_with_real_obj_classes\">\n <i class=\"scrivito_icon scrivito_spinning\" title=\""; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "loading", options) : helperMissing.call(depth0, "translate", "loading", options))) + "\"></i>\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "loading", options) : helperMissing.call(depth0, "translate", "loading", options))) + "\n </div>\n </div>\n\n <div class=\"scrivito_modal_footer\">\n <a href=\"#\" class=\"scrivito_button scrivito_cancel\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "cancel", options) : helperMissing.call(depth0, "translate", "cancel", options))) + "</a>\n </div>\n\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["choose_obj_class_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["choose_obj_class_list"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['with'].call(depth0, depth0, {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program2(depth0,data) { var buffer = "", stack1; buffer += "\n <div class=\"scrivito_obj_class_thumbnail scrivito_editing_widget_preview\" data-scrivito-private-obj-class-name=\""; if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\">\n "; if (stack1 = helpers.markup) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.markup; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n "; return buffer; } stack1 = helpers.each.call(depth0, depth0.obj_classes, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["choose_obj_class_list"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["confirmation_dialog"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "scrivito_"; if (stack1 = helpers.color) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.color; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1); return buffer; } function program3(depth0,data) { var buffer = "", stack1; buffer += "\n <p class=\"scrivito_description\">"; if (stack1 = helpers.description) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.description; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</p>\n "; return buffer; } buffer += "<div class=\"scrivito_confirmation_dialog scrivito_modal_prompt scrivito_center_dialog\n "; stack1 = helpers['if'].call(depth0, depth0.color, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n <div class=\"scrivito_modal_header\">\n <i class=\"scrivito_icon\">"; if (stack1 = helpers.icon) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.icon; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</i>\n <h3 class=\"scrivito_title\">"; if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</h3>\n "; stack1 = helpers['if'].call(depth0, depth0.description, {hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n <div class=\"scrivito_modal_footer\">\n <a href=\"#\" class=\"scrivito_button scrivito_"; if (stack1 = helpers.cancel_button_color) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.cancel_button_color; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + " scrivito_cancel\">\n "; if (stack1 = helpers.cancel_button_text) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.cancel_button_text; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\n </a>\n <a href=\"#\" class=\"scrivito_button scrivito_"; if (stack1 = helpers.confirm_button_color) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.confirm_button_color; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + " scrivito_confirm\">\n "; if (stack1 = helpers.confirm_button_text) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.confirm_button_text; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\n </a>\n </div>\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["confirmation_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["current_page_restriction"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; buffer += "<div class=\"scrivito_button_bar scrivito_right\" title=\""; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.array_to_title),stack1 ? stack1.call(depth0, depth0.restriction_messages, options) : helperMissing.call(depth0, "array_to_title", depth0.restriction_messages, options))) + "\">\n <i class=\"scrivito_icon\"></i>\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["current_page_restriction"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["details_dialog"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, options, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data) { return "\n <div class=\"scrivito_button_bar scrivito_obj_menu\"></div>\n "; } buffer += "<div class=\"scrivito_details_dialog scrivito_modal_medium scrivito_adjust_dialog\">\n <div class=\"scrivito_modal_header\">\n <h3><i class=\"scrivito_icon\"></i>"; if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</h3>\n <div class=\"scrivito_saving_indicator\"></div>\n "; stack1 = helpers['if'].call(depth0, depth0.obj, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n\n <div class=\"scrivito_modal_body scrivito_auto_height\">\n <i class=\"scrivito_icon scrivito_spinning\"></i>\n <div class=\"scrivito_details_dialog_markup scrivito_auto_height\">\n <iframe src=\""; if (stack1 = helpers.src) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.src; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\" name=\"scrivito_details_dialog\" class=\"scrivito_auto_height\"></iframe>\n </div>\n </div>\n\n <div class=\"scrivito_modal_footer\">\n <a href=\"#\" class=\"scrivito_button scrivito_cancel scrivito_green\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "done", options) : helperMissing.call(depth0, "translate", "done", options))) + "</a>\n </div>\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["details_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["editable_workspace_dialog"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, self=this, functionType="function"; function program1(depth0,data) { return "scrivito_green"; } function program3(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, depth0.can_create, {hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program4(depth0,data) { var buffer = "", stack1, options; buffer += "\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "editable_ws_dialog.title.select_or_create", options) : helperMissing.call(depth0, "translate", "editable_ws_dialog.title.select_or_create", options))) + "\n "; return buffer; } function program6(depth0,data) { var buffer = "", stack1, options; buffer += "\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "editable_ws_dialog.title.select", options) : helperMissing.call(depth0, "translate", "editable_ws_dialog.title.select", options))) + "\n "; return buffer; } function program8(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, depth0.can_create, {hash:{},inverse:self.program(11, program11, data),fn:self.program(9, program9, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program9(depth0,data) { var buffer = "", stack1, options; buffer += "\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "editable_ws_dialog.title.create", options) : helperMissing.call(depth0, "translate", "editable_ws_dialog.title.create", options))) + "\n "; return buffer; } function program11(depth0,data) { var buffer = "", stack1, options; buffer += "\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "editable_ws_dialog.title.forbidden", options) : helperMissing.call(depth0, "translate", "editable_ws_dialog.title.forbidden", options))) + "\n "; return buffer; } function program13(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, depth0.can_create, {hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program14(depth0,data) { var buffer = "", stack1, options; buffer += "\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "editable_ws_dialog.description.select_or_create", options) : helperMissing.call(depth0, "translate", "editable_ws_dialog.description.select_or_create", options))) + "\n "; return buffer; } function program16(depth0,data) { var buffer = "", stack1, options; buffer += "\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "editable_ws_dialog.description.select", options) : helperMissing.call(depth0, "translate", "editable_ws_dialog.description.select", options))) + "\n "; return buffer; } function program18(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, depth0.can_create, {hash:{},inverse:self.program(21, program21, data),fn:self.program(19, program19, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program19(depth0,data) { var buffer = "", stack1, options; buffer += "\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "editable_ws_dialog.description.create", options) : helperMissing.call(depth0, "translate", "editable_ws_dialog.description.create", options))) + "\n "; return buffer; } function program21(depth0,data) { var buffer = "", stack1, options; buffer += "\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "editable_ws_dialog.description.forbidden", options) : helperMissing.call(depth0, "translate", "editable_ws_dialog.description.forbidden", options))) + "\n "; return buffer; } function program23(depth0,data) { var buffer = "", stack1, stack2, options; buffer += "\n <div class=\"scrivito_input_list_of_ws\">\n <label for=\"scrivito_list_of_ws\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "editable_ws_dialog.choose_existing", options) : helperMissing.call(depth0, "translate", "editable_ws_dialog.choose_existing", options))) + "</label>\n <select id=\"scrivito_list_of_ws\">\n "; stack2 = helpers.each.call(depth0, depth0.workspaces, {hash:{},inverse:self.noop,fn:self.program(24, program24, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n </select>\n </div>\n "; return buffer; } function program24(depth0,data) { var buffer = "", stack1, stack2; buffer += "\n <option value=\"" + escapeExpression(((stack1 = depth0.id),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">\n "; stack2 = helpers['if'].call(depth0, depth0.title, {hash:{},inverse:self.program(27, program27, data),fn:self.program(25, program25, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n </option>\n "; return buffer; } function program25(depth0,data) { var buffer = "", stack1; buffer += "\n " + escapeExpression(((stack1 = depth0.title),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n "; return buffer; } function program27(depth0,data) { var buffer = "", stack1, options; buffer += "\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "menu_bar.empty_workspace_title", options) : helperMissing.call(depth0, "translate", "menu_bar.empty_workspace_title", options))) + "\n "; return buffer; } function program29(depth0,data) { var buffer = "", stack1, options; buffer += "\n <div class=\"scrivito_input_new_ws_name\">\n <label for=\"scrivito_new_ws_name\">\n "; stack1 = helpers['if'].call(depth0, depth0.workspaces, {hash:{},inverse:self.program(32, program32, data),fn:self.program(30, program30, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </label>\n <input type=\"text\" id=\"scrivito_new_ws_name\" value=\"\"\n placeholder=\""; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "editable_ws_dialog.create_new_playholder", options) : helperMissing.call(depth0, "translate", "editable_ws_dialog.create_new_playholder", options))) + "\">\n </div>\n "; return buffer; } function program30(depth0,data) { var buffer = "", stack1, options; buffer += "\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "editable_ws_dialog.or_create_new", options) : helperMissing.call(depth0, "translate", "editable_ws_dialog.or_create_new", options))) + "\n "; return buffer; } function program32(depth0,data) { var buffer = "", stack1, options; buffer += "\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "editable_ws_dialog.create_new", options) : helperMissing.call(depth0, "translate", "editable_ws_dialog.create_new", options))) + "\n "; return buffer; } function program34(depth0,data) { var buffer = "", stack1, options; buffer += "\n <a href=\"#\" class=\"scrivito_button scrivito_cancel\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "cancel", options) : helperMissing.call(depth0, "translate", "cancel", options))) + "</a>\n <a href=\"#\" class=\"scrivito_button scrivito_green scrivito_confirm\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "confirm", options) : helperMissing.call(depth0, "translate", "confirm", options))) + "</a>\n "; return buffer; } function program36(depth0,data) { var buffer = "", stack1, options; buffer += "\n <a href=\"#\" class=\"scrivito_button scrivito_cancel\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "close", options) : helperMissing.call(depth0, "translate", "close", options))) + "</a>\n "; return buffer; } buffer += "<div class=\"scrivito_editable_workspace_dialog scrivito_modal_prompt scrivito_center_dialog\n "; stack1 = helpers['if'].call(depth0, depth0.can_select_or_create, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n <div class=\"scrivito_modal_header\">\n <i class=\"scrivito_icon\"></i>\n <h3 class=\"scrivito_title\">\n "; stack1 = helpers['if'].call(depth0, depth0.can_select, {hash:{},inverse:self.program(8, program8, data),fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </h3>\n </div>\n <div class=\"scrivito_modal_body\">\n <div class=\"scrivito_description\">\n "; stack1 = helpers['if'].call(depth0, depth0.can_select, {hash:{},inverse:self.program(18, program18, data),fn:self.program(13, program13, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n <div>\n \n </div>\n "; stack1 = helpers['if'].call(depth0, depth0.workspaces, {hash:{},inverse:self.noop,fn:self.program(23, program23, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = helpers['if'].call(depth0, depth0.can_create, {hash:{},inverse:self.noop,fn:self.program(29, program29, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n <div class=\"scrivito_modal_footer\">\n "; stack1 = helpers['if'].call(depth0, depth0.can_select_or_create, {hash:{},inverse:self.program(36, program36, data),fn:self.program(34, program34, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["editable_workspace_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["element_overlay"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; return "<div class=\"scrivito_element_overlay\"></div>\n"; }); return this.ScrivitoHandlebarsTemplates["element_overlay"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["inplace_marker"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "\n <span class=\"scrivito_editing_marker_title\">"; if (stack1 = helpers.description) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.description; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</span>\n "; return buffer; } buffer += "<span class=\"scrivito_editing_marker "; if (stack1 = helpers.css_classes) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.css_classes; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\" title=\""; if (stack1 = helpers.tooltip) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.tooltip; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\">\n <i class=\"scrivito_icon "; if (stack1 = helpers.icon) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.icon; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\"></i>\n "; stack1 = helpers['if'].call(depth0, depth0.description, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</span>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["inplace_marker"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "scrivito_"; if (stack1 = helpers.align) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.align; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1); return buffer; } function program3(depth0,data) { return "scrivito_right"; } function program5(depth0,data) { var buffer = "", stack1, stack2; buffer += "\n "; stack2 = ((stack1 = depth0.render),typeof stack1 === functionType ? stack1.apply(depth0) : stack1); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n "; return buffer; } buffer += "<div class=\"scrivito_editing_marker_menu\">\n <ul class=\"scrivito_menu_box "; stack1 = helpers['if'].call(depth0, depth0.align, {hash:{},inverse:self.program(3, program3, data),fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n "; stack1 = helpers.each.call(depth0, depth0.menu_items, {hash:{},inverse:self.noop,fn:self.program(5, program5, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["menu"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_bar"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; return "<div class=\"scrivito_topbar\">\n <div class=\"scrivito_first_level\">\n <div id=\"scrivito_menu_bar_toggle\" class=\"scrivito_viewmodes_wrapper\"></div>\n <div class=\"scrivito_button_bar scrivito_app scrivito_no_hover\"><span class=\"scrivito_logo\"></span></div>\n <div id=\"scrivito_workspace_select\" class=\"scrivito_button_bar\"></div>\n <div id=\"scrivito_current_page_menu\" class=\"scrivito_button_bar scrivito_right\"></div>\n <div id=\"scrivito_menu_bar_browse_content\"></div>\n <div id=\"scrivito_current_page_restriction\"></div>\n <div id=\"scrivito_menu_bar_warning\"></div>\n <div id=\"scrivito_menu_bar_saving_indicator\"></div>\n </div>\n</div>\n"; }); return this.ScrivitoHandlebarsTemplates["menu_bar"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_bar_browse_content"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; return "<i class=\"scrivito_select_content_icon\"></i>\n"; }); return this.ScrivitoHandlebarsTemplates["menu_bar_browse_content"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_bar_toggle"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, stack2, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div class=\"scrivito_viewmodes scrivito_viewmode_"; if (stack1 = helpers.mode) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.mode; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "_active\">\n <span class=\"scrivito_viewmode_pill\"></span>\n\n <div class=\"scrivito_viewmode_view\">\n <span class=\"scrivito_viewmode_icon " + escapeExpression(((stack1 = ((stack1 = depth0.switch_to_view_mode_command),stack1 == null || stack1 === false ? stack1 : stack1.id)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"></span>\n <span class=\"scrivito_viewmode_label\">" + escapeExpression(((stack1 = ((stack1 = depth0.switch_to_view_mode_command),stack1 == null || stack1 === false ? stack1 : stack1.title)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span>\n </div>\n\n <div class=\"scrivito_viewmode_editing\">\n <span class=\"scrivito_viewmode_icon " + escapeExpression(((stack1 = ((stack1 = depth0.switch_to_editing_mode_command),stack1 == null || stack1 === false ? stack1 : stack1.id)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"></span>\n <span class=\"scrivito_viewmode_label\">" + escapeExpression(((stack1 = ((stack1 = depth0.switch_to_editing_mode_command),stack1 == null || stack1 === false ? stack1 : stack1.title)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span>\n </div>\n\n <div class=\"scrivito_viewmode_"; if (stack2 = helpers.comparing_mode) { stack2 = stack2.call(depth0, {hash:{},data:data}); } else { stack2 = depth0.comparing_mode; stack2 = typeof stack2 === functionType ? stack2.apply(depth0) : stack2; } buffer += escapeExpression(stack2) + "\">\n <span class=\"scrivito_viewmode_icon " + escapeExpression(((stack1 = ((stack1 = depth0.switch_to_comparing_mode_command),stack1 == null || stack1 === false ? stack1 : stack1.id)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"></span>\n <span class=\"scrivito_viewmode_label scrivito_comparing_mode_toggle\">\n " + escapeExpression(((stack1 = ((stack1 = depth0.switch_to_comparing_mode_command),stack1 == null || stack1 === false ? stack1 : stack1.title)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " <i class=\"scrivito_icon\"></i>\n </span>\n </div>\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["menu_bar_toggle"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_bar_warning"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; buffer += "<span class=\"scrivito_menu_bar_warning scrivito_hidden\">\n <i class=\"scrivito_icon\"></i>\n <span class=\"scrivito_button_label\"><span>"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "menu_bar_warning.warning", options) : helperMissing.call(depth0, "translate", "menu_bar_warning.warning", options))) + "</span></span>\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["menu_bar_warning"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_item"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { return "scrivito_disabled"; } function program3(depth0,data) { var stack1; if (stack1 = helpers.tooltip) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.tooltip; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } return escapeExpression(stack1); } function program5(depth0,data) { var stack1; if (stack1 = helpers.reason_for_being_disabled) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.reason_for_being_disabled; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } return escapeExpression(stack1); } buffer += "<li class=\"scrivito_menu_item "; if (stack1 = helpers.dom_id) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.dom_id; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + " "; stack1 = helpers['if'].call(depth0, depth0.is_disabled, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n <span title=\""; stack1 = helpers['if'].call(depth0, depth0.is_enabled, {hash:{},inverse:self.program(5, program5, data),fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n "; if (stack1 = helpers.icon) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.icon; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } if(stack1 || stack1 === 0) { buffer += stack1; } if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\n </span>\n</li>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["menu_item"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_item/customer_icon"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression; buffer += "<i class=\"scrivito_customer_icon sci_"; if (stack1 = helpers.icon) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.icon; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\"></i>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["menu_item/customer_icon"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_item/factory_icon"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, functionType="function"; buffer += "<i class=\"scrivito_icon\">"; if (stack1 = helpers.icon) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.icon; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</i>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["menu_item/factory_icon"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["menu_item/spinner"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing; buffer += "<li id=\""; if (stack1 = helpers.id) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.id; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\" class=\"scrivito_menu_item\">\n <span>\n <i class=\"scrivito_icon scrivito_spinning\"></i>\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "menu_item.spinner.loading", options) : helperMissing.call(depth0, "translate", "menu_item.spinner.loading", options))) + "\n </span>\n</li>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["menu_item/spinner"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["obj_menu"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, stack2, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { return "\n scrivito_new\n "; } function program3(depth0,data) { return "\n scrivito_changed\n "; } function program5(depth0,data) { return "\n scrivito_deleted\n "; } function program7(depth0,data) { return "\n scrivito_conflict\n "; } buffer += "<i title=\"" + escapeExpression(((stack1 = ((stack1 = depth0.obj),stack1 == null || stack1 === false ? stack1 : stack1.tooltip)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" class=\"scrivito_icon\n "; stack2 = helpers['if'].call(depth0, ((stack1 = depth0.obj),stack1 == null || stack1 === false ? stack1 : stack1.is_new), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n\n "; stack2 = helpers['if'].call(depth0, ((stack1 = depth0.obj),stack1 == null || stack1 === false ? stack1 : stack1.is_edited), {hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n\n "; stack2 = helpers['if'].call(depth0, ((stack1 = depth0.obj),stack1 == null || stack1 === false ? stack1 : stack1.is_deleted), {hash:{},inverse:self.noop,fn:self.program(5, program5, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n\n "; stack2 = helpers['if'].call(depth0, ((stack1 = depth0.obj),stack1 == null || stack1 === false ? stack1 : stack1.has_conflict), {hash:{},inverse:self.noop,fn:self.program(7, program7, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n\"></i>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["obj_menu"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["obj_sorting_dialog"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, stack2, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "\n <li data-scrivito-private-obj-id="; if (stack1 = helpers.id) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.id; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + ">"; if (stack1 = helpers.description_for_editor) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.description_for_editor; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</li>\n "; return buffer; } buffer += "<div class=\"scrivito_obj_sorting_dialog scrivito_modal_large scrivito_adjust_dialog\">\n\n <div class=\"scrivito_modal_header\">\n <h3><i class=\"scrivito_icon\">"; if (stack1 = helpers.icon) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.icon; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</i>"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "obj_sorting_dialog.title", options) : helperMissing.call(depth0, "translate", "obj_sorting_dialog.title", options))) + "</h3>\n </div>\n\n <div class=\"scrivito_modal_body scrivito_auto_height\">\n <ul id=\"scrivito_obj_sorting_sortable\">\n "; stack2 = helpers.each.call(depth0, depth0.child_list, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n </ul>\n </div>\n\n <div class=\"scrivito_modal_footer\">\n <a href=\"#\" class=\"scrivito_button scrivito_cancel\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "cancel", options) : helperMissing.call(depth0, "translate", "cancel", options))) + "</a>\n <a href=\"#\" class=\"scrivito_button scrivito_green scrivito_confirm\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "confirm", options) : helperMissing.call(depth0, "translate", "confirm", options))) + "</a>\n </div>\n\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["obj_sorting_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["overlay"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; return "<div class=\"scrivito_overlay\"></div>\n"; }); return this.ScrivitoHandlebarsTemplates["overlay"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["prompt_dialog"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "scrivito_"; if (stack1 = helpers.color) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.color; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1); return buffer; } function program3(depth0,data) { var buffer = "", stack1; buffer += "\n <p class=\"scrivito_description\">"; if (stack1 = helpers.description) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.description; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</p>\n "; return buffer; } buffer += "<div class=\"scrivito_prompt_dialog scrivito_center_dialog scrivito_modal_prompt\n "; stack1 = helpers['if'].call(depth0, depth0.color, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n <div class=\"scrivito_modal_header\">\n <i class=\"scrivito_icon\">"; if (stack1 = helpers.icon) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.icon; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</i>\n <h3 class=\"scrivito_title\">"; if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</h3>\n "; stack1 = helpers['if'].call(depth0, depth0.description, {hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n <div class=\"scrivito_modal_body\">\n <input type=\"text\" value=\""; if (stack1 = helpers.value) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.value; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\" placeholder=\""; if (stack1 = helpers.placeholder) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.placeholder; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\"></input>\n </div>\n <div class=\"scrivito_modal_footer\">\n <a href=\"#\" class=\"scrivito_button scrivito_"; if (stack1 = helpers.cancel_button_color) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.cancel_button_color; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + " scrivito_cancel\">\n "; if (stack1 = helpers.cancel_button_text) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.cancel_button_text; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\n </a>\n <a href=\"#\" class=\"scrivito_button scrivito_"; if (stack1 = helpers.accept_button_color) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.accept_button_color; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + " scrivito_accept\">\n "; if (stack1 = helpers.accept_button_text) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.accept_button_text; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\n </a>\n </div>\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["prompt_dialog"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["saving_indicator"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; buffer += "<span class=\"scrivito_saving_indicator scrivito_saving_state_bar\">\n <span class=\"scrivito_saving_in_progress scrivito_hidden\">\n <i class=\"scrivito_icon scrivito_spinning\"></i>\n <span class=\"scrivito_button_label\"><span>"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "saving_indicator_item.saving", options) : helperMissing.call(depth0, "translate", "saving_indicator_item.saving", options))) + "</span></span>\n </span>\n\n <span class=\"scrivito_saving_done scrivito_hidden\">\n <i class=\"scrivito_icon\"></i>\n <span class=\"scrivito_button_label\"><span>"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "saving_indicator_item.saved", options) : helperMissing.call(depth0, "translate", "saving_indicator_item.saved", options))) + "</span></span>\n </span>\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["saving_indicator"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["saving_overlay"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; return "<div class=\"scrivito_saving_overlay scrivito_overlay\">\n <i class=\"scrivito_icon scrivito_processing\"></i>\n</div>\n"; }); return this.ScrivitoHandlebarsTemplates["saving_overlay"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["title"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression; buffer += "<h1>"; if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</h1>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["title"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["workspace_select"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, stack2, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, functionType="function", self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "\n <i class=\"scrivito_icon\">"; if (stack1 = helpers.icon) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.icon; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</i>\n <span class=\"scrivito_button_label\">"; if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</span>\n "; stack1 = helpers['if'].call(depth0, depth0.is_outdated, {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program2(depth0,data) { var buffer = "", stack1, options; buffer += "\n <span class=\"scrivito_button_notice\">\n <i class=\"scrivito_icon\"></i>\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "workspace_select.outdated", options) : helperMissing.call(depth0, "translate", "workspace_select.outdated", options))) + "\n </span>\n "; return buffer; } function program4(depth0,data) { var buffer = "", stack1, stack2, options; buffer += "\n <li class=\"scrivito_menu_separator\">\n <span>"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "workspace_select.this_workspace", options) : helperMissing.call(depth0, "translate", "workspace_select.this_workspace", options))) + "</span>\n </li>\n "; stack2 = helpers.each.call(depth0, ((stack1 = depth0.commands),stack1 == null || stack1 === false ? stack1 : stack1.for_editable), {hash:{},inverse:self.noop,fn:self.program(5, program5, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n <li class=\"scrivito_menu_separator\"></li>\n "; return buffer; } function program5(depth0,data) { var buffer = "", stack1, stack2, options; buffer += "\n "; options = {hash:{},data:data}; stack2 = ((stack1 = helpers.render),stack1 ? stack1.call(depth0, "workspace_select/menu_item", depth0, options) : helperMissing.call(depth0, "render", "workspace_select/menu_item", depth0, options)); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n "; return buffer; } function program7(depth0,data) { var buffer = "", stack1, stack2, options; buffer += "\n <li class=\"scrivito_menu_separator\"></li>\n "; options = {hash:{},data:data}; stack2 = ((stack1 = helpers.render),stack1 ? stack1.call(depth0, "workspace_select/menu_item", ((stack1 = depth0.commands),stack1 == null || stack1 === false ? stack1 : stack1.select_published), options) : helperMissing.call(depth0, "render", "workspace_select/menu_item", ((stack1 = depth0.commands),stack1 == null || stack1 === false ? stack1 : stack1.select_published), options)); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n "; return buffer; } stack1 = helpers['with'].call(depth0, depth0.selected_workspace, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n<ul class=\"scrivito_menu_box scrivito_hidden\">\n "; stack2 = helpers['if'].call(depth0, ((stack1 = depth0.selected_workspace),stack1 == null || stack1 === false ? stack1 : stack1.is_editable), {hash:{},inverse:self.noop,fn:self.program(4, program4, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n\n <li class=\"scrivito_menu_separator\">\n <span>"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "workspace_select.other_workspaces", options) : helperMissing.call(depth0, "translate", "workspace_select.other_workspaces", options))) + "</span>\n </li>\n\n "; options = {hash:{},data:data}; stack2 = ((stack1 = helpers.render),stack1 ? stack1.call(depth0, "workspace_select/menu_item", ((stack1 = depth0.commands),stack1 == null || stack1 === false ? stack1 : stack1.create_workspace), options) : helperMissing.call(depth0, "render", "workspace_select/menu_item", ((stack1 = depth0.commands),stack1 == null || stack1 === false ? stack1 : stack1.create_workspace), options)); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n\n "; stack2 = helpers.unless.call(depth0, ((stack1 = depth0.selected_workspace),stack1 == null || stack1 === false ? stack1 : stack1.is_published), {hash:{},inverse:self.noop,fn:self.program(7, program7, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n\n <li class=\"scrivito_menu_item scrivito_workspace_list\">\n <span>\n <i class=\"scrivito_icon scrivito_spinning\"></i>\n "; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "menu_bar.loading_workspaces", options) : helperMissing.call(depth0, "translate", "menu_bar.loading_workspaces", options))) + "\n </span>\n </li>\n</ul>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["workspace_select"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["workspace_select/menu_item"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { return "scrivito_highlight"; } function program3(depth0,data) { return "scrivito_disabled"; } function program5(depth0,data) { var stack1; if (stack1 = helpers.tooltip) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.tooltip; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } return escapeExpression(stack1); } function program7(depth0,data) { var stack1; if (stack1 = helpers.reason_for_being_disabled) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.reason_for_being_disabled; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } return escapeExpression(stack1); } buffer += "<li id=\""; if (stack1 = helpers.dom_id) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.dom_id; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\" class=\"scrivito_menu_item "; if (stack1 = helpers.dom_id) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.dom_id; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\n "; stack1 = helpers['if'].call(depth0, depth0.is_action_required, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = helpers['if'].call(depth0, depth0.is_disabled, {hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n <span title=\""; stack1 = helpers['if'].call(depth0, depth0.is_enabled, {hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n <i class=\"scrivito_icon\">"; if (stack1 = helpers.icon) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.icon; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</i> "; if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\n </span>\n</li>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["workspace_select/menu_item"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["workspace_select/other_workspaces"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data) { return "\n <li class=\"scrivito_menu_separator\"></li>\n"; } function program3(depth0,data) { var buffer = "", stack1, stack2, options; buffer += "\n "; options = {hash:{},data:data}; stack2 = ((stack1 = helpers.render),stack1 ? stack1.call(depth0, "workspace_select/menu_item", depth0, options) : helperMissing.call(depth0, "render", "workspace_select/menu_item", depth0, options)); if(stack2 || stack2 === 0) { buffer += stack2; } buffer += "\n"; return buffer; } stack1 = helpers['if'].call(depth0, depth0.has_separator, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; stack1 = helpers.each.call(depth0, depth0.commands, {hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["workspace_select/other_workspaces"]; }).call(this); (function() { this.ScrivitoHandlebarsTemplates || (this.ScrivitoHandlebarsTemplates = {}); this.ScrivitoHandlebarsTemplates["workspace_settings_dialog"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [3,'>= 1.0.0-rc.4']; helpers = helpers || Handlebars.helpers; data = data || {}; var buffer = "", stack1, stack2, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing; buffer += "<div class=\"scrivito_workspace_settings_dialog scrivito_modal_large scrivito_adjust_dialog\">\n <div class=\"scrivito_modal_header\">\n <h3><i class=\"scrivito_icon\"></i>"; if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</h3>\n </div>\n\n <div class=\"scrivito_modal_body scrivito_auto_height\">\n <h4><i class=\"scrivito_icon\"></i>"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "workspace_settings_dialog.owners", options) : helperMissing.call(depth0, "translate", "workspace_settings_dialog.owners", options))) + "</h4>\n <input type=\"hidden\" class=\"scrivito_select_owners\" value=\""; if (stack2 = helpers.owners) { stack2 = stack2.call(depth0, {hash:{},data:data}); } else { stack2 = depth0.owners; stack2 = typeof stack2 === functionType ? stack2.apply(depth0) : stack2; } buffer += escapeExpression(stack2) + "\" />\n </div>\n\n <div class=\"scrivito_modal_footer\">\n <a href=\"#\" class=\"scrivito_button scrivito_cancel\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "cancel", options) : helperMissing.call(depth0, "translate", "cancel", options))) + "</a>\n <a href=\"#\" class=\"scrivito_button scrivito_green scrivito_confirm\">"; options = {hash:{},data:data}; buffer += escapeExpression(((stack1 = helpers.translate),stack1 ? stack1.call(depth0, "confirm", options) : helperMissing.call(depth0, "translate", "confirm", options))) + "</a>\n </div>\n</div>\n"; return buffer; }); return this.ScrivitoHandlebarsTemplates["workspace_settings_dialog"]; }).call(this); $.i18n().load({ 'confirm': 'Bestätigen', 'cancel': 'Abbrechen', 'save': 'Speichern', 'welcome': 'Willkommen', 'welcome_x': 'Willkommen $1', 'accept': 'Übernehmen', 'close': 'Schließen', 'done': 'Fertig', 'loading': 'Lade...', 'current_page': 'Aktuelle Seite', 'ok': 'Ok', 'obj.tooltip.is_new': 'Diese Seite ist neu.', 'obj.tooltip.is_edited': 'Diese Seite wurde geändert.', 'obj.tooltip.has_conflict': 'Auf dieser Seite gab es parallele Änderungen, die mit den Änderungen in dieser Arbeitskopie zusammengeführt werden sollten.', 'obj.tooltip.is_deleted': 'Diese Seite wurde gelöscht.', 'workspace.title_published': 'Veröffentlichte Inhalte', 'workspace.empty_title': '<leerer Titel>', 'workspace_settings_dialog.owners': 'Besitzer', 'workspace_settings_dialog.nothing_found': 'Nichts gefunden', 'workspace_settings_dialog.searching': 'Suche...', 'workspace_settings_dialog.too_short': 'Benutzer suchen...', 'workspace_select.outdated': 'veraltet', 'workspace_select.this_workspace': 'Diese Arbeitskopie', 'workspace_select.other_workspaces': 'Andere Arbeitskopien', 'menu_item.spinner.loading': 'Laden...', 'choose_obj_class_dialog.add_child_page.title': 'Seitenvorlage auswählen', 'choose_obj_class_dialog.create_widget.title': 'Widget auswählen', 'editable_ws_dialog.title.select_or_create': 'Arbeitskopie wählen', 'editable_ws_dialog.title.select': 'Arbeitskopie auswählen', 'editable_ws_dialog.title.create': 'Arbeitskopie anlegen', 'editable_ws_dialog.title.forbidden': 'Keine Arbeitskopie verfügbar', 'editable_ws_dialog.description.select_or_create': 'Wählen Sie eine Arbeitskopie aus oder legen Sie eine neue an, um Inhalte zu ändern. Veröffentlichen Sie die Arbeitskopie nach Abschluss der Bearbeitung, oder lassen Sie sie veröffentlichen.', 'editable_ws_dialog.description.select': 'Wählen Sie eine Arbeitskopie aus, um Inhalte zu ändern. Veröffentlichen Sie die Arbeitskopie nach Abschluss der Bearbeitung, oder lassen Sie sie veröffentlichen.', 'editable_ws_dialog.description.create': 'Legen Sie eine neue Arbeitskopie an, um Inhalte zu ändern. Veröffentlichen Sie die Arbeitskopie nach Abschluss der Bearbeitung, oder lassen Sie sie veröffentlichen.', 'editable_ws_dialog.description.forbidden': 'Es gibt keine Arbeitskopie, in der Sie Inhalte ändern könnten. Auch wurde es Ihnen nicht ermöglicht, Arbeitskopien anzulegen.', 'editable_ws_dialog.choose_existing': 'Wählen Sie eine bestehende Arbeitskopie aus:', 'editable_ws_dialog.create_new': 'Legen Sie eine neue Arbeitskopie an:', 'editable_ws_dialog.or_create_new': 'Oder legen Sie eine neue an:', 'editable_ws_dialog.create_new_playholder': 'Titel der neuen Arbeitskopie', 'editable_ws_dialog.select': 'Auswählen', 'resource_dialog.title': 'Eigenschaften der Ressource "$1"', 'resource_dialog.commands.revert_obj.title': 'Änderungen an Ressource verwerfen', 'resource_dialog.commands.revert_obj.rtc_workspace': 'Diese Ressource ist Teil der "rtc"-Arbeitskopie, bei der Änderungen nicht verworfen werden können.', 'resource_dialog.commands.revert_obj.new_obj': 'Dies ist eine neue Ressource. Um die Erstellung dieser Ressource rückgängig zu machen, löschen Sie sie bitte.', 'resource_dialog.commands.revert_obj.not_modified_obj': 'Diese Ressource wurde nicht geändert. Daher gibt es nichts zu verwerfen.', 'resource_dialog.commands.revert_obj.dialog.title': 'Wirklich Änderungen an dieser Ressource verwerfen?', 'resource_dialog.commands.restore_obj.title': 'Ressource wiederherstellen', 'resource_dialog.commands.restore_obj.rtc_workspace': 'Diese Ressource ist Teil der "rtc"-Arbeitskopie, bei der gelöschte Seiten nicht wiederhergestellt werden können.', 'resource_dialog.commands.mark_resolved_obj.title': 'Parallele Änderungen an der Ressource überschreiben', 'resource_dialog.commands.mark_resolved_obj.dialog.description': 'Diese Ressource wurde in einer anderen, inzwischen veröffentlichten Arbeitskopie geändert. Bitte bestätigen Sie, dass Ihre Änderungen erhalten und die parallel durchgeführten Änderungen verworfen werden.', 'resource_dialog.commands.delete_obj.title': 'Ressource löschen', 'resource_dialog.commands.delete_obj.dialog.title': 'Wirklich diese Ressource löschen?', 'resource_dialog.commands.delete_obj.dialog.description': 'Änderungen an einer gelöschten Ressource können nicht wiederhergestellt werden.', 'menu_bar.loading_workspaces': 'Lade Arbeitskopien', 'menu_bar.move': 'Verschieben', 'menu_bar.copy': 'Kopieren', 'menu_bar.create': 'Anlegen', 'saving_indicator_item.saving': 'Wird gespeichert...', 'saving_indicator_item.saved': 'Änderungen gespeichert', 'menu_bar_warning.warning': 'JS-Konsole überprüfen', 'menu_bar_warning.open_console': 'Es gibt Warnhinweise. Bitte öffnen Sie die JavaScript-Konsole, um Details zu erfahren.', 'inplace_marker.overlapping': 'Zwei oder mehrere Menü-Handles überschneiden sich. Bitte passen Sie Ihr CSS an. Die folgenden Menü-Handles überschneiden sich:', 'widget_marker.widget_is_new': 'Widget ist neu', 'widget_marker.widget_is_edited': 'Widget wurde geändert', 'widget_marker.widget_is_edited_and_dragged_here': 'Widget wurde geändert und hierher gezogen', 'widget_marker.widget_is_edited_and_dragged_away': 'Widget wurde geändert und von hier weggezogen', 'widget_marker.widget_is_deleted': 'Widget wurde gelöscht', 'widget_marker.widget_is_dragged_here': 'Widget wurde hierher gezogen', 'widget_marker.widget_is_dragged_away': 'Widget wurde von hier weggezogen', 'child_list_menu.description': 'Elemente von $1', 'changes_dialog.title': 'Änderungen von "$1"', 'changes_dialog.empty_result': 'In dieser Arbeitskopie wurde nichts geändert.', 'changes_dialog.more': 'Mehr...', 'changes_dialog.row.change': 'Änderung', 'changes_dialog.row.rights': 'Veröffentlichen erlaubt', 'changes_dialog.row.description_for_editor': 'Titel', 'changes_dialog.row.type': 'Typ', 'changes_dialog.row.last_changed': 'Letzte Änderung', 'commands.create_workspace.forbidden': 'Eine Arbeitskopie kann aufgrund fehlender Benutzerrechte nicht angelegt werden.', 'commands.create_workspace.title': 'Arbeitskopie anlegen', 'commands.create_workspace.dialog.title': 'Arbeitskopie anlegen', 'commands.create_workspace.dialog.description': 'Bitte geben Sie den Titel der neuen Arbeitskopie ein.', 'commands.create_workspace.dialog.placeholder': 'Neuer Titel', 'commands.create_workspace.dialog.accept': 'Anlegen', 'commands.rename_workspace.title': 'Umbenennen', 'commands.rename_workspace.dialog.title': '"$1" umbenennen', 'commands.rename_workspace.dialog.description': 'Bitte geben Sie den neuen Titel der Arbeitskopie ein.', 'commands.rename_workspace.dialog.accept': 'Umbenennen', 'commands.rebase_workspace.title': 'Aktualisieren', 'commands.rebase_workspace.tooltip': 'Arbeitskopie "$1" is veraltet. Bitte aktualisieren Sie sie.', 'commands.rebase_workspace.uptodate': 'Arbeitskopie "$1" muss nicht aktualisiert werden.', 'commands.rebase_workspace.has_conflicts.title': 'Geänderte Inhalte wurden zwischenzeitlich veröffentlicht', 'commands.rebase_workspace.has_conflicts.description': 'Ihre Arbeitskopie konnte nicht vollständig aktualisiert werden. Einige Inhalte wurden auch in einer anderen Arbeitskopie geändert, die inzwischen veröffentlicht wurde. Bitte entnehmen Sie die Details der Liste der Änderungen.', 'commands.rebase_workspace.open_changes_dialog': 'Änderungen anzeigen', 'commands.delete_workspace.title': 'Löschen', 'commands.delete_workspace.dialog.title': 'Wirklich "$1" löschen?', 'commands.delete_workspace.dialog.description': 'Eine gelöschte Arbeitskopie kann nicht wiederhergestellt werden.', 'commands.delete_workspace.dialog.confirm': 'Löschen', 'commands.workspace_settings.title': 'Einstellungen bearbeiten', 'commands.workspace_settings.dialog.title': 'Einstellungen von "$1"', 'commands.workspace_changes.title': 'Änderungen anzeigen', 'commands.obj_details.title': 'Seiteneigenschaften', 'commands.obj_details.dialog.title': 'Eigenschaften von "$1"', 'commands.save_obj_to_clipboard.title': 'Seite zum Kopieren oder Verschieben markieren', 'commands.save_obj_to_clipboard.has_children': 'Seiten mit Unterseiten können noch nicht verschoben oder kopiert werden.', 'commands.delete_obj.title': 'Seite löschen', 'commands.delete_obj.published_workspace': 'Die veröffentlichten Inhalte können nicht direkt geändert werden.', 'commands.delete_obj.has_children': 'Seiten mit Unterseiten können noch nicht gelöscht werden.', 'commands.delete_obj.dialog.title': 'Wirklich diese Seite löschen?', 'commands.delete_obj.dialog.description': 'Änderungen an einer gelöschten Seite können nicht wiederhergestellt werden.', 'commands.delete_obj.dialog.confirm': 'Löschen', 'commands.revert_obj.title': 'Änderungen an Seite verwerfen', 'commands.revert_obj.published_workspace': 'Die veröffentlichten Inhalte können nicht direkt geändert werden. Daher gibt es nichts zu verwerfen.', 'commands.revert_obj.rtc_workspace': 'Diese Seite ist Teil der "rtc"-Arbeitskopie, bei der Änderungen nicht verworfen werden können.', 'commands.revert_obj.new_obj': 'Dies ist eine neue Seite. Um die Erstellung dieser Seite rückgängig zu machen, löschen Sie sie bitte.', 'commands.revert_obj.not_modified_obj': 'Diese Seite wurde nicht geändert. Daher gibt es nichts zu verwerfen.', 'commands.revert_obj.is_binary': 'Verwerfen von Änderungen ist nicht verfügbar für binäre Daten.', 'commands.revert_obj.dialog.title': 'Wirklich Änderungen an dieser Seite verwerfen?', 'commands.revert_obj.dialog.description': 'Verworfene Änderungen können nicht wiederhergestellt werden.', 'commands.revert_obj.dialog.confirm': 'Verwerfen', 'commands.revert_widget.content_title': 'Änderungen am Inhalt verwerfen', 'commands.revert_widget.widget_title': 'Änderungen am Widget verwerfen', 'commands.revert_widget.rtc_workspace': 'Dieses Widget ist Teil der "rtc"-Arbeitskopie, bei der Änderungen an Widgets nicht verworfen werden können.', 'commands.revert_widget.is_new': 'Dies ist ein neues Widget. Um die Erstellung dieses Widgets rückgängig zu machen, löschen Sie es bitte.', 'commands.revert_widget.is_not_modified': 'Dieses Widget wurde nicht geändert. Daher gibt es nichts zu verwerfen.', 'commands.revert_widget.dialog.title': 'Wirklich Änderungen an diesem Widget verwerfen?', 'commands.revert_widget.dialog.description': 'Verworfene Änderungen können nicht wiederhergestellt werden.', 'commands.revert_widget.dialog.confirm': 'Verwerfen', 'commands.restore_widget.title': 'Widget wiederherstellen', 'commands.restore_widget.rtc_workspace': 'Dieses Widget ist Teil der "rtc"-Arbeitskopie, bei der gelöschte Widgets nicht wiederhergestellt werden können.', 'commands.restore_obj.title': 'Seite wiederherstellen', 'commands.restore_obj.rtc_workspace': 'Diese Seite ist Teil der "rtc"-Arbeitskopie, bei der gelöschte Seiten nicht wiederhergestellt werden können.', 'commands.mark_resolved_obj.title': 'Parallele Änderungen an der Seite überschreiben', 'commands.mark_resolved_obj.dialog.title': 'Wirklich parallele Änderungen an der Seite überschreiben?', 'commands.mark_resolved_obj.dialog.description': 'Diese Seite wurde in einer anderen, inzwischen veröffentlichten Arbeitskopie geändert. Bitte bestätigen Sie, dass Ihre Änderungen erhalten und die parallel durchgeführten Änderungen verworfen werden.', 'commands.mark_resolved_obj.dialog.confirm': 'Änderungen überschreiben', 'commands.duplicate_obj.title': 'Seite duplizieren', 'commands.duplicate_obj.published_workspace': 'Die veröffentlichten Inhalte können nicht direkt geändert werden.', 'commands.duplicate_obj.has_children': 'Seiten mit Unterseiten können noch nicht dupliziert werden.', 'commands.add_subpage.title': 'Neue Seite anlegen', 'commands.add_subpage.tooltip': 'Seite unterhalb $1 anlegen', 'commands.copy_page_from_clipboard.title': 'Markierte Seite hierher kopieren', 'commands.copy_page_from_clipboard.paste_forbidden': 'Aufgrund ihres Typs kann die Seite hier nicht eingefügt werden. Nur Seiten der folgenden Typen können hierher verschoben oder kopiert werden: $1', 'commands.move_page_from_clipboard.title': 'Markierte Seite hierher verschieben', 'commands.move_page_from_clipboard.paste_forbidden': 'Aufgrund ihres Typs kann die Seite hier nicht eingefügt werden. Nur Seiten der folgenden Typen können hierher verschoben oder kopiert werden: $1', 'commands.sort_items.title': 'Elemente sortieren', 'commands.sort_items.tooltip': 'Reihenfolge der Elemente unterhalb $1 bearbeiten', 'commands.sort_items.auto_sort': 'Diese Navigation wird automatisch sortiert.', 'commands.sort_items.too_less_children': 'Die Navigation kann nicht sortiert werden, weil sie weniger als zwei Elemente enthält.', 'commands.choose_and_create_widget.title': 'Widget einfügen', 'commands.choose_and_create_widget.disabled': 'Sie können hier keine Widgets einfügen.', 'commands.create_widget.title': '$1 einfügen', 'commands.add_content.title': 'Inhalt einfügen', 'commands.add_content.not_allowed': 'Es ist nicht erlaubt in dieses Feld beliebige Inhalte einzufügen', 'obj_sorting_dialog.title': 'Elemente sortieren', 'commands.widget_details.title': 'Widget-Eigenschaften', 'commands.widget_details.no_details_view': 'Dieses Widget hat keine Eigenschaften', 'commands.widget_details.dialog.title': 'Eigenschaften von "$1"', 'commands.save_widget_to_clipboard.content_title': 'Inhalt zum Kopieren markieren', 'commands.save_widget_to_clipboard.widget_title': 'Widget zum Kopieren markieren', 'commands.copy_widget_from_clipboard.content_title': 'Kopie des markierten Inhalts einfügen', 'commands.copy_widget_from_clipboard.widget_title': 'Kopie des markierten Widgets einfügen', 'commands.copy_widget_from_clipboard.paste_forbidden': 'Aufgrund seines Typs kann das Widget hier nicht eingefügt werden. Nur Widgets der folgenden Typen können hierher verschoben oder kopiert werden: $1.', 'commands.delete_widget.content_title': 'Inhalt löschen', 'commands.delete_widget.widget_title': 'Widget löschen', 'commands.delete_widget.dialog.title': 'Wirklich dieses Widget löschen?', 'commands.delete_widget.dialog.description': 'Ein gelöschtes Widget kann nicht wiederhergestellt werden.', 'commands.delete_widget.dialog.confirm': 'Löschen', 'commands.switch_mode.view': 'Vorschau', 'commands.switch_mode.editing': 'Bearbeiten', 'commands.switch_mode.diff': 'Vergleichen', 'commands.switch_mode.added': 'Hinzugefügt', 'commands.switch_mode.deleted': 'Gelöscht', 'commands.switch_mode.disabled': 'Aktuell ausgewählter Anzeigemodus', 'commands.publish_workspace.title': 'Veröffentlichen', 'commands.publish_workspace.permission_denied': 'Die Arbeitskopie kann aufgrund fehlender Benutzerrechte nicht veröffentlicht werden.', 'commands.publish_workspace.dialog.confirm': 'Veröffentlichen', 'commands.publish_workspace.dialog.title': '"$1" veröffentlichen?', 'commands.publish_workspace.dialog.description': 'Eine Arbeitskopie zu veröffentlichen ist endgültig. Dieser Vorgang kann nicht rückgängig gemacht werden.', 'commands.publish_workspace.error_dialog.title': 'Arbeitskopie konnte nicht veröffentlicht werden', 'commands.publish_workspace.error_dialog.description': 'Bitte entnehmen Sie die Details der Liste der Änderungen.', 'commands.publish_workspace.error_dialog.confirm': 'Liste der Änderungen', 'commands.publish_workspace.alert.invalid_certificates': 'Die Arbeitskopie konnte nicht veröffentlicht werden, weil mindestens ein Benutzer gerade Inhalte darin ändert.', 'ajax.error': 'Die Kommunikation mit dem CMS ist aufgrund eines Fehlers fehlgeschlagen: $1', 'ajax.error.communication': 'Die Kommunikation mit dem CMS ist fehlgeschlagen. Bitte überprüfen Sie Ihre Netzwerkverbindung.', 'ajax.error.unknown': 'Die Kommunikation mit dem CMS ist aufgrund eines unbekannten Fehlers fehlgeschlagen.', 'ajax.error.production': 'Bei Ihrer letzten Aktion ist ein technischer Fehler aufgetreten. Bitte versuchen Sie es später noch einmal. Falls das Problem bestehen bleibt, wenden Sie sich bitte an Ihren technischen Ansprechpartner für diese Website.', 'workspace_limit_exceeded.message': 'In Ihrem Tarif sind keine weiteren Arbeitskopien verfügbar. Bitte wechseln Sie den Tarif.', 'warn_before_unloading': 'Sie haben nicht gespeicherte Änderungen! Sind Sie sicher, dass sie schließen wollen?' }, 'de'); $.i18n().load({ 'confirm': 'Confirm', 'cancel': 'Cancel', 'save': 'Save', 'welcome': 'Welcome', 'welcome_x': 'Welcome $1', 'accept': 'Accept', 'close': 'Close', 'done': 'Done', 'loading': 'Loading...', 'current_page': 'current page', 'ok': 'Ok', 'obj.tooltip.is_new': 'This page is new.', 'obj.tooltip.is_edited': 'This page has been modified.', 'obj.tooltip.has_conflict': 'To this page concurrent changes were made that should be merged with the changes in this working copy.', 'obj.tooltip.is_deleted': 'This page has been deleted.', 'workspace.title_published': 'Published content', 'workspace.empty_title': '<empty title>', 'workspace_settings_dialog.owners': 'Owners', 'workspace_settings_dialog.nothing_found': 'Nothing found', 'workspace_settings_dialog.searching': 'Searching...', 'workspace_settings_dialog.too_short': 'Find user...', 'workspace_select.outdated': 'outdated', 'workspace_select.this_workspace': 'This working copy', 'workspace_select.other_workspaces': 'Other working copies', 'menu_item.spinner.loading': 'Loading...', 'choose_obj_class_dialog.add_child_page.title': 'Select Page Type', 'choose_obj_class_dialog.create_widget.title': 'Select Widget', 'editable_ws_dialog.title.select_or_create': 'Choose a working copy', 'editable_ws_dialog.title.select': 'Select a working copy', 'editable_ws_dialog.title.create': 'Create a working copy', 'editable_ws_dialog.title.forbidden': 'No working copy available', 'editable_ws_dialog.description.select_or_create': 'To alter content, select or create a working copy first. When you finished editing, publish the working copy or have it published.', 'editable_ws_dialog.description.select': 'To alter content, select a working copy first. When you finished editing, publish the working copy or have it published.', 'editable_ws_dialog.description.create': 'To alter content, create a working copy first. When you finished editing, publish the working copy or have it published.', 'editable_ws_dialog.description.forbidden': 'There is no working copy you could use to alter content. Also, creating working copies has not been enabled for you.', 'editable_ws_dialog.choose_existing': 'Select an existing working copy:', 'editable_ws_dialog.create_new': 'Create a new working copy:', 'editable_ws_dialog.or_create_new': 'Or, create a new one:', 'editable_ws_dialog.create_new_playholder': 'new working copy title', 'editable_ws_dialog.select': 'Select', 'resource_dialog.title': 'Properties of resource "$1"', 'resource_dialog.commands.revert_obj.title': 'Discard changes to resource', 'resource_dialog.commands.revert_obj.rtc_workspace': 'This resource is part of the "rtc" working copy, for which discarding changes is not supported.', 'resource_dialog.commands.revert_obj.new_obj': 'This is a new resource. To discard the creation of this resource, please delete it.', 'resource_dialog.commands.revert_obj.not_modified_obj': 'This resource has not been modified. Therefore, nothing can be discarded.', 'resource_dialog.commands.revert_obj.dialog.title': 'Really discard changes to this resource?', 'resource_dialog.commands.restore_obj.title': 'Restore resource', 'resource_dialog.commands.restore_obj.rtc_workspace': 'This resource is part of the "rtc" working copy, for which restoring resources is not supported.', 'resource_dialog.commands.mark_resolved_obj.title': 'Override concurrent changes to resource', 'resource_dialog.commands.mark_resolved_obj.dialog.description': 'This resource was altered in a different working copy that has been published. Please confirm that you want to keep your changes and discard the ones concurrently made by others.', 'resource_dialog.commands.delete_obj.title': 'Delete resource', 'resource_dialog.commands.delete_obj.dialog.title': 'Really delete this resource?', 'resource_dialog.commands.delete_obj.dialog.description': 'Changes to a deleted resource cannot be restored.', 'menu_bar.loading_workspaces': 'Loading working copies', 'menu_bar.create': 'Create', 'menu_bar.move': 'Move', 'menu_bar.copy': 'Copy', 'saving_indicator_item.saving': 'Saving...', 'saving_indicator_item.saved': 'Changes saved', 'menu_bar_warning.warning': 'Check JS console', 'menu_bar_warning.open_console': 'There are warnings. Please open the JavaScript console for details.', 'inplace_marker.overlapping': 'Two or more menu handles are overlapping. Please adjust your CSS. The following menu handles are overlapping:', 'widget_marker.widget_is_new': 'Widget is new', 'widget_marker.widget_is_edited': 'Widget has been modified', 'widget_marker.widget_is_edited_and_dragged_here': 'Widget has been modified and dragged here', 'widget_marker.widget_is_edited_and_dragged_away': 'Widget has been modified and dragged away from here', 'widget_marker.widget_is_deleted': 'Widget has been deleted', 'widget_marker.widget_is_dragged_here': 'Widget has been dragged here', 'widget_marker.widget_is_dragged_away': 'Widget has been dragged away from here', 'child_list_menu.description': 'Items of $1', 'changes_dialog.title': 'Changes to "$1"', 'changes_dialog.empty_result': 'Nothing was changed in this working copy.', 'changes_dialog.more': 'More...', 'changes_dialog.row.change': 'Change', 'changes_dialog.row.rights': 'Publishing permitted', 'changes_dialog.row.description_for_editor': 'Title', 'changes_dialog.row.type': 'Type', 'changes_dialog.row.last_changed': 'Last change', 'commands.create_workspace.forbidden': 'You can not create a workspace due to missing user permissions.', 'commands.create_workspace.title': 'Create working copy', 'commands.create_workspace.dialog.title': 'Create working copy', 'commands.create_workspace.dialog.description': 'Please enter the title of the new working copy.', 'commands.create_workspace.dialog.placeholder': 'new title', 'commands.create_workspace.dialog.accept': 'Create', 'commands.rename_workspace.title': 'Rename', 'commands.rename_workspace.dialog.title': 'Rename "$1"', 'commands.rename_workspace.dialog.description': 'Please enter the new title of the working copy.', 'commands.rename_workspace.dialog.accept': 'Rename', 'commands.rebase_workspace.title': 'Update', 'commands.rebase_workspace.tooltip': 'Working copy "$1" is outdated. Please update it.', 'commands.rebase_workspace.uptodate': 'Working copy "$1" is up to date.', 'commands.rebase_workspace.has_conflicts.title': 'Changed content has been published intermediately', 'commands.rebase_workspace.has_conflicts.description': 'Your working copy could not be fully updated. Some of its content has also been altered in a different working copy that has been published in the meantime. Please refer to the changes list for details.', 'commands.rebase_workspace.open_changes_dialog': 'Show changes', 'commands.delete_workspace.title': 'Delete', 'commands.delete_workspace.dialog.title': 'Really delete "$1"?', 'commands.delete_workspace.dialog.description': 'A deleted working copy cannot be restored.', 'commands.delete_workspace.dialog.confirm': 'Delete', 'commands.workspace_settings.title': 'Edit settings', 'commands.workspace_settings.dialog.title': 'Settings for "$1"', 'commands.workspace_changes.title': 'Show changes', 'commands.obj_details.title': 'Page properties', 'commands.obj_details.dialog.title': 'Properties of "$1"', 'commands.save_obj_to_clipboard.title': 'Mark page for copying or moving', 'commands.save_obj_to_clipboard.has_children': 'Pages with subpages cannot be copied or moved yet.', 'commands.delete_obj.title': 'Delete page', 'commands.delete_obj.published_workspace': 'Since this is the published content, nothing can be modified.', 'commands.delete_obj.has_children': 'Pages with subpages cannot be deleted yet.', 'commands.delete_obj.dialog.title': 'Really delete this page?', 'commands.delete_obj.dialog.description': 'Changes to a deleted page cannot be restored.', 'commands.delete_obj.dialog.confirm': 'Delete', 'commands.revert_obj.title': 'Discard changes to page', 'commands.revert_obj.published_workspace': 'Since this is the published content, nothing has been modified. Therefore, nothing can be discarded.', 'commands.revert_obj.rtc_workspace': 'This page is part of the "rtc" working copy, for which discarding changes is not supported.', 'commands.revert_obj.new_obj': 'This is a new page. To discard the creation of this page, please delete it.', 'commands.revert_obj.is_binary': 'Discarding changes is not available for binary content.', 'commands.revert_obj.not_modified_obj': 'This page has not been modified. Therefore, nothing can be discarded.', 'commands.revert_obj.dialog.title': 'Really discard changes to this page?', 'commands.revert_obj.dialog.description': 'Discarded changes cannot be restored.', 'commands.revert_obj.dialog.confirm': 'Discard', 'commands.revert_widget.content_title': 'Discard changes to content', 'commands.revert_widget.widget_title': 'Discard changes to widget', 'commands.revert_widget.rtc_workspace': 'This widget is part of the "rtc" working copy, for which discarding changes to a widgets is not supported.', 'commands.revert_widget.is_new': 'This is a new widget. To discard the creation of this widget, please delete it.', 'commands.revert_widget.is_not_modified': 'This widget has not been modified. Therefore, nothing can be discarded.', 'commands.revert_widget.dialog.title': 'Really discard changes to this widget?', 'commands.revert_widget.dialog.description': 'Discarded changes cannot be restored.', 'commands.revert_widget.dialog.confirm': 'Discard', 'commands.restore_widget.title': 'Restore widget', 'commands.restore_widget.rtc_workspace': 'This widget is part of the "rtc" working copy, for which restoring widgets is not supported.', 'commands.restore_obj.title': 'Restore page', 'commands.restore_obj.rtc_workspace': 'This page is part of the "rtc" working copy, for which restoring pages is not supported.', 'commands.mark_resolved_obj.title': 'Override concurrent changes to page', 'commands.mark_resolved_obj.dialog.confirm': 'Override changes', 'commands.mark_resolved_obj.dialog.title': 'Really override changes made by others in the meantime?', 'commands.mark_resolved_obj.dialog.description': 'This page was altered in a different working copy that has been published. Please confirm that you want to keep your changes and discard the ones concurrently made by others.', 'commands.duplicate_obj.title': 'Duplicate page', 'commands.duplicate_obj.published_workspace': 'Since this is the published content, nothing can be modified.', 'commands.duplicate_obj.has_children': 'Pages with subpages cannot be duplicated yet.', 'commands.add_subpage.title': 'Create new page', 'commands.add_subpage.tooltip': 'Create page underneath $1', 'commands.copy_page_from_clipboard.title': 'Copy marked page here', 'commands.copy_page_from_clipboard.paste_forbidden': 'Due to its type, the page cannot be moved or copied here. Only pages of the following types can be inserted here: $1', 'commands.move_page_from_clipboard.title': 'Move marked page here', 'commands.move_page_from_clipboard.paste_forbidden': 'Due to its type, the page cannot be moved or copied here. Only pages of the following types can be inserted here: $1', 'commands.sort_items.title': 'Sort items', 'commands.sort_items.tooltip': 'Edit order of items underneath $1', 'commands.sort_items.auto_sort': 'This navigation is sorted automatically.', 'commands.sort_items.too_less_children': 'This navigation cannot be sorted because it consists of less than two items.', 'obj_sorting_dialog.title': 'Sort items', 'commands.choose_and_create_widget.title': 'Insert widget', 'commands.choose_and_create_widget.disabled': 'You cannot insert any widgets here.', 'commands.create_widget.title': 'Insert $1', 'commands.add_content.title': 'Insert content', 'commands.add_content.not_allowed': 'It is not allowed to insert random content into this field.', 'commands.widget_details.title': 'Widget properties', 'commands.widget_details.no_details_view': 'This widget has no properties', 'commands.widget_details.dialog.title': 'Properties of "$1"', 'commands.save_widget_to_clipboard.content_title': 'Mark content for copying', 'commands.save_widget_to_clipboard.widget_title': 'Mark widget for copying', 'commands.copy_widget_from_clipboard.content_title': 'Insert copy of marked content', 'commands.copy_widget_from_clipboard.widget_title': 'Insert copy of marked widget', 'commands.copy_widget_from_clipboard.paste_forbidden': 'Due to its type, the widget cannot be moved or copied here. Only widgets of the following types can be inserted here: $1.', 'commands.delete_widget.content_title': 'Delete content', 'commands.delete_widget.widget_title': 'Delete widget', 'commands.delete_widget.dialog.title': 'Really delete this widget?', 'commands.delete_widget.dialog.description': 'A deleted widget cannot be restored.', 'commands.delete_widget.dialog.confirm': 'Delete', 'commands.switch_mode.view': 'Preview', 'commands.switch_mode.editing': 'Edit', 'commands.switch_mode.diff': 'All changes', 'commands.switch_mode.added': 'Additions', 'commands.switch_mode.deleted': 'Deletions', 'commands.switch_mode.disabled': 'Currently selected display mode', 'commands.publish_workspace.title': 'Publish', 'commands.publish_workspace.permission_denied': 'The working copy can not be published due to missing user permissions.', 'commands.publish_workspace.dialog.confirm': 'Publish', 'commands.publish_workspace.dialog.title': 'Publish "$1"?', 'commands.publish_workspace.dialog.description': 'Publishing a working copy is final. This action cannot be undone.', 'commands.publish_workspace.error_dialog.title': 'Working copy could not be published', 'commands.publish_workspace.error_dialog.description': 'Please check the changes list for details.', 'commands.publish_workspace.error_dialog.confirm': 'Open changes list', 'commands.publish_workspace.alert.invalid_certificates': 'The working copy could not be published because at least one user is currently modifying content in it.', 'ajax.error': 'Communication with the CMS failed with error: $1', 'ajax.error.communication': 'Communication with the CMS failed. Please check your network connectivity.', 'ajax.error.unknown': 'Communication with the CMS failed for unknown reasons.', 'ajax.error.production': 'During your last action, a technical error occurred. Please try again later. If the problem persists, please contact a technician familiar with this website.', 'workspace_limit_exceeded.message': 'You have reached the maximum number of working copies included in your plan. Please consider to have your plan upgraded.', 'warn_before_unloading': 'You have unsaved changes. Are you sure you want to quit?', 'test.two_arguments': '$1, $2', 'test.four_arguments': '$1, $2, $3, $4' }, 'en'); /* global alert:false */ var scrivito = {}; (function() { var inited = false; var wait_until_write_ends = function() { var deferred = $.Deferred(); if (scrivito.write_monitor.is_writing()) { scrivito.write_monitor.on('end_write', function() { wait_until_write_ends().done(function() { deferred.resolve(); }); }); } else { deferred.resolve(); } return deferred; }; var convert_internal_error = function(error) { // message is the only field of an error that is public API return {message: error.message}; }; $.extend(scrivito, { suppress_alerts: false, alert: function(message) { if (!scrivito.suppress_alerts) { window.alert(message); } }, warn: function() { if (scrivito.is_development_mode) { scrivito.menu_bar_warning.show(); } if (window.console) { window.console.warn.apply(window.console, arguments); } }, log_error: function(message, exception) { if (window.console) { window.console.error(message, exception); } }, redirect_to: function(location, target_window) { wait_until_write_ends().done(function() { scrivito.change_location(location, target_window); }); return $.Deferred(); }, // For testing purpose only. change_location: function(location, target_window) { (target_window || window).location = location; }, wait: function(seconds) { // this is a proxy method, so we can stub it easier. return $.Deferred(function(dfd) { setTimeout(dfd.resolve, seconds * 1000); }); }, run_new_event: function(method) { scrivito.wait(0).done(method); }, reload: function(target_window) { wait_until_write_ends().done(function() { scrivito.reload_location(target_window); }); return $.Deferred(); }, // For testing purpose only. reload_location: function(target_window) { (target_window || window).location.reload(); }, center: function(elem) { if (elem.length === 1) { elem.css({ marginLeft: -elem.innerWidth() / 2, marginTop: -elem.innerHeight() / 2, left: '50%' }); } }, ensure_fully_visible_within: function(dom_element, viewport_container, viewport_height) { var viewport_offset = viewport_container.scrollTop(); var dom_element_offset = dom_element.offset().top; var dom_element_height = dom_element.height(); var scroll_top; if (viewport_offset > dom_element_offset) { scroll_top = dom_element_offset - 50; } else if (dom_element_offset + dom_element_height > viewport_offset + viewport_height) { scroll_top = dom_element_height + dom_element_offset + 50 - viewport_height; } if (scroll_top) { viewport_container.animate({scrollTop: scroll_top}); } }, ensure_fully_visible_within_window: function(dom_element) { var cms_document = scrivito.cms_document.from(dom_element); scrivito.ensure_fully_visible_within(dom_element, cms_document.dom_element().find('body'), $(cms_document.browser_window()).height() ); }, describe_element: function(elem) { var description = elem.get(0).nodeName; if (elem.attr("id")) { description += "#"+elem.attr("id"); } var css_class = elem.attr('class'); if (css_class) { _(css_class.split(" ")).each(function(class_name) { description += "."+class_name; }); } return "["+description+"]"; }, remove_enter_and_escape_action: function() { $(document).off('keyup.scrivito_enter_escape_action'); }, random_hex: function() { var hex = Math.floor(Math.random() * Math.pow(16, 8)).toString(16); while (hex.length < 8) { hex = '0' + hex; } return hex; }, // 16 chars hex string random_id: function() { return scrivito.random_hex() + scrivito.random_hex(); }, deprecation_warning: function(subject, alternative) { var message = 'DEPRECATION WARNING: "' + subject + '" is deprecated.'; if (alternative) { message += ' Please use "' + alternative + '" instead.'; } scrivito.warn(message); }, // @api public on: function(event, callback) { if (event === 'load') { scrivito.gui.on('open', function() { callback(); }); if (scrivito.gui.is_started()) { scrivito.run_new_event(function() { callback(); }); } } else if (event === 'content') { scrivito.gui.on('content', function(dom_element) { callback(dom_element); }); if (scrivito.gui.is_started()) { scrivito.run_new_event(function() { callback(window.document); }); } } else { $.error('Unknown event "' + event + '"'); } }, // @api public create_obj: function(attributes) { return scrivito.obj.create(attributes).then(function(obj) { return {id: obj.id()}; }, convert_internal_error); }, // @api public delete_obj: function(id) { if (id) { return scrivito.obj.create_instance({id: id}).destroy() .then(null, convert_internal_error); } else { $.error("Can't delete without ID"); } }, // @api public is_current_page_restricted: function() { var current_page = scrivito.application_window.document().page(); if (current_page) { return current_page.has_restriction(); } }, never_resolve: function() { return $.Deferred(); }, // @api public trigger: function(event_name, dom_element) { if (event_name === 'content') { _.each($(dom_element), function(e) { scrivito.gui.new_content(e); }); } else if (event_name === 'new_content') { scrivito.deprecation_warning( 'scrivito.trigger("new_content")', 'scrivito.trigger("content")'); scrivito.trigger('content', dom_element); } else { $.error('Unknown event "' + event_name + '"'); } }, // @api public in_editable_view: function() { return scrivito.editing_context.display_mode === 'editing' && scrivito.editing_context.visible_workspace.is_editable(); }, open_resource_dialog: function(obj_id) { return scrivito.resource_dialog.open(obj_id); }, // See http://underscorejs.org/#throttle throttle: function(fn, ms) { return scrivito.bypass_throttle ? fn : _.throttle(fn, ms); }, json_parse_base64: function(base64_string) { // See http://mzl.la/1p1zI9k. var dom_string = decodeURIComponent(window.escape(atob(base64_string))); return JSON.parse(dom_string); }, json_stringify_base64: function(object) { var dom_string = JSON.stringify(object); // See http://mzl.la/1p1zI9k. return btoa(window.unescape(encodeURIComponent(dom_string))); }, t: function() { return scrivito.i18n.translate.apply(null, arguments); }, // proxy function so that other gems need no knowledge of `cms_document` register_public_api: function() { return scrivito.cms_document.register_public_api.apply(this, arguments); }, is_inited: function() { return inited; }, application_document: function() { return scrivito.application_window.document(); }, root_path: function() { return scrivito.application_window.is_frame() ? '/scrivito/' : '/'; }, details_url_for_obj_id: function(id) { return scrivito.obj.create_instance({id: id}).details_src(); }, workspace_limit_exceeded: function() { scrivito.info_dialog(scrivito.t('workspace_limit_exceeded.message')); }, // @api public register_default_obj_class_for_content_type: function(mapping) { scrivito.obj_class_defaults.register(mapping); }, // @api public default_obj_class_for_content_type: function(content_type) { return scrivito.obj_class_defaults.lookup(content_type); }, // @api public configure_menu_order: function(order) { scrivito.menu_order = order; }, pattern_sort: function(items, patterns) { if (patterns && patterns.length) { var results = []; _.each(patterns, function(pattern, index) { if (!pattern.match(/(.*)\.\*$/)) { var hit = _.find(items, function(item) { return item.id() === pattern; }); if (hit) { results[index] = hit; items = _.without(items, hit); } } }); _.each(patterns, function(pattern, index) { if (pattern.match(/(.*)\.\*$/)) { var hits = _.select(items, function(item) { return !item.id().indexOf(pattern.replace('.*', '')); }); if (hits.length) { results[index] = hits; items = _.difference(items, hits); } } }); return _.flatten(_.compact(results.concat(items))); } else { return items; } }, // @api beta register_select_content: function(select_content) { scrivito.select_content = select_content; }, // @api public page_menu: function(cms_document) { return scrivito.menu_builder.create_instance(cms_document); }, register_browse_content: function (browse_content) { scrivito.browse_content = browse_content; }, // FIXME content-widget enable_content_upload: false, is_development_mode: false, init: function(config) { scrivito.config = config; scrivito.editing_context.init(config.editing_context); scrivito.i18n.init(config.i18n); scrivito.resource_dialog.init(config.resource_dialog); scrivito.user.init(config.user); scrivito.user_permissions.init(config.user_permissions); scrivito.is_development_mode = config.is_development_mode; scrivito.inplace_marker.init(); scrivito.menu_bar_saving_indicator.init(); scrivito.menu_bar_warning.init(); scrivito.menu_bar_toggle.init(); scrivito.current_page_menu.init(); scrivito.menu_bar_browse_content.init(); scrivito.current_page_restriction.init(); scrivito.workspace_select.init(); scrivito.menu_bar.init(); scrivito.child_list_commands.init(); scrivito.current_page_commands.init(); scrivito.widget_commands.init(); scrivito.widgetlist_field_commands.init(); scrivito.child_list_marker.init(); scrivito.widgetlist_field_menu.init(); scrivito.widget_marker.init(); scrivito.menus.init(); scrivito.external_links.init(); scrivito.widget_reloading.init(); scrivito.widget_sorting.init(); // FIXME content-widget if (scrivito.enable_content_upload) { scrivito.content_upload.init(); } scrivito.reloading.init(); window.onbeforeunload = scrivito.warn_before_unloading; scrivito.url_update(scrivito.application_window, scrivito.cms_window.from(window)); inited = true; } }); }()); (function() { var valid_locale = ['en', 'de']; var language; $.extend(scrivito, { i18n: { init: function(config) { scrivito.i18n.set_locale(config.locale); }, locale: function() { return language; }, set_locale: function(locale) { if($.inArray(locale, valid_locale) !== -1) { language = locale; } else { language = 'en'; } moment.locale(language); }, // In addition to the key you can pass multiple parameters that will be interpolated into // the translated string. translate: function(key) { if (!scrivito.i18n.locale()) { $.error('scrivito.i18n locale not yet set!'); } $.i18n().locale = scrivito.i18n.locale(); return $.i18n.apply(0, arguments); }, // localize_date localizes an ISO6801 date string according to the current locale. localize_date: function(date_string) { return moment(date_string).format('LLLL'); }, // localize_date_relative converts an ISO6801 date string to a relative time and localizes it // according to the current locale. localize_date_relative: function(date_string) { return moment(date_string).fromNow(); }, // Test purpose only. reset_locale: function() { language = undefined; } } }); }()); (function() { var assert_valid_dom_element = function(dom_element) { if (dom_element.length < 1) { $.error('Can not call "scrivito" method on an empty element'); } if (dom_element.length > 1) { $.error('Can not call "scrivito" method on more than one tag'); } }; var build_cms_element = function(dom_element) { return scrivito.cms_element.from_dom_element(dom_element); }; var save_content = function(dom_element, content) { if (dom_element.length > 0) { if (dom_element.length === 1) { if (content === undefined) { $.error('Can not call "save" with no content'); } else { var cms_element = build_cms_element(dom_element); cms_element.set_original_content(content); return cms_element.save(content).then(function() { return; }, function(error) { return {message: error.message}; }); } } else { $.error('Can not call "scrivito" method on more than one tag'); } } }; var get_original_content = function(dom_element) { assert_valid_dom_element(dom_element); return build_cms_element(dom_element).original_content(); }; var get_menu = function(dom_element) { assert_valid_dom_element(dom_element); var cms_element = build_cms_element(dom_element); return scrivito.menu_builder.create_instance(cms_element); }; var reload = function(dom_element) { assert_valid_dom_element(dom_element); build_cms_element(dom_element); $(dom_element).trigger('reload.scrivito'); }; $.extend(scrivito, { // @api public jquery_plugin: function(method, content) { switch (method) { case 'save': return save_content($(this), content); case 'content': return get_original_content($(this)); case 'menu': return get_menu($(this)); case 'reload': reload($(this)); break; default: $.error('Unknown method "' + method + '"'); } } }); $.fn.scrivito = scrivito.jquery_plugin; }()); (function() { var attr_name = 'data-scrivito-private-config'; var selector = '[' + attr_name + ']'; _.extend(scrivito, { dom_config: { read: function(dom_element) { var config = dom_element.find(selector).addBack(selector).attr(attr_name); if (config) { return JSON.parse(config); } }, write: function(dom_element, config) { dom_element.attr(attr_name, JSON.stringify(config)); } } }); }()); (function() { _.extend(scrivito, { url_update: function(application_cms_window, ui_cms_window) { if (application_cms_window === ui_cms_window) { return; } application_cms_window.on('document', function(application_document) { var ui_window = ui_cms_window.browser_window(); var application_window = application_document.browser_window(); var ui_url = ui_window.location.origin + '/scrivito' + application_window.location.pathname + application_window.location.search + application_window.location.hash; ui_window.history.replaceState({}, '', ui_url); }); } }); }()); (function() { var is_started = false; var callbacks = {}; // The callback has to be function that takes no arguments var log_exception_in_callback = function(event_name, callback) { if (scrivito.gui.sandbox_callbacks) { try { callback(); } catch(exception) { var text = "'"+event_name+"' callback threw exception: "; scrivito.log_error(text, exception); } } else { callback(); } }; var run_open_callbacks = function() { if (callbacks.open) { _.each(callbacks.open, function(callback) { log_exception_in_callback('open', callback); }); } if (scrivito.editing_context.is_editing_mode() && callbacks.editing) { _.each(callbacks.editing, function(callback) { log_exception_in_callback('editing', callback); }); } }; var assert_no_turbolinks = function() { if (scrivito.application_window.browser_window().Turbolinks) { scrivito.alert_dialog( 'You have Turbolinks enabled. ' + 'Scrivito does not yet support Turbolink. ' + 'Please remove it from your assets.' ); } }; $.extend(scrivito, { gui: { start: function() { scrivito.gui.on('document', function(document) { var body = document.dom_element().find('body'); body.attr('data-scrivito-display-mode', scrivito.editing_context.display_mode); _.each(['dragenter', 'dragover', 'drop'], function(e) { body.on(e, false); }); }); $('body').append('<div id="scrivito_editing"></div>'); run_open_callbacks(); scrivito.gui.run_content_callbacks(window.document); assert_no_turbolinks(); is_started = true; }, // For test purpose only. stop: function() { is_started = false; }, new_content: function(dom_element) { scrivito.gui.run_content_callbacks(dom_element); if (dom_element) { var cms_document = scrivito.cms_document.from($(dom_element)); cms_document.notify_new_content(dom_element); } }, new_document: function(document) { _.each(callbacks.document, function(callback) { callback(document); }); document.window().notify_new_document(document); }, on: function(event_name, callback) { if (callbacks[event_name] === undefined) { callbacks[event_name] = []; } callbacks[event_name].push(callback); }, run_content_callbacks: function(dom_element) { if (callbacks.content) { _.each(callbacks.content, function(callback) { if (dom_element) { log_exception_in_callback('content', function() { callback(dom_element); }); } }); } }, // For testing purpose only. reset_callbacks: function() { callbacks = {}; }, // For testing purpose only. sandbox_callbacks: true, is_started: function() { return is_started; } } }); }()); (function() { $.extend(scrivito, { editing_context: { display_mode: null, selected_workspace: null, visible_workspace: null, init: function(config) { scrivito.editing_context.display_mode = config.display_mode; var visible_workspace = scrivito.workspace.from_data(config.visible_workspace); var selected_workspace = scrivito.workspace.from_data(config.selected_workspace); scrivito.editing_context.visible_workspace = visible_workspace; scrivito.editing_context.selected_workspace = selected_workspace; if (scrivito.mock_always_focus_during_integration_test || document.hasFocus()) { scrivito.editing_context.write_cookie(); } $.ajaxPrefilter(scrivito.editing_context.ajax_prefilter); scrivito.gui.on('document', function(cms_document) { if (!window.cms_documents) { window.cms_documents = []; } window.cms_documents.push(cms_document); cms_document.local_jquery().ajaxPrefilter(scrivito.editing_context.ajax_prefilter); }); // This can not be unit tested, since it is not possible to trigger a 'focus' // event on a 'window' object with JavaScript. $(window).focus(function() { scrivito.editing_context.write_cookie(); }); }, is_view_mode: function() { return scrivito.editing_context.display_mode === 'view'; }, is_editing_mode: function() { return scrivito.editing_context.display_mode === 'editing'; }, is_added_mode: function() { return scrivito.editing_context.display_mode === 'added'; }, is_deleted_mode: function() { return scrivito.editing_context.display_mode === 'deleted'; }, is_diff_mode: function() { return scrivito.editing_context.display_mode === 'diff'; }, is_comparing_mode: function() { return scrivito.editing_context.is_added_mode() || scrivito.editing_context.is_deleted_mode() || scrivito.editing_context.is_diff_mode(); }, ajax_prefilter: function(options, originalOptions, xhr) { if (!options.crossDomain) { xhr.setRequestHeader('Scrivito-Editing-Context', serialize()); } }, write_cookie: function() { $.cookie('scrivito_editing_context', serialize(), {path: '/'}); }, comparing_mode: function() { var storage_key = 'editing_context.comparing_mode'; if (scrivito.editing_context.is_comparing_mode()) { var mode = scrivito.editing_context.display_mode; scrivito.storage.set(storage_key, mode); return mode; } else { if (scrivito.storage.has_key(storage_key)) { return scrivito.storage.get(storage_key); } else { return 'diff'; } } } } }); var serialize = function() { return JSON.stringify({ display_mode: scrivito.editing_context.display_mode, workspace_id: scrivito.editing_context.selected_workspace.id() }); }; }()); (function() { $.extend(scrivito, { user_permissions: { permissions_hash: {}, init: function(permissions_hash) { scrivito.user_permissions.permissions_hash = permissions_hash; }, can: function(permission_key) { return !!scrivito.user_permissions.permissions_hash[permission_key]; } } }); }()); (function() { var handle_task = function(task) { switch (task.status) { case 'success': return $.Deferred().resolve(task.result); case 'error': return $.Deferred().reject({ message: task.message, code: task.code }); case 'open': return scrivito.wait(2).then(function() { return single_ajax('GET', 'tasks/' + task.id).then(function(data) { return handle_task(data); }); }); default: throw { message: "Invalid task (unknown status)", task: task }; } }; var single_ajax = function(type, path, options) { var base_url = window.location.protocol + '//' + window.location.host + '/__scrivito/'; if (options && options.data) { options.data = JSON.stringify(options.data); } return $.ajax(base_url + path, $.extend({ type: type, dataType: 'json', contentType: 'application/json; charset=utf-8', cache: false // Don't cache GET requests. }, options || {})).then( function(result, text_status, xhr) { return $.Deferred().resolve(result); }, function(xhr, text_status, error) { var error_message; var error_code; try { var error_json = JSON.parse(xhr.responseText); error_message = error_json.error; error_code = error_json.code; } catch (SyntaxError) {} if (!error_message) { error_message = error; } return $.Deferred().reject({ status: xhr.status, message: error_message, code: error_code }); } ); }; $.extend(scrivito, { silent_ajax: function(type, path, options) { var is_write_request = type === 'PUT' || type === 'POST' || type === 'DELETE'; if (is_write_request) { options = options || {}; options.timeout = 15000; // miliseconds scrivito.write_monitor.start_write(); } var ajax_promise = single_ajax(type, path, options).then(function(result) { if (result && result.task && _.size(result) === 1) { return handle_task(result.task); } else { return $.Deferred().resolve(result); } }); if (is_write_request) { ajax_promise.always(function() { scrivito.write_monitor.end_write(); }); } return ajax_promise; }, ajax: function(type, path, options) { return scrivito.silent_ajax(type, path, options).fail(function(error) { scrivito.display_ajax_error(error); }); }, display_ajax_error: function(error) { var ajax_error = error.message; var error_message; if (_.contains(['abort', 'parsererror', 'timeout'], ajax_error)) { error_message = scrivito.t('ajax.error.communication'); } else if (ajax_error === 'error') { error_message = scrivito.t('ajax.error.unknown'); } else if (ajax_error) { error_message = scrivito.t('ajax.error', ajax_error); } else { error_message = scrivito.t('ajax.error.unknown'); } if (scrivito.is_development_mode) { scrivito.alert_dialog(error_message); } else { scrivito.log_error(error_message); scrivito.info_dialog(scrivito.t('ajax.error.production')); } } }); }()); (function() { $.extend(scrivito, { command: { create_instance: function(params) { var that = { id: function() { return params.id; }, dom_id: function() { return params.id.replace(/\./g, '_'); }, title: function() { var title = params.title; return typeof title === 'function' ? title() : title; }, icon: function() { return params.icon || ''; }, tooltip: function() { return params.tooltip; }, is_present: function() { var is_present = params.present; switch (typeof is_present) { case 'undefined': return true; case 'function': return !!is_present(); default: return !!is_present; } }, is_enabled: function() { return !that.is_disabled(); }, is_disabled: function() { return !!that.reason_for_being_disabled(); }, is_action_required: function() { var is_action_required = params.action_required; return typeof is_action_required === 'function' && is_action_required(); }, reason_for_being_disabled: function() { var reason_for_being_disabled = params.disabled; if (typeof reason_for_being_disabled === 'function') { return reason_for_being_disabled(); } }, update: function() { if (that.needs_update()) { return params.update(); } }, needs_update: function() { return !!params.update; }, execute: function() { if (that.is_present() && that.is_enabled()) { params.execute(); return true; } return false; }, update_params: function(new_params) { return _.extend(params, new_params); } }; return that; } } }); }()); (function() { $.extend(scrivito, { menu_item: { create_instance: function(command) { var icon = command.icon(); var icon_template = 'menu_item/' + (icon.indexOf('&') ? 'customer' : 'factory') + '_icon'; var render_menu_item = function() { return scrivito.template.render('menu_item', _.extend({}, command, {icon: function() { return scrivito.template.render(icon_template, {icon: icon}); }})); }; return { render: function() { if (command.is_present()) { var view; if (command.needs_update()) { var id = _.uniqueId(command.dom_id()); view = scrivito.template.render('menu_item/spinner', {id: id}); command.update().then(function() { $('#'+id).replaceWith(render_menu_item()); }); } else { view = render_menu_item(); } return view; } } }; } } }); }()); (function() { _.extend(scrivito, { menu_builder: { create_instance: function(cms_element) { return { list: function() { return cms_element.menu(); }, add: function(id, params) { var menu = cms_element.menu(); menu.push(scrivito.command.create_instance(_.extend(params, {id: id}))); cms_element.set_menu(menu); }, update: function(id, params) { var menu = cms_element.menu(); _.find(menu, function(command, index) { if (command.id() === id) { return command.update_params(params); } }); cms_element.set_menu(menu); }, replace: function(id, params) { var menu = cms_element.menu(); _.find(menu, function(command, index) { if (command.id() === id) { return menu[index] = scrivito.command.create_instance(_.extend(params, {id: id})); } }); cms_element.set_menu(menu); }, remove: function(id) { var menu = cms_element.menu(); var command = _.find(menu, function(command) { return command.id() === id; }); cms_element.set_menu(_.without(menu, command)); } }; } } }); }()); (function() { var callbacks = {}; var current_token = 0; var counter = 0; var run_callbacks = function(event_name) { _.each(callbacks[event_name], function(callback) { callback(); }); }; $.extend(scrivito, { write_monitor: { on: function(event_name, callback) { if (callbacks[event_name] === undefined) { callbacks[event_name] = {}; } current_token += 1; callbacks[event_name][current_token] = callback; return current_token; }, off: function(token) { _.each(callbacks, function(event_callbacks) { delete event_callbacks[token]; }); }, is_writing: function() { return counter > 0; }, start_write: function() { if (!scrivito.write_monitor.is_writing()) { run_callbacks('start_write'); } counter += 1; }, end_write: function() { counter -= 1; if (!scrivito.write_monitor.is_writing()) { scrivito.run_new_event(function() { if (!scrivito.write_monitor.is_writing()) { run_callbacks('end_write'); } }); } }, track_changes: function(fn, on_change_callback) { var has_changes = false; var changes_finished = false; var start_token = scrivito.write_monitor.on('start_write', function() { has_changes = true; changes_finished = false; }); var end_token = scrivito.write_monitor.on('end_write', function() { changes_finished = true; }); return fn().done(function() { scrivito.write_monitor.off(start_token); scrivito.write_monitor.off(end_token); if (has_changes) { if (changes_finished) { on_change_callback(); } else { var saving_promise = $.Deferred(); var final_end_token = scrivito.write_monitor.on('end_write', function() { scrivito.write_monitor.off(final_end_token); saving_promise.resolve(); on_change_callback(); }); scrivito.with_saving_overlay(saving_promise); } } }); }, // For test purpose only. reset_callbacks: function() { callbacks = {}; current_token = 0; }, // For test purpose only. reset_counter: function() { counter = 0; } } }); }()); (function() { var menu_bar_items_renderer = []; $.extend(scrivito, { menu_bar: { init: function() { // Add the corresponding CSS class to all documents (including iframe in details dialog). scrivito.gui.on('document', function(document) { document.dom_element().find('body').addClass('scrivito_editing_active'); }); // Re-render the menu bar if the application window changes. scrivito.application_window.on('document', function(document) { scrivito.menu_bar.render(); }); }, register_item_renderer: function(item_renderer) { menu_bar_items_renderer.push(item_renderer); }, render: function() { var view = $(scrivito.template.render('menu_bar')); _.each(menu_bar_items_renderer, function(item_renderer) { item_renderer(view); }); var menu_bar = $('.scrivito_topbar'); if (menu_bar.length) { menu_bar.replaceWith(view); } else { $('body').append(view); } }, // For test purpose only. reset_items_renderer: function() { menu_bar_items_renderer = []; }, // For test purpose only. remove: function() { $('.scrivito_topbar').remove(); } } }); }()); (function() { $.extend(scrivito, { menu_bar_saving_indicator: { init: function() { scrivito.menu_bar.register_item_renderer(function(parent_view) { scrivito.saving_indicator.create(parent_view.find('#scrivito_menu_bar_saving_indicator')); }); } } }); }()); (function() { $.extend(scrivito, { menu_bar_warning: { init: function() { scrivito.menu_bar.register_item_renderer(function(parent_view) { scrivito.menu_bar_warning.create( parent_view.find('#scrivito_menu_bar_warning')); }); }, create: function(parent_view) { parent_view.append(scrivito.template.render('menu_bar_warning')); $(parent_view).on('click', function() { scrivito.alert_dialog(scrivito.t('menu_bar_warning.open_console')); scrivito.menu_bar_warning.hide(); }); }, show: function() { $('.scrivito_menu_bar_warning').show(); }, hide: function() { $('.scrivito_menu_bar_warning').hide(); } } }); }()); (function() { $.extend(scrivito, { menu_bar_toggle: { init: function() { scrivito.menu_bar.register_item_renderer(function(menu_bar) { var comparing_mode = scrivito.editing_context.comparing_mode(); var switch_to_view_mode_command = scrivito.switch_mode_command('view'); var switch_to_editing_mode_command = scrivito.switch_mode_command('editing'); var switch_to_comparing_mode_command = scrivito.switch_mode_command(comparing_mode); var template = scrivito.template.render('menu_bar_toggle', { mode: scrivito.editing_context.display_mode, comparing_mode: comparing_mode, switch_to_view_mode_command: switch_to_view_mode_command, switch_to_editing_mode_command: switch_to_editing_mode_command, switch_to_comparing_mode_command: switch_to_comparing_mode_command }); var menu_bar_toggle = menu_bar.find('#scrivito_menu_bar_toggle').html(template); _.each([ switch_to_view_mode_command, switch_to_editing_mode_command, switch_to_comparing_mode_command ], function(command) { menu_bar_toggle.find('.' + command.id()).on('click', function() { command.execute(); return false; }); }); menu_bar_toggle.find('.scrivito_comparing_mode_toggle').on('click', function() { scrivito.inline_menus.toggle($(this), [ scrivito.switch_mode_command('diff'), scrivito.switch_mode_command('added'), scrivito.switch_mode_command('deleted') ], 'left'); return false; }); }); } } }); }()); (function() { _.extend(scrivito, { obj_menu: { create: function(dom_element, obj, commands) { dom_element.append(scrivito.template.render('obj_menu', {obj: obj})); dom_element.on('click', function() { scrivito.inline_menus.toggle(dom_element, _.isFunction(commands) ? commands() : commands); return false; }); } } }); }()); (function() { _.extend(scrivito, { current_page_menu: { init: function() { scrivito.menu_bar.register_item_renderer(function(menu_bar) { var current_page = scrivito.application_document().page(); if (current_page) { var dom_element = menu_bar.find('#scrivito_current_page_menu'); scrivito.obj_menu.create(dom_element, current_page, function() { return scrivito.application_document().menu(); }); } }); } } }); }()); (function() { _.extend(scrivito, { menu_bar_browse_content: { init: function() { scrivito.menu_bar.register_item_renderer(function(menu_bar) { if (scrivito.browse_content && scrivito.in_editable_view()) { var button = menu_bar.find('#scrivito_menu_bar_browse_content'); button.addClass('scrivito_button_bar scrivito_right'); button.append(scrivito.template.render('menu_bar_browse_content')); button.on('click', function() { scrivito.browse_content(); return false; }); } }); } } }); }()); (function() { $.extend(scrivito, { current_page_restriction: { init: function() { var current_page = scrivito.application_window.document().page(); if (current_page && current_page.has_restriction()) { scrivito.menu_bar.register_item_renderer(function(menu_bar) { $(scrivito.template.render('current_page_restriction', { restriction_messages: current_page.restriction_messages })).appendTo(menu_bar.find('#scrivito_current_page_restriction')); }); } } } }); }()); (function() { $.extend(scrivito, { workspace_select: { init: function() { var selected_workspace = scrivito.editing_context.selected_workspace; var commands = { create_workspace: scrivito.create_workspace_command(), select_published: scrivito.select_workspace_command(scrivito.workspace.published()), for_editable: [ scrivito.workspace_changes_command(), scrivito.workspace_settings_command(selected_workspace), scrivito.rename_workspace_command(selected_workspace), scrivito.rebase_workspace_command(selected_workspace), scrivito.publish_workspace_command(selected_workspace), scrivito.delete_workspace_command(selected_workspace) ] }; scrivito.menu_bar.register_item_renderer(function(menu_bar) { var workspace_select = menu_bar.find('#scrivito_workspace_select'); workspace_select.append(scrivito.template.render('workspace_select', { selected_workspace: selected_workspace, commands: commands })); var bind_command = function(command) { workspace_select.on('click', '#'+command.dom_id(), function() { return command.execute(); }); }; bind_command(commands.create_workspace); bind_command(commands.select_published); _.each(commands.for_editable, function(command) { bind_command(command); }); workspace_select.on('click', function() { var menu_box = workspace_select.find('.scrivito_menu_box'); menu_box.fadeToggle('50'); var workspace_list = menu_box.find('.scrivito_workspace_list'); if (workspace_list.find('.scrivito_spinning').length) { scrivito.workspace.editable().then(function(workspaces) { var commands = _(workspaces).reject(function(workspace) { return workspace.id() === selected_workspace.id(); }).map(function(workspace) { return scrivito.select_workspace_command(workspace); }); workspace_list.replaceWith(scrivito.template.render( 'workspace_select/other_workspaces', { has_separator: selected_workspace.is_published() && commands.length, commands: commands } )); _.each(commands, function(command) { bind_command(command); }); }); } return false; }); }); } } }); }()); (function() { $.extend(scrivito, { changes_dialog: { open: function() { loaded_objs = []; total_obj_count = 0; batch = basic_batch(); view = $(scrivito.template.render('changes_dialog', { selected_workspace_title: scrivito.editing_context.selected_workspace.title() })); $('#scrivito_editing').append(view); var next_loader = view.find('.scrivito_load_more'); target = view.find('#scrivito_changes_table_loaded'); var spinner = view.find('#scrivito_changes_table_loading'); var empty_result = view.find('#scrivito_changes_table_empty_result'); var obj_count = view.find('#scrivito_obj_count'); loaded_obj_count_ref = view.find('#scrivito_loaded_obj_count'); total_obj_count_ref = view.find('#scrivito_total_obj_count'); load_markup = function() { loading_in_progress = true; spinner.show(); batch.load_batch().then(function(data, next) { loading_in_progress = false; batch = next; if (!batch) { next_loader.hide(); } else { next_loader.show(); } if (data.total > 0) { loaded_objs = loaded_objs.concat(data.hits); total_obj_count = data.total; render_objs(loaded_objs); } else { empty_result.show(); } spinner.hide(); loaded_obj_count_ref.text(loaded_objs.length); total_obj_count_ref.text(total_obj_count); obj_count.show(); view.on('click.scrivito_link_to_obj', '.scrivito_link_to_obj', function(e) { var element = $(e.currentTarget); var obj_id = element.attr('data-scrivito-private-changes-list-obj-id'); var obj_modification = element.attr( 'data-scrivito-private-changes-list-obj-modification'); var obj_is_binary = element.attr('data-scrivito-private-changes-list-obj-is-binary'); if (can_use_resource_dialog_directly(obj_modification, obj_is_binary)) { var loaded_obj = _.find(loaded_objs, function(obj) { return obj.id === obj_id; }); scrivito.resource_dialog.open(scrivito.obj.create_instance(loaded_obj)); } else { scrivito.changes_dialog.redirect_to_obj(obj_id, obj_modification, obj_is_binary); } return false; }); }); }; next_loader.on('click', load_markup); load_markup(); activate_sorting(); var deferred = $.Deferred(); cancel = function() { scrivito.dialog.close(view); deferred.resolve(); return false; }; view.find('.scrivito_cancel').on('click', cancel); scrivito.dialog.open_and_adjust(view); return scrivito.with_dialog_behaviour(view, deferred, {escape: cancel}); }, redirect_to_obj: function(obj_id, modification, is_binary) { var base_url = scrivito.root_path(); var query_params = {}; if (!!is_binary) { base_url += '__scrivito/resource_details/'; query_params.return_to = document.URL; } if (modification === 'deleted' && !scrivito.editing_context.is_deleted_mode()) { query_params._scrivito_display_mode = 'deleted'; } if (modification === 'new' && scrivito.editing_context.is_deleted_mode()) { query_params._scrivito_display_mode = 'added'; } cancel(); var redirect_url = base_url + obj_id; if (!_.isEmpty(query_params)) { redirect_url += '?' + $.param(query_params); } scrivito.with_saving_overlay(scrivito.redirect_to(redirect_url)); } } }); var batch; var view; var loaded_obj_count_ref; var total_obj_count_ref; var loaded_objs; var total_obj_count; var target; var load_markup; var loading_in_progress; var cancel; var can_use_resource_dialog_directly = function(modification, is_binary) { return is_binary && ( modification === 'edited' || modification === 'deleted' && scrivito.editing_context.is_deleted_mode() || modification === 'new' && !scrivito.editing_context.is_deleted_mode()); }; var basic_batch = function() { return scrivito. obj_where('_modification', 'equals', ['new', 'edited', 'deleted']). batch_size(100). order('_last_changed'). reverse_order(). format('_default'). include_deleted(); }; var render_objs = function(obj_specs) { target.html(_.map(obj_specs, function(obj_spec) { return scrivito.template.render('changes_dialog/row', scrivito.obj.create_instance(obj_spec)); })); }; var activate_sorting = function() { var sortables = view.find('.scrivito_sortable'); view.on('click.scrivito_sortable', '.scrivito_sortable', function() { if (loading_in_progress) { return; } var sortable = $(this); var sorting_by = {}; sorting_by.attribute = sortable.attr('data-scrivito-private-sort-by'); var order_was_asc = sortable.hasClass('sort_up'); if (order_was_asc) { sorting_by.order = 'desc'; } else { sorting_by.order = 'asc'; } sortables.removeClass('sort_up').removeClass('sort_down'); var local_sort = function() { var sort_function_or_attribute = sorting_by.attribute; if (sort_function_or_attribute === 'rights') { sort_function_or_attribute = function(obj) { return -obj.restriction_messages.length; }; } var objs = _.sortBy(loaded_objs, sort_function_or_attribute); if (sorting_by.order === 'desc') { objs = objs.reverse(); } render_objs(objs); }; var backend_sort = function() { batch = basic_batch(); batch.order('_' + sorting_by.attribute); if (sorting_by.order === 'asc') { batch.reverse_order(); } loaded_objs = []; render_objs(loaded_objs); load_markup(); }; if (loaded_objs.length === total_obj_count || sorting_by.attribute === 'rights') { local_sort(); } else { backend_sort(); } if (sorting_by.order === 'asc') { sortable.addClass('sort_up'); } else { sortable.addClass('sort_down'); } }); }; }()); (function() { var defaults; _.extend(scrivito, { obj_class_defaults: { register: function(mapping) { _.extend(defaults, mapping); }, lookup: function(content_type) { return defaults[content_type] || defaults[content_type.split('/')[0] + '/*'] || defaults['*/*']; }, reset: function() { defaults = {}; scrivito.obj_class_defaults.register({'image/*': 'Image', '*/*': 'Download'}); } } }); scrivito.obj_class_defaults.reset(); }()); (function() { var expando = "scrivito_cms_element"; _.extend(scrivito, { cms_element: { create_instance: function(dom_element) { var that = { dom_element: function() { return dom_element; }, equals: function(cms_element) { return cms_element.dom_element().get(0) === that.dom_element().get(0); }, menu: function() { var menu = dom_element.data('scrivito-menu'); if (!menu) { menu = []; that.set_menu(menu); } return menu; }, set_menu: function(menu) { dom_element.data('scrivito-menu', menu); } }; return that; }, from_dom_element: function(dom_element) { if (!dom_element || !dom_element.jquery) { dom_element = $(dom_element); } if (dom_element.length === 0) { $.error("Expected a jquery instance with exactly one element, " + "instead got " + dom_element); } var instance = dom_element[0][expando]; if (!instance) { var cms_element = scrivito.cms_element.create_instance(dom_element); _.find(scrivito.cms_element.definitions, function(definition) { instance = definition.create_instance(cms_element); return instance; }); if (!instance) { $.error("This dom element is not a scrivito tag."); } dom_element[0][expando] = instance; } return instance; }, definitions: [], all: function(selector, root_element) { return _.map(root_element.find(selector).addBack(selector), function(dom_element) { return scrivito.cms_element.from_dom_element($(dom_element)); }); } } }); }()); (function() { $.extend(scrivito, { blob: { create: function(file) { return get_upload_permission().then(function(permission) { scrivito.write_monitor.start_write(); return upload_to_s3(file, permission).always(function() { scrivito.write_monitor.end_write(); }); }); }, // For testing purpose only. get_form_data: function() { return new FormData(); } } }); var get_upload_permission = function() { return scrivito.ajax('GET', 'blobs/upload_permission'); }; var upload_to_s3 = function(file, permission) { var form_data = scrivito.blob.get_form_data(); _.each(permission.fields, function(value, name) { form_data.append(name, value); }); form_data.append('file', file); // File must be appended last, otherwise S3 will complain. permission.blob.filename = file.name.replace(/[^\w\-_\.$]/g, '-'); permission.blob.content_type = file.type; return $.ajax({type: 'POST', url: permission.url, data: form_data, // These are needed in order for jQuery to work properly with a FormData. contentType: false, processData: false }).then(function() { return permission.blob; }); }; }()); (function() { $.extend(scrivito, { child_list_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-private-child-list-path')) { var that = cms_element; $.extend(that, { path: function() { return that.dom_element().attr('data-scrivito-private-child-list-path'); }, obj: function() { return scrivito.obj.create_instance({ id: that.dom_element().attr('data-scrivito-private-child-list-order-obj-id'), description_for_editor: that.dom_element() .attr('data-scrivito-private-obj-description-for-editor') }); }, fetch_page_class_selection: function() { return scrivito.ajax('GET', 'objs/page_class_selection?' + $.param({parent_path: that.path()})); }, allowed_classes: function() { return JSON.parse( that.dom_element().attr('data-scrivito-private-child-list-allowed-classes')); }, create_child: function(obj_class) { var id = scrivito.random_id(); return scrivito.obj.create({ _id: id, _path: that.path() + '/' + id, _obj_class: obj_class }); }, add_child: function(child) { return child.save({ _path: that.path() + '/' + child.id() }); }, children: function() { return _.map(that.dom_element().find('>[data-scrivito-private-obj-id]'), function(dom_element) { return scrivito.cms_element.from_dom_element($(dom_element)); }); }, has_child_order: function() { return !!that.dom_element().attr('data-scrivito-private-child-list-order-obj-id'); }, save_order: function() { if (that.has_child_order()) { var new_child_order = _.map(that.children(), function(child) { return child.obj().id(); }); return that.obj().save({child_order: new_child_order}); } else { $.error("Can't save order, when child order is not allowed!"); } }, is_valid_child_class: function(obj_class_name) { var allowed_classes = that.allowed_classes(); if (allowed_classes) { return _.contains(allowed_classes, obj_class_name); } else { return true; } } }); return that; } }, all: function(root_element) { return scrivito.cms_element.all('[data-scrivito-private-child-list-path]', root_element); } } }); scrivito.cms_element.definitions.push(scrivito.child_list_element); }()); (function() { $.extend(scrivito, { cms_document: { // return offset of given element relative to scrivito window offset: function(dom_element) { var document = scrivito.cms_document.from(dom_element); return document.offset(dom_element); }, local_jquery: function(dom_element) { return scrivito.cms_document.from($(dom_element)).local_jquery(dom_element); }, from: function(dom_element) { var element_document; if (!dom_element.jquery) { $.error("not a jquery instance"); } if (dom_element.length === 0) { $.error("empty jquery instance given"); } if (dom_element[0].ownerDocument) { element_document = $(dom_element[0].ownerDocument); } else if (dom_element[0].nodeType === 9) { element_document = dom_element; } else { $.error("scrivito.cms_document.from must be called with " + "a dom element"); } return scrivito.cms_element.from_dom_element(element_document); }, create_instance: function(cms_element) { if (cms_element.dom_element()[0].nodeType === 9) { return create_instance(cms_element); } }, // for testing purposes only reset_public_api: function() { additional_public_api = {}; }, register_public_api: function(namespace, implementation) { additional_public_api[namespace] = implementation; } } }); var additional_public_api = {}; var create_instance = function(cms_element) { var that = cms_element; // PUBLIC _.extend(that, { install_public_api: function() { local_$().fn.scrivito = scrivito.jquery_plugin; browser_window.scrivito = _.extend({}, additional_public_api, { on: local_on_function, trigger: scrivito.trigger, create_obj: scrivito.create_obj, delete_obj: scrivito.delete_obj, obj_where: scrivito.obj_where, is_current_page_restricted: scrivito.is_current_page_restricted, in_editable_view: scrivito.in_editable_view, register_default_obj_class_for_content_type: scrivito.register_default_obj_class_for_content_type, default_obj_class_for_content_type: scrivito.default_obj_class_for_content_type, register_select_content: scrivito.register_select_content, configure_menu_order: scrivito.configure_menu_order, page_menu: function() { return scrivito.page_menu(that); } }); }, connect: function() { if (connected) { $.error("document connected twice!"); } _.each(load_callbacks, function(callback) { scrivito.run_new_event(callback); }); connected = true; scrivito.gui.new_document(that); scrivito.gui.new_content(that.dom_element()[0]); }, notify_new_content: function(content) { if (!connected) { return; } _.each(content_callbacks, function(callback) { scrivito.run_new_event(function() { callback.apply(this, [content]); }); }); }, page: function() { var config = scrivito.dom_config.read(that.dom_element()); if (config && !_.isEmpty(config.current_page)) { return scrivito.obj.create_instance(config.current_page); } }, window: function() { return scrivito.cms_window.from(browser_window); }, // return the given dom element using the local jQuery lib or the lib itself. local_jquery: function(element) { return element ? local_$()(element) : local_$(); }, browser_window: function() { return browser_window; }, // Return offset of given element relative to scrivito window. offset: function(dom_element) { var element_offset = dom_element.offset(); var iframe_offset = $(that.window().iframe()).offset(); if (iframe_offset) { return { top: iframe_offset.top - $(browser_window.document).scrollTop() + element_offset.top, left: iframe_offset.left - $(browser_window.document).scrollLeft() + element_offset.left }; } else { return element_offset; } }, // For test purpose only. mock_config: function(config) { scrivito.dom_config.write(that.dom_element().find('body'), config); }, // For test purpose only. mock_current_page: function(attrs) { that.mock_config({current_page: attrs}); } }); // PRIVATE var browser_document = cms_element.dom_element()[0]; var browser_window = browser_document.defaultView; var local_$ = function() { return browser_window.jQuery; }; var connected = false; var load_callbacks = []; var content_callbacks = []; var local_on_function = function(event, callback) { if (event === "load") { if (!connected) { load_callbacks.push(callback); } else { scrivito.run_new_event(callback); } } else if (event === "content") { content_callbacks.push(callback); if (connected) { scrivito.run_new_event(function() { callback(browser_document); }); } } else { $.error("unknown event " + event); } }; return that; }; scrivito.cms_element.definitions.push(scrivito.cms_document); }()); (function() { var has_original_content = function(field_type) { return _.contains([ 'enum', 'html', 'multienum', 'reference', 'referencelist', 'string', 'text', 'binary', 'date' ], field_type); }; $.extend(scrivito, { cms_field_element: { create_instance: function(cms_element) { var that = cms_element; var to_be_saved_data; $.extend(that, { field_name: function() { return that.dom_element().attr('data-scrivito-field-name'); }, field_type: function() { return that.dom_element().attr('data-scrivito-field-type'); }, obj: function() { return scrivito.obj.create_instance({ id: that.dom_element().attr('data-scrivito-private-field-obj-id'), obj_class_name: that.dom_element().attr('data-scrivito-field-obj-class') }); }, workspace_id: function() { return that.dom_element().attr('data-scrivito-private-field-workspace-id'); }, widget: function() { var widget_id = that.dom_element().attr('data-scrivito-private-field-widget-id'); if (widget_id) { return scrivito.widget.create_instance(that.obj(), widget_id, that.dom_element().attr('data-scrivito-widget-obj-class')); } }, save: function(content) { assert_valid_workspace_id(); if (content === undefined) { if (that.content) { content = that.content(); } else { $.error("Can't save without content"); } } var request_promise = $.Deferred(); var to_be_saved = to_be_saved_data || {}; to_be_saved.value = content; to_be_saved.promises = to_be_saved.promises || []; to_be_saved.promises.push(request_promise); to_be_saved_data = to_be_saved; if (!currently_saving()) { next_save_request(); } return request_promise.then(function(model_data) { var field_data = model_data[that.field_name()]; if (field_data) { return field_data[0]; } }); }, original_content: function() { assert_valid_workspace_id(); if (has_original_content(that.field_type())) { var raw_value = scrivito.json_parse_base64( that.dom_element().attr('data-scrivito-private-field-original-content')); return prepare_original_content(raw_value, that.field_type()); } else { $.error('Fields of type ' + that.field_type() + ' do not support original content'); } }, set_original_content: function(content) { if (has_original_content(that.field_type())) { that.dom_element().attr('data-scrivito-private-field-original-content', scrivito.json_stringify_base64(content)); } } }); var assert_valid_workspace_id = function() { if (that.workspace_id() !== scrivito.editing_context.selected_workspace.id()) { $.error('Tried to edit cms data from wrong workspace!'); } }; var next_save_request = function() { currently_saving(true); var to_be_saved = to_be_saved_data; to_be_saved_data = undefined; var changes = {}; changes[that.field_name()] = to_be_saved.value; var widget = that.widget(); var save_promise = widget ? widget.save(changes) : that.obj().save(changes); save_promise.done(function(result) { _.each(to_be_saved.promises, function(succeeding_promise) { succeeding_promise.resolve(result); }); if (to_be_saved_data) { next_save_request(); } else { remove_currently_saving(); } }).fail(function(error) { var new_promises = (to_be_saved_data || {}).promises; var failing_promises = to_be_saved.promises.concat(new_promises || []); _.each(failing_promises, function(failing_promise) { failing_promise.reject(error); }); to_be_saved_data = undefined; remove_currently_saving(); }); }; var currently_saving = function(new_currently_saving) { if (new_currently_saving) { return that.dom_element().data('scrivito-currently-saving', new_currently_saving); } else { return that.dom_element().data('scrivito-currently-saving'); } }; var remove_currently_saving = function() { that.dom_element().removeData('scrivito-currently-saving'); }; var prepare_original_content = function(value, field_type) { if (value && field_type === 'date') { var DateClass = scrivito.cms_document.from(that.dom_element()).browser_window().Date; return new DateClass(value); } else { return value; } }; return that; } } }); }()); (function() { scrivito.cms_window = { from: function(element) { if (!element) { $.error("no element given!"); } var browser_window; if ($.isWindow(element)) { browser_window = element; } else if (element.jquery && element[0].tagName === "IFRAME") { var doc = $(element).contents()[0]; browser_window = doc.defaultView; } else { $.error("element is a closed browser window or " + "not a cms window element at all"); } if (browser_window.closed) { $.error("element belongs to closed browser window"); } var instance = find_instance(browser_window); if (!instance) { instance = create_instance(browser_window); store_instance(instance); } return instance; }, // for test purposes only! instances: function() { return instances; } }; var instances = []; var create_instance = function(browser_window) { // PUBLIC var that = { document: function() { return scrivito.cms_element.from_dom_element($(browser_window.document)); }, on: function(event, callback) { if (event !== "document") { $.error("invalid event name: " + event); } document_callbacks.push(callback); }, notify_new_document: function(document) { _.each(document_callbacks, function(callback) { callback(document); }); }, browser_window: function() { return browser_window; }, reload: function() { return with_saving_overlay(scrivito.reload(browser_window)); }, redirect_to: function(location) { return with_saving_overlay(scrivito.redirect_to(location, browser_window)); }, is_frame: function() { return browser_window.parent !== browser_window; }, iframe: function() { return _.find($(browser_window.parent.document).find('iframe'), function(iframe) { // Remove this try-catch after non-iframe mode has been disabled. try { return $(iframe).contents()[0].defaultView === browser_window; } catch (e) { // Ignore cross-origin security errors. } }); } }; // PRIVATE var document_callbacks = []; var with_saving_overlay = function(promise) { promise = scrivito.with_saving_overlay(promise); var my_frame = that.iframe(); if (my_frame) { $(my_frame).one('load', function() { promise.resolve(); }); } return promise; }; return that; }; var cleanup_instances = function() { // remove closed windows to allow the garbage collector to reap them instances = _.reject(instances, function(instance) { var win = instance.browser_window(); var closed = true; if (win) { try { closed = win.closed; } catch(e) { // some browser prevent us from accessing closed windows // by throwing an error } } return closed; }); }; var find_instance = function(browser_window) { cleanup_instances(); return _.detect(instances, function(instance) { return instance.browser_window() === browser_window; }); }; var store_instance = function(instance) { instances.push(instance); }; }()); (function() { $.extend(scrivito, { date_field_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-field-type') === 'date') { return scrivito.cms_field_element.create_instance(cms_element); } }, all: function() { return _.map($('[data-scrivito-field-type="date"]'), function(dom_element) { return scrivito.cms_element.from_dom_element($(dom_element)); }); } } }); scrivito.cms_element.definitions.push(scrivito.date_field_element); }()); (function() { $.extend(scrivito, { html_field_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-field-type') === 'html') { var that = scrivito.cms_field_element.create_instance(cms_element); $.extend(that, { content: function() { var content = that.dom_element().html(); return $.trim(content); } }); return that; } }, all: function() { return _.map($('[data-scrivito-field-type="html"]'), function(dom_element) { return scrivito.cms_element.from_dom_element($(dom_element)); }); } } }); scrivito.cms_element.definitions.push(scrivito.html_field_element); }()); (function() { var is_file = function(object) { return object && _.isFunction(object.slice) && _.isDate(object.lastModifiedDate) && _.isString(object.name); }; var format_date_number = function(number) { var string = number.toString(); return string.length === 1 ? '0' + string : string; }; var serialize_date = function(date) { return date.getUTCFullYear().toString() + format_date_number(date.getUTCMonth() + 1) + // Month numbers are starting at 0. format_date_number(date.getUTCDate()) + format_date_number(date.getUTCHours()) + format_date_number(date.getUTCMinutes()) + format_date_number(date.getUTCSeconds()); }; var convert_attrs = function(attrs) { var collected_promises = _.map(attrs, function(value, field_name) { if (is_file(value)) { return scrivito.blob.create(value).then(function(value) { return [field_name, value]; }); } else { return $.Deferred().resolve([field_name, scrivito.obj.serialize_value(value)]); } }); return $.when.apply(this, collected_promises).then(function() { return _.object(arguments); }); }; var convert_widget_pool = function(widget_pool) { if (widget_pool) { var conversion_promises = _.map(widget_pool, function(attrs, widget_id) { return convert_attrs(attrs).then(function(converted_attrs) { return [widget_id, converted_attrs]; }); }); return $.when.apply(this, conversion_promises).then(function() { return _.object(arguments); }); } else { return $.Deferred().resolve(widget_pool); } }; var prepare_attrs = function(attrs) { return convert_widget_pool(attrs._widget_pool).then(function(widget_pool) { return convert_attrs(attrs).then(function(converted_attrs) { converted_attrs._widget_pool = widget_pool; return converted_attrs; }); }); }; $.extend(scrivito, { obj: { serialize_value: function(value) { if (_.isDate(value)) { return serialize_date(value); } else { return value; } }, create_instance: function(params) { var that = { id: function() { return params.id; }, obj_class_name: function() { return params.obj_class_name; }, description_for_editor: function() { return params.description_for_editor; }, modification: function() { return params.modification; }, is_new: function() { return that.modification() === 'new'; }, is_edited: function() { return that.modification() === 'edited'; }, is_deleted: function() { return that.modification() === 'deleted'; }, has_children: function() { return !!params.has_children; }, has_conflict: function() { return !!params.has_conflict; }, has_restriction : function() { return that.restriction_messages().length > 0; }, restriction_messages: function() { return params.restriction_messages || []; }, is_binary: function() { return !!params.is_binary; }, has_details_view: function() { return !!params.has_details_view; }, tooltip: function() { if (editing_state()) { return scrivito.t('obj.tooltip.' + editing_state()); } }, last_changed: function() { return params.last_changed; }, save: function(attrs) { return prepare_attrs(attrs).then(function(prepared_attrs) { return scrivito.ajax('PUT', 'objs/'+that.id(), {data: {obj: prepared_attrs}}); }); }, destroy: function() { return scrivito.ajax('DELETE', 'objs/' + that.id()).then(function(result) { return result.redirect_to; }); }, destroy_widget: function(widget_id) { return scrivito.ajax('PUT', 'objs/' + that.id() + '/destroy_widget?widget_id=' + widget_id); }, revert: function() { return scrivito.ajax('PUT', 'objs/' + that.id() + '/revert'); }, revert_widget: function(widget_id) { return scrivito.ajax('PUT', 'objs/'+that.id()+'/revert_widget?widget_id='+widget_id); }, restore: function() { return scrivito.ajax('PUT', 'objs/' + that.id() + '/restore'); }, restore_widget: function(widget_id) { return scrivito.ajax('PUT', 'objs/'+that.id()+'/restore_widget?widget_id='+widget_id); }, details_src: function() { // TODO unify with ajax url generation return '/__scrivito/page_details/' + that.id(); }, mark_resolved: function() { return scrivito.ajax('PUT', 'objs/' + that.id() + '/mark_resolved'); }, copy_to: function(path) { var attrs = {data: {parent_path: path}}; return scrivito.ajax('POST', 'objs/'+that.id()+'/copy', attrs).then(function(data) { return scrivito.obj.create_instance(data); }); }, duplicate: function() { return scrivito.ajax('POST', 'objs/'+that.id()+'/duplicate').then(function(data) { return scrivito.obj.create_instance(data); }); }, reload: function() { return scrivito.ajax('GET', 'objs/'+that.id()).then(function(data) { params.has_conflict = data.has_conflict; params.modification = data.modification; }); }, reload_widget: function(widget_id) { return scrivito.ajax('GET', 'objs/'+that.id()+'/widget?widget_id='+widget_id); } }; var editing_state = function() { if (that.is_new()) { return 'is_new'; } if (that.is_edited()) { if (that.has_conflict()) { return 'has_conflict'; } else { return 'is_edited'; } } if (that.is_deleted()) { return 'is_deleted'; } }; return that; }, create: function(attrs) { return prepare_attrs(attrs).then(function(prepared_attrs) { return scrivito.ajax('POST', 'objs', {data: {obj: prepared_attrs}}).then(function(data) { return scrivito.obj.create_instance(data); }); }); } } }); }()); (function() { $.extend(scrivito, { obj_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-private-obj-id')) { var that = cms_element; $.extend(that, { obj: function() { return scrivito.obj.create_instance({ id: that.dom_element().attr('data-scrivito-private-obj-id'), description_for_editor: that.dom_element() .attr('data-scrivito-private-obj-description-for-editor') }); } }); return that; } }, // for testing purposes only all: function() { return _.map($('[data-scrivito-private-obj-id]'), function(dom_element) { return scrivito.cms_element.from_dom_element($(dom_element)); }); } } }); scrivito.cms_element.definitions.push(scrivito.obj_element); }()); (function() { _.extend(scrivito, { chainable_search: { create_instance: function(build_query) { var query = build_query || { predicates: [] }; var add_predicate = function(field, operator, value, boost, negate) { var new_query = { field: field, operator: operator, value: scrivito.obj.serialize_value(value) }; if (negate) { new_query.negate = true; } if (boost) { new_query.boost = boost; } query.predicates.push(new_query); return that; }; var execute_search = function(query, action) { return scrivito.ajax('GET', 'objs/search?' + $.param({query: JSON.stringify(query), query_action: action})); }; var that = { // @api public query: function() { return query; }, // @api public and: function(field_or_search, operator, value, boost) { if (_.isString(field_or_search)) { add_predicate(field_or_search, operator, value, boost); } else { var other_predicates = field_or_search.query().predicates; query.predicates = query.predicates.concat(other_predicates); } return that; }, // @api public and_not: function(field, operator, value) { add_predicate(field, operator, value, undefined, true); return that; }, // @api public offset: function(offset) { query.offset = offset; return that; }, // @api public order: function(order) { query.order = order; return that; }, // @api public reverse_order: function() { if (query.reverse_order) { delete query.reverse_order; } else { query.reverse_order = true; } return that; }, // @api public batch_size: function(batch_size) { query.batch_size = batch_size; return that; }, // @api public format: function(name) { query.format = name; return that; }, // @api public include_deleted: function() { query.include_deleted = true; return that; }, // @api public load_batch: function() { var offset = query.offset || 0; var next; return execute_search(query).then(function(result) { var batch_size = result.hits.length; var total_matches = result.total; if (total_matches > (batch_size + offset)) { var next_offset = offset + batch_size; var next_query = $.extend({}, query, {offset: next_offset}); next = scrivito.chainable_search.create_instance(next_query); } else { next = undefined; } return $.Deferred().resolve(result, next); }); }, // @api public size: function() { return execute_search(query, 'size').then(function(result) { return $.Deferred().resolve(result.total); }); }, // @api public clone: function() { var cloned_query = $.extend(true, {}, query); return scrivito.chainable_search.create_instance(cloned_query); } }; return that; } } }); }()); (function() { $.extend(scrivito, { // @api public obj_where: function(field, operator, value, boost) { return scrivito.chainable_search.create_instance().and(field, operator, value, boost); } }); }()); (function() { var field_types = [ 'binary', 'enum', 'link', 'linklist', 'multienum', 'reference', 'referencelist', 'text' ]; $.extend(scrivito, { standard_field_element: { create_instance: function(cms_element) { if (_.include(field_types, cms_element.dom_element().attr('data-scrivito-field-type'))) { return scrivito.cms_field_element.create_instance(cms_element); } } } }); scrivito.cms_element.definitions.push(scrivito.standard_field_element); }()); (function() { $.extend(scrivito, { string_field_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-field-type') === 'string') { var that = scrivito.cms_field_element.create_instance(cms_element); $.extend(that, { content: function() { var content = that.dom_element().text(); return $.trim(content); } }); return that; } }, all: function() { return _.map($('[data-scrivito-field-type="string"]'), function(dom_element) { return scrivito.cms_element.from_dom_element($(dom_element)); }); } } }); scrivito.cms_element.definitions.push(scrivito.string_field_element); }()); (function() { $.extend(scrivito, { user: { init: function(config) { scrivito.user.current = scrivito.user.create_instance(config.current); }, create_instance: function(params) { var that = { id: function() { return params.id; } }; return that; }, suggest: function(input) { return scrivito.ajax('GET', 'users/suggest?input=' + input); } } }); }()); (function() { $.extend(scrivito, { widget: { create_instance: function(obj, id, widget_class_name, options) { options = options || {}; var that = { id: function() { return id; }, obj: function() { return obj; }, widget_class_name: function() { return widget_class_name; }, modification: function() { return options.modification; }, placement_modification: function() { return options.placement_modification; }, description_for_editor: function() { return options.description_for_editor; }, is_modified: function() { return !!that.modification(); }, is_new: function() { return that.modification() === 'new'; }, is_edited: function() { return that.modification() === 'edited'; }, is_deleted: function() { return that.modification() === 'deleted'; }, is_placement_modified: function() { return !!that.placement_modification(); }, is_content_widget: function() { return widget_class_name === 'Scrivito::ContentWidget'; }, save: function(widget_attributes) { var obj_attributes = build_obj_attributes(widget_attributes); return that.obj().save(obj_attributes).then(function(obj_data) { return obj_data._widget_pool[0][that.id()]; }); }, destroy: function() { return that.obj().destroy_widget(that.id()); }, details_src: function() { // TODO unify with ajax url generation return "/__scrivito/" + markup_url('widget_details'); }, revert: function() { return that.obj().revert_widget(that.id()).then(function() { options.modification = null; }); }, restore: function() { return that.obj().restore_widget(that.id()).then(function() { options.modification = null; }); }, fetch_markup: function(template_name) { return scrivito.ajax('GET', markup_url('show_widget')+'?template_name='+template_name, {dataType: 'html'}); }, reload: function() { return that.obj().reload_widget(that.id()).then(function(data) { options.modification = data.modification; }); } }; var build_obj_attributes = function(widget_attributes) { var obj_attributes = {_widget_pool: {}}; obj_attributes._widget_pool[that.id()] = widget_attributes; return obj_attributes; }; var markup_url = function(action_name) { var obj_id = that.obj().id(); var widget_id = that.id(); return 'render_widget/'+obj_id+'/'+action_name+'/'+widget_id; }; return that; } } }); }()); (function() { $.extend(scrivito, { widget_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-private-widget-id')) { var that = cms_element; $.extend(that, { widget: function() { var dom_element = that.dom_element(); return scrivito.widget.create_instance(that.widget_field().obj(), dom_element.attr('data-scrivito-private-widget-id'), dom_element.attr('data-scrivito-widget-obj-class'), { modification: dom_element.attr('data-scrivito-private-widget-modification'), placement_modification: dom_element.attr( 'data-scrivito-private-widget-placement-modification'), description_for_editor: dom_element.attr( 'data-scrivito-private-widget-description-for-editor') } ); }, widget_field: function() { return scrivito.cms_element.from_dom_element(that.dom_element().parent()); }, has_details_view: function() { return !!that.dom_element().attr('data-scrivito-private-widget-has-details-view'); }, fetch_markup: function() { return that.widget().fetch_markup(that.widget_field().template_name()); }, details_src: function() { return that.widget().details_src(); }, field_name: function() { return that.widget_field().field_name(); }, has_widgetlist: function() { return !!that.dom_element().find('[data-scrivito-field-type=widgetlist]').length; } }); return that; } }, all: function(root_element) { return scrivito.cms_element.all('[data-scrivito-private-widget-id]', root_element); } } }); scrivito.cms_element.definitions.push(scrivito.widget_element); }()); (function() { $.extend(scrivito, { widgetlist_field_element: { create_instance: function(cms_element) { if (cms_element.dom_element().attr('data-scrivito-field-type') === 'widgetlist') { var that = scrivito.cms_field_element.create_instance(cms_element); $.extend(that, { content: function() { return _.map(that.widget_elements(), function(widget_element) { return widget_element.widget().id(); }); }, widget_elements: function() { var widget_elements_dom = that.dom_element() .children('[data-scrivito-private-widget-id]'); var widget_elements = _.map(widget_elements_dom, function(widget_element_dom) { return scrivito.cms_element.from_dom_element($(widget_element_dom)); }); return widget_elements; }, is_empty: function() { return that.widget_elements().length === 0; }, add_widget: function(widget_spec, widget_element) { var position; if (widget_element) { position = widget_element.dom_element() .prevAll('[data-scrivito-private-widget-id]').length; } else { position = that.widget_elements().length; } var content = that.content(); content.splice(position, 0, widget_spec); return that.save(content).then(function(field_data) { var new_widget_id; if (field_data.list) { new_widget_id = field_data.list[position].widget; } else { new_widget_id = field_data[position]; } var widget = scrivito.widget.create_instance(that.obj(), new_widget_id); return prepend_widget(widget, widget_element); }); }, fetch_widget_class_selection: function() { var params = {field_name: that.field_name()}; if (that.widget()) { params.widget_id = that.widget().id(); } return scrivito.ajax('GET', 'objs/' + that.obj().id() + '/widget_class_selection?' + $.param(params)); }, allowed_classes: function() { return _.map(allowed_classes_json(), function(obj_class) { return obj_class.name; }); }, allowed_classes_for_create: function() { return _.without(that.allowed_classes(), 'Scrivito::ContentWidget'); }, can_create_widget: function() { return that.allowed_classes_for_create().length !== 0; }, can_choose_widget_class: function() { return that.allowed_classes_for_create().length > 1; }, description_for_allowed_classes: function() { return _.map(allowed_classes_json(), function(allowed_class_json) { return allowed_class_json.description; }); }, description_for_allowed_class: function(class_name) { var allowed_class = _.findWhere(allowed_classes_json(), {name: class_name}); if (allowed_class) { return allowed_class.description; } }, is_valid_child_class: function(widget_class_name) { var allowed_classes = that.allowed_classes(); if (allowed_classes) { return _.contains(allowed_classes, widget_class_name); } else { return true; } }, is_content_widget_allowed: function() { return that.is_valid_child_class('Scrivito::ContentWidget'); }, template_name: function() { return that.dom_element().attr('data-scrivito-private-field-widget-template'); } }); var allowed_classes_json = function() { return JSON.parse(that.dom_element() .attr('data-scrivito-private-field-widget-allowed-classes')); }; var prepend_widget = function(widget, widget_element) { return widget.fetch_markup(that.template_name()).then(function(widget_markup) { var dom_element = $($.trim(widget_markup)); if (widget_element) { widget_element.dom_element().before(dom_element); } else { that.dom_element().prepend(dom_element); } scrivito.gui.new_content(dom_element.get(0)); scrivito.ensure_fully_visible_within_window(dom_element); scrivito.widget_sorting.update_placeholder(that); return widget; }); }; return that; } }, all: function(root_element) { return scrivito.cms_element.all('[data-scrivito-field-type="widgetlist"]', root_element); } } }); scrivito.cms_element.definitions.push(scrivito.widgetlist_field_element); }()); (function() { $.extend(scrivito, { workspace: { from_data: function(data) { var that = { id: function() { return data.id; }, title: function() { return that.original_title() || default_title(); }, original_title: function() { return data.title; }, icon: function() { return that.is_published() ? '' : ''; }, is_published: function() { return that.id() === 'published'; }, is_outdated: function() { return !!data.outdated; }, mark_as_outdated: function() { data.outdated = true; }, is_editable: function() { return !that.is_published(); }, is_rtc: function() { return that.id() === 'rtc'; }, check: function() { return check(0).then(function(result) { return handle_check_result(result, []); }); }, check_and_publish: function() { return check_and_publish(0); }, publish: function(certificates) { return scrivito.silent_ajax('PUT', 'workspaces/' + that.id() + '/publish', {data: { certificates: certificates }}); }, rebase: function() { return scrivito.ajax('PUT', 'workspaces/' + that.id() + '/rebase').done(function() { data.outdated = false; }); }, update: function(attributes) { return scrivito.ajax('PUT', 'workspaces/' + that.id(), {data: {workspace: attributes}}); }, rename: function(new_title) { return that.update({title: new_title}); }, destroy: function() { return scrivito.ajax('DELETE', 'workspaces/' + that.id()); }, fetch_memberships: function() { return scrivito.ajax('GET', 'workspaces/' + that.id()).then(function(details) { return details.memberships; }); }, has_conflicts: function() { return scrivito.obj_where('_conflicts', 'equals', true).size().then(function(size) { var promise = $.Deferred(); return size === 0 ? promise.reject() : promise.resolve(); }); } }; var check_and_publish = function(number_of_retries) { return rebase_outdated().then(function() { return that.check().then(function(certificates) { if (certificates) { return that.publish(certificates).then(null, function(error) { return handle_check_and_publish_error(error, number_of_retries); }); } else { return $.Deferred().reject({type: 'check_failed'}); } }, function(error) { return handle_check_and_publish_error(error, number_of_retries); }); }); }; var rebase_outdated = function() { return that.is_outdated() ? that.rebase() : $.Deferred().resolve(); }; var check = function(offset) { return scrivito.silent_ajax('GET', 'workspaces/' + that.id() + '/check?from=' + offset); }; var handle_check_result = function(result, certificates) { if (result.result === 'fail') { return $.Deferred().resolve(false); } certificates.push(result.certificate); if (result.pass.until === 'END') { return $.Deferred().resolve(certificates); } else { var offset = parseInt(result.pass.until, 10) + 1; return check(offset).then(function(result) { return handle_check_result(result, certificates); }); } }; var handle_check_and_publish_error = function(error, number_of_retries) { if (error.code === 'precondition_not_verifiable.workspace.publish.content_state_id') { // Another workspace has been published since last check. that.mark_as_outdated(); return check_and_publish(number_of_retries); } else if (error.code === 'precondition_not_met.workspace.publish.content_state_id') { // The workspace has been changed since last check. if (number_of_retries === 2) { return $.Deferred().reject({type: 'outdated_certificates'}); } else { return check_and_publish(number_of_retries + 1); } } else { scrivito.display_ajax_error(error); return error; } }; var default_title = function() { if (that.is_published()) { return scrivito.t('workspace.title_published'); } else { return scrivito.t('workspace.empty_title'); } }; return that; }, all: function() { return scrivito.ajax('GET', 'workspaces').then(function(workspace_datas) { return _.sortBy(_.map(workspace_datas, function(workspace_data) { return scrivito.workspace.from_data(workspace_data); }, function(workspace) { return workspace.is_published() ? '' : workspace.title().toUpperCase(); })); }); }, editable: function() { return scrivito.workspace.all().then(function(workspaces) { return _.select(workspaces, function(workspace) { return workspace.is_editable(); }); }); }, published: function() { return scrivito.workspace.from_data({id: 'published'}); }, create: function(title) { var params = {data: {workspace: {title: title}}}; return scrivito.silent_ajax('POST', 'workspaces', params).then(function(ws_data) { return scrivito.workspace.from_data(ws_data); }, function(error) { if (error.code === 'precondition_not_met.workspace.create.exceeds_limit') { scrivito.workspace_limit_exceeded(); } else { scrivito.display_ajax_error(error); } }); } } }); }()); (function() { scrivito.storage = { set: function(key, object) { localStorage.setItem(full_key(key), JSON.stringify(object)); }, get: function(key) { return JSON.parse(localStorage.getItem(full_key(key))); }, has_key: function(key) { return !!scrivito.storage.get(key); }, remove: function(key) { localStorage.removeItem(full_key(key)); }, clear: function() { for (var i=0; i < localStorage.length; i++) { var key = localStorage.key(i); if (key.indexOf(storage_key_prefix) === 0) { localStorage.removeItem(key); } } } }; var storage_key_prefix = '_scrivito_'; var full_key = function(key_suffix) { return storage_key_prefix + key_suffix; }; })(); (function() { $.extend(scrivito, { /* * This component has two main purposes: * * 1. It wraps a function triggering a CSS transition * in an additional javascript event, so that that * transition will be executed even if associated target * has just been added to the DOM. * * 2. It skips any transitions and immediately executes * all functions in correct order if configured to do so, * e.g. in specs. */ transition: function(target, trigger_fn) { var deferred = $.Deferred(); if (!scrivito.transition.immediate_mode) { target.on('webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd', function() { deferred.resolve(); }); setTimeout(trigger_fn, 0); } else { trigger_fn(); deferred.resolve(); } return deferred; } }); $.extend(scrivito.transition, {immediate_mode: false}); }()); (function() { var auto_height_dirty = false; var relevant_siblings_for = function(elem) { return elem.siblings().filter(":not(.hover):visible"); }; var target_height_for = function(elem, dont_store_height) { var parent = elem.parent(); var heightOfParent = parent.innerHeight(); if (!dont_store_height) { parent.data("scrivito_last_inner_height", heightOfParent); } var heightOfAllSiblings = _(relevant_siblings_for(elem)) .chain() .map($) .reduce(function(sum, sibling) { var height = sibling.outerHeight(true); if (!dont_store_height) { sibling.data("scrivito_last_outer_height", height); } return sum + height; }, 0).value() ; return Math.max(0, heightOfParent - heightOfAllSiblings); }; var set_auto_height_for = function(elem) { elem.css('height', target_height_for(elem)); elem.addClass("scrivito_height_done"); }; var sibling_height_changes = function(elem) { return _(relevant_siblings_for(elem)).map(function(sibling) { sibling = $(sibling); var last = sibling.data("scrivito_last_outer_height"); var actual = sibling.outerHeight(true); if (last !== actual) { return scrivito.describe_element(sibling) + " unexpectantly changed it's height from " + (last === undefined ? "<invisible>" : last) + " to " + actual ; } }); }; var parent_height_changes = function(elem) { var parent = elem.parent(); var last = parent.data("scrivito_last_inner_height"); var actual = parent.innerHeight(); if (last !== actual) { return scrivito.describe_element(parent) + " unexpectantly changed it's height from " + (last || "<invisible>") + " to " + actual ; } }; $.extend(scrivito, { update_auto_height_for: function(root_element) { var elements = root_element.find('.scrivito_auto_height:visible'); if (root_element.hasClass("scrivito_auto_height")) { elements = elements.add(root_element); } elements.not(".scrivito_height_done").each(function (i, elem) { set_auto_height_for($(elem)); }); }, invalidate_auto_height: function() { $(".scrivito_height_done").removeClass("scrivito_height_done"); auto_height_dirty = true; }, invalidate_auto_height_for: function(elem) { elem.find(".scrivito_height_done").removeClass("scrivito_height_done"); }, process_auto_height: function() { if (auto_height_dirty) { scrivito.update_auto_height_for($("body")); auto_height_dirty = false; } }, auto_height_errors: function() { return _($(".scrivito_auto_height:visible")).chain().map($).map(function(elem) { var expected = target_height_for(elem, true); var actual = parseInt(elem.css('height'), 10); if (actual !== expected) { if (!elem.hasClass("scrivito_height_done")) { return [scrivito.describe_element(elem) + " was never updated"]; } else { var errors = sibling_height_changes(elem); errors.push(parent_height_changes(elem)); return _(errors).compact(); } } }).compact().flatten().value(); } }); }()); /*global ScrivitoHandlebarsTemplates:false */ /*global Handlebars:false */ (function() { Handlebars.registerHelper('translate', scrivito.i18n.translate); Handlebars.registerHelper('localize_date', function(date_value_function) { return scrivito.i18n.localize_date(date_value_function()); }); Handlebars.registerHelper('localize_date_relative', function(date_value_function) { return scrivito.i18n.localize_date_relative(date_value_function()); }); Handlebars.registerHelper('array_to_title', function(array_fn) { var escaped_array = array_fn().map(function(text) { return Handlebars.Utils.escapeExpression(text); }); return new Handlebars.SafeString(escaped_array.join(' ')); }); Handlebars.registerHelper('render', function(template_path, object) { return new Handlebars.SafeString(scrivito.template.render(template_path, object)); }); $.extend(scrivito, { template: { load_templates_from_server: false, render: function(template_path, data) { var template; if(typeof ScrivitoHandlebarsTemplates !== 'undefined') { template = ScrivitoHandlebarsTemplates[template_path]; } if(template === undefined) { if(scrivito.template.load_templates_from_server) { var url = "/app/assets/javascripts/templates/" + template_path + ".hbs?" + Math.random(); var source = jQuery.ajax(url, { async: false }).responseText; template = Handlebars.compile(source); } else { throw('could not load template' + template_path); } } return template(data); } } }); }()); (function() { _.extend(scrivito, { with_dialog_overlay: function(dom_element, promise) { var token = scrivito.dialog_overlay.create(dom_element); return promise.always(function() { scrivito.dialog_overlay.destroy(token); }); }, dialog_overlay: { create: function(dom_element) { var predecessor = $('.scrivito_overlay').last(); predecessor.removeClass('scrivito_show'); var overlay = $(scrivito.template.render('overlay')); dom_element.before(overlay); scrivito.transition(overlay, function() { overlay.addClass('scrivito_show'); }); return {overlay: overlay, predecessor: predecessor}; }, destroy: function(token) { var overlay = token.overlay; var predecessor = token.predecessor; scrivito.transition(overlay, function() { overlay.removeClass('scrivito_show'); }).then(function() { overlay.remove(); if (predecessor.length) { predecessor.addClass('scrivito_show'); } }); }, // Test purpose only. remove_all: function() { $('.scrivito_overlay').remove(); } } }); }()); (function() { var view; _.extend(scrivito, { with_saving_overlay: function(promise) { scrivito.saving_overlay.show(); return promise.always(function() { scrivito.saving_overlay.hide(); }); }, saving_overlay: { show: function() { if (!view) { view = $(scrivito.template.render('saving_overlay')); $('#scrivito_editing').append(view); } scrivito.transition(view, function() { view.addClass('scrivito_show'); }); }, hide: function() { if (view) { scrivito.transition(view, function() { view.removeClass('scrivito_show'); }).then(function(e) { // Remove the view only if event is triggered by a "fade-out" transition. if (e && $(e.target).hasClass('scrivito_show')) { return; } if (view) { view.remove(); } view = null; }); } }, // Test purpose only. remove_all: function() { $('.scrivito_saving_overlay').remove(); view = null; } } }); return scrivito; }()); (function() { $.extend(scrivito, { saving_indicator: { create: function(parent_view) { var target_selector = '.scrivito_saving_indicator'; var saving_in_progress_selector = target_selector + ' .scrivito_saving_in_progress'; var saving_done_selector = target_selector + ' .scrivito_saving_done'; parent_view.append(scrivito.template.render('saving_indicator')); var start_write_token = scrivito.write_monitor.on('start_write', function() { parent_view.find(saving_in_progress_selector).show(); parent_view.find(saving_done_selector).hide(); }); var end_write_token = scrivito.write_monitor.on('end_write', function() { if (!scrivito.write_monitor.is_writing()) { parent_view.find(saving_in_progress_selector).hide(); var saving_done_element = parent_view.find(saving_done_selector); saving_done_element.show(); if (!scrivito.transition.immediate_mode) { setTimeout(function() { saving_done_element.fadeOut(1000); }, 3000); } } }); return { destroy: function() { scrivito.write_monitor.off(start_write_token); scrivito.write_monitor.off(end_write_token); parent_view.find(target_selector).remove(); }, // Test purpose only. start_write_token: start_write_token, end_write_token: end_write_token }; } } }); }()); (function() { $.extend(scrivito, { with_element_overlay: function(dom_element, promise) { var element_overlay = scrivito.element_overlay.create(dom_element); return promise.always(function() { element_overlay.remove(); }); }, element_overlay: { create: function(dom_element) { var dom_element_position = dom_element.position(); var view = $(scrivito.template.render('element_overlay')).css({ position: 'absolute', // Required for unit tests to pass without an extra CSS file. top: 0, left: dom_element_position.left, width: dom_element.width(), height: dom_element.height() }); dom_element.append(view); return view; } } }); }()); (function() { _.extend(scrivito, { alert_dialog: function(message) { return scrivito.alert_dialog.open(message); } }); _.extend(scrivito.alert_dialog, { open: function(message, options) { var view = $(scrivito.template.render('alert_dialog', _.extend({message: message, color: 'red', icon: ''}, options || {}))); view.appendTo($('#scrivito_editing')); var promise = $.Deferred(); var close = function() { scrivito.dialog.close(view); promise.resolve(); return false; }; view.find('.scrivito_close').on('click', close); scrivito.dialog.open_and_center(view); return scrivito.with_dialog_behaviour(view, promise, {enter: close, escape: close}); }, // For test purpose only. remove_all: function() { $('.scrivito_alert_dialog').remove(); } }); }()); (function() { _.extend(scrivito, { info_dialog: function(message) { return scrivito.alert_dialog.open(message, {color: 'yellow', icon: ''}); } }); }()); (function() { $.extend(scrivito, { confirmation_dialog: function(options) { return scrivito.confirmation_dialog.open(options); } }); $.extend(scrivito.confirmation_dialog, { open: function(options) { var view = $(scrivito.template.render('confirmation_dialog', $.extend({ icon: '', cancel_button_text: scrivito.t('cancel'), confirm_button_text: scrivito.t('confirm') }, options || {}))); $('#scrivito_editing').append(view); var deferred = $.Deferred(); var accept = function() { scrivito.dialog.close(view); deferred.resolve(); return false; }; var cancel = function() { scrivito.dialog.close(view); deferred.reject(); return false; }; view.find('.scrivito_confirm').on('click', accept); view.find('.scrivito_cancel').on('click', cancel); scrivito.dialog.open_and_center(view); return scrivito.with_dialog_behaviour(view, deferred, {enter: accept, escape: cancel}); }, // Test purpose only. remove_all: function() { $('.scrivito_confirmation_dialog').remove(); } }); }()); (function() { $.extend(scrivito, { prompt_dialog: function(options) { return scrivito.prompt_dialog.open(options); } }); $.extend(scrivito.prompt_dialog, { open: function(options) { var view = $(scrivito.template.render('prompt_dialog', $.extend({ icon: '', accept_button_text: scrivito.t('accept'), cancel_button_text: scrivito.t('cancel') }, options || {}))); $('#scrivito_editing').append(view); var deferred = $.Deferred(); var accept = function() { var val = view.find('input').val(); if (val) { scrivito.dialog.close(view); deferred.resolve(val); } return false; }; var cancel = function() { scrivito.dialog.close(view); deferred.reject(); return false; }; view.find('.scrivito_accept').on('click', accept); view.find('.scrivito_cancel').on('click', cancel); scrivito.dialog.open_and_center(view).then(function() { view.find('input').focus(); }); return scrivito.with_dialog_behaviour(view, deferred, {enter: accept, escape: cancel}); } }); }()); (function() { $.extend(scrivito, { dialog: { open: function(view) { return scrivito.transition(view, function() { view.addClass('scrivito_show'); }); }, open_and_adjust: function(view) { return scrivito.dialog.open(view).then(function() { scrivito.dialog.adjust(view); }); }, open_and_center: function(view) { return scrivito.dialog.open(view).then(function() { scrivito.center(view); }); }, close: function(view) { scrivito.transition(view, function() { view.removeClass('scrivito_show'); }).then(function() { view.remove(); view = null; }); }, adjust: function(view) { scrivito.invalidate_auto_height_for(view); scrivito.update_auto_height_for(view); } } }); $(window).on('resize', function() { _.each($('.scrivito_adjust_dialog'), function(elem) { scrivito.dialog.adjust($(elem)); }); _.each($('.scrivito_center_dialog'), function(elem) { scrivito.center($(elem)); }); }); }()); (function() { _.extend(scrivito, { reloading: { init: function() { scrivito.gui.on('document', function(cms_document) { var body = cms_document.dom_element().find('body'); $(body).on('reload.scrivito', function() { cms_document.window().reload(); }); // TODO: remove this in 1.0.0. cms_document.local_jquery(body).on('scrivito_reload', function() { scrivito.deprecation_warning('$.trigger("scrivito_reload")', '$.scrivito("reload")'); cms_document.window().reload(); }); }); } } }); }()); (function() { $.extend(scrivito, { choose_obj_class_dialog: function(obj_classes_deferred, locale_path) { return scrivito.choose_obj_class_dialog.open(obj_classes_deferred, locale_path); } }); $.extend(scrivito.choose_obj_class_dialog, { open: function(obj_classes_deferred, locale_path) { var deferred = $.Deferred(); var view = $(scrivito.template.render('choose_obj_class_dialog', { title: scrivito.t('choose_obj_class_dialog.' + locale_path + '.title'), description: scrivito.t('choose_obj_class_dialog.' + locale_path + '.description') })); obj_classes_deferred.done(function(obj_class_selection) { var selection_view = scrivito.template.render('choose_obj_class_list', {obj_classes: obj_class_selection}); selection_view = $($.trim(selection_view)); view.find('#scrivito_replace_with_real_obj_classes').replaceWith(selection_view); view.on('click', '.scrivito_obj_class_thumbnail', function(e) { e.preventDefault(); scrivito.dialog.close(view); deferred.resolve($(this).attr('data-scrivito-private-obj-class-name')); }); }); $('#scrivito_editing').append(view); var cancel = function() { scrivito.dialog.close(view); deferred.reject(); return false; }; view.find('.scrivito_cancel').on('click', cancel); scrivito.dialog.open_and_adjust(view); return scrivito.with_dialog_behaviour(view, deferred, {escape: cancel}); } }); }()); (function() { _.extend(scrivito, { details_dialog: { open: function(src, title, obj, commands) { var deferred = $.Deferred(); var view = $(scrivito.template.render('details_dialog', {src: src, title: title, obj: obj})); if (obj) { scrivito.obj_menu.create(view.find('.scrivito_obj_menu'), obj, commands); } $('#scrivito_editing').append(view); var indicator = scrivito.saving_indicator.create(view.find('.scrivito_saving_indicator')); var target = view.find('.scrivito_details_dialog_markup').hide(); var spinner = view.find('.scrivito_modal_body .scrivito_spinning').show(); var iframe = view.find('iframe'); iframe.on('load', function() { if (iframe.contents().find('body').hasClass('scrivito_dialog') && !iframe.contents().get(0).defaultView.scrivito) { scrivito.alert_dialog('Missing required Scrivito assets in the details dialog. ' + 'Are you sure your "scrivito_dialog.html.*" sources the Scrivito assets?'); } spinner.hide(); target.show(); var size_attr = 'data-scrivito-modal-size'; var modal_size = iframe.contents().find('['+size_attr+']').attr(size_attr); if (_.contains(['small', 'medium', 'large'], modal_size)) { view.removeClass('scrivito_modal_medium'); scrivito.transition(view, function() { view.addClass('scrivito_modal_' + modal_size); }).then(function() { scrivito.dialog.adjust(view); }); } else { scrivito.dialog.adjust(view); } }); var cancel = function() { indicator.destroy(); scrivito.dialog.close(view); deferred.resolve(); return false; }; view.find('.scrivito_cancel').on('click', cancel); scrivito.dialog.open_and_adjust(view); return scrivito.with_dialog_behaviour(view, deferred, {escape: cancel}); } } }); }()); (function() { _.extend(scrivito, { menus: { init: function() { scrivito.gui.on('document', function(cms_document) { var browser_window = $(cms_document.browser_window()); var dom_element = cms_document.dom_element(); _.each(['resize', 'scroll', 'load'], function(event) { browser_window.on(event, function() { scrivito.menus.update_positions(); }); }); }); }, open: function(dom_element, commands, anchor_point) { scrivito.close_all_menus(); var menu = $(scrivito.template.render('menu', { menu_items: _.map(scrivito.pattern_sort(commands, scrivito.menu_order), function(command) { return scrivito.menu_item.create_instance(command); }) })); dom_element.data('scrivito-private-menu', menu); menu.data('scrivito-menu-close', function() { dom_element.removeData('scrivito-private-menu'); menu.fadeOut(500, function() { menu.remove(); }); }); if (anchor_point) { menu.addClass('scrivito_precise_offset'); } menu.data('scrivito-menu-update-position', function() { var element_offset = scrivito.cms_document.offset(dom_element); if (anchor_point) { element_offset.left += anchor_point.x * dom_element.width(); element_offset.top += anchor_point.y * dom_element.height(); } menu.offset(element_offset); }); _.each(commands, function(command) { menu.on('click', '.'+command.dom_id(), function() { if (command.is_enabled()) { menu.data('scrivito-menu-close')(); } command.execute(); return false; }); }); menu.appendTo($('#scrivito_editing')); menu.data('scrivito-menu-update-position')(); // Bugfix IE: can't set offset before append. menu.find('.scrivito_menu_box').fadeIn(500); }, toggle: function(dom_element, commands, anchor_point) { var menu = dom_element.data('scrivito-private-menu'); if (menu) { menu.data('scrivito-menu-close')(); } else { scrivito.menus.open(dom_element, commands, anchor_point); } }, update_positions: function() { _.each($('.scrivito_editing_marker_menu'), function(menu) { var update_position = $(menu).data('scrivito-menu-update-position'); if (update_position) { update_position(); } }); } } }); }()); (function() { $.extend(scrivito, { inline_menus: { toggle: function(dom_element, commands, align) { var menu = dom_element.find('.scrivito_editing_marker_menu'); if (menu.length) { menu.data('scrivito-menu-close')(); } else { open(dom_element, commands, align); } } } }); var open = function(dom_element, commands, align) { scrivito.close_all_menus(); var menu = $(scrivito.template.render('menu', {align: align, menu_items: _.map(scrivito.pattern_sort(commands, scrivito.menu_order), function(command) { return scrivito.menu_item.create_instance(command); }) })); menu.data('scrivito-menu-close', function() { menu.find('.scrivito_menu_box').fadeOut(500, function() { menu.remove(); }); }); _.each(commands, function(command) { menu.on('click', '.'+command.dom_id(), function() { if (command.is_enabled()) { menu.data('scrivito-menu-close')(); } command.execute(); return false; }); }); menu.appendTo(dom_element); menu.find('.scrivito_menu_box').fadeIn(500); }; }()); (function() { $.extend(scrivito, { close_all_menus: function() { _.each($('.scrivito_editing_marker_menu'), function(menu) { $(menu).data('scrivito-menu-close')(); }); } }); }()); (function() { var callbacks = []; _.extend(scrivito, { inplace_marker: { init: function() { scrivito.on('content', function(content) { scrivito.inplace_marker.refresh(scrivito.cms_document.from($(content)).dom_element()); }); }, define: function(callback) { callbacks.push(callback); }, refresh: function(root_element) { if (!scrivito.editing_context.is_view_mode()) { root_element.find('.scrivito_editing_marker').remove(); _.each(callbacks, function(callback) { callback(builder, root_element); }); scrivito.menus.update_positions(); } }, are_overlapping: function(dom_element1, dom_element2) { var a = dom_element1.getBoundingClientRect(); var b = dom_element2.getBoundingClientRect(); return a.left <= b.right && b.left <= a.right && a.top <= b.bottom && b.top <= a.bottom; }, // For test purpose only. reset_callbacks: function() { callbacks = []; } } }); var warn_overlapping = function(dom_element) { var other_dom_elements = $($(dom_element).closest('body')).find('.scrivito_editing_marker').not(dom_element); var overlapping_dom_elements = _.filter(other_dom_elements, function(other_dom_element) { return scrivito.inplace_marker.are_overlapping(dom_element, other_dom_element); }); if (overlapping_dom_elements.length) { scrivito.warn.apply(null, [scrivito.t('inplace_marker.overlapping'), dom_element].concat(overlapping_dom_elements)); } }; var lights_on = function(highlightable_element) { highlightable_element.addClass('scrivito_active scrivito_entered'); var timer = setTimeout(function() { highlightable_element.removeClass('scrivito_entered'); }, 2000); highlightable_element.data('scrivito-entered-timer', timer); }; var lights_off = function(document) { document.find('.scrivito_active').removeClass('scrivito_active'); document.find('.scrivito_entered').removeClass('scrivito_entered').each(function () { clearTimeout($(this).data('scrivito-entered-timer')); }); }; var enable_highlighting_for = function(marker_container) { if (marker_container.data('scrivito-highlightable')) { return; } marker_container.data('scrivito-highlightable', true); var document = scrivito.cms_document.from(marker_container).dom_element(); marker_container.on('mouseenter', function(event) { var target = $(event.target).closest(':data(scrivito-highlightable)'); if (target.is(marker_container)) { lights_off(document); lights_on(marker_container); } }); marker_container.on('mouseleave', function(event) { lights_off(document); var target = $(event.relatedTarget).closest(':data(scrivito-highlightable)'); if (target.length) { lights_on(target); } }); }; var builder = { activate_for: function(cms_element, options) { var marker = $(scrivito.template.render('inplace_marker', options || {})); marker.on('click', function() { if (scrivito.is_development_mode) { warn_overlapping(marker.get(0)); } scrivito.menus.toggle(marker, cms_element.menu()); return false; }); var marker_container = cms_element.dom_element(); marker.prependTo(marker_container); enable_highlighting_for(marker_container); } }; }()); (function() { $.extend(scrivito, { resource_dialog: { init: function(config) { if (config.obj) { var obj = scrivito.obj.create_instance(config.obj); scrivito.gui.on('open', function() { scrivito.resource_dialog.open(obj).then(function() { return scrivito.with_saving_overlay(scrivito.redirect_to(config.return_to)); }); }); } }, open: function(obj) { var title = scrivito.t('resource_dialog.title', obj.obj_class_name()); return scrivito.details_dialog.open(obj.details_src(), title, obj, [ scrivito.revert_obj_command(obj, 'resource_dialog.commands.revert_obj'), scrivito.restore_obj_command(obj, 'resource_dialog.commands.restore_obj'), scrivito.mark_resolved_obj_command(obj, 'resource_dialog.commands.mark_resolved_obj'), scrivito.delete_obj_command(obj, 'resource_dialog.commands.delete_obj') ]); } } }); }()); (function() { $.extend(scrivito, { external_links: { init: function() { scrivito.gui.on('document', function(cms_document) { var new_document = cms_document.dom_element(); var base = new_document.find('head > base'); if (!base.length) { base = $('<base>'); new_document.find('head').prepend(base); } base.attr('target', '_top'); }); scrivito.on('content', function(content) { content = $(content); _.each(content.find('a').not( '[data-scrivito-display-mode="editing"] [data-scrivito-field-type="html"] a'), function(link) { var element = $(link); var target = convert_target(link, element.attr('target')); element.attr('target', target); }); _.each(content.find('form').not( '[data-scrivito-display-mode="editing"] [data-scrivito-field-type="html"] form'), function(form) { var element = $(form); var link = document.createElement('a'); link.href = form.action; var target = convert_target(link, element.attr('target')); element.attr('target', target); }); }); } } }); var convert_target = function(link, target) { if (link.protocol === window.location.protocol && link.host === window.location.host) { if (!target) { return '_self'; } } else { if ( target === '' || target === '_self' || target === '_parent' || (/^scrivito/).test(target) ) { return '_top'; } } return target; }; }()); (function() { $.extend(scrivito, { add_content_command: function(cms_element) { var widgetlist_field_element, widget_element; if (cms_element.widget_field) { widget_element = cms_element; } else { widgetlist_field_element = cms_element; } return scrivito.command.create_instance({ id: 'scrivito.sdk.add_content', title: scrivito.t('commands.add_content.title'), icon: '', present: function() { return scrivito.select_content && scrivito.editing_context.is_editing_mode() && (widget_element || widgetlist_field_element.is_empty()); }, disabled: function() { if (!(widgetlist_field_element || widget_element.widget_field()) .is_content_widget_allowed()) { return scrivito.t('commands.add_content.not_allowed'); } }, execute: function() { if (!widgetlist_field_element) { widgetlist_field_element = widget_element.widget_field(); } scrivito.select_content().then(function(contents) { var content = contents[0]; if (content) { var widget_params = { create: { _obj_class: 'Scrivito::ContentWidget', content: content } }; scrivito.with_saving_overlay( widgetlist_field_element.add_widget(widget_params, widget_element) ); } }); } }); } }); }()); (function() { $.extend(scrivito, { add_subpage_command: function(child_list_element) { return scrivito.command.create_instance({ id: 'scrivito.sdk.add_subpage', title: scrivito.t('commands.add_subpage.title'), icon: '', tooltip: scrivito.t('commands.add_subpage.tooltip', child_list_element.obj().description_for_editor()), execute: function() { var class_selection = child_list_element.fetch_page_class_selection(); var choose_obj_class = scrivito.choose_obj_class_dialog(class_selection, 'add_child_page'); return choose_obj_class.then(function(obj_class) { var add_subpage = child_list_element.create_child(obj_class); return scrivito.with_saving_overlay(add_subpage).then(function(obj) { return scrivito.application_window.redirect_to('/' + obj.id()); }); }); } }); } }); }()); (function() { $.extend(scrivito, { choose_and_create_widget_command: function(cms_element) { var widgetlist_field_element, widget_element; if (cms_element.widget_field) { widget_element = cms_element; widgetlist_field_element = widget_element.widget_field(); } else { widgetlist_field_element = cms_element; } return scrivito.command.create_instance({ id: 'scrivito.sdk.choose_and_create_widget', title: scrivito.t('commands.choose_and_create_widget.title'), icon: '', present: function() { return scrivito.editing_context.is_editing_mode() && (widget_element || widgetlist_field_element.is_empty()) && (widgetlist_field_element.can_choose_widget_class() || !widgetlist_field_element.can_create_widget()); }, disabled: function() { if (!widgetlist_field_element.can_create_widget()) { return scrivito.t('commands.choose_and_create_widget.disabled'); } }, execute: function() { var choose_obj_class = scrivito.choose_obj_class_dialog( widgetlist_field_element.fetch_widget_class_selection(), 'create_widget'); return choose_obj_class.then(function(obj_class) { return scrivito.with_saving_overlay( widgetlist_field_element.add_widget({create: {_obj_class: obj_class}}, widget_element) ); }); } }); } }); }()); (function() { $.extend(scrivito, { copy_page_from_clipboard_command: function(child_list_element) { return scrivito.command.create_instance({ id: 'scrivito.sdk.copy_page_from_clipboard', title: scrivito.t('commands.copy_page_from_clipboard.title'), icon: '', present: function() { return scrivito.obj_clipboard.is_present(); }, disabled: function() { var obj_class_name = scrivito.obj_clipboard.obj().obj_class_name(); if (!child_list_element.is_valid_child_class(obj_class_name)) { return scrivito.t('commands.copy_page_from_clipboard.paste_forbidden', child_list_element.allowed_classes().join(', ')); } }, execute: function() { var copy_page = scrivito.obj_clipboard.obj().copy_to(child_list_element.path()); return scrivito.with_saving_overlay(copy_page).then(function() { scrivito.application_window.reload(); }); } }); } }); }()); (function() { $.extend(scrivito, { copy_widget_from_clipboard_command: function(cms_element) { var widgetlist_field_element, widget_element; if (cms_element.widget_field) { widget_element = cms_element; } else { widgetlist_field_element = cms_element; } return scrivito.command.create_instance({ id: 'scrivito.sdk.copy_widget_from_clipboard', title: function() { return scrivito.t('commands.copy_widget_from_clipboard.' + (scrivito.widget_clipboard.widget().is_content_widget() ? 'content' : 'widget') + '_title'); }, icon: '', present: function() { return scrivito.editing_context.is_editing_mode() && scrivito.widget_clipboard.is_present() && (widget_element || widgetlist_field_element.is_empty()); }, disabled: function() { if (!widgetlist_field_element) { widgetlist_field_element = widget_element.widget_field(); } var widget_class_name = scrivito.widget_clipboard.widget().widget_class_name(); if (!widgetlist_field_element.is_valid_child_class(widget_class_name)) { return scrivito.t('commands.copy_widget_from_clipboard.paste_forbidden', widgetlist_field_element.description_for_allowed_classes().join(', ')); } }, execute: function() { if (!widgetlist_field_element) { widgetlist_field_element = widget_element.widget_field(); } var widget = scrivito.widget_clipboard.widget(); var workspace_id = scrivito.widget_clipboard.workspace_id(); var copy_params = { copy: { workspace_id: workspace_id, obj_id: widget.obj().id(), widget_id: widget.id() } }; return scrivito.with_saving_overlay( widgetlist_field_element.add_widget(copy_params, widget_element) ); } }); } }); }()); (function() { $.extend(scrivito, { create_widget_command: function(cms_element) { var widgetlist_field_element, widget_element, description, obj_class; if (cms_element.widget_field) { widget_element = cms_element; widgetlist_field_element = widget_element.widget_field(); } else { widgetlist_field_element = cms_element; } obj_class = widgetlist_field_element.allowed_classes_for_create()[0]; description = widgetlist_field_element.description_for_allowed_class(obj_class); return scrivito.command.create_instance({ id: 'scrivito.sdk.create_widget', title: scrivito.t('commands.create_widget.title', description), icon: '', present: function() { return scrivito.editing_context.is_editing_mode() && (widget_element || widgetlist_field_element.is_empty()) && widgetlist_field_element.can_create_widget() && !widgetlist_field_element.can_choose_widget_class(); }, execute: function() { var widget_params = {create: {_obj_class: obj_class}}; return scrivito.with_saving_overlay( widgetlist_field_element.add_widget(widget_params, widget_element) ); } }); } }); }()); (function() { _.extend(scrivito, { create_workspace_command: function() { return scrivito.command.create_instance({ id: 'scrivito.sdk.create_workspace', title: scrivito.t('commands.create_workspace.title'), icon: '', disabled: function() { if (!scrivito.user_permissions.can('create_workspace')) { return scrivito.t('commands.create_workspace.forbidden'); } }, execute: function() { scrivito.prompt_dialog({ title: scrivito.t('commands.create_workspace.dialog.title'), description: scrivito.t('commands.create_workspace.dialog.description'), placeholder: scrivito.t('commands.create_workspace.dialog.placeholder'), icon: '', color: 'green', accept_button_text: scrivito.t('commands.create_workspace.dialog.accept'), accept_button_color: 'green' }).then(function(title) { scrivito.with_saving_overlay(scrivito.workspace.create(title)).then(function(workspace) { var path = '?_scrivito_workspace_id=' + workspace.id(); if (!scrivito.editing_context.selected_workspace.is_editable()) { path += '&_scrivito_display_mode=editing'; } return scrivito.redirect_to(path); }); }); } }); } }); }()); (function() { $.extend(scrivito, { delete_obj_command: function(obj, translations_namespace) { if (!translations_namespace) { translations_namespace = 'commands.delete_obj'; } return scrivito.command.create_instance({ id: 'scrivito.sdk.delete_obj', title: scrivito.t(translations_namespace + '.title'), icon: '', present: function() { return obj && !scrivito.editing_context.is_deleted_mode(); }, disabled: function() { if (!scrivito.editing_context.selected_workspace.is_editable()) { return scrivito.t('commands.delete_obj.published_workspace'); } if (obj.has_children()) { return scrivito.t('commands.delete_obj.has_children'); } }, execute: function() { scrivito.confirmation_dialog({ title: scrivito.t(translations_namespace + '.dialog.title'), description: scrivito.t(translations_namespace + '.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('commands.delete_obj.dialog.confirm'), confirm_button_color: 'red' }).then(function() { return scrivito.with_saving_overlay(obj.destroy().then(function(redirect_to) { if (scrivito.obj_clipboard.is_present() && scrivito.obj_clipboard.obj().id() === obj.id()) { scrivito.obj_clipboard.clear(); } return scrivito.redirect_to(redirect_to); })); }); } }); } }); }()); (function() { $.extend(scrivito, { delete_widget_command: function(widget_element) { return scrivito.command.create_instance({ id: 'scrivito.sdk.delete_widget', title: scrivito.t('commands.delete_widget.' + (widget_element.widget().is_content_widget() ? 'content' : 'widget') + '_title'), icon: '', present: function() { return scrivito.editing_context.is_editing_mode(); }, execute: function() { return scrivito.confirmation_dialog({ title: scrivito.t('commands.delete_widget.dialog.title'), description: scrivito.t('commands.delete_widget.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('commands.delete_widget.dialog.confirm'), confirm_button_color: 'red' }).then(function() { var widgetlist_field_element = widget_element.widget_field(); var widget = widget_element.widget(); widget_element.dom_element().remove(); scrivito.widget_sorting.update_placeholder(widgetlist_field_element); return widget.destroy().then(function() { if (scrivito.widget_clipboard.is_present() && scrivito.widget_clipboard.widget().id() === widget.id()) { scrivito.widget_clipboard.clear(); } }); }); } }); } }); }()); (function() { $.extend(scrivito, { delete_workspace_command: function(workspace) { return scrivito.command.create_instance({ id: 'scrivito.sdk.delete_workspace', title: scrivito.t('commands.delete_workspace.title'), icon: '', execute: function() { scrivito.confirmation_dialog({ title: scrivito.t('commands.delete_workspace.dialog.title', workspace.title()), description: scrivito.t('commands.delete_workspace.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('commands.delete_workspace.dialog.confirm'), confirm_button_color: 'red' }).done(function() { scrivito.with_saving_overlay(workspace.destroy().then(function() { return scrivito.redirect_to('?_scrivito_workspace_id=published'); })); }); } }); } }); }()); (function() { $.extend(scrivito, { duplicate_obj_command: function(obj) { return scrivito.command.create_instance({ id: 'scrivito.sdk.duplicate_obj', title: scrivito.t('commands.duplicate_obj.title'), icon: '', present: function() { return obj && !scrivito.editing_context.is_deleted_mode(); }, disabled: function() { if (!scrivito.editing_context.selected_workspace.is_editable()) { return scrivito.t('commands.duplicate_obj.published_workspace'); } if (obj.has_children()) { return scrivito.t('commands.duplicate_obj.has_children'); } }, execute: function() { return scrivito.with_saving_overlay(obj.duplicate()).then(function(obj) { return scrivito.application_window.redirect_to('/' + obj.id()); }); } }); } }); }()); (function() { $.extend(scrivito, { mark_resolved_obj_command: function(obj, translations_namespace) { if (!translations_namespace) { translations_namespace = 'commands.mark_resolved_obj'; } return scrivito.command.create_instance({ id: 'scrivito.sdk.mark_resolved_obj', title: scrivito.t(translations_namespace + '.title'), icon: '', present: function() { return obj && obj.has_conflict(); }, execute: function() { return scrivito.confirmation_dialog({ title: scrivito.t('commands.mark_resolved_obj.dialog.title'), description: scrivito.t(translations_namespace + '.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('commands.mark_resolved_obj.dialog.confirm'), confirm_button_color: 'red' }).then(function() { return scrivito.with_saving_overlay(obj.mark_resolved()).then(function() { scrivito.application_window.reload(); }); }); } }); } }); }()); (function() { $.extend(scrivito, { move_page_from_clipboard_command: function(child_list_element) { return scrivito.command.create_instance({ id: 'scrivito.sdk.move_page_from_clipboard', title: scrivito.t('commands.move_page_from_clipboard.title'), icon: '', present: function() { return scrivito.obj_clipboard.is_present(); }, disabled: function() { var obj_class_name = scrivito.obj_clipboard.obj().obj_class_name(); if (!child_list_element.is_valid_child_class(obj_class_name)) { return scrivito.t('commands.move_page_from_clipboard.paste_forbidden', child_list_element.allowed_classes().join(', ')); } }, execute: function() { var move_page = child_list_element.add_child(scrivito.obj_clipboard.obj()); return scrivito.with_saving_overlay(move_page).then(function() { scrivito.obj_clipboard.clear(); scrivito.application_window.reload(); }); } }); } }); }()); (function() { $.extend(scrivito, { obj_details_command: function(obj) { return scrivito.command.create_instance({ id: 'scrivito.sdk.obj_details', title: scrivito.t('commands.obj_details.title'), icon: '', present: function() { return obj.has_details_view(); }, execute: function() { return scrivito.write_monitor.track_changes(function() { return scrivito.details_dialog.open(obj.details_src(), scrivito.t('commands.obj_details.dialog.title', obj.obj_class_name())); }, function() { scrivito.application_window.reload(); }); } }); } }); }()); (function() { $.extend(scrivito, { publish_workspace_command: function(workspace) { var open_confirmation_dialog = function() { return scrivito.confirmation_dialog({ title: scrivito.t('commands.publish_workspace.dialog.title', workspace.title()), description: scrivito.t('commands.publish_workspace.dialog.description'), icon: '', color: 'green', confirm_button_text: scrivito.t('commands.publish_workspace.dialog.confirm'), confirm_button_color: 'green' }); }; var open_check_failed_dialog = function() { scrivito.confirmation_dialog({ title: scrivito.t('commands.publish_workspace.error_dialog.title'), description: scrivito.t('commands.publish_workspace.error_dialog.description'), icon: '', confirm_button_text: scrivito.t('commands.publish_workspace.error_dialog.confirm') }).then(function() { scrivito.changes_dialog.open(); }); }; return scrivito.command.create_instance({ id: 'scrivito.sdk.publish_workspace', title: scrivito.t('commands.publish_workspace.title'), icon: '', tooltip: scrivito.t('commands.publish_workspace.title', workspace.title()), disabled: function() { if (!scrivito.user_permissions.can('publish_workspace')) { return scrivito.t('commands.publish_workspace.permission_denied'); } }, execute: function() { if (scrivito.user_permissions.can('publish_workspace')) { open_confirmation_dialog().done(function() { scrivito.with_saving_overlay(workspace.check_and_publish().done(function() { return scrivito.redirect_to('?_scrivito_workspace_id=published'); }).fail(function(error) { if (error.type === 'check_failed') { open_check_failed_dialog(); } else if (error.type === 'outdated_certificates') { scrivito.alert_dialog( scrivito.t('commands.publish_workspace.alert.invalid_certificates')); } })); }); } } }); } }); }()); (function() { $.extend(scrivito, { rebase_workspace_command: function(workspace) { return scrivito.command.create_instance({ id: 'scrivito.sdk.rebase_workspace', title: scrivito.t('commands.rebase_workspace.title'), icon: '', tooltip: scrivito.t('commands.rebase_workspace.tooltip', workspace.title()), disabled: function() { if (!workspace.is_outdated()) { return scrivito.t('commands.rebase_workspace.uptodate', workspace.title()); } }, action_required: function() { return workspace.is_outdated(); }, execute: function() { scrivito.with_saving_overlay(workspace.rebase().then(function() { return workspace.has_conflicts().then(function() { return scrivito.confirmation_dialog({ title: scrivito.t('commands.rebase_workspace.has_conflicts.title'), description: scrivito.t('commands.rebase_workspace.has_conflicts.description'), confirm_button_text: scrivito.t('commands.rebase_workspace.open_changes_dialog'), cancel_button_text: scrivito.t('close') }).done(function() { scrivito.changes_dialog.open(); }); }).always(function() { return scrivito.application_window.reload(); }); })); } }); } }); }()); (function() { $.extend(scrivito, { rename_workspace_command: function(workspace) { return scrivito.command.create_instance({ id: 'scrivito.sdk.rename_workspace', title: scrivito.t('commands.rename_workspace.title'), icon: '', execute: function() { scrivito.prompt_dialog({ title: scrivito.t('commands.rename_workspace.dialog.title', workspace.title()), description: scrivito.t('commands.rename_workspace.dialog.description'), value: workspace.original_title(), icon: '', color: 'green', accept_button_text: scrivito.t('commands.rename_workspace.dialog.accept'), accept_button_color: 'green' }).done(function(new_title) { scrivito.with_saving_overlay(workspace.rename(new_title).then(function() { return scrivito.reload(); })); }); } }); } }); }()); (function() { $.extend(scrivito, { restore_obj_command: function(obj, translations_namespace) { if (!translations_namespace) { translations_namespace = 'commands.restore_obj'; } return scrivito.command.create_instance({ id: 'scrivito.sdk.restore_obj', title: scrivito.t(translations_namespace + '.title'), icon: '', present: function() { return obj && obj.is_deleted(); }, disabled: function() { if (scrivito.editing_context.selected_workspace.is_rtc()) { return scrivito.t(translations_namespace + '.rtc_workspace'); } }, execute: function() { scrivito.with_saving_overlay(obj.restore().then(function() { return scrivito.reload(); })); } }); } }); }()); (function() { $.extend(scrivito, { restore_widget_command: function(widget_element) { var widget = widget_element.widget(); return scrivito.command.create_instance({ id: 'scrivito.sdk.restore_widget', title: scrivito.t('commands.restore_widget.title'), icon: '', present: function() { return widget.is_deleted(); }, disabled: function() { if (scrivito.editing_context.selected_workspace.is_rtc()) { return scrivito.t('commands.restore_widget.rtc_workspace'); } }, execute: function() { scrivito.with_saving_overlay(widget.restore()).then(function() { scrivito.application_window.reload(); }); } }); } }); }()); (function() { $.extend(scrivito, { revert_obj_command: function(obj, translations_namespace) { if (!translations_namespace) { translations_namespace = 'commands.revert_obj'; } return scrivito.command.create_instance({ id: 'scrivito.sdk.revert_obj', title: scrivito.t(translations_namespace + '.title'), icon: '', present: function() { return scrivito.editing_context.selected_workspace.is_editable() && obj && !obj.is_deleted(); }, disabled: function() { if (scrivito.editing_context.selected_workspace.is_rtc()) { return scrivito.t(translations_namespace + '.rtc_workspace'); } if (!obj.modification()) { return scrivito.t(translations_namespace + '.not_modified_obj'); } if (obj.is_new()) { return scrivito.t(translations_namespace + '.new_obj'); } }, update: function() { return obj.reload(); }, execute: function() { return scrivito.confirmation_dialog({ title: scrivito.t(translations_namespace + '.dialog.title'), description: scrivito.t('commands.revert_obj.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('commands.revert_obj.dialog.confirm'), confirm_button_color: 'red' }).then(function() { return scrivito.with_saving_overlay(obj.revert()).then(function() { scrivito.application_window.reload(); }); }); } }); } }); }()); (function() { $.extend(scrivito, { revert_widget_command: function(widget_element) { var widget = widget_element.widget(); return scrivito.command.create_instance({ id: 'scrivito.sdk.revert_widget', title: scrivito.t('commands.revert_widget.' + (widget.is_content_widget() ? 'content' : 'widget') + '_title'), icon: '', present: function() { return scrivito.editing_context.selected_workspace.is_editable() && !widget.is_deleted(); }, disabled: function() { if (scrivito.editing_context.selected_workspace.is_rtc()) { return scrivito.t('commands.revert_widget.rtc_workspace'); } if (widget.is_new()) { return scrivito.t('commands.revert_widget.is_new'); } if (!widget.is_modified()) { return scrivito.t('commands.revert_widget.is_not_modified'); } }, update: function() { return widget.reload(); }, execute: function() { return scrivito.confirmation_dialog({ title: scrivito.t('commands.revert_widget.dialog.title'), description: scrivito.t('commands.revert_widget.dialog.description'), icon: '', color: 'red', confirm_button_text: scrivito.t('commands.revert_obj.dialog.confirm'), confirm_button_color: 'red' }).then(function() { var dom_element = widget_element.dom_element(); scrivito.with_element_overlay(dom_element, widget.revert().then(function() { dom_element.scrivito('reload'); })); }); } }); } }); }()); (function() { $.extend(scrivito, { save_obj_to_clipboard_command: function(obj) { return scrivito.command.create_instance({ id: 'scrivito.sdk.save_obj_to_clipboard', title: scrivito.t('commands.save_obj_to_clipboard.title'), icon: '', present: function() { return !scrivito.editing_context.is_deleted_mode(); }, disabled: function() { if (obj.has_children()) { return scrivito.t('commands.save_obj_to_clipboard.has_children'); } }, execute: function() { scrivito.obj_clipboard.save_obj(obj); } }); } }); }()); (function() { $.extend(scrivito, { save_widget_to_clipboard_command: function(widget_element) { return scrivito.command.create_instance({ id: 'scrivito.sdk.save_widget_to_clipboard', title: scrivito.t('commands.save_widget_to_clipboard.' + (widget_element.widget().is_content_widget() ? 'content' : 'widget') + '_title'), icon: '', present: function() { return scrivito.editing_context.is_editing_mode(); }, execute: function() { scrivito.widget_clipboard.save_widget(widget_element.widget()); } }); } }); }()); (function() { $.extend(scrivito, { select_workspace_command: function(workspace) { return scrivito.command.create_instance({ id: 'scrivito.sdk.select_workspace_'+workspace.id(), title: workspace.title(), icon: workspace.icon(), execute: function() { scrivito.with_saving_overlay( scrivito.redirect_to('?_scrivito_workspace_id='+workspace.id())); } }); } }); }()); (function() { $.extend(scrivito, { sort_items_command: function(child_list_element) { return scrivito.command.create_instance({ id: 'scrivito.sdk.sort_items', title: scrivito.t('commands.sort_items.title'), icon: '', tooltip: scrivito.t('commands.sort_items.tooltip', child_list_element.obj().description_for_editor()), disabled: function() { if (!child_list_element.has_child_order()) { return scrivito.t('commands.sort_items.auto_sort'); } if (child_list_element.children().length < 2) { return scrivito.t('commands.sort_items.too_less_children'); } }, execute: function() { var children = child_list_element.children(); return scrivito.obj_sorting_dialog.open(children).then(function(sorted_children) { var dom_element = child_list_element.dom_element(); _.each(sorted_children, function(sorted_child) { dom_element.append(sorted_child.dom_element()); }); return child_list_element.save_order(); }); } }); } }); }()); (function() { $.extend(scrivito, { switch_mode_command: function(mode) { var icon; switch (mode) { case 'diff': icon = ''; break; case 'added': icon = ''; break; case 'deleted': icon = ''; break; } return scrivito.command.create_instance({ id: 'switch_to_' + mode + '_mode', title: scrivito.t('commands.switch_mode.' + mode), icon: icon, disabled: function() { if (scrivito.editing_context.display_mode === mode) { return scrivito.t('commands.switch_mode.disabled'); } }, execute: function() { if (mode !== 'view' && !scrivito.editing_context.selected_workspace.is_editable()) { scrivito.with_saving_overlay(scrivito.workspace.editable()).then(function(workspaces) { scrivito.editable_workspace_dialog(workspaces).then(function(workspace_id) { redirect_to(mode, workspace_id); }); }); } else { redirect_to(mode); } } }); } }); var redirect_to = function(mode, workspace_id) { var path = '?_scrivito_display_mode=' + mode; if (workspace_id) { path += '&_scrivito_workspace_id=' + workspace_id; } scrivito.with_saving_overlay(scrivito.redirect_to(path)); }; }()); (function() { $.extend(scrivito, { widget_details_command: function(widget_element) { var widget = function() { return widget_element.widget(); }; return scrivito.command.create_instance({ id: 'scrivito.sdk.widget_details', title: scrivito.t('commands.widget_details.title'), icon: '', present: function() { return widget_element.widget_field().template_name() === 'show' && !widget().is_content_widget() && (scrivito.editing_context.is_editing_mode() || widget().is_modified() || widget().is_placement_modified()); }, disabled: function() { if (!widget_element.has_details_view()) { return scrivito.t('commands.widget_details.no_details_view'); } }, execute: function() { return scrivito.write_monitor.track_changes(function() { return scrivito.details_dialog.open(widget_element.details_src(), scrivito.t('commands.widget_details.dialog.title', widget().widget_class_name())); }, function() { widget_element.dom_element().scrivito('reload'); }); } }); } }); }()); (function() { $.extend(scrivito, { workspace_changes_command: function() { return scrivito.command.create_instance({ id: 'scrivito.sdk.workspace_changes', title: scrivito.t('commands.workspace_changes.title'), icon: '', execute: function() { scrivito.changes_dialog.open(); } }); } }); }()); (function() { $.extend(scrivito, { workspace_settings_command: function(workspace) { return scrivito.command.create_instance({ id: 'scrivito.sdk.workspace_settings', title: scrivito.t('commands.workspace_settings.title'), icon: '', execute: function() { workspace.fetch_memberships().then(function(memberships) { var title = scrivito.t('commands.workspace_settings.dialog.title', workspace.title()); scrivito.workspace_settings_dialog.open(title, memberships).then(function(memberships) { scrivito.with_saving_overlay( workspace.update({memberships: memberships}).then(function() { return scrivito.reload(); }) ); }); }); } }); } }); }()); (function() { $.extend(scrivito, { child_list_commands: { init: function() { if (scrivito.editing_context.is_editing_mode()) { scrivito.on('content', function(content) { _.each(scrivito.child_list_element.all($(content)), function(child_list_element) { child_list_element.set_menu([ scrivito.add_subpage_command(child_list_element), scrivito.copy_page_from_clipboard_command(child_list_element), scrivito.move_page_from_clipboard_command(child_list_element), scrivito.sort_items_command(child_list_element) ].concat(child_list_element.menu())); }); }); } } } }); }()); (function() { _.extend(scrivito, { current_page_commands: { init: function() { scrivito.gui.on('document', function(cms_document) { var current_page = cms_document.page(); if (current_page) { cms_document.set_menu([ scrivito.obj_details_command(current_page), scrivito.save_obj_to_clipboard_command(current_page), scrivito.delete_obj_command(current_page), scrivito.revert_obj_command(current_page), scrivito.restore_obj_command(current_page), scrivito.mark_resolved_obj_command(current_page), scrivito.duplicate_obj_command(current_page) ].concat(cms_document.menu())); } }); } } }); }()); (function() { $.extend(scrivito, { widget_commands: { init: function() { if (!scrivito.editing_context.is_view_mode()) { scrivito.on('content', function(content) { _.each(scrivito.widget_element.all($(content)), function(widget_element) { var widgetlist_field_element = widget_element.widget_field(); widget_element.set_menu([ scrivito.create_widget_command(widget_element), scrivito.choose_and_create_widget_command(widget_element), // // FIXME content-widget // // scrivito.add_content_command(widget_element), scrivito.widget_details_command(widget_element), scrivito.save_widget_to_clipboard_command(widget_element), scrivito.copy_widget_from_clipboard_command(widget_element), scrivito.revert_widget_command(widget_element), scrivito.restore_widget_command(widget_element), scrivito.delete_widget_command(widget_element) ].concat(widget_element.menu())); }); }); } } } }); }()); (function() { $.extend(scrivito, { widgetlist_field_commands: { init: function() { if (scrivito.editing_context.is_editing_mode()) { scrivito.on('content', function(content) { _.each(scrivito.widgetlist_field_element.all($(content)), function(widgetlist_field_element) { widgetlist_field_element.set_menu([ scrivito.create_widget_command(widgetlist_field_element), scrivito.choose_and_create_widget_command(widgetlist_field_element), // // FIXME content-widget // // scrivito.add_content_command(widgetlist_field_element), scrivito.copy_widget_from_clipboard_command(widgetlist_field_element) ].concat(widgetlist_field_element.menu())); }); }); } } } }); }()); (function() { _.extend(scrivito, { child_list_marker: { init: function() { scrivito.inplace_marker.define(function(inplace_marker, root_element) { if (scrivito.editing_context.is_editing_mode()) { _.each(scrivito.child_list_element.all(root_element), function(child_list_element) { var description = scrivito.t('child_list_menu.description', child_list_element.obj().description_for_editor()); inplace_marker.activate_for(child_list_element, {description: description}); }); } }); } } }); }()); (function() { _.extend(scrivito, { widgetlist_field_menu: { init: function() { scrivito.on('content', function(content) { if (scrivito.editing_context.is_editing_mode()) { var widgetlist_field_elements = scrivito.widgetlist_field_element.all($(content)); _.each(widgetlist_field_elements, function(widgetlist_field_element) { activate_menu_for(widgetlist_field_element); }); } }); } } }); var activate_menu_for = function(widgetlist_field_element) { var container = widgetlist_field_element.dom_element(); container.on('click.scrivito', function(e) { if (!widgetlist_field_element.is_empty()) { return; } var container_offset = container.offset(); var relative_offset = { left: e.pageX - container_offset.left, top: e.pageY - container_offset.top }; var anchor_point = { x: relative_offset.left / container.width(), y: relative_offset.top / container.height() }; scrivito.menus.toggle(container, widgetlist_field_element.menu(), anchor_point); return false; }); }; }()); (function() { _.extend(scrivito, { widget_marker: { init: function() { scrivito.inplace_marker.define(function(inplace_marker, root_element) { if (scrivito.editing_context.selected_workspace.is_editable()) { var widgetlist_field_elements = scrivito.widgetlist_field_element.all(root_element); _.each(widgetlist_field_elements, function(widgetlist_field_element) { _.each(widgetlist_field_element.widget_elements(), function(widget_element) { var show_as_modified = widget_element.widget().is_modified() || widget_element.widget().is_placement_modified(); if (scrivito.editing_context.is_editing_mode() || scrivito.editing_context.is_comparing_mode() && show_as_modified) { if (widget_element.has_widgetlist()) { widget_element.dom_element().attr('data-scrivito-private-structure-widget', true); } inplace_marker.activate_for(widget_element, inplace_marker_options(widget_element)); } }); }); } }); } } }); var inplace_marker_options = function(widget_element) { var options = {}; if (widget_element.has_widgetlist()) { options.icon = 'scrivito_icon_structure_widget'; } if (scrivito.editing_context.is_comparing_mode()) { var tooltip_translation_key; var modification = widget_element.widget().modification(); var placement_modification = widget_element.widget().placement_modification(); switch (modification) { case 'new': tooltip_translation_key = 'widget_is_new'; options.icon = 'scrivito_icon_inv_plus'; break; case 'deleted': tooltip_translation_key = 'widget_is_deleted'; options.icon = 'scrivito_icon_trash'; break; case 'edited': options.icon = 'scrivito_icon_edited'; switch (placement_modification) { case 'new': tooltip_translation_key = 'widget_is_edited_and_dragged_here'; options.css_classes = 'scrivito_widget_moved_icon'; break; case 'deleted': tooltip_translation_key = 'widget_is_edited_and_dragged_away'; options.css_classes = 'scrivito_widget_moved_icon'; break; default: tooltip_translation_key = 'widget_is_edited'; } break; default: options.icon = 'scrivito_icon_moved'; switch (placement_modification) { case 'new': tooltip_translation_key = 'widget_is_dragged_here'; break; case 'deleted': tooltip_translation_key = 'widget_is_dragged_away'; break; } } if (tooltip_translation_key) { options.tooltip = scrivito.t('widget_marker.' + tooltip_translation_key); } } options.description = widget_element.widget().description_for_editor(); return options; }; }()); (function() { $.extend(scrivito, { widget_reloading: { init: function() { scrivito.on('content', function(dom_element) { if (scrivito.in_editable_view()) { var jquery_object = $(dom_element); if (jquery_object.attr('data-scrivito-private-widget-id')) { activate_for(jquery_object); } _.each(jquery_object.find('[data-scrivito-private-widget-id]'), function(dom_element) { activate_for($(dom_element)); }); } }); } } }); var activate_for = function(jquery_object) { var activate = function() { var widget_element = scrivito.cms_element.from_dom_element(jquery_object); scrivito.with_element_overlay(jquery_object, widget_element.fetch_markup().then(function(show_markup) { var new_jquery_object = $(show_markup); jquery_object.replaceWith(new_jquery_object); scrivito.gui.new_content(new_jquery_object); }) ); return false; }; $(jquery_object).on('reload.scrivito', function() { activate(); return false; }); // TODO: remove this in 1.0.0. scrivito.cms_document.local_jquery(jquery_object).on('scrivito_reload', function() { scrivito.deprecation_warning('$.trigger("scrivito_reload")', '$.scrivito("reload")'); activate(); return false; }); }; }()); (function() { _.extend(scrivito, { widget_sorting: { init: function() { scrivito.on('content', function(root_element) { if (scrivito.in_editable_view()) { create($(root_element)); } }); }, start: function(event, ui) { var cms_document = scrivito.cms_document.from(ui.item); cms_document.dom_element().find('body').addClass('scrivito_widget_dragging_active'); scrivito.close_all_menus(); var widget_element = scrivito.cms_element.from_dom_element(ui.item); var widget_class_name = widget_element.widget().widget_class_name(); _.each(widgetlist_field_elements, function(widgetlist_field_element) { var dom_element = widgetlist_field_element.dom_element(); if (dom_element.data('ui-sortable')) { if (widgetlist_field_element.is_valid_child_class(widget_class_name)) { dom_element.addClass('scrivito_widget_drop_allowed'); } else { dom_element.sortable('disable'); } } }); $(event.target).sortable('refresh'); }, stop: function(event, ui) { var root_element = scrivito.cms_document.from(ui.item).dom_element(); root_element.find('body').removeClass('scrivito_widget_dragging_active'); // Drag the _last_ widget out of a widget field and then drop it back. if (!ui.sender) { var widgetlist_field_element = scrivito.cms_element.from_dom_element(ui.item).widget_field(); scrivito.widget_sorting.update_placeholder(widgetlist_field_element); } _.each(widget_field_dom_elements, function(dom_element) { dom_element.removeClass('scrivito_widget_drop_allowed'); if (dom_element.data('ui-sortable')) { dom_element.sortable('enable'); } }); }, update: function(event, ui) { if (event.target === ui.item.parent()[0]) { var target_field_element = scrivito.cms_element.from_dom_element(ui.item).widget_field(); scrivito.widget_sorting.update_placeholder(target_field_element); if (ui.sender) { var source_field_element = scrivito.cms_element.from_dom_element(ui.sender); scrivito.widget_sorting.update_placeholder(source_field_element); var changes = {}; add_changes(changes, source_field_element); add_changes(changes, target_field_element); source_field_element.obj().save(changes); } else { target_field_element.save(); } } }, // We can not listen to "out", because of the a bug in jQuery-Sortable. // The bug in http://bugs.jqueryui.com/ticket/5671 is still present. over: function(event, ui) { if (ui.sender) { var widgetlist_field_element = scrivito.cms_element.from_dom_element(ui.sender); // If "over" is triggered, then exactly one item has been removed from the sender field. var number_of_widget_elements = widgetlist_field_element.widget_elements().length - 1; scrivito.widget_sorting.update_placeholder(widgetlist_field_element, number_of_widget_elements); } }, update_placeholder: function(widgetlist_field_element, number_of_widget_elements) { var dom_element = widgetlist_field_element.dom_element(); if (number_of_widget_elements === undefined) { number_of_widget_elements = widgetlist_field_element.widget_elements().length; } if (number_of_widget_elements === 0) { dom_element.addClass('scrivito_empty_widget_field'); } else { dom_element.removeClass('scrivito_empty_widget_field'); } } } }); var widgetlist_field_elements = []; var widget_field_dom_elements = []; var create = function(root_element) { var cms_document = scrivito.cms_document.from(root_element); if (scrivito.editing_context.visible_workspace.is_editable()) { _.each(scrivito.widgetlist_field_element.all(root_element), function(widgetlist_field_element) { var dom_element = widgetlist_field_element.dom_element(); if (!dom_element.data('ui-sortable')) { dom_element.sortable({ items: '> [data-scrivito-private-widget-id]', handle: '> .scrivito_editing_marker', placeholder: 'scrivito_widget_drop_placeholder', connectWith: '*[data-scrivito-field-type="widgetlist"]', start: scrivito.widget_sorting.start, stop: scrivito.widget_sorting.stop, update: scrivito.widget_sorting.update, over: scrivito.widget_sorting.over, cursor: 'move', forcePlaceholderSize: true, // Force placeholders to be always visible. tolerance: 'pointer' // jQuery fails to correctly determine the intersection. }); scrivito.widget_sorting.update_placeholder(widgetlist_field_element); widgetlist_field_elements.push(widgetlist_field_element); widget_field_dom_elements.push(dom_element); } }); } }; var add_changes = function(changes, widgetlist_field_element) { var widget = widgetlist_field_element.widget(); if (widget) { add_widget_changes(changes, widgetlist_field_element, widget.id()); } else { add_field_changes(changes, widgetlist_field_element); } }; var add_field_changes = function(changes, widgetlist_field_element) { changes[widgetlist_field_element.field_name()] = widgetlist_field_element.content(); }; var add_widget_changes = function(changes, widgetlist_field_element, widget_id) { if (!changes._widget_pool) { changes._widget_pool = {}; } if (!changes._widget_pool[widget_id]) { changes._widget_pool[widget_id] = {}; } add_field_changes(changes._widget_pool[widget_id], widgetlist_field_element); }; }()); (function() { $.extend(scrivito, { content_upload: { init: function() { scrivito.on('content', function(content) { if (scrivito.in_editable_view()) { _.each(scrivito.widgetlist_field_element.all($(content)), function(widgetlist_field_element) { scrivito.content_upload.create(widgetlist_field_element); }); _.each(scrivito.widget_element.all($(content)), function(widget_element) { scrivito.content_upload.create(widget_element.widget_field(), widget_element); }); } }); }, create: function(widgetlist_field_element, widget_element) { var dropzone = (widget_element || widgetlist_field_element).dom_element(); var is_active = function() { return widget_element || widgetlist_field_element.is_empty(); }; dropzone.on('dragenter', function() { if (is_active()) { dropzone.addClass('scrivito_content_upload'); } return false; }); dropzone.on('dragleave', function() { if (is_active()) { dropzone.removeClass('scrivito_content_upload'); } return false; }); dropzone.on('drop', function(event) { if (is_active()) { dropzone.removeClass('scrivito_content_upload'); var data_transfer = event.originalEvent.dataTransfer; if (data_transfer) { var files = data_transfer.files; if (files.length === 1) { scrivito.content_upload.upload(files[0], widgetlist_field_element, widget_element); } } } return false; }); }, upload: function(file, widgetlist_field_element, widget_element) { var obj_class = scrivito.default_obj_class_for_content_type(file.type); var create_obj = scrivito.create_obj({blob: file, _obj_class: obj_class}); scrivito.with_saving_overlay(create_obj.then(function(obj) { return widgetlist_field_element.create_content_widget(obj.id, widget_element); })); } } }); }()); (function() { $.extend(scrivito, { hotkeys: { add_actions_while: function(promise, key_map) { var key_actions = { 13: key_map.enter, // enter key 27: key_map.escape // escape key }; $(document).on('keyup.scrivito_hotkeys_add_actions_while', function(e) { if (key_actions[e.keyCode]) { e.preventDefault(); key_actions[e.keyCode](e); } }); return promise.always(function() { $(document).off('keyup.scrivito_hotkeys_add_actions_while'); }); } } }); }()); (function() { $.extend(scrivito, { with_dialog_behaviour: function(dom_element, promise, key_map) { return scrivito.with_dialog_overlay(dom_element, scrivito.hotkeys.add_actions_while(promise, key_map)); } }); }()); (function() { _.extend(scrivito, { editable_workspace_dialog: function(workspaces) { var can_select = workspaces.length; var can_create = scrivito.user_permissions.can('create_workspace'); var view = $(scrivito.template.render('editable_workspace_dialog', { workspaces: workspaces, can_select: can_select, can_create: can_create, can_select_or_create: can_select || can_create })); $('#scrivito_editing').append(view); var create_new_ws = false; view.on('focus click', '.scrivito_input_list_of_ws', function(e) { create_new_ws = false; view.find(".scrivito_confirm").html(scrivito.t('editable_ws_dialog.select')); view.find(".scrivito_disabled").removeClass("scrivito_disabled"); view.find(".scrivito_input_new_ws_name label, .scrivito_input_new_ws_name input").addClass("scrivito_disabled"); }); view.on('focus click drop', '.scrivito_input_new_ws_name', function(e) { create_new_ws = true; view.find(".scrivito_confirm").html(scrivito.t('menu_bar.create')); view.find(".scrivito_disabled").removeClass("scrivito_disabled"); view.find(".scrivito_input_list_of_ws label, .scrivito_input_list_of_ws select").addClass("scrivito_disabled"); }); var deferred = $.Deferred(); var confirm_action = function() { if (create_new_ws) { create_workspace(); } else { select_workspace(); } return false; }; var create_workspace = function() { var title = $('#scrivito_new_ws_name').val(); scrivito.dialog.close(view); scrivito.with_saving_overlay(scrivito.workspace.create(title)).then(function(workspace) { deferred.resolve(workspace.id()); }, function() { deferred.reject(); }); }; var select_workspace = function() { var ws_id = $('select#scrivito_list_of_ws').val(); scrivito.dialog.close(view); deferred.resolve(ws_id); }; var cancel_action = function() { scrivito.dialog.close(view); deferred.reject(); return false; }; view.find('.scrivito_confirm').on('click', confirm_action); view.find('.scrivito_cancel').on('click', cancel_action); scrivito.dialog.open_and_center(view); if (can_select) { view.find('.scrivito_input_list_of_ws').click(); view.find('#scrivito_list_of_ws').focus(); } else if (can_create) { view.find('.scrivito_input_new_ws_name').click(); view.find('#scrivito_new_ws_name').focus(); } return scrivito.with_dialog_behaviour(view, deferred, { enter: confirm_action, escape: cancel_action }); } }); }()); (function() { $.extend(scrivito, { obj_sorting_dialog: { open: function(children) { var child_list = _.map(children, function(child) { return child.obj(); }); var view = $(scrivito.template.render('obj_sorting_dialog', { icon: '', child_list: child_list })); $('#scrivito_editing').append(view); $('#scrivito_obj_sorting_sortable').sortable({ placeholder: 'scrivito_obj_sorting_placeholder' }); var deferred = $.Deferred(); var confirm_action = function(e) { var new_id_order = _.map($('#scrivito_obj_sorting_sortable li'), function(child) { return $(child).attr('data-scrivito-private-obj-id'); }); var sorted_children = _.sortBy(children, function(child) { return _.indexOf(new_id_order, child.obj().id()); }); deferred.resolve(sorted_children); scrivito.dialog.close(view); return false; }; var cancel_action = function(e) { deferred.reject(); scrivito.dialog.close(view); return false; }; view.find('.scrivito_confirm').on('click', confirm_action); view.find('.scrivito_cancel').on('click', cancel_action); scrivito.dialog.open_and_adjust(view); return scrivito.with_dialog_behaviour(view, deferred, { enter: confirm_action, escape: cancel_action }); } } }); }()); (function() { $.extend(scrivito, { workspace_settings_dialog: { open: function(title, memberships) { var promise = $.Deferred(); var view = $(scrivito.template.render('workspace_settings_dialog', { title: title, owners: _.pluck(_.where(memberships, {role: 'owner'}), 'user_id').join() })); view.appendTo($('#scrivito_editing')); var select_owners = view.find('.scrivito_select_owners'); var confirm = function() { var new_memberships = {}; _.each(select_owners.select2('val'), function(user_id) { new_memberships[user_id] = {role: 'owner'}; }); promise.resolve(new_memberships); scrivito.dialog.close(view); return false; }; var cancel = function() { promise.reject(); scrivito.dialog.close(view); return false; }; select_owners.select2({ multiple: true, minimumInputLength: 1, query: scrivito.throttle(function(query) { scrivito.user.suggest(query.term).then(function(users) { query.callback({results: _.map(users, function(user) { return {id: user.id, text: user.description}; })}); }); }, 500), initSelection: function(element, callback) { var value = $(element).val(); if (value) { callback(_.map(value.split(','), function(user_id) { return { id: user_id, text: _.findWhere(memberships, {user_id: user_id}).description, locked: user_id === scrivito.user.current.id() }; })); } }, formatNoMatches: scrivito.t('workspace_settings_dialog.nothing_found'), formatSearching: scrivito.t('workspace_settings_dialog.searching'), formatInputTooShort: scrivito.t('workspace_settings_dialog.too_short') }); view.find('.scrivito_confirm').on('click', confirm); view.find('.scrivito_cancel').on('click', cancel); scrivito.dialog.open_and_adjust(view); view.on('keyup', function(e) { if ((e.keyCode === 13 || e.keyCode === 27) && $(e.target).attr('class').indexOf('select2') > -1) { return false; } }); return scrivito.with_dialog_behaviour(view, promise, {enter: confirm, escape: cancel}); } } }); }()); (function() { $.extend(scrivito, { warn_before_unloading: function() { if (scrivito.write_monitor.is_writing()) { return scrivito.t('warn_before_unloading'); } } }); }()); (function(){ scrivito.obj_clipboard = { save_obj: function(obj) { store_obj(obj); }, is_present: function() { return !!scrivito.storage.has_key(storage_key); }, obj: function() { var data = stored_data(); return scrivito.obj.create_instance({id: data.id, obj_class_name: data.obj_class_name}); }, clear: function() { scrivito.storage.remove(storage_key); } }; var storage_key = 'obj_clipboard'; var store_obj = function(obj) { var data = {id: obj.id(), obj_class_name: obj.obj_class_name()}; scrivito.storage.set(storage_key, data); }; var stored_data = function() { var data = scrivito.storage.get(storage_key); return data || {}; }; })(); (function(){ scrivito.widget_clipboard = { save_widget: function(widget) { store_widget(widget); }, is_present: function() { return !!scrivito.storage.has_key(storage_key); }, widget: function() { var data = stored_data(); var obj = scrivito.obj.create_instance({ id: data.obj_id, obj_class_name: data.obj_class_name }); return scrivito.widget.create_instance(obj, data.id, data.widget_class_name); }, workspace_id: function() { return stored_data().workspace_id; }, clear: function() { scrivito.storage.remove(storage_key); } }; var storage_key = 'widget_clipboard'; var store_widget = function(widget) { var data = { id: widget.id(), widget_class_name: widget.widget_class_name(), obj_id: widget.obj().id(), obj_class_name: widget.obj().obj_class_name(), workspace_id: scrivito.editing_context.selected_workspace.id() }; scrivito.storage.set(storage_key, data); }; var stored_data = function() { var data = scrivito.storage.get(storage_key); return data || {}; }; })(); // // // // // (function() { $(function() { var iframe = $('iframe[name=scrivito_application]'); scrivito.application_window = scrivito.cms_window.from(iframe); // Fallback behavior in case that application window renders a page with no SDK, e.g. an error // or a static page. iframe.on('load', function() { var has_config = !!scrivito.application_document().dom_element() .find('[data-scrivito-private-config]').length; var has_sdk = !!scrivito.application_window.browser_window().scrivito; // The application window is completely missing the SDK and the config. if (!has_config && !has_sdk) { // Install jQuery in order to allow correct application document bootstrapping. var browser_window = scrivito.application_window.browser_window(); if (!browser_window.jQuery) { browser_window.jQuery = jQuery; } if (!browser_window.$) { browser_window.$ = $; } // Bootstrap the application document. var application_document = scrivito.application_document(); application_document.install_public_api(); if (!scrivito.is_inited()) { // Start the UI if it is the first open, which responds with an error. // Use the fallback config with no page context. scrivito.init(scrivito.dom_config.read($('body'))); scrivito.gui.start(); } application_document.connect(); } }); }); }());