PageRenderTime 66ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 2ms

/ajax/libs/thorax/2.0.0rc3/thorax.js

https://bitbucket.org/kolbyjAFK/cdnjs
JavaScript | 15921 lines | 12818 code | 1565 blank | 1538 comment | 2156 complexity | 1dc03ae90e8300b2fe4942338fcf9d7c MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception
  1. /*!
  2. * jQuery JavaScript Library v1.9.0
  3. * http://jquery.com/
  4. *
  5. * Includes Sizzle.js
  6. * http://sizzlejs.com/
  7. *
  8. * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
  9. * Released under the MIT license
  10. * http://jquery.org/license
  11. *
  12. * Date: 2013-1-14
  13. */
  14. (function( window, undefined ) {
  15. "use strict";
  16. var
  17. // A central reference to the root jQuery(document)
  18. rootjQuery,
  19. // The deferred used on DOM ready
  20. readyList,
  21. // Use the correct document accordingly with window argument (sandbox)
  22. document = window.document,
  23. location = window.location,
  24. // Map over jQuery in case of overwrite
  25. _jQuery = window.jQuery,
  26. // Map over the $ in case of overwrite
  27. _$ = window.$,
  28. // [[Class]] -> type pairs
  29. class2type = {},
  30. // List of deleted data cache ids, so we can reuse them
  31. core_deletedIds = [],
  32. core_version = "1.9.0",
  33. // Save a reference to some core methods
  34. core_concat = core_deletedIds.concat,
  35. core_push = core_deletedIds.push,
  36. core_slice = core_deletedIds.slice,
  37. core_indexOf = core_deletedIds.indexOf,
  38. core_toString = class2type.toString,
  39. core_hasOwn = class2type.hasOwnProperty,
  40. core_trim = core_version.trim,
  41. // Define a local copy of jQuery
  42. jQuery = function( selector, context ) {
  43. // The jQuery object is actually just the init constructor 'enhanced'
  44. return new jQuery.fn.init( selector, context, rootjQuery );
  45. },
  46. // Used for matching numbers
  47. core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
  48. // Used for splitting on whitespace
  49. core_rnotwhite = /\S+/g,
  50. // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
  51. rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
  52. // A simple way to check for HTML strings
  53. // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
  54. // Strict HTML recognition (#11290: must start with <)
  55. rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
  56. // Match a standalone tag
  57. rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
  58. // JSON RegExp
  59. rvalidchars = /^[\],:{}\s]*$/,
  60. rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
  61. rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
  62. rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
  63. // Matches dashed string for camelizing
  64. rmsPrefix = /^-ms-/,
  65. rdashAlpha = /-([\da-z])/gi,
  66. // Used by jQuery.camelCase as callback to replace()
  67. fcamelCase = function( all, letter ) {
  68. return letter.toUpperCase();
  69. },
  70. // The ready event handler and self cleanup method
  71. DOMContentLoaded = function() {
  72. if ( document.addEventListener ) {
  73. document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
  74. jQuery.ready();
  75. } else if ( document.readyState === "complete" ) {
  76. // we're here because readyState === "complete" in oldIE
  77. // which is good enough for us to call the dom ready!
  78. document.detachEvent( "onreadystatechange", DOMContentLoaded );
  79. jQuery.ready();
  80. }
  81. };
  82. jQuery.fn = jQuery.prototype = {
  83. // The current version of jQuery being used
  84. jquery: core_version,
  85. constructor: jQuery,
  86. init: function( selector, context, rootjQuery ) {
  87. var match, elem;
  88. // HANDLE: $(""), $(null), $(undefined), $(false)
  89. if ( !selector ) {
  90. return this;
  91. }
  92. // Handle HTML strings
  93. if ( typeof selector === "string" ) {
  94. if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
  95. // Assume that strings that start and end with <> are HTML and skip the regex check
  96. match = [ null, selector, null ];
  97. } else {
  98. match = rquickExpr.exec( selector );
  99. }
  100. // Match html or make sure no context is specified for #id
  101. if ( match && (match[1] || !context) ) {
  102. // HANDLE: $(html) -> $(array)
  103. if ( match[1] ) {
  104. context = context instanceof jQuery ? context[0] : context;
  105. // scripts is true for back-compat
  106. jQuery.merge( this, jQuery.parseHTML(
  107. match[1],
  108. context && context.nodeType ? context.ownerDocument || context : document,
  109. true
  110. ) );
  111. // HANDLE: $(html, props)
  112. if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
  113. for ( match in context ) {
  114. // Properties of context are called as methods if possible
  115. if ( jQuery.isFunction( this[ match ] ) ) {
  116. this[ match ]( context[ match ] );
  117. // ...and otherwise set as attributes
  118. } else {
  119. this.attr( match, context[ match ] );
  120. }
  121. }
  122. }
  123. return this;
  124. // HANDLE: $(#id)
  125. } else {
  126. elem = document.getElementById( match[2] );
  127. // Check parentNode to catch when Blackberry 4.6 returns
  128. // nodes that are no longer in the document #6963
  129. if ( elem && elem.parentNode ) {
  130. // Handle the case where IE and Opera return items
  131. // by name instead of ID
  132. if ( elem.id !== match[2] ) {
  133. return rootjQuery.find( selector );
  134. }
  135. // Otherwise, we inject the element directly into the jQuery object
  136. this.length = 1;
  137. this[0] = elem;
  138. }
  139. this.context = document;
  140. this.selector = selector;
  141. return this;
  142. }
  143. // HANDLE: $(expr, $(...))
  144. } else if ( !context || context.jquery ) {
  145. return ( context || rootjQuery ).find( selector );
  146. // HANDLE: $(expr, context)
  147. // (which is just equivalent to: $(context).find(expr)
  148. } else {
  149. return this.constructor( context ).find( selector );
  150. }
  151. // HANDLE: $(DOMElement)
  152. } else if ( selector.nodeType ) {
  153. this.context = this[0] = selector;
  154. this.length = 1;
  155. return this;
  156. // HANDLE: $(function)
  157. // Shortcut for document ready
  158. } else if ( jQuery.isFunction( selector ) ) {
  159. return rootjQuery.ready( selector );
  160. }
  161. if ( selector.selector !== undefined ) {
  162. this.selector = selector.selector;
  163. this.context = selector.context;
  164. }
  165. return jQuery.makeArray( selector, this );
  166. },
  167. // Start with an empty selector
  168. selector: "",
  169. // The default length of a jQuery object is 0
  170. length: 0,
  171. // The number of elements contained in the matched element set
  172. size: function() {
  173. return this.length;
  174. },
  175. toArray: function() {
  176. return core_slice.call( this );
  177. },
  178. // Get the Nth element in the matched element set OR
  179. // Get the whole matched element set as a clean array
  180. get: function( num ) {
  181. return num == null ?
  182. // Return a 'clean' array
  183. this.toArray() :
  184. // Return just the object
  185. ( num < 0 ? this[ this.length + num ] : this[ num ] );
  186. },
  187. // Take an array of elements and push it onto the stack
  188. // (returning the new matched element set)
  189. pushStack: function( elems ) {
  190. // Build a new jQuery matched element set
  191. var ret = jQuery.merge( this.constructor(), elems );
  192. // Add the old object onto the stack (as a reference)
  193. ret.prevObject = this;
  194. ret.context = this.context;
  195. // Return the newly-formed element set
  196. return ret;
  197. },
  198. // Execute a callback for every element in the matched set.
  199. // (You can seed the arguments with an array of args, but this is
  200. // only used internally.)
  201. each: function( callback, args ) {
  202. return jQuery.each( this, callback, args );
  203. },
  204. ready: function( fn ) {
  205. // Add the callback
  206. jQuery.ready.promise().done( fn );
  207. return this;
  208. },
  209. slice: function() {
  210. return this.pushStack( core_slice.apply( this, arguments ) );
  211. },
  212. first: function() {
  213. return this.eq( 0 );
  214. },
  215. last: function() {
  216. return this.eq( -1 );
  217. },
  218. eq: function( i ) {
  219. var len = this.length,
  220. j = +i + ( i < 0 ? len : 0 );
  221. return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
  222. },
  223. map: function( callback ) {
  224. return this.pushStack( jQuery.map(this, function( elem, i ) {
  225. return callback.call( elem, i, elem );
  226. }));
  227. },
  228. end: function() {
  229. return this.prevObject || this.constructor(null);
  230. },
  231. // For internal use only.
  232. // Behaves like an Array's method, not like a jQuery method.
  233. push: core_push,
  234. sort: [].sort,
  235. splice: [].splice
  236. };
  237. // Give the init function the jQuery prototype for later instantiation
  238. jQuery.fn.init.prototype = jQuery.fn;
  239. jQuery.extend = jQuery.fn.extend = function() {
  240. var options, name, src, copy, copyIsArray, clone,
  241. target = arguments[0] || {},
  242. i = 1,
  243. length = arguments.length,
  244. deep = false;
  245. // Handle a deep copy situation
  246. if ( typeof target === "boolean" ) {
  247. deep = target;
  248. target = arguments[1] || {};
  249. // skip the boolean and the target
  250. i = 2;
  251. }
  252. // Handle case when target is a string or something (possible in deep copy)
  253. if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
  254. target = {};
  255. }
  256. // extend jQuery itself if only one argument is passed
  257. if ( length === i ) {
  258. target = this;
  259. --i;
  260. }
  261. for ( ; i < length; i++ ) {
  262. // Only deal with non-null/undefined values
  263. if ( (options = arguments[ i ]) != null ) {
  264. // Extend the base object
  265. for ( name in options ) {
  266. src = target[ name ];
  267. copy = options[ name ];
  268. // Prevent never-ending loop
  269. if ( target === copy ) {
  270. continue;
  271. }
  272. // Recurse if we're merging plain objects or arrays
  273. if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
  274. if ( copyIsArray ) {
  275. copyIsArray = false;
  276. clone = src && jQuery.isArray(src) ? src : [];
  277. } else {
  278. clone = src && jQuery.isPlainObject(src) ? src : {};
  279. }
  280. // Never move original objects, clone them
  281. target[ name ] = jQuery.extend( deep, clone, copy );
  282. // Don't bring in undefined values
  283. } else if ( copy !== undefined ) {
  284. target[ name ] = copy;
  285. }
  286. }
  287. }
  288. }
  289. // Return the modified object
  290. return target;
  291. };
  292. jQuery.extend({
  293. noConflict: function( deep ) {
  294. if ( window.$ === jQuery ) {
  295. window.$ = _$;
  296. }
  297. if ( deep && window.jQuery === jQuery ) {
  298. window.jQuery = _jQuery;
  299. }
  300. return jQuery;
  301. },
  302. // Is the DOM ready to be used? Set to true once it occurs.
  303. isReady: false,
  304. // A counter to track how many items to wait for before
  305. // the ready event fires. See #6781
  306. readyWait: 1,
  307. // Hold (or release) the ready event
  308. holdReady: function( hold ) {
  309. if ( hold ) {
  310. jQuery.readyWait++;
  311. } else {
  312. jQuery.ready( true );
  313. }
  314. },
  315. // Handle when the DOM is ready
  316. ready: function( wait ) {
  317. // Abort if there are pending holds or we're already ready
  318. if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
  319. return;
  320. }
  321. // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
  322. if ( !document.body ) {
  323. return setTimeout( jQuery.ready );
  324. }
  325. // Remember that the DOM is ready
  326. jQuery.isReady = true;
  327. // If a normal DOM Ready event fired, decrement, and wait if need be
  328. if ( wait !== true && --jQuery.readyWait > 0 ) {
  329. return;
  330. }
  331. // If there are functions bound, to execute
  332. readyList.resolveWith( document, [ jQuery ] );
  333. // Trigger any bound ready events
  334. if ( jQuery.fn.trigger ) {
  335. jQuery( document ).trigger("ready").off("ready");
  336. }
  337. },
  338. // See test/unit/core.js for details concerning isFunction.
  339. // Since version 1.3, DOM methods and functions like alert
  340. // aren't supported. They return false on IE (#2968).
  341. isFunction: function( obj ) {
  342. return jQuery.type(obj) === "function";
  343. },
  344. isArray: Array.isArray || function( obj ) {
  345. return jQuery.type(obj) === "array";
  346. },
  347. isWindow: function( obj ) {
  348. return obj != null && obj == obj.window;
  349. },
  350. isNumeric: function( obj ) {
  351. return !isNaN( parseFloat(obj) ) && isFinite( obj );
  352. },
  353. type: function( obj ) {
  354. if ( obj == null ) {
  355. return String( obj );
  356. }
  357. return typeof obj === "object" || typeof obj === "function" ?
  358. class2type[ core_toString.call(obj) ] || "object" :
  359. typeof obj;
  360. },
  361. isPlainObject: function( obj ) {
  362. // Must be an Object.
  363. // Because of IE, we also have to check the presence of the constructor property.
  364. // Make sure that DOM nodes and window objects don't pass through, as well
  365. if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
  366. return false;
  367. }
  368. try {
  369. // Not own constructor property must be Object
  370. if ( obj.constructor &&
  371. !core_hasOwn.call(obj, "constructor") &&
  372. !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
  373. return false;
  374. }
  375. } catch ( e ) {
  376. // IE8,9 Will throw exceptions on certain host objects #9897
  377. return false;
  378. }
  379. // Own properties are enumerated firstly, so to speed up,
  380. // if last one is own, then all properties are own.
  381. var key;
  382. for ( key in obj ) {}
  383. return key === undefined || core_hasOwn.call( obj, key );
  384. },
  385. isEmptyObject: function( obj ) {
  386. var name;
  387. for ( name in obj ) {
  388. return false;
  389. }
  390. return true;
  391. },
  392. error: function( msg ) {
  393. throw new Error( msg );
  394. },
  395. // data: string of html
  396. // context (optional): If specified, the fragment will be created in this context, defaults to document
  397. // keepScripts (optional): If true, will include scripts passed in the html string
  398. parseHTML: function( data, context, keepScripts ) {
  399. if ( !data || typeof data !== "string" ) {
  400. return null;
  401. }
  402. if ( typeof context === "boolean" ) {
  403. keepScripts = context;
  404. context = false;
  405. }
  406. context = context || document;
  407. var parsed = rsingleTag.exec( data ),
  408. scripts = !keepScripts && [];
  409. // Single tag
  410. if ( parsed ) {
  411. return [ context.createElement( parsed[1] ) ];
  412. }
  413. parsed = jQuery.buildFragment( [ data ], context, scripts );
  414. if ( scripts ) {
  415. jQuery( scripts ).remove();
  416. }
  417. return jQuery.merge( [], parsed.childNodes );
  418. },
  419. parseJSON: function( data ) {
  420. // Attempt to parse using the native JSON parser first
  421. if ( window.JSON && window.JSON.parse ) {
  422. return window.JSON.parse( data );
  423. }
  424. if ( data === null ) {
  425. return data;
  426. }
  427. if ( typeof data === "string" ) {
  428. // Make sure leading/trailing whitespace is removed (IE can't handle it)
  429. data = jQuery.trim( data );
  430. if ( data ) {
  431. // Make sure the incoming data is actual JSON
  432. // Logic borrowed from http://json.org/json2.js
  433. if ( rvalidchars.test( data.replace( rvalidescape, "@" )
  434. .replace( rvalidtokens, "]" )
  435. .replace( rvalidbraces, "")) ) {
  436. return ( new Function( "return " + data ) )();
  437. }
  438. }
  439. }
  440. jQuery.error( "Invalid JSON: " + data );
  441. },
  442. // Cross-browser xml parsing
  443. parseXML: function( data ) {
  444. var xml, tmp;
  445. if ( !data || typeof data !== "string" ) {
  446. return null;
  447. }
  448. try {
  449. if ( window.DOMParser ) { // Standard
  450. tmp = new DOMParser();
  451. xml = tmp.parseFromString( data , "text/xml" );
  452. } else { // IE
  453. xml = new ActiveXObject( "Microsoft.XMLDOM" );
  454. xml.async = "false";
  455. xml.loadXML( data );
  456. }
  457. } catch( e ) {
  458. xml = undefined;
  459. }
  460. if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
  461. jQuery.error( "Invalid XML: " + data );
  462. }
  463. return xml;
  464. },
  465. noop: function() {},
  466. // Evaluates a script in a global context
  467. // Workarounds based on findings by Jim Driscoll
  468. // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
  469. globalEval: function( data ) {
  470. if ( data && jQuery.trim( data ) ) {
  471. // We use execScript on Internet Explorer
  472. // We use an anonymous function so that context is window
  473. // rather than jQuery in Firefox
  474. ( window.execScript || function( data ) {
  475. window[ "eval" ].call( window, data );
  476. } )( data );
  477. }
  478. },
  479. // Convert dashed to camelCase; used by the css and data modules
  480. // Microsoft forgot to hump their vendor prefix (#9572)
  481. camelCase: function( string ) {
  482. return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
  483. },
  484. nodeName: function( elem, name ) {
  485. return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
  486. },
  487. // args is for internal usage only
  488. each: function( obj, callback, args ) {
  489. var value,
  490. i = 0,
  491. length = obj.length,
  492. isArray = isArraylike( obj );
  493. if ( args ) {
  494. if ( isArray ) {
  495. for ( ; i < length; i++ ) {
  496. value = callback.apply( obj[ i ], args );
  497. if ( value === false ) {
  498. break;
  499. }
  500. }
  501. } else {
  502. for ( i in obj ) {
  503. value = callback.apply( obj[ i ], args );
  504. if ( value === false ) {
  505. break;
  506. }
  507. }
  508. }
  509. // A special, fast, case for the most common use of each
  510. } else {
  511. if ( isArray ) {
  512. for ( ; i < length; i++ ) {
  513. value = callback.call( obj[ i ], i, obj[ i ] );
  514. if ( value === false ) {
  515. break;
  516. }
  517. }
  518. } else {
  519. for ( i in obj ) {
  520. value = callback.call( obj[ i ], i, obj[ i ] );
  521. if ( value === false ) {
  522. break;
  523. }
  524. }
  525. }
  526. }
  527. return obj;
  528. },
  529. // Use native String.trim function wherever possible
  530. trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
  531. function( text ) {
  532. return text == null ?
  533. "" :
  534. core_trim.call( text );
  535. } :
  536. // Otherwise use our own trimming functionality
  537. function( text ) {
  538. return text == null ?
  539. "" :
  540. ( text + "" ).replace( rtrim, "" );
  541. },
  542. // results is for internal usage only
  543. makeArray: function( arr, results ) {
  544. var ret = results || [];
  545. if ( arr != null ) {
  546. if ( isArraylike( Object(arr) ) ) {
  547. jQuery.merge( ret,
  548. typeof arr === "string" ?
  549. [ arr ] : arr
  550. );
  551. } else {
  552. core_push.call( ret, arr );
  553. }
  554. }
  555. return ret;
  556. },
  557. inArray: function( elem, arr, i ) {
  558. var len;
  559. if ( arr ) {
  560. if ( core_indexOf ) {
  561. return core_indexOf.call( arr, elem, i );
  562. }
  563. len = arr.length;
  564. i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
  565. for ( ; i < len; i++ ) {
  566. // Skip accessing in sparse arrays
  567. if ( i in arr && arr[ i ] === elem ) {
  568. return i;
  569. }
  570. }
  571. }
  572. return -1;
  573. },
  574. merge: function( first, second ) {
  575. var l = second.length,
  576. i = first.length,
  577. j = 0;
  578. if ( typeof l === "number" ) {
  579. for ( ; j < l; j++ ) {
  580. first[ i++ ] = second[ j ];
  581. }
  582. } else {
  583. while ( second[j] !== undefined ) {
  584. first[ i++ ] = second[ j++ ];
  585. }
  586. }
  587. first.length = i;
  588. return first;
  589. },
  590. grep: function( elems, callback, inv ) {
  591. var retVal,
  592. ret = [],
  593. i = 0,
  594. length = elems.length;
  595. inv = !!inv;
  596. // Go through the array, only saving the items
  597. // that pass the validator function
  598. for ( ; i < length; i++ ) {
  599. retVal = !!callback( elems[ i ], i );
  600. if ( inv !== retVal ) {
  601. ret.push( elems[ i ] );
  602. }
  603. }
  604. return ret;
  605. },
  606. // arg is for internal usage only
  607. map: function( elems, callback, arg ) {
  608. var value,
  609. i = 0,
  610. length = elems.length,
  611. isArray = isArraylike( elems ),
  612. ret = [];
  613. // Go through the array, translating each of the items to their
  614. if ( isArray ) {
  615. for ( ; i < length; i++ ) {
  616. value = callback( elems[ i ], i, arg );
  617. if ( value != null ) {
  618. ret[ ret.length ] = value;
  619. }
  620. }
  621. // Go through every key on the object,
  622. } else {
  623. for ( i in elems ) {
  624. value = callback( elems[ i ], i, arg );
  625. if ( value != null ) {
  626. ret[ ret.length ] = value;
  627. }
  628. }
  629. }
  630. // Flatten any nested arrays
  631. return core_concat.apply( [], ret );
  632. },
  633. // A global GUID counter for objects
  634. guid: 1,
  635. // Bind a function to a context, optionally partially applying any
  636. // arguments.
  637. proxy: function( fn, context ) {
  638. var tmp, args, proxy;
  639. if ( typeof context === "string" ) {
  640. tmp = fn[ context ];
  641. context = fn;
  642. fn = tmp;
  643. }
  644. // Quick check to determine if target is callable, in the spec
  645. // this throws a TypeError, but we will just return undefined.
  646. if ( !jQuery.isFunction( fn ) ) {
  647. return undefined;
  648. }
  649. // Simulated bind
  650. args = core_slice.call( arguments, 2 );
  651. proxy = function() {
  652. return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
  653. };
  654. // Set the guid of unique handler to the same of original handler, so it can be removed
  655. proxy.guid = fn.guid = fn.guid || jQuery.guid++;
  656. return proxy;
  657. },
  658. // Multifunctional method to get and set values of a collection
  659. // The value/s can optionally be executed if it's a function
  660. access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
  661. var i = 0,
  662. length = elems.length,
  663. bulk = key == null;
  664. // Sets many values
  665. if ( jQuery.type( key ) === "object" ) {
  666. chainable = true;
  667. for ( i in key ) {
  668. jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
  669. }
  670. // Sets one value
  671. } else if ( value !== undefined ) {
  672. chainable = true;
  673. if ( !jQuery.isFunction( value ) ) {
  674. raw = true;
  675. }
  676. if ( bulk ) {
  677. // Bulk operations run against the entire set
  678. if ( raw ) {
  679. fn.call( elems, value );
  680. fn = null;
  681. // ...except when executing function values
  682. } else {
  683. bulk = fn;
  684. fn = function( elem, key, value ) {
  685. return bulk.call( jQuery( elem ), value );
  686. };
  687. }
  688. }
  689. if ( fn ) {
  690. for ( ; i < length; i++ ) {
  691. fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
  692. }
  693. }
  694. }
  695. return chainable ?
  696. elems :
  697. // Gets
  698. bulk ?
  699. fn.call( elems ) :
  700. length ? fn( elems[0], key ) : emptyGet;
  701. },
  702. now: function() {
  703. return ( new Date() ).getTime();
  704. }
  705. });
  706. jQuery.ready.promise = function( obj ) {
  707. if ( !readyList ) {
  708. readyList = jQuery.Deferred();
  709. // Catch cases where $(document).ready() is called after the browser event has already occurred.
  710. // we once tried to use readyState "interactive" here, but it caused issues like the one
  711. // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
  712. if ( document.readyState === "complete" ) {
  713. // Handle it asynchronously to allow scripts the opportunity to delay ready
  714. setTimeout( jQuery.ready );
  715. // Standards-based browsers support DOMContentLoaded
  716. } else if ( document.addEventListener ) {
  717. // Use the handy event callback
  718. document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
  719. // A fallback to window.onload, that will always work
  720. window.addEventListener( "load", jQuery.ready, false );
  721. // If IE event model is used
  722. } else {
  723. // Ensure firing before onload, maybe late but safe also for iframes
  724. document.attachEvent( "onreadystatechange", DOMContentLoaded );
  725. // A fallback to window.onload, that will always work
  726. window.attachEvent( "onload", jQuery.ready );
  727. // If IE and not a frame
  728. // continually check to see if the document is ready
  729. var top = false;
  730. try {
  731. top = window.frameElement == null && document.documentElement;
  732. } catch(e) {}
  733. if ( top && top.doScroll ) {
  734. (function doScrollCheck() {
  735. if ( !jQuery.isReady ) {
  736. try {
  737. // Use the trick by Diego Perini
  738. // http://javascript.nwbox.com/IEContentLoaded/
  739. top.doScroll("left");
  740. } catch(e) {
  741. return setTimeout( doScrollCheck, 50 );
  742. }
  743. // and execute any waiting functions
  744. jQuery.ready();
  745. }
  746. })();
  747. }
  748. }
  749. }
  750. return readyList.promise( obj );
  751. };
  752. // Populate the class2type map
  753. jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
  754. class2type[ "[object " + name + "]" ] = name.toLowerCase();
  755. });
  756. function isArraylike( obj ) {
  757. var length = obj.length,
  758. type = jQuery.type( obj );
  759. if ( jQuery.isWindow( obj ) ) {
  760. return false;
  761. }
  762. if ( obj.nodeType === 1 && length ) {
  763. return true;
  764. }
  765. return type === "array" || type !== "function" &&
  766. ( length === 0 ||
  767. typeof length === "number" && length > 0 && ( length - 1 ) in obj );
  768. }
  769. // All jQuery objects should point back to these
  770. rootjQuery = jQuery(document);
  771. // String to Object options format cache
  772. var optionsCache = {};
  773. // Convert String-formatted options into Object-formatted ones and store in cache
  774. function createOptions( options ) {
  775. var object = optionsCache[ options ] = {};
  776. jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
  777. object[ flag ] = true;
  778. });
  779. return object;
  780. }
  781. /*
  782. * Create a callback list using the following parameters:
  783. *
  784. * options: an optional list of space-separated options that will change how
  785. * the callback list behaves or a more traditional option object
  786. *
  787. * By default a callback list will act like an event callback list and can be
  788. * "fired" multiple times.
  789. *
  790. * Possible options:
  791. *
  792. * once: will ensure the callback list can only be fired once (like a Deferred)
  793. *
  794. * memory: will keep track of previous values and will call any callback added
  795. * after the list has been fired right away with the latest "memorized"
  796. * values (like a Deferred)
  797. *
  798. * unique: will ensure a callback can only be added once (no duplicate in the list)
  799. *
  800. * stopOnFalse: interrupt callings when a callback returns false
  801. *
  802. */
  803. jQuery.Callbacks = function( options ) {
  804. // Convert options from String-formatted to Object-formatted if needed
  805. // (we check in cache first)
  806. options = typeof options === "string" ?
  807. ( optionsCache[ options ] || createOptions( options ) ) :
  808. jQuery.extend( {}, options );
  809. var // Last fire value (for non-forgettable lists)
  810. memory,
  811. // Flag to know if list was already fired
  812. fired,
  813. // Flag to know if list is currently firing
  814. firing,
  815. // First callback to fire (used internally by add and fireWith)
  816. firingStart,
  817. // End of the loop when firing
  818. firingLength,
  819. // Index of currently firing callback (modified by remove if needed)
  820. firingIndex,
  821. // Actual callback list
  822. list = [],
  823. // Stack of fire calls for repeatable lists
  824. stack = !options.once && [],
  825. // Fire callbacks
  826. fire = function( data ) {
  827. memory = options.memory && data;
  828. fired = true;
  829. firingIndex = firingStart || 0;
  830. firingStart = 0;
  831. firingLength = list.length;
  832. firing = true;
  833. for ( ; list && firingIndex < firingLength; firingIndex++ ) {
  834. if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
  835. memory = false; // To prevent further calls using add
  836. break;
  837. }
  838. }
  839. firing = false;
  840. if ( list ) {
  841. if ( stack ) {
  842. if ( stack.length ) {
  843. fire( stack.shift() );
  844. }
  845. } else if ( memory ) {
  846. list = [];
  847. } else {
  848. self.disable();
  849. }
  850. }
  851. },
  852. // Actual Callbacks object
  853. self = {
  854. // Add a callback or a collection of callbacks to the list
  855. add: function() {
  856. if ( list ) {
  857. // First, we save the current length
  858. var start = list.length;
  859. (function add( args ) {
  860. jQuery.each( args, function( _, arg ) {
  861. var type = jQuery.type( arg );
  862. if ( type === "function" ) {
  863. if ( !options.unique || !self.has( arg ) ) {
  864. list.push( arg );
  865. }
  866. } else if ( arg && arg.length && type !== "string" ) {
  867. // Inspect recursively
  868. add( arg );
  869. }
  870. });
  871. })( arguments );
  872. // Do we need to add the callbacks to the
  873. // current firing batch?
  874. if ( firing ) {
  875. firingLength = list.length;
  876. // With memory, if we're not firing then
  877. // we should call right away
  878. } else if ( memory ) {
  879. firingStart = start;
  880. fire( memory );
  881. }
  882. }
  883. return this;
  884. },
  885. // Remove a callback from the list
  886. remove: function() {
  887. if ( list ) {
  888. jQuery.each( arguments, function( _, arg ) {
  889. var index;
  890. while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
  891. list.splice( index, 1 );
  892. // Handle firing indexes
  893. if ( firing ) {
  894. if ( index <= firingLength ) {
  895. firingLength--;
  896. }
  897. if ( index <= firingIndex ) {
  898. firingIndex--;
  899. }
  900. }
  901. }
  902. });
  903. }
  904. return this;
  905. },
  906. // Control if a given callback is in the list
  907. has: function( fn ) {
  908. return jQuery.inArray( fn, list ) > -1;
  909. },
  910. // Remove all callbacks from the list
  911. empty: function() {
  912. list = [];
  913. return this;
  914. },
  915. // Have the list do nothing anymore
  916. disable: function() {
  917. list = stack = memory = undefined;
  918. return this;
  919. },
  920. // Is it disabled?
  921. disabled: function() {
  922. return !list;
  923. },
  924. // Lock the list in its current state
  925. lock: function() {
  926. stack = undefined;
  927. if ( !memory ) {
  928. self.disable();
  929. }
  930. return this;
  931. },
  932. // Is it locked?
  933. locked: function() {
  934. return !stack;
  935. },
  936. // Call all callbacks with the given context and arguments
  937. fireWith: function( context, args ) {
  938. args = args || [];
  939. args = [ context, args.slice ? args.slice() : args ];
  940. if ( list && ( !fired || stack ) ) {
  941. if ( firing ) {
  942. stack.push( args );
  943. } else {
  944. fire( args );
  945. }
  946. }
  947. return this;
  948. },
  949. // Call all the callbacks with the given arguments
  950. fire: function() {
  951. self.fireWith( this, arguments );
  952. return this;
  953. },
  954. // To know if the callbacks have already been called at least once
  955. fired: function() {
  956. return !!fired;
  957. }
  958. };
  959. return self;
  960. };
  961. jQuery.extend({
  962. Deferred: function( func ) {
  963. var tuples = [
  964. // action, add listener, listener list, final state
  965. [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
  966. [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
  967. [ "notify", "progress", jQuery.Callbacks("memory") ]
  968. ],
  969. state = "pending",
  970. promise = {
  971. state: function() {
  972. return state;
  973. },
  974. always: function() {
  975. deferred.done( arguments ).fail( arguments );
  976. return this;
  977. },
  978. then: function( /* fnDone, fnFail, fnProgress */ ) {
  979. var fns = arguments;
  980. return jQuery.Deferred(function( newDefer ) {
  981. jQuery.each( tuples, function( i, tuple ) {
  982. var action = tuple[ 0 ],
  983. fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
  984. // deferred[ done | fail | progress ] for forwarding actions to newDefer
  985. deferred[ tuple[1] ](function() {
  986. var returned = fn && fn.apply( this, arguments );
  987. if ( returned && jQuery.isFunction( returned.promise ) ) {
  988. returned.promise()
  989. .done( newDefer.resolve )
  990. .fail( newDefer.reject )
  991. .progress( newDefer.notify );
  992. } else {
  993. newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
  994. }
  995. });
  996. });
  997. fns = null;
  998. }).promise();
  999. },
  1000. // Get a promise for this deferred
  1001. // If obj is provided, the promise aspect is added to the object
  1002. promise: function( obj ) {
  1003. return obj != null ? jQuery.extend( obj, promise ) : promise;
  1004. }
  1005. },
  1006. deferred = {};
  1007. // Keep pipe for back-compat
  1008. promise.pipe = promise.then;
  1009. // Add list-specific methods
  1010. jQuery.each( tuples, function( i, tuple ) {
  1011. var list = tuple[ 2 ],
  1012. stateString = tuple[ 3 ];
  1013. // promise[ done | fail | progress ] = list.add
  1014. promise[ tuple[1] ] = list.add;
  1015. // Handle state
  1016. if ( stateString ) {
  1017. list.add(function() {
  1018. // state = [ resolved | rejected ]
  1019. state = stateString;
  1020. // [ reject_list | resolve_list ].disable; progress_list.lock
  1021. }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
  1022. }
  1023. // deferred[ resolve | reject | notify ]
  1024. deferred[ tuple[0] ] = function() {
  1025. deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
  1026. return this;
  1027. };
  1028. deferred[ tuple[0] + "With" ] = list.fireWith;
  1029. });
  1030. // Make the deferred a promise
  1031. promise.promise( deferred );
  1032. // Call given func if any
  1033. if ( func ) {
  1034. func.call( deferred, deferred );
  1035. }
  1036. // All done!
  1037. return deferred;
  1038. },
  1039. // Deferred helper
  1040. when: function( subordinate /* , ..., subordinateN */ ) {
  1041. var i = 0,
  1042. resolveValues = core_slice.call( arguments ),
  1043. length = resolveValues.length,
  1044. // the count of uncompleted subordinates
  1045. remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
  1046. // the master Deferred. If resolveValues consist of only a single Deferred, just use that.
  1047. deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
  1048. // Update function for both resolve and progress values
  1049. updateFunc = function( i, contexts, values ) {
  1050. return function( value ) {
  1051. contexts[ i ] = this;
  1052. values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
  1053. if( values === progressValues ) {
  1054. deferred.notifyWith( contexts, values );
  1055. } else if ( !( --remaining ) ) {
  1056. deferred.resolveWith( contexts, values );
  1057. }
  1058. };
  1059. },
  1060. progressValues, progressContexts, resolveContexts;
  1061. // add listeners to Deferred subordinates; treat others as resolved
  1062. if ( length > 1 ) {
  1063. progressValues = new Array( length );
  1064. progressContexts = new Array( length );
  1065. resolveContexts = new Array( length );
  1066. for ( ; i < length; i++ ) {
  1067. if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
  1068. resolveValues[ i ].promise()
  1069. .done( updateFunc( i, resolveContexts, resolveValues ) )
  1070. .fail( deferred.reject )
  1071. .progress( updateFunc( i, progressContexts, progressValues ) );
  1072. } else {
  1073. --remaining;
  1074. }
  1075. }
  1076. }
  1077. // if we're not waiting on anything, resolve the master
  1078. if ( !remaining ) {
  1079. deferred.resolveWith( resolveContexts, resolveValues );
  1080. }
  1081. return deferred.promise();
  1082. }
  1083. });
  1084. jQuery.support = (function() {
  1085. var support, all, a, select, opt, input, fragment, eventName, isSupported, i,
  1086. div = document.createElement("div");
  1087. // Setup
  1088. div.setAttribute( "className", "t" );
  1089. div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
  1090. // Support tests won't run in some limited or non-browser environments
  1091. all = div.getElementsByTagName("*");
  1092. a = div.getElementsByTagName("a")[ 0 ];
  1093. if ( !all || !a || !all.length ) {
  1094. return {};
  1095. }
  1096. // First batch of tests
  1097. select = document.createElement("select");
  1098. opt = select.appendChild( document.createElement("option") );
  1099. input = div.getElementsByTagName("input")[ 0 ];
  1100. a.style.cssText = "top:1px;float:left;opacity:.5";
  1101. support = {
  1102. // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
  1103. getSetAttribute: div.className !== "t",
  1104. // IE strips leading whitespace when .innerHTML is used
  1105. leadingWhitespace: div.firstChild.nodeType === 3,
  1106. // Make sure that tbody elements aren't automatically inserted
  1107. // IE will insert them into empty tables
  1108. tbody: !div.getElementsByTagName("tbody").length,
  1109. // Make sure that link elements get serialized correctly by innerHTML
  1110. // This requires a wrapper element in IE
  1111. htmlSerialize: !!div.getElementsByTagName("link").length,
  1112. // Get the style information from getAttribute
  1113. // (IE uses .cssText instead)
  1114. style: /top/.test( a.getAttribute("style") ),
  1115. // Make sure that URLs aren't manipulated
  1116. // (IE normalizes it by default)
  1117. hrefNormalized: a.getAttribute("href") === "/a",
  1118. // Make sure that element opacity exists
  1119. // (IE uses filter instead)
  1120. // Use a regex to work around a WebKit issue. See #5145
  1121. opacity: /^0.5/.test( a.style.opacity ),
  1122. // Verify style float existence
  1123. // (IE uses styleFloat instead of cssFloat)
  1124. cssFloat: !!a.style.cssFloat,
  1125. // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
  1126. checkOn: !!input.value,
  1127. // Make sure that a selected-by-default option has a working selected property.
  1128. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
  1129. optSelected: opt.selected,
  1130. // Tests for enctype support on a form (#6743)
  1131. enctype: !!document.createElement("form").enctype,
  1132. // Makes sure cloning an html5 element does not cause problems
  1133. // Where outerHTML is undefined, this still works
  1134. html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
  1135. // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
  1136. boxModel: document.compatMode === "CSS1Compat",
  1137. // Will be defined later
  1138. deleteExpando: true,
  1139. noCloneEvent: true,
  1140. inlineBlockNeedsLayout: false,
  1141. shrinkWrapBlocks: false,
  1142. reliableMarginRight: true,
  1143. boxSizingReliable: true,
  1144. pixelPosition: false
  1145. };
  1146. // Make sure checked status is properly cloned
  1147. input.checked = true;
  1148. support.noCloneChecked = input.cloneNode( true ).checked;
  1149. // Make sure that the options inside disabled selects aren't marked as disabled
  1150. // (WebKit marks them as disabled)
  1151. select.disabled = true;
  1152. support.optDisabled = !opt.disabled;
  1153. // Support: IE<9
  1154. try {
  1155. delete div.test;
  1156. } catch( e ) {
  1157. support.deleteExpando = false;
  1158. }
  1159. // Check if we can trust getAttribute("value")
  1160. input = document.createElement("input");
  1161. input.setAttribute( "value", "" );
  1162. support.input = input.getAttribute( "value" ) === "";
  1163. // Check if an input maintains its value after becoming a radio
  1164. input.value = "t";
  1165. input.setAttribute( "type", "radio" );
  1166. support.radioValue = input.value === "t";
  1167. // #11217 - WebKit loses check when the name is after the checked attribute
  1168. input.setAttribute( "checked", "t" );
  1169. input.setAttribute( "name", "t" );
  1170. fragment = document.createDocumentFragment();
  1171. fragment.appendChild( input );
  1172. // Check if a disconnected checkbox will retain its checked
  1173. // value of true after appended to the DOM (IE6/7)
  1174. support.appendChecked = input.checked;
  1175. // WebKit doesn't clone checked state correctly in fragments
  1176. support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
  1177. // Support: IE<9
  1178. // Opera does not clone events (and typeof div.attachEvent === undefined).
  1179. // IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
  1180. if ( div.attachEvent ) {
  1181. div.attachEvent( "onclick", function() {
  1182. support.noCloneEvent = false;
  1183. });
  1184. div.cloneNode( true ).click();
  1185. }
  1186. // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
  1187. // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php
  1188. for ( i in { submit: true, change: true, focusin: true }) {
  1189. div.setAttribute( eventName = "on" + i, "t" );
  1190. support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
  1191. }
  1192. div.style.backgroundClip = "content-box";
  1193. div.cloneNode( true ).style.backgroundClip = "";
  1194. support.clearCloneStyle = div.style.backgroundClip === "content-box";
  1195. // Run tests that need a body at doc ready
  1196. jQuery(function() {
  1197. var container, marginDiv, tds,
  1198. divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
  1199. body = document.getElementsByTagName("body")[0];
  1200. if ( !body ) {
  1201. // Return for frameset docs that don't have a body
  1202. return;
  1203. }
  1204. container = document.createElement("div");
  1205. container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
  1206. body.appendChild( container ).appendChild( div );
  1207. // Support: IE8
  1208. // Check if table cells still have offsetWidth/Height when they are set
  1209. // to display:none and there are still other visible table cells in a
  1210. // table row; if so, offsetWidth/Height are not reliable for use when
  1211. // determining if an element has been hidden directly using
  1212. // display:none (it is still safe to use offsets if a parent element is
  1213. // hidden; don safety goggles and see bug #4512 for more information).
  1214. div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
  1215. tds = div.getElementsByTagName("td");
  1216. tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
  1217. isSupported = ( tds[ 0 ].offsetHeight === 0 );
  1218. tds[ 0 ].style.display = "";
  1219. tds[ 1 ].style.display = "none";
  1220. // Support: IE8
  1221. // Check if empty table cells still have offsetWidth/Height
  1222. support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
  1223. // Check box-sizing and margin behavior
  1224. div.innerHTML = "";
  1225. div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
  1226. support.boxSizing = ( div.offsetWidth === 4 );
  1227. support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
  1228. // Use window.getComputedStyle because jsdom on node.js will break without it.
  1229. if ( window.getComputedStyle ) {
  1230. support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
  1231. support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
  1232. // Check if div with explicit width and no margin-right incorrectly
  1233. // gets computed margin-right based on width of container. (#3333)
  1234. // Fails in WebKit before Feb 2011 nightlies
  1235. // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
  1236. marginDiv = div.appendChild( document.createElement("div") );
  1237. marginDiv.style.cssText = div.style.cssText = divReset;
  1238. marginDiv.style.marginRight = marginDiv.style.width = "0";
  1239. div.style.width = "1px";
  1240. support.reliableMarginRight =
  1241. !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
  1242. }
  1243. if ( typeof div.style.zoom !== "undefined" ) {
  1244. // Support: IE<8
  1245. // Check if natively block-level elements act like inline-block
  1246. // elements when setting their display to 'inline' and giving
  1247. // them layout
  1248. div.innerHTML = "";
  1249. div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
  1250. support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
  1251. // Support: IE6
  1252. // Check if elements with layout shrink-wrap their children
  1253. div.style.display = "block";
  1254. div.innerHTML = "<div></div>";
  1255. div.firstChild.style.width = "5px";
  1256. support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
  1257. // Prevent IE 6 from affecting layout for positioned elements #11048
  1258. // Prevent IE from shrinking the body in IE 7 mode #12869
  1259. body.style.zoom = 1;
  1260. }
  1261. body.removeChild( container );
  1262. // Null elements to avoid leaks in IE
  1263. container = div = tds = marginDiv = null;
  1264. });
  1265. // Null elements to avoid leaks in IE
  1266. all = select = fragment = opt = a = input = null;
  1267. return support;
  1268. })();
  1269. var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
  1270. rmultiDash = /([A-Z])/g;
  1271. function internalData( elem, name, data, pvt /* Internal Use Only */ ){
  1272. if ( !jQuery.acceptData( elem ) ) {
  1273. return;
  1274. }
  1275. var thisCache, ret,
  1276. internalKey = jQuery.expando,
  1277. getByName = typeof name === "string",
  1278. // We have to handle DOM nodes and JS objects differently because IE6-7
  1279. // can't GC object references properly across the DOM-JS boundary
  1280. isNode = elem.nodeType,
  1281. // Only DOM nodes need the global jQuery cache; JS object data is
  1282. // attached directly to the object so GC can occur automatically
  1283. cache = isNode ? jQuery.cache : elem,
  1284. // Only defining an ID for JS objects if its cache already exists allows
  1285. // the code to shortcut on the same path as a DOM node with no cache
  1286. id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
  1287. // Avoid doing any more work than we need to when trying to get data on an
  1288. // object that has no data at all
  1289. if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
  1290. return;
  1291. }
  1292. if ( !id ) {
  1293. // Only DOM nodes need a new unique ID for each element since their data
  1294. // ends up in the global cache
  1295. if ( isNode ) {
  1296. elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++;
  1297. } else {
  1298. id = internalKey;
  1299. }
  1300. }
  1301. if ( !cache[ id ] ) {
  1302. cache[ id ] = {};
  1303. // Avoids exposing jQuery metadata on plain JS objects when the object
  1304. // is serialized using JSON.stringify
  1305. if ( !isNode ) {
  1306. cache[ id ].toJSON = jQuery.noop;
  1307. }
  1308. }
  1309. // An object can be passed to jQuery.data instead of a key/value pair; this gets
  1310. // shallow copied over onto the existing cache
  1311. if ( typeof name === "object" || typeof name === "function" ) {
  1312. if ( pvt ) {
  1313. cache[ id ] = jQuery.extend( cache[ id ], name );
  1314. } else {
  1315. cache[ id ].data = jQuery.extend( cache[ id ].data, name );
  1316. }
  1317. }
  1318. thisCache = cache[ id ];
  1319. // jQuery data() is stored in a separate object inside the object's internal data
  1320. // cache in order to avoid key collisions between internal data and user-defined
  1321. // data.
  1322. if ( !pvt ) {
  1323. if ( !thisCache.data ) {
  1324. thisCache.data = {};
  1325. }
  1326. thisCache = thisCache.data;
  1327. }
  1328. if ( data !== undefined ) {
  1329. thisCache[ jQuery.camelCase( name ) ] = data;
  1330. }
  1331. // Check for both converted-to-camel and non-converted data property names
  1332. // If a data property was specified
  1333. if ( getByName ) {
  1334. // First Try to find as-is property data
  1335. ret = thisCache[ name ];
  1336. // Test for null|undefined property data
  1337. if ( ret == null ) {
  1338. // Try to find the camelCased property
  1339. ret = thisCache[ jQuery.camelCase( name ) ];
  1340. }
  1341. } else {
  1342. ret = thisCache;
  1343. }
  1344. return ret;
  1345. }
  1346. function internalRemoveData( elem, name, pvt /* For internal use only */ ){
  1347. if ( !jQuery.acceptData( elem ) ) {
  1348. return;
  1349. }
  1350. var thisCache, i, l,
  1351. isNode = elem.nodeType,
  1352. // See jQuery.data for more information
  1353. cache = isNode ? jQuery.cache : elem,
  1354. id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
  1355. // If there is already no cache entry for this object, there is no
  1356. // purpose in continuing
  1357. if ( !cache[ id ] ) {
  1358. return;
  1359. }
  1360. if ( name ) {
  1361. thisCache = pvt ? cache[ id ] : cache[ id ].data;
  1362. if ( thisCache ) {
  1363. // Support array or space separated string names for data keys
  1364. if ( !jQuery.isArray( name ) ) {
  1365. // try the string as a key before any manipulation
  1366. if ( name in thisCache ) {
  1367. name = [ name ];
  1368. } else {
  1369. // split the camel cased version by spaces unless a key with the spaces exists
  1370. name = jQuery.camelCase( name );
  1371. if ( name in thisCache ) {
  1372. name = [ name ];
  1373. } else {
  1374. name = name.split(" ");
  1375. }
  1376. }
  1377. } else {
  1378. // If "name" is an array of keys...
  1379. // When data is initially created, via ("key", "val") signature,
  1380. // keys will be converted to camelCase.
  1381. // Since there is no way to tell _how_ a key was added, remove
  1382. // both plain key and camelCase key. #12786
  1383. // This will only penalize the array argument path.
  1384. name = name.concat( jQuery.map( name, jQuery.camelCase ) );
  1385. }
  1386. for ( i = 0, l = name.length; i < l; i++ ) {
  1387. delete thisCache[ name[i] ];
  1388. }
  1389. // If there is no data left in the cache, we want to continue
  1390. // and let the cache object itself get destroyed
  1391. if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
  1392. return;
  1393. }
  1394. }
  1395. }
  1396. // See jQuery.data for more information
  1397. if ( !pvt ) {
  1398. delete cache[ id ].data;
  1399. // Don't destroy the parent cache unless the internal data object
  1400. // had been the only thing left in it
  1401. if ( !isEmptyDataObject( cache[ id ] ) ) {
  1402. return;
  1403. }
  1404. }
  1405. // Destroy the cache
  1406. if ( isNode ) {
  1407. jQuery.cleanData( [ elem ], true );
  1408. // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
  1409. } else if ( jQuery.support.deleteExpando || cache != cache.window ) {
  1410. delete cache[ id ];
  1411. // When all else fails, null
  1412. } else {
  1413. cache[ id ] = null;
  1414. }
  1415. }
  1416. jQuery.extend({
  1417. cache: {},
  1418. // Unique for each copy of jQuery on the page
  1419. // Non-digits removed to match rinlinejQuery
  1420. expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
  1421. // The following elements throw uncatchable exceptions if you
  1422. // attempt to add expando properties to them.
  1423. noData: {
  1424. "embed": true,
  1425. // Ban all objects except for Flash (which handle expandos)
  1426. "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
  1427. "applet": true
  1428. },
  1429. hasData: function( elem ) {
  1430. elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
  1431. return !!elem && !isEmptyDataObject( elem );
  1432. },
  1433. data: function( elem, name, data ) {
  1434. return internalData( elem, name, data, false );
  1435. },
  1436. removeData: function( elem, name ) {
  1437. return internalRemoveData( elem, name, false );
  1438. },
  1439. // For internal use only.
  1440. _data: function( elem, name, data ) {
  1441. return internalData( elem, name, data, true );
  1442. },
  1443. _removeData: function( elem, name ) {
  1444. return internalRemoveData( elem, name, true );
  1445. },
  1446. // A method for determining if a DOM node can handle the data expando
  1447. acceptData: function( elem ) {
  1448. var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
  1449. // nodes accept data unless otherwise specified; rejection can be conditional
  1450. return !noData || noData !== true && elem.getAttribute("classid") === noData;
  1451. }
  1452. });
  1453. jQuery.fn.extend({
  1454. data: function( key, value ) {
  1455. var attrs, name,
  1456. elem = this[0],
  1457. i = 0,
  1458. data = null;
  1459. // Gets all values
  1460. if ( key === undefined ) {
  1461. if ( this.length ) {
  1462. data = jQuery.data( elem );
  1463. if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
  1464. attrs = elem.attributes;
  1465. for ( ; i < attrs.length; i++ ) {
  1466. name = attrs[i].name;
  1467. if ( !name.indexOf( "data-" ) ) {
  1468. name = jQuery.camelCase( name.substring(5) );
  1469. dataAttr( elem, name, data[ name ] );
  1470. }
  1471. }
  1472. jQuery._data( elem, "parsedAttrs", true );
  1473. }
  1474. }
  1475. return data;
  1476. }
  1477. // Sets multiple values
  1478. if ( typeof key === "object" ) {
  1479. return this.each(function() {
  1480. jQuery.data( this, key );
  1481. });
  1482. }
  1483. return jQuery.access( this, function( value ) {
  1484. if ( value === undefined ) {
  1485. // Try to fetch any internally stored data first
  1486. return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
  1487. }
  1488. this.each(function() {
  1489. jQuery.data( this, key, value );
  1490. });
  1491. }, null, value, arguments.length > 1, null, true );
  1492. },
  1493. removeData: function( key ) {
  1494. return this.each(function() {
  1495. jQuery.removeData( this, key );
  1496. });
  1497. }
  1498. });
  1499. function dataAttr( elem, key, data ) {
  1500. // If nothing was found internally, try to fetch any
  1501. // data from the HTML5 data-* attribute
  1502. if ( data === undefined && elem.nodeType === 1 ) {
  1503. var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
  1504. data = elem.getAttribute( name );
  1505. if ( typeof data === "string" ) {
  1506. try {
  1507. data = data === "true" ? true :
  1508. data === "false" ? false :
  1509. data === "null" ? null :
  1510. // Only convert to a number if it doesn't change the string
  1511. +data + "" === data ? +data :
  1512. rbrace.test( data ) ? jQuery.parseJSON( data ) :
  1513. data;
  1514. } catch( e ) {}
  1515. // Make sure we set the data so it isn't changed later
  1516. jQuery.data( elem, key, data );
  1517. } else {
  1518. data = undefined;
  1519. }
  1520. }
  1521. return data;
  1522. }
  1523. // checks a cache object for emptiness
  1524. function isEmptyDataObject( obj ) {
  1525. var name;
  1526. for ( name in obj ) {
  1527. // if the public data object is empty, the private is still empty
  1528. if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
  1529. continue;
  1530. }
  1531. if ( name !== "toJSON" ) {
  1532. return false;
  1533. }
  1534. }
  1535. return true;
  1536. }
  1537. jQuery.extend({
  1538. queue: function( elem, type, data ) {
  1539. var queue;
  1540. if ( elem ) {
  1541. type = ( type || "fx" ) + "queue";
  1542. queue = jQuery._data( elem, type );
  1543. // Speed up dequeue by getting out quickly if this is just a lookup
  1544. if ( data ) {
  1545. if ( !queue || jQuery.isArray(data) ) {
  1546. queue = jQuery._data( elem, type, jQuery.makeArray(data) );
  1547. } else {
  1548. queue.push( data );
  1549. }
  1550. }
  1551. return queue || [];
  1552. }
  1553. },
  1554. dequeue: function( elem, type ) {
  1555. type = type || "fx";
  1556. var queue = jQuery.queue( elem, type ),
  1557. startLength = queue.length,
  1558. fn = queue.shift(),
  1559. hooks = jQuery._queueHooks( elem, type ),
  1560. next = function() {
  1561. jQuery.dequeue( elem, type );
  1562. };
  1563. // If the fx queue is dequeued, always remove the progress sentinel
  1564. if ( fn === "inprogress" ) {
  1565. fn = queue.shift();
  1566. startLength--;
  1567. }
  1568. hooks.cur = fn;
  1569. if ( fn ) {
  1570. // Add a progress sentinel to prevent the fx queue from being
  1571. // automatically dequeued
  1572. if ( type === "fx" ) {
  1573. queue.unshift( "inprogress" );
  1574. }
  1575. // clear up the last queue stop function
  1576. delete hooks.stop;
  1577. fn.call( elem, next, hooks );
  1578. }
  1579. if ( !startLength && hooks ) {
  1580. hooks.empty.fire();
  1581. }
  1582. },
  1583. // not intended for public consumption - generates a queueHooks object, or returns the current one
  1584. _queueHooks: function( elem, type ) {
  1585. var key = type + "queueHooks";
  1586. return jQuery._data( elem, key ) || jQuery._data( elem, key, {
  1587. empty: jQuery.Callbacks("once memory").add(function() {
  1588. jQuery._removeData( elem, type + "queue" );
  1589. jQuery._removeData( elem, key );
  1590. })
  1591. });
  1592. }
  1593. });
  1594. jQuery.fn.extend({
  1595. queue: function( type, data ) {
  1596. var setter = 2;
  1597. if ( typeof type !== "string" ) {
  1598. data = type;
  1599. type = "fx";
  1600. setter--;
  1601. }
  1602. if ( arguments.length < setter ) {
  1603. return jQuery.queue( this[0], type );
  1604. }
  1605. return data === undefined ?
  1606. this :
  1607. this.each(function() {
  1608. var queue = jQuery.queue( this, type, data );
  1609. // ensure a hooks for this queue
  1610. jQuery._queueHooks( this, type );
  1611. if ( type === "fx" && queue[0] !== "inprogress" ) {
  1612. jQuery.dequeue( this, type );
  1613. }
  1614. });
  1615. },
  1616. dequeue: function( type ) {
  1617. return this.each(function() {
  1618. jQuery.dequeue( this, type );
  1619. });
  1620. },
  1621. // Based off of the plugin by Clint Helfers, with permission.
  1622. // http://blindsignals.com/index.php/2009/07/jquery-delay/
  1623. delay: function( time, type ) {
  1624. time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
  1625. type = type || "fx";
  1626. return this.queue( type, function( next, hooks ) {
  1627. var timeout = setTimeout( next, time );
  1628. hooks.stop = function() {
  1629. clearTimeout( timeout );
  1630. };
  1631. });
  1632. },
  1633. clearQueue: function( type ) {
  1634. return this.queue( type || "fx", [] );
  1635. },
  1636. // Get a promise resolved when queues of a certain type
  1637. // are emptied (fx is the type by default)
  1638. promise: function( type, obj ) {
  1639. var tmp,
  1640. count = 1,
  1641. defer = jQuery.Deferred(),
  1642. elements = this,
  1643. i = this.length,
  1644. resolve = function() {
  1645. if ( !( --count ) ) {
  1646. defer.resolveWith( elements, [ elements ] );
  1647. }
  1648. };
  1649. if ( typeof type !== "string" ) {
  1650. obj = type;
  1651. type = undefined;
  1652. }
  1653. type = type || "fx";
  1654. while( i-- ) {
  1655. tmp = jQuery._data( elements[ i ], type + "queueHooks" );
  1656. if ( tmp && tmp.empty ) {
  1657. count++;
  1658. tmp.empty.add( resolve );
  1659. }
  1660. }
  1661. resolve();
  1662. return defer.promise( obj );
  1663. }
  1664. });
  1665. var nodeHook, boolHook,
  1666. rclass = /[\t\r\n]/g,
  1667. rreturn = /\r/g,
  1668. rfocusable = /^(?:input|select|textarea|button|object)$/i,
  1669. rclickable = /^(?:a|area)$/i,
  1670. rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,
  1671. ruseDefault = /^(?:checked|selected)$/i,
  1672. getSetAttribute = jQuery.support.getSetAttribute,
  1673. getSetInput = jQuery.support.input;
  1674. jQuery.fn.extend({
  1675. attr: function( name, value ) {
  1676. return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
  1677. },
  1678. removeAttr: function( name ) {
  1679. return this.each(function() {
  1680. jQuery.removeAttr( this, name );
  1681. });
  1682. },
  1683. prop: function( name, value ) {
  1684. return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
  1685. },
  1686. removeProp: function( name ) {
  1687. name = jQuery.propFix[ name ] || name;
  1688. return this.each(function() {
  1689. // try/catch handles cases where IE balks (such as removing a property on window)
  1690. try {
  1691. this[ name ] = undefined;
  1692. delete this[ name ];
  1693. } catch( e ) {}
  1694. });
  1695. },
  1696. addClass: function( value ) {
  1697. var classes, elem, cur, clazz, j,
  1698. i = 0,
  1699. len = this.length,
  1700. proceed = typeof value === "string" && value;
  1701. if ( jQuery.isFunction( value ) ) {
  1702. return this.each(function( j ) {
  1703. jQuery( this ).addClass( value.call( this, j, this.className ) );
  1704. });
  1705. }
  1706. if ( proceed ) {
  1707. // The disjunction here is for better compressibility (see removeClass)
  1708. classes = ( value || "" ).match( core_rnotwhite ) || [];
  1709. for ( ; i < len; i++ ) {
  1710. elem = this[ i ];
  1711. cur = elem.nodeType === 1 && ( elem.className ?
  1712. ( " " + elem.className + " " ).replace( rclass, " " ) :
  1713. " "
  1714. );
  1715. if ( cur ) {
  1716. j = 0;
  1717. while ( (clazz = classes[j++]) ) {
  1718. if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
  1719. cur += clazz + " ";
  1720. }
  1721. }
  1722. elem.className = jQuery.trim( cur );
  1723. }
  1724. }
  1725. }
  1726. return this;
  1727. },
  1728. removeClass: function( value ) {
  1729. var classes, elem, cur, clazz, j,
  1730. i = 0,
  1731. len = this.length,
  1732. proceed = arguments.length === 0 || typeof value === "string" && value;
  1733. if ( jQuery.isFunction( value ) ) {
  1734. return this.each(function( j ) {
  1735. jQuery( this ).removeClass( value.call( this, j, this.className ) );
  1736. });
  1737. }
  1738. if ( proceed ) {
  1739. classes = ( value || "" ).match( core_rnotwhite ) || [];
  1740. for ( ; i < len; i++ ) {
  1741. elem = this[ i ];
  1742. // This expression is here for better compressibility (see addClass)
  1743. cur = elem.nodeType === 1 && ( elem.className ?
  1744. ( " " + elem.className + " " ).replace( rclass, " " ) :
  1745. ""
  1746. );
  1747. if ( cur ) {
  1748. j = 0;
  1749. while ( (clazz = classes[j++]) ) {
  1750. // Remove *all* instances
  1751. while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
  1752. cur = cur.replace( " " + clazz + " ", " " );
  1753. }
  1754. }
  1755. elem.className = value ? jQuery.trim( cur ) : "";
  1756. }
  1757. }
  1758. }
  1759. return this;
  1760. },
  1761. toggleClass: function( value, stateVal ) {
  1762. var type = typeof value,
  1763. isBool = typeof stateVal === "boolean";
  1764. if ( jQuery.isFunction( value ) ) {
  1765. return this.each(function( i ) {
  1766. jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
  1767. });
  1768. }
  1769. return this.each(function() {
  1770. if ( type === "string" ) {
  1771. // toggle individual class names
  1772. var className,
  1773. i = 0,
  1774. self = jQuery( this ),
  1775. state = stateVal,
  1776. classNames = value.match( core_rnotwhite ) || [];
  1777. while ( (className = classNames[ i++ ]) ) {
  1778. // check each className given, space separated list
  1779. state = isBool ? state : !self.hasClass( className );
  1780. self[ state ? "addClass" : "removeClass" ]( className );
  1781. }
  1782. // Toggle whole class name
  1783. } else if ( type === "undefined" || type === "boolean" ) {
  1784. if ( this.className ) {
  1785. // store className if set
  1786. jQuery._data( this, "__className__", this.className );
  1787. }
  1788. // If the element has a class name or if we're passed "false",
  1789. // then remove the whole classname (if there was one, the above saved it).
  1790. // Otherwise bring back whatever was previously saved (if anything),
  1791. // falling back to the empty string if nothing was stored.
  1792. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
  1793. }
  1794. });
  1795. },
  1796. hasClass: function( selector ) {
  1797. var className = " " + selector + " ",
  1798. i = 0,
  1799. l = this.length;
  1800. for ( ; i < l; i++ ) {
  1801. if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
  1802. return true;
  1803. }
  1804. }
  1805. return false;
  1806. },
  1807. val: function( value ) {
  1808. var hooks, ret, isFunction,
  1809. elem = this[0];
  1810. if ( !arguments.length ) {
  1811. if ( elem ) {
  1812. hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
  1813. if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
  1814. return ret;
  1815. }
  1816. ret = elem.value;
  1817. return typeof ret === "string" ?
  1818. // handle most common string cases
  1819. ret.replace(rreturn, "") :
  1820. // handle cases where value is null/undef or number
  1821. ret == null ? "" : ret;
  1822. }
  1823. return;
  1824. }
  1825. isFunction = jQuery.isFunction( value );
  1826. return this.each(function( i ) {
  1827. var val,
  1828. self = jQuery(this);
  1829. if ( this.nodeType !== 1 ) {
  1830. return;
  1831. }
  1832. if ( isFunction ) {
  1833. val = value.call( this, i, self.val() );
  1834. } else {
  1835. val = value;
  1836. }
  1837. // Treat null/undefined as ""; convert numbers to string
  1838. if ( val == null ) {
  1839. val = "";
  1840. } else if ( typeof val === "number" ) {
  1841. val += "";
  1842. } else if ( jQuery.isArray( val ) ) {
  1843. val = jQuery.map(val, function ( value ) {
  1844. return value == null ? "" : value + "";
  1845. });
  1846. }
  1847. hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
  1848. // If set returns undefined, fall back to normal setting
  1849. if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
  1850. this.value = val;
  1851. }
  1852. });
  1853. }
  1854. });
  1855. jQuery.extend({
  1856. valHooks: {
  1857. option: {
  1858. get: function( elem ) {
  1859. // attributes.value is undefined in Blackberry 4.7 but
  1860. // uses .value. See #6932
  1861. var val = elem.attributes.value;
  1862. return !val || val.specified ? elem.value : elem.text;
  1863. }
  1864. },
  1865. select: {
  1866. get: function( elem ) {
  1867. var value, option,
  1868. options = elem.options,
  1869. index = elem.selectedIndex,
  1870. one = elem.type === "select-one" || index < 0,
  1871. values = one ? null : [],
  1872. max = one ? index + 1 : options.length,
  1873. i = index < 0 ?
  1874. max :
  1875. one ? index : 0;
  1876. // Loop through all the selected options
  1877. for ( ; i < max; i++ ) {
  1878. option = options[ i ];
  1879. // oldIE doesn't update selected after form reset (#2551)
  1880. if ( ( option.selected || i === index ) &&
  1881. // Don't return options that are disabled or in a disabled optgroup
  1882. ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
  1883. ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
  1884. // Get the specific value for the option
  1885. value = jQuery( option ).val();
  1886. // We don't need an array for one selects
  1887. if ( one ) {
  1888. return value;
  1889. }
  1890. // Multi-Selects return an array
  1891. values.push( value );
  1892. }
  1893. }
  1894. return values;
  1895. },
  1896. set: function( elem, value ) {
  1897. var values = jQuery.makeArray( value );
  1898. jQuery(elem).find("option").each(function() {
  1899. this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
  1900. });
  1901. if ( !values.length ) {
  1902. elem.selectedIndex = -1;
  1903. }
  1904. return values;
  1905. }
  1906. }
  1907. },
  1908. attr: function( elem, name, value ) {
  1909. var ret, hooks, notxml,
  1910. nType = elem.nodeType;
  1911. // don't get/set attributes on text, comment and attribute nodes
  1912. if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
  1913. return;
  1914. }
  1915. // Fallback to prop when attributes are not supported
  1916. if ( typeof elem.getAttribute === "undefined" ) {
  1917. return jQuery.prop( elem, name, value );
  1918. }
  1919. notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
  1920. // All attributes are lowercase
  1921. // Grab necessary hook if one is defined
  1922. if ( notxml ) {
  1923. name = name.toLowerCase();
  1924. hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
  1925. }
  1926. if ( value !== undefined ) {
  1927. if ( value === null ) {
  1928. jQuery.removeAttr( elem, name );
  1929. } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
  1930. return ret;
  1931. } else {
  1932. elem.setAttribute( name, value + "" );
  1933. return value;
  1934. }
  1935. } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
  1936. return ret;
  1937. } else {
  1938. // In IE9+, Flash objects don't have .getAttribute (#12945)
  1939. // Support: IE9+
  1940. if ( typeof elem.getAttribute !== "undefined" ) {
  1941. ret = elem.getAttribute( name );
  1942. }
  1943. // Non-existent attributes return null, we normalize to undefined
  1944. return ret == null ?
  1945. undefined :
  1946. ret;
  1947. }
  1948. },
  1949. removeAttr: function( elem, value ) {
  1950. var name, propName,
  1951. i = 0,
  1952. attrNames = value && value.match( core_rnotwhite );
  1953. if ( attrNames && elem.nodeType === 1 ) {
  1954. while ( (name = attrNames[i++]) ) {
  1955. propName = jQuery.propFix[ name ] || name;
  1956. // Boolean attributes get special treatment (#10870)
  1957. if ( rboolean.test( name ) ) {
  1958. // Set corresponding property to false for boolean attributes
  1959. // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8
  1960. if ( !getSetAttribute && ruseDefault.test( name ) ) {
  1961. elem[ jQuery.camelCase( "default-" + name ) ] =
  1962. elem[ propName ] = false;
  1963. } else {
  1964. elem[ propName ] = false;
  1965. }
  1966. // See #9699 for explanation of this approach (setting first, then removal)
  1967. } else {
  1968. jQuery.attr( elem, name, "" );
  1969. }
  1970. elem.removeAttribute( getSetAttribute ? name : propName );
  1971. }
  1972. }
  1973. },
  1974. attrHooks: {
  1975. type: {
  1976. set: function( elem, value ) {
  1977. if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
  1978. // Setting the type on a radio button after the value resets the value in IE6-9
  1979. // Reset value to default in case type is set after value during creation
  1980. var val = elem.value;
  1981. elem.setAttribute( "type", value );
  1982. if ( val ) {
  1983. elem.value = val;
  1984. }
  1985. return value;
  1986. }
  1987. }
  1988. }
  1989. },
  1990. propFix: {
  1991. tabindex: "tabIndex",
  1992. readonly: "readOnly",
  1993. "for": "htmlFor",
  1994. "class": "className",
  1995. maxlength: "maxLength",
  1996. cellspacing: "cellSpacing",
  1997. cellpadding: "cellPadding",
  1998. rowspan: "rowSpan",
  1999. colspan: "colSpan",
  2000. usemap: "useMap",
  2001. frameborder: "frameBorder",
  2002. contenteditable: "contentEditable"
  2003. },
  2004. prop: function( elem, name, value ) {
  2005. var ret, hooks, notxml,
  2006. nType = elem.nodeType;
  2007. // don't get/set properties on text, comment and attribute nodes
  2008. if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
  2009. return;
  2010. }
  2011. notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
  2012. if ( notxml ) {
  2013. // Fix name and attach hooks
  2014. name = jQuery.propFix[ name ] || name;
  2015. hooks = jQuery.propHooks[ name ];
  2016. }
  2017. if ( value !== undefined ) {
  2018. if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
  2019. return ret;
  2020. } else {
  2021. return ( elem[ name ] = value );
  2022. }
  2023. } else {
  2024. if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
  2025. return ret;
  2026. } else {
  2027. return elem[ name ];
  2028. }
  2029. }
  2030. },
  2031. propHooks: {
  2032. tabIndex: {
  2033. get: function( elem ) {
  2034. // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
  2035. // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
  2036. var attributeNode = elem.getAttributeNode("tabindex");
  2037. return attributeNode && attributeNode.specified ?
  2038. parseInt( attributeNode.value, 10 ) :
  2039. rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
  2040. 0 :
  2041. undefined;
  2042. }
  2043. }
  2044. }
  2045. });
  2046. // Hook for boolean attributes
  2047. boolHook = {
  2048. get: function( elem, name ) {
  2049. var
  2050. // Use .prop to determine if this attribute is understood as boolean
  2051. prop = jQuery.prop( elem, name ),
  2052. // Fetch it accordingly
  2053. attr = typeof prop === "boolean" && elem.getAttribute( name ),
  2054. detail = typeof prop === "boolean" ?
  2055. getSetInput && getSetAttribute ?
  2056. attr != null :
  2057. // oldIE fabricates an empty string for missing boolean attributes
  2058. // and conflates checked/selected into attroperties
  2059. ruseDefault.test( name ) ?
  2060. elem[ jQuery.camelCase( "default-" + name ) ] :
  2061. !!attr :
  2062. // fetch an attribute node for properties not recognized as boolean
  2063. elem.getAttributeNode( name );
  2064. return detail && detail.value !== false ?
  2065. name.toLowerCase() :
  2066. undefined;
  2067. },
  2068. set: function( elem, value, name ) {
  2069. if ( value === false ) {
  2070. // Remove boolean attributes when set to false
  2071. jQuery.removeAttr( elem, name );
  2072. } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
  2073. // IE<8 needs the *property* name
  2074. elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
  2075. // Use defaultChecked and defaultSelected for oldIE
  2076. } else {
  2077. elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
  2078. }
  2079. return name;
  2080. }
  2081. };
  2082. // fix oldIE value attroperty
  2083. if ( !getSetInput || !getSetAttribute ) {
  2084. jQuery.attrHooks.value = {
  2085. get: function( elem, name ) {
  2086. var ret = elem.getAttributeNode( name );
  2087. return jQuery.nodeName( elem, "input" ) ?
  2088. // Ignore the value *property* by using defaultValue
  2089. elem.defaultValue :
  2090. ret && ret.specified ? ret.value : undefined;
  2091. },
  2092. set: function( elem, value, name ) {
  2093. if ( jQuery.nodeName( elem, "input" ) ) {
  2094. // Does not return so that setAttribute is also used
  2095. elem.defaultValue = value;
  2096. } else {
  2097. // Use nodeHook if defined (#1954); otherwise setAttribute is fine
  2098. return nodeHook && nodeHook.set( elem, value, name );
  2099. }
  2100. }
  2101. };
  2102. }
  2103. // IE6/7 do not support getting/setting some attributes with get/setAttribute
  2104. if ( !getSetAttribute ) {
  2105. // Use this for any attribute in IE6/7
  2106. // This fixes almost every IE6/7 issue
  2107. nodeHook = jQuery.valHooks.button = {
  2108. get: function( elem, name ) {
  2109. var ret = elem.getAttributeNode( name );
  2110. return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ?
  2111. ret.value :
  2112. undefined;
  2113. },
  2114. set: function( elem, value, name ) {
  2115. // Set the existing or create a new attribute node
  2116. var ret = elem.getAttributeNode( name );
  2117. if ( !ret ) {
  2118. elem.setAttributeNode(
  2119. (ret = elem.ownerDocument.createAttribute( name ))
  2120. );
  2121. }
  2122. ret.value = value += "";
  2123. // Break association with cloned elements by also using setAttribute (#9646)
  2124. return name === "value" || value === elem.getAttribute( name ) ?
  2125. value :
  2126. undefined;
  2127. }
  2128. };
  2129. // Set contenteditable to false on removals(#10429)
  2130. // Setting to empty string throws an error as an invalid value
  2131. jQuery.attrHooks.contenteditable = {
  2132. get: nodeHook.get,
  2133. set: function( elem, value, name ) {
  2134. nodeHook.set( elem, value === "" ? false : value, name );
  2135. }
  2136. };
  2137. // Set width and height to auto instead of 0 on empty string( Bug #8150 )
  2138. // This is for removals
  2139. jQuery.each([ "width", "height" ], function( i, name ) {
  2140. jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
  2141. set: function( elem, value ) {
  2142. if ( value === "" ) {
  2143. elem.setAttribute( name, "auto" );
  2144. return value;
  2145. }
  2146. }
  2147. });
  2148. });
  2149. }
  2150. // Some attributes require a special call on IE
  2151. // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
  2152. if ( !jQuery.support.hrefNormalized ) {
  2153. jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
  2154. jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
  2155. get: function( elem ) {
  2156. var ret = elem.getAttribute( name, 2 );
  2157. return ret == null ? undefined : ret;
  2158. }
  2159. });
  2160. });
  2161. // href/src property should get the full normalized URL (#10299/#12915)
  2162. jQuery.each([ "href", "src" ], function( i, name ) {
  2163. jQuery.propHooks[ name ] = {
  2164. get: function( elem ) {
  2165. return elem.getAttribute( name, 4 );
  2166. }
  2167. };
  2168. });
  2169. }
  2170. if ( !jQuery.support.style ) {
  2171. jQuery.attrHooks.style = {
  2172. get: function( elem ) {
  2173. // Return undefined in the case of empty string
  2174. // Note: IE uppercases css property names, but if we were to .toLowerCase()
  2175. // .cssText, that would destroy case senstitivity in URL's, like in "background"
  2176. return elem.style.cssText || undefined;
  2177. },
  2178. set: function( elem, value ) {
  2179. return ( elem.style.cssText = value + "" );
  2180. }
  2181. };
  2182. }
  2183. // Safari mis-reports the default selected property of an option
  2184. // Accessing the parent's selectedIndex property fixes it
  2185. if ( !jQuery.support.optSelected ) {
  2186. jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
  2187. get: function( elem ) {
  2188. var parent = elem.parentNode;
  2189. if ( parent ) {
  2190. parent.selectedIndex;
  2191. // Make sure that it also works with optgroups, see #5701
  2192. if ( parent.parentNode ) {
  2193. parent.parentNode.selectedIndex;
  2194. }
  2195. }
  2196. return null;
  2197. }
  2198. });
  2199. }
  2200. // IE6/7 call enctype encoding
  2201. if ( !jQuery.support.enctype ) {
  2202. jQuery.propFix.enctype = "encoding";
  2203. }
  2204. // Radios and checkboxes getter/setter
  2205. if ( !jQuery.support.checkOn ) {
  2206. jQuery.each([ "radio", "checkbox" ], function() {
  2207. jQuery.valHooks[ this ] = {
  2208. get: function( elem ) {
  2209. // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
  2210. return elem.getAttribute("value") === null ? "on" : elem.value;
  2211. }
  2212. };
  2213. });
  2214. }
  2215. jQuery.each([ "radio", "checkbox" ], function() {
  2216. jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
  2217. set: function( elem, value ) {
  2218. if ( jQuery.isArray( value ) ) {
  2219. return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
  2220. }
  2221. }
  2222. });
  2223. });
  2224. var rformElems = /^(?:input|select|textarea)$/i,
  2225. rkeyEvent = /^key/,
  2226. rmouseEvent = /^(?:mouse|contextmenu)|click/,
  2227. rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
  2228. rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
  2229. function returnTrue() {
  2230. return true;
  2231. }
  2232. function returnFalse() {
  2233. return false;
  2234. }
  2235. /*
  2236. * Helper functions for managing events -- not part of the public interface.
  2237. * Props to Dean Edwards' addEvent library for many of the ideas.
  2238. */
  2239. jQuery.event = {
  2240. global: {},
  2241. add: function( elem, types, handler, data, selector ) {
  2242. var handleObjIn, eventHandle, tmp,
  2243. events, t, handleObj,
  2244. special, handlers, type, namespaces, origType,
  2245. // Don't attach events to noData or text/comment nodes (but allow plain objects)
  2246. elemData = elem.nodeType !== 3 && elem.nodeType !== 8 && jQuery._data( elem );
  2247. if ( !elemData ) {
  2248. return;
  2249. }
  2250. // Caller can pass in an object of custom data in lieu of the handler
  2251. if ( handler.handler ) {
  2252. handleObjIn = handler;
  2253. handler = handleObjIn.handler;
  2254. selector = handleObjIn.selector;
  2255. }
  2256. // Make sure that the handler has a unique ID, used to find/remove it later
  2257. if ( !handler.guid ) {
  2258. handler.guid = jQuery.guid++;
  2259. }
  2260. // Init the element's event structure and main handler, if this is the first
  2261. if ( !(events = elemData.events) ) {
  2262. events = elemData.events = {};
  2263. }
  2264. if ( !(eventHandle = elemData.handle) ) {
  2265. eventHandle = elemData.handle = function( e ) {
  2266. // Discard the second event of a jQuery.event.trigger() and
  2267. // when an event is called after a page has unloaded
  2268. return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
  2269. jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
  2270. undefined;
  2271. };
  2272. // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
  2273. eventHandle.elem = elem;
  2274. }
  2275. // Handle multiple events separated by a space
  2276. // jQuery(...).bind("mouseover mouseout", fn);
  2277. types = ( types || "" ).match( core_rnotwhite ) || [""];
  2278. t = types.length;
  2279. while ( t-- ) {
  2280. tmp = rtypenamespace.exec( types[t] ) || [];
  2281. type = origType = tmp[1];
  2282. namespaces = ( tmp[2] || "" ).split( "." ).sort();
  2283. // If event changes its type, use the special event handlers for the changed type
  2284. special = jQuery.event.special[ type ] || {};
  2285. // If selector defined, determine special event api type, otherwise given type
  2286. type = ( selector ? special.delegateType : special.bindType ) || type;
  2287. // Update special based on newly reset type
  2288. special = jQuery.event.special[ type ] || {};
  2289. // handleObj is passed to all event handlers
  2290. handleObj = jQuery.extend({
  2291. type: type,
  2292. origType: origType,
  2293. data: data,
  2294. handler: handler,
  2295. guid: handler.guid,
  2296. selector: selector,
  2297. needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
  2298. namespace: namespaces.join(".")
  2299. }, handleObjIn );
  2300. // Init the event handler queue if we're the first
  2301. if ( !(handlers = events[ type ]) ) {
  2302. handlers = events[ type ] = [];
  2303. handlers.delegateCount = 0;
  2304. // Only use addEventListener/attachEvent if the special events handler returns false
  2305. if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
  2306. // Bind the global event handler to the element
  2307. if ( elem.addEventListener ) {
  2308. elem.addEventListener( type, eventHandle, false );
  2309. } else if ( elem.attachEvent ) {
  2310. elem.attachEvent( "on" + type, eventHandle );
  2311. }
  2312. }
  2313. }
  2314. if ( special.add ) {
  2315. special.add.call( elem, handleObj );
  2316. if ( !handleObj.handler.guid ) {
  2317. handleObj.handler.guid = handler.guid;
  2318. }
  2319. }
  2320. // Add to the element's handler list, delegates in front
  2321. if ( selector ) {
  2322. handlers.splice( handlers.delegateCount++, 0, handleObj );
  2323. } else {
  2324. handlers.push( handleObj );
  2325. }
  2326. // Keep track of which events have ever been used, for event optimization
  2327. jQuery.event.global[ type ] = true;
  2328. }
  2329. // Nullify elem to prevent memory leaks in IE
  2330. elem = null;
  2331. },
  2332. // Detach an event or set of events from an element
  2333. remove: function( elem, types, handler, selector, mappedTypes ) {
  2334. var j, origCount, tmp,
  2335. events, t, handleObj,
  2336. special, handlers, type, namespaces, origType,
  2337. elemData = jQuery.hasData( elem ) && jQuery._data( elem );
  2338. if ( !elemData || !(events = elemData.events) ) {
  2339. return;
  2340. }
  2341. // Once for each type.namespace in types; type may be omitted
  2342. types = ( types || "" ).match( core_rnotwhite ) || [""];
  2343. t = types.length;
  2344. while ( t-- ) {
  2345. tmp = rtypenamespace.exec( types[t] ) || [];
  2346. type = origType = tmp[1];
  2347. namespaces = ( tmp[2] || "" ).split( "." ).sort();
  2348. // Unbind all events (on this namespace, if provided) for the element
  2349. if ( !type ) {
  2350. for ( type in events ) {
  2351. jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
  2352. }
  2353. continue;
  2354. }
  2355. special = jQuery.event.special[ type ] || {};
  2356. type = ( selector ? special.delegateType : special.bindType ) || type;
  2357. handlers = events[ type ] || [];
  2358. tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
  2359. // Remove matching events
  2360. origCount = j = handlers.length;
  2361. while ( j-- ) {
  2362. handleObj = handlers[ j ];
  2363. if ( ( mappedTypes || origType === handleObj.origType ) &&
  2364. ( !handler || handler.guid === handleObj.guid ) &&
  2365. ( !tmp || tmp.test( handleObj.namespace ) ) &&
  2366. ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
  2367. handlers.splice( j, 1 );
  2368. if ( handleObj.selector ) {
  2369. handlers.delegateCount--;
  2370. }
  2371. if ( special.remove ) {
  2372. special.remove.call( elem, handleObj );
  2373. }
  2374. }
  2375. }
  2376. // Remove generic event handler if we removed something and no more handlers exist
  2377. // (avoids potential for endless recursion during removal of special event handlers)
  2378. if ( origCount && !handlers.length ) {
  2379. if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
  2380. jQuery.removeEvent( elem, type, elemData.handle );
  2381. }
  2382. delete events[ type ];
  2383. }
  2384. }
  2385. // Remove the expando if it's no longer used
  2386. if ( jQuery.isEmptyObject( events ) ) {
  2387. delete elemData.handle;
  2388. // removeData also checks for emptiness and clears the expando if empty
  2389. // so use it instead of delete
  2390. jQuery._removeData( elem, "events" );
  2391. }
  2392. },
  2393. trigger: function( event, data, elem, onlyHandlers ) {
  2394. var i, cur, tmp, bubbleType, ontype, handle, special,
  2395. eventPath = [ elem || document ],
  2396. type = event.type || event,
  2397. namespaces = event.namespace ? event.namespace.split(".") : [];
  2398. cur = tmp = elem = elem || document;
  2399. // Don't do events on text and comment nodes
  2400. if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
  2401. return;
  2402. }
  2403. // focus/blur morphs to focusin/out; ensure we're not firing them right now
  2404. if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
  2405. return;
  2406. }
  2407. if ( type.indexOf(".") >= 0 ) {
  2408. // Namespaced trigger; create a regexp to match event type in handle()
  2409. namespaces = type.split(".");
  2410. type = namespaces.shift();
  2411. namespaces.sort();
  2412. }
  2413. ontype = type.indexOf(":") < 0 && "on" + type;
  2414. // Caller can pass in a jQuery.Event object, Object, or just an event type string
  2415. event = event[ jQuery.expando ] ?
  2416. event :
  2417. new jQuery.Event( type, typeof event === "object" && event );
  2418. event.isTrigger = true;
  2419. event.namespace = namespaces.join(".");
  2420. event.namespace_re = event.namespace ?
  2421. new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
  2422. null;
  2423. // Clean up the event in case it is being reused
  2424. event.result = undefined;
  2425. if ( !event.target ) {
  2426. event.target = elem;
  2427. }
  2428. // Clone any incoming data and prepend the event, creating the handler arg list
  2429. data = data == null ?
  2430. [ event ] :
  2431. jQuery.makeArray( data, [ event ] );
  2432. // Allow special events to draw outside the lines
  2433. special = jQuery.event.special[ type ] || {};
  2434. if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
  2435. return;
  2436. }
  2437. // Determine event propagation path in advance, per W3C events spec (#9951)
  2438. // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
  2439. if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
  2440. bubbleType = special.delegateType || type;
  2441. if ( !rfocusMorph.test( bubbleType + type ) ) {
  2442. cur = cur.parentNode;
  2443. }
  2444. for ( ; cur; cur = cur.parentNode ) {
  2445. eventPath.push( cur );
  2446. tmp = cur;
  2447. }
  2448. // Only add window if we got to document (e.g., not plain obj or detached DOM)
  2449. if ( tmp === (elem.ownerDocument || document) ) {
  2450. eventPath.push( tmp.defaultView || tmp.parentWindow || window );
  2451. }
  2452. }
  2453. // Fire handlers on the event path
  2454. i = 0;
  2455. while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
  2456. event.type = i > 1 ?
  2457. bubbleType :
  2458. special.bindType || type;
  2459. // jQuery handler
  2460. handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
  2461. if ( handle ) {
  2462. handle.apply( cur, data );
  2463. }
  2464. // Native handler
  2465. handle = ontype && cur[ ontype ];
  2466. if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
  2467. event.preventDefault();
  2468. }
  2469. }
  2470. event.type = type;
  2471. // If nobody prevented the default action, do it now
  2472. if ( !onlyHandlers && !event.isDefaultPrevented() ) {
  2473. if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
  2474. !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
  2475. // Call a native DOM method on the target with the same name name as the event.
  2476. // Can't use an .isFunction() check here because IE6/7 fails that test.
  2477. // Don't do default actions on window, that's where global variables be (#6170)
  2478. if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
  2479. // Don't re-trigger an onFOO event when we call its FOO() method
  2480. tmp = elem[ ontype ];
  2481. if ( tmp ) {
  2482. elem[ ontype ] = null;
  2483. }
  2484. // Prevent re-triggering of the same event, since we already bubbled it above
  2485. jQuery.event.triggered = type;
  2486. try {
  2487. elem[ type ]();
  2488. } catch ( e ) {
  2489. // IE<9 dies on focus/blur to hidden element (#1486,#12518)
  2490. // only reproducible on winXP IE8 native, not IE9 in IE8 mode
  2491. }
  2492. jQuery.event.triggered = undefined;
  2493. if ( tmp ) {
  2494. elem[ ontype ] = tmp;
  2495. }
  2496. }
  2497. }
  2498. }
  2499. return event.result;
  2500. },
  2501. dispatch: function( event ) {
  2502. // Make a writable jQuery.Event from the native event object
  2503. event = jQuery.event.fix( event );
  2504. var i, j, ret, matched, handleObj,
  2505. handlerQueue = [],
  2506. args = core_slice.call( arguments ),
  2507. handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
  2508. special = jQuery.event.special[ event.type ] || {};
  2509. // Use the fix-ed jQuery.Event rather than the (read-only) native event
  2510. args[0] = event;
  2511. event.delegateTarget = this;
  2512. // Call the preDispatch hook for the mapped type, and let it bail if desired
  2513. if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
  2514. return;
  2515. }
  2516. // Determine handlers
  2517. handlerQueue = jQuery.event.handlers.call( this, event, handlers );
  2518. // Run delegates first; they may want to stop propagation beneath us
  2519. i = 0;
  2520. while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
  2521. event.currentTarget = matched.elem;
  2522. j = 0;
  2523. while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
  2524. // Triggered event must either 1) have no namespace, or
  2525. // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
  2526. if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
  2527. event.handleObj = handleObj;
  2528. event.data = handleObj.data;
  2529. ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
  2530. .apply( matched.elem, args );
  2531. if ( ret !== undefined ) {
  2532. if ( (event.result = ret) === false ) {
  2533. event.preventDefault();
  2534. event.stopPropagation();
  2535. }
  2536. }
  2537. }
  2538. }
  2539. }
  2540. // Call the postDispatch hook for the mapped type
  2541. if ( special.postDispatch ) {
  2542. special.postDispatch.call( this, event );
  2543. }
  2544. return event.result;
  2545. },
  2546. handlers: function( event, handlers ) {
  2547. var i, matches, sel, handleObj,
  2548. handlerQueue = [],
  2549. delegateCount = handlers.delegateCount,
  2550. cur = event.target;
  2551. // Find delegate handlers
  2552. // Black-hole SVG <use> instance trees (#13180)
  2553. // Avoid non-left-click bubbling in Firefox (#3861)
  2554. if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
  2555. for ( ; cur != this; cur = cur.parentNode || this ) {
  2556. // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
  2557. if ( cur.disabled !== true || event.type !== "click" ) {
  2558. matches = [];
  2559. for ( i = 0; i < delegateCount; i++ ) {
  2560. handleObj = handlers[ i ];
  2561. // Don't conflict with Object.prototype properties (#13203)
  2562. sel = handleObj.selector + " ";
  2563. if ( matches[ sel ] === undefined ) {
  2564. matches[ sel ] = handleObj.needsContext ?
  2565. jQuery( sel, this ).index( cur ) >= 0 :
  2566. jQuery.find( sel, this, null, [ cur ] ).length;
  2567. }
  2568. if ( matches[ sel ] ) {
  2569. matches.push( handleObj );
  2570. }
  2571. }
  2572. if ( matches.length ) {
  2573. handlerQueue.push({ elem: cur, handlers: matches });
  2574. }
  2575. }
  2576. }
  2577. }
  2578. // Add the remaining (directly-bound) handlers
  2579. if ( delegateCount < handlers.length ) {
  2580. handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
  2581. }
  2582. return handlerQueue;
  2583. },
  2584. fix: function( event ) {
  2585. if ( event[ jQuery.expando ] ) {
  2586. return event;
  2587. }
  2588. // Create a writable copy of the event object and normalize some properties
  2589. var i, prop,
  2590. originalEvent = event,
  2591. fixHook = jQuery.event.fixHooks[ event.type ] || {},
  2592. copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
  2593. event = new jQuery.Event( originalEvent );
  2594. i = copy.length;
  2595. while ( i-- ) {
  2596. prop = copy[ i ];
  2597. event[ prop ] = originalEvent[ prop ];
  2598. }
  2599. // Support: IE<9
  2600. // Fix target property (#1925)
  2601. if ( !event.target ) {
  2602. event.target = originalEvent.srcElement || document;
  2603. }
  2604. // Support: Chrome 23+, Safari?
  2605. // Target should not be a text node (#504, #13143)
  2606. if ( event.target.nodeType === 3 ) {
  2607. event.target = event.target.parentNode;
  2608. }
  2609. // Support: IE<9
  2610. // For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
  2611. event.metaKey = !!event.metaKey;
  2612. return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
  2613. },
  2614. // Includes some event props shared by KeyEvent and MouseEvent
  2615. props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
  2616. fixHooks: {},
  2617. keyHooks: {
  2618. props: "char charCode key keyCode".split(" "),
  2619. filter: function( event, original ) {
  2620. // Add which for key events
  2621. if ( event.which == null ) {
  2622. event.which = original.charCode != null ? original.charCode : original.keyCode;
  2623. }
  2624. return event;
  2625. }
  2626. },
  2627. mouseHooks: {
  2628. props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
  2629. filter: function( event, original ) {
  2630. var eventDoc, doc, body,
  2631. button = original.button,
  2632. fromElement = original.fromElement;
  2633. // Calculate pageX/Y if missing and clientX/Y available
  2634. if ( event.pageX == null && original.clientX != null ) {
  2635. eventDoc = event.target.ownerDocument || document;
  2636. doc = eventDoc.documentElement;
  2637. body = eventDoc.body;
  2638. event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  2639. event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
  2640. }
  2641. // Add relatedTarget, if necessary
  2642. if ( !event.relatedTarget && fromElement ) {
  2643. event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
  2644. }
  2645. // Add which for click: 1 === left; 2 === middle; 3 === right
  2646. // Note: button is not normalized, so don't use it
  2647. if ( !event.which && button !== undefined ) {
  2648. event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
  2649. }
  2650. return event;
  2651. }
  2652. },
  2653. special: {
  2654. load: {
  2655. // Prevent triggered image.load events from bubbling to window.load
  2656. noBubble: true
  2657. },
  2658. click: {
  2659. // For checkbox, fire native event so checked state will be right
  2660. trigger: function() {
  2661. if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
  2662. this.click();
  2663. return false;
  2664. }
  2665. }
  2666. },
  2667. focus: {
  2668. // Fire native event if possible so blur/focus sequence is correct
  2669. trigger: function() {
  2670. if ( this !== document.activeElement && this.focus ) {
  2671. try {
  2672. this.focus();
  2673. return false;
  2674. } catch ( e ) {
  2675. // Support: IE<9
  2676. // If we error on focus to hidden element (#1486, #12518),
  2677. // let .trigger() run the handlers
  2678. }
  2679. }
  2680. },
  2681. delegateType: "focusin"
  2682. },
  2683. blur: {
  2684. trigger: function() {
  2685. if ( this === document.activeElement && this.blur ) {
  2686. this.blur();
  2687. return false;
  2688. }
  2689. },
  2690. delegateType: "focusout"
  2691. },
  2692. beforeunload: {
  2693. postDispatch: function( event ) {
  2694. // Even when returnValue equals to undefined Firefox will still show alert
  2695. if ( event.result !== undefined ) {
  2696. event.originalEvent.returnValue = event.result;
  2697. }
  2698. }
  2699. }
  2700. },
  2701. simulate: function( type, elem, event, bubble ) {
  2702. // Piggyback on a donor event to simulate a different one.
  2703. // Fake originalEvent to avoid donor's stopPropagation, but if the
  2704. // simulated event prevents default then we do the same on the donor.
  2705. var e = jQuery.extend(
  2706. new jQuery.Event(),
  2707. event,
  2708. { type: type,
  2709. isSimulated: true,
  2710. originalEvent: {}
  2711. }
  2712. );
  2713. if ( bubble ) {
  2714. jQuery.event.trigger( e, null, elem );
  2715. } else {
  2716. jQuery.event.dispatch.call( elem, e );
  2717. }
  2718. if ( e.isDefaultPrevented() ) {
  2719. event.preventDefault();
  2720. }
  2721. }
  2722. };
  2723. jQuery.removeEvent = document.removeEventListener ?
  2724. function( elem, type, handle ) {
  2725. if ( elem.removeEventListener ) {
  2726. elem.removeEventListener( type, handle, false );
  2727. }
  2728. } :
  2729. function( elem, type, handle ) {
  2730. var name = "on" + type;
  2731. if ( elem.detachEvent ) {
  2732. // #8545, #7054, preventing memory leaks for custom events in IE6-8
  2733. // detachEvent needed property on element, by name of that event, to properly expose it to GC
  2734. if ( typeof elem[ name ] === "undefined" ) {
  2735. elem[ name ] = null;
  2736. }
  2737. elem.detachEvent( name, handle );
  2738. }
  2739. };
  2740. jQuery.Event = function( src, props ) {
  2741. // Allow instantiation without the 'new' keyword
  2742. if ( !(this instanceof jQuery.Event) ) {
  2743. return new jQuery.Event( src, props );
  2744. }
  2745. // Event object
  2746. if ( src && src.type ) {
  2747. this.originalEvent = src;
  2748. this.type = src.type;
  2749. // Events bubbling up the document may have been marked as prevented
  2750. // by a handler lower down the tree; reflect the correct value.
  2751. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
  2752. src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
  2753. // Event type
  2754. } else {
  2755. this.type = src;
  2756. }
  2757. // Put explicitly provided properties onto the event object
  2758. if ( props ) {
  2759. jQuery.extend( this, props );
  2760. }
  2761. // Create a timestamp if incoming event doesn't have one
  2762. this.timeStamp = src && src.timeStamp || jQuery.now();
  2763. // Mark it as fixed
  2764. this[ jQuery.expando ] = true;
  2765. };
  2766. // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
  2767. // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
  2768. jQuery.Event.prototype = {
  2769. isDefaultPrevented: returnFalse,
  2770. isPropagationStopped: returnFalse,
  2771. isImmediatePropagationStopped: returnFalse,
  2772. preventDefault: function() {
  2773. var e = this.originalEvent;
  2774. this.isDefaultPrevented = returnTrue;
  2775. if ( !e ) {
  2776. return;
  2777. }
  2778. // If preventDefault exists, run it on the original event
  2779. if ( e.preventDefault ) {
  2780. e.preventDefault();
  2781. // Support: IE
  2782. // Otherwise set the returnValue property of the original event to false
  2783. } else {
  2784. e.returnValue = false;
  2785. }
  2786. },
  2787. stopPropagation: function() {
  2788. var e = this.originalEvent;
  2789. this.isPropagationStopped = returnTrue;
  2790. if ( !e ) {
  2791. return;
  2792. }
  2793. // If stopPropagation exists, run it on the original event
  2794. if ( e.stopPropagation ) {
  2795. e.stopPropagation();
  2796. }
  2797. // Support: IE
  2798. // Set the cancelBubble property of the original event to true
  2799. e.cancelBubble = true;
  2800. },
  2801. stopImmediatePropagation: function() {
  2802. this.isImmediatePropagationStopped = returnTrue;
  2803. this.stopPropagation();
  2804. }
  2805. };
  2806. // Create mouseenter/leave events using mouseover/out and event-time checks
  2807. jQuery.each({
  2808. mouseenter: "mouseover",
  2809. mouseleave: "mouseout"
  2810. }, function( orig, fix ) {
  2811. jQuery.event.special[ orig ] = {
  2812. delegateType: fix,
  2813. bindType: fix,
  2814. handle: function( event ) {
  2815. var ret,
  2816. target = this,
  2817. related = event.relatedTarget,
  2818. handleObj = event.handleObj;
  2819. // For mousenter/leave call the handler if related is outside the target.
  2820. // NB: No relatedTarget if the mouse left/entered the browser window
  2821. if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
  2822. event.type = handleObj.origType;
  2823. ret = handleObj.handler.apply( this, arguments );
  2824. event.type = fix;
  2825. }
  2826. return ret;
  2827. }
  2828. };
  2829. });
  2830. // IE submit delegation
  2831. if ( !jQuery.support.submitBubbles ) {
  2832. jQuery.event.special.submit = {
  2833. setup: function() {
  2834. // Only need this for delegated form submit events
  2835. if ( jQuery.nodeName( this, "form" ) ) {
  2836. return false;
  2837. }
  2838. // Lazy-add a submit handler when a descendant form may potentially be submitted
  2839. jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
  2840. // Node name check avoids a VML-related crash in IE (#9807)
  2841. var elem = e.target,
  2842. form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
  2843. if ( form && !jQuery._data( form, "submitBubbles" ) ) {
  2844. jQuery.event.add( form, "submit._submit", function( event ) {
  2845. event._submit_bubble = true;
  2846. });
  2847. jQuery._data( form, "submitBubbles", true );
  2848. }
  2849. });
  2850. // return undefined since we don't need an event listener
  2851. },
  2852. postDispatch: function( event ) {
  2853. // If form was submitted by the user, bubble the event up the tree
  2854. if ( event._submit_bubble ) {
  2855. delete event._submit_bubble;
  2856. if ( this.parentNode && !event.isTrigger ) {
  2857. jQuery.event.simulate( "submit", this.parentNode, event, true );
  2858. }
  2859. }
  2860. },
  2861. teardown: function() {
  2862. // Only need this for delegated form submit events
  2863. if ( jQuery.nodeName( this, "form" ) ) {
  2864. return false;
  2865. }
  2866. // Remove delegated handlers; cleanData eventually reaps submit handlers attached above
  2867. jQuery.event.remove( this, "._submit" );
  2868. }
  2869. };
  2870. }
  2871. // IE change delegation and checkbox/radio fix
  2872. if ( !jQuery.support.changeBubbles ) {
  2873. jQuery.event.special.change = {
  2874. setup: function() {
  2875. if ( rformElems.test( this.nodeName ) ) {
  2876. // IE doesn't fire change on a check/radio until blur; trigger it on click
  2877. // after a propertychange. Eat the blur-change in special.change.handle.
  2878. // This still fires onchange a second time for check/radio after blur.
  2879. if ( this.type === "checkbox" || this.type === "radio" ) {
  2880. jQuery.event.add( this, "propertychange._change", function( event ) {
  2881. if ( event.originalEvent.propertyName === "checked" ) {
  2882. this._just_changed = true;
  2883. }
  2884. });
  2885. jQuery.event.add( this, "click._change", function( event ) {
  2886. if ( this._just_changed && !event.isTrigger ) {
  2887. this._just_changed = false;
  2888. }
  2889. // Allow triggered, simulated change events (#11500)
  2890. jQuery.event.simulate( "change", this, event, true );
  2891. });
  2892. }
  2893. return false;
  2894. }
  2895. // Delegated event; lazy-add a change handler on descendant inputs
  2896. jQuery.event.add( this, "beforeactivate._change", function( e ) {
  2897. var elem = e.target;
  2898. if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
  2899. jQuery.event.add( elem, "change._change", function( event ) {
  2900. if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
  2901. jQuery.event.simulate( "change", this.parentNode, event, true );
  2902. }
  2903. });
  2904. jQuery._data( elem, "changeBubbles", true );
  2905. }
  2906. });
  2907. },
  2908. handle: function( event ) {
  2909. var elem = event.target;
  2910. // Swallow native change events from checkbox/radio, we already triggered them above
  2911. if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
  2912. return event.handleObj.handler.apply( this, arguments );
  2913. }
  2914. },
  2915. teardown: function() {
  2916. jQuery.event.remove( this, "._change" );
  2917. return !rformElems.test( this.nodeName );
  2918. }
  2919. };
  2920. }
  2921. // Create "bubbling" focus and blur events
  2922. if ( !jQuery.support.focusinBubbles ) {
  2923. jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
  2924. // Attach a single capturing handler while someone wants focusin/focusout
  2925. var attaches = 0,
  2926. handler = function( event ) {
  2927. jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
  2928. };
  2929. jQuery.event.special[ fix ] = {
  2930. setup: function() {
  2931. if ( attaches++ === 0 ) {
  2932. document.addEventListener( orig, handler, true );
  2933. }
  2934. },
  2935. teardown: function() {
  2936. if ( --attaches === 0 ) {
  2937. document.removeEventListener( orig, handler, true );
  2938. }
  2939. }
  2940. };
  2941. });
  2942. }
  2943. jQuery.fn.extend({
  2944. on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
  2945. var origFn, type;
  2946. // Types can be a map of types/handlers
  2947. if ( typeof types === "object" ) {
  2948. // ( types-Object, selector, data )
  2949. if ( typeof selector !== "string" ) {
  2950. // ( types-Object, data )
  2951. data = data || selector;
  2952. selector = undefined;
  2953. }
  2954. for ( type in types ) {
  2955. this.on( type, selector, data, types[ type ], one );
  2956. }
  2957. return this;
  2958. }
  2959. if ( data == null && fn == null ) {
  2960. // ( types, fn )
  2961. fn = selector;
  2962. data = selector = undefined;
  2963. } else if ( fn == null ) {
  2964. if ( typeof selector === "string" ) {
  2965. // ( types, selector, fn )
  2966. fn = data;
  2967. data = undefined;
  2968. } else {
  2969. // ( types, data, fn )
  2970. fn = data;
  2971. data = selector;
  2972. selector = undefined;
  2973. }
  2974. }
  2975. if ( fn === false ) {
  2976. fn = returnFalse;
  2977. } else if ( !fn ) {
  2978. return this;
  2979. }
  2980. if ( one === 1 ) {
  2981. origFn = fn;
  2982. fn = function( event ) {
  2983. // Can use an empty set, since event contains the info
  2984. jQuery().off( event );
  2985. return origFn.apply( this, arguments );
  2986. };
  2987. // Use same guid so caller can remove using origFn
  2988. fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
  2989. }
  2990. return this.each( function() {
  2991. jQuery.event.add( this, types, fn, data, selector );
  2992. });
  2993. },
  2994. one: function( types, selector, data, fn ) {
  2995. return this.on( types, selector, data, fn, 1 );
  2996. },
  2997. off: function( types, selector, fn ) {
  2998. var handleObj, type;
  2999. if ( types && types.preventDefault && types.handleObj ) {
  3000. // ( event ) dispatched jQuery.Event
  3001. handleObj = types.handleObj;
  3002. jQuery( types.delegateTarget ).off(
  3003. handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
  3004. handleObj.selector,
  3005. handleObj.handler
  3006. );
  3007. return this;
  3008. }
  3009. if ( typeof types === "object" ) {
  3010. // ( types-object [, selector] )
  3011. for ( type in types ) {
  3012. this.off( type, selector, types[ type ] );
  3013. }
  3014. return this;
  3015. }
  3016. if ( selector === false || typeof selector === "function" ) {
  3017. // ( types [, fn] )
  3018. fn = selector;
  3019. selector = undefined;
  3020. }
  3021. if ( fn === false ) {
  3022. fn = returnFalse;
  3023. }
  3024. return this.each(function() {
  3025. jQuery.event.remove( this, types, fn, selector );
  3026. });
  3027. },
  3028. bind: function( types, data, fn ) {
  3029. return this.on( types, null, data, fn );
  3030. },
  3031. unbind: function( types, fn ) {
  3032. return this.off( types, null, fn );
  3033. },
  3034. delegate: function( selector, types, data, fn ) {
  3035. return this.on( types, selector, data, fn );
  3036. },
  3037. undelegate: function( selector, types, fn ) {
  3038. // ( namespace ) or ( selector, types [, fn] )
  3039. return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
  3040. },
  3041. trigger: function( type, data ) {
  3042. return this.each(function() {
  3043. jQuery.event.trigger( type, data, this );
  3044. });
  3045. },
  3046. triggerHandler: function( type, data ) {
  3047. var elem = this[0];
  3048. if ( elem ) {
  3049. return jQuery.event.trigger( type, data, elem, true );
  3050. }
  3051. },
  3052. hover: function( fnOver, fnOut ) {
  3053. return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
  3054. }
  3055. });
  3056. jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
  3057. "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
  3058. "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
  3059. // Handle event binding
  3060. jQuery.fn[ name ] = function( data, fn ) {
  3061. return arguments.length > 0 ?
  3062. this.on( name, null, data, fn ) :
  3063. this.trigger( name );
  3064. };
  3065. if ( rkeyEvent.test( name ) ) {
  3066. jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
  3067. }
  3068. if ( rmouseEvent.test( name ) ) {
  3069. jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
  3070. }
  3071. });
  3072. /*!
  3073. * Sizzle CSS Selector Engine
  3074. * Copyright 2012 jQuery Foundation and other contributors
  3075. * Released under the MIT license
  3076. * http://sizzlejs.com/
  3077. */
  3078. (function( window, undefined ) {
  3079. var i,
  3080. cachedruns,
  3081. Expr,
  3082. getText,
  3083. isXML,
  3084. compile,
  3085. hasDuplicate,
  3086. outermostContext,
  3087. // Local document vars
  3088. setDocument,
  3089. document,
  3090. docElem,
  3091. documentIsXML,
  3092. rbuggyQSA,
  3093. rbuggyMatches,
  3094. matches,
  3095. contains,
  3096. sortOrder,
  3097. // Instance-specific data
  3098. expando = "sizzle" + -(new Date()),
  3099. preferredDoc = window.document,
  3100. support = {},
  3101. dirruns = 0,
  3102. done = 0,
  3103. classCache = createCache(),
  3104. tokenCache = createCache(),
  3105. compilerCache = createCache(),
  3106. // General-purpose constants
  3107. strundefined = typeof undefined,
  3108. MAX_NEGATIVE = 1 << 31,
  3109. // Array methods
  3110. arr = [],
  3111. pop = arr.pop,
  3112. push = arr.push,
  3113. slice = arr.slice,
  3114. // Use a stripped-down indexOf if we can't use a native one
  3115. indexOf = arr.indexOf || function( elem ) {
  3116. var i = 0,
  3117. len = this.length;
  3118. for ( ; i < len; i++ ) {
  3119. if ( this[i] === elem ) {
  3120. return i;
  3121. }
  3122. }
  3123. return -1;
  3124. },
  3125. // Regular expressions
  3126. // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
  3127. whitespace = "[\\x20\\t\\r\\n\\f]",
  3128. // http://www.w3.org/TR/css3-syntax/#characters
  3129. characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
  3130. // Loosely modeled on CSS identifier characters
  3131. // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
  3132. // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
  3133. identifier = characterEncoding.replace( "w", "w#" ),
  3134. // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
  3135. operators = "([*^$|!~]?=)",
  3136. attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
  3137. "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
  3138. // Prefer arguments quoted,
  3139. // then not containing pseudos/brackets,
  3140. // then attribute selectors/non-parenthetical expressions,
  3141. // then anything else
  3142. // These preferences are here to reduce the number of selectors
  3143. // needing tokenize in the PSEUDO preFilter
  3144. pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
  3145. // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
  3146. rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
  3147. rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
  3148. rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
  3149. rpseudo = new RegExp( pseudos ),
  3150. ridentifier = new RegExp( "^" + identifier + "$" ),
  3151. matchExpr = {
  3152. "ID": new RegExp( "^#(" + characterEncoding + ")" ),
  3153. "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
  3154. "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
  3155. "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
  3156. "ATTR": new RegExp( "^" + attributes ),
  3157. "PSEUDO": new RegExp( "^" + pseudos ),
  3158. "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
  3159. "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
  3160. "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
  3161. // For use in libraries implementing .is()
  3162. // We use this for POS matching in `select`
  3163. "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
  3164. whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
  3165. },
  3166. rsibling = /[\x20\t\r\n\f]*[+~]/,
  3167. rnative = /\{\s*\[native code\]\s*\}/,
  3168. // Easily-parseable/retrievable ID or TAG or CLASS selectors
  3169. rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
  3170. rinputs = /^(?:input|select|textarea|button)$/i,
  3171. rheader = /^h\d$/i,
  3172. rescape = /'|\\/g,
  3173. rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
  3174. // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
  3175. runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
  3176. funescape = function( _, escaped ) {
  3177. var high = "0x" + escaped - 0x10000;
  3178. // NaN means non-codepoint
  3179. return high !== high ?
  3180. escaped :
  3181. // BMP codepoint
  3182. high < 0 ?
  3183. String.fromCharCode( high + 0x10000 ) :
  3184. // Supplemental Plane codepoint (surrogate pair)
  3185. String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
  3186. };
  3187. // Use a stripped-down slice if we can't use a native one
  3188. try {
  3189. slice.call( docElem.childNodes, 0 )[0].nodeType;
  3190. } catch ( e ) {
  3191. slice = function( i ) {
  3192. var elem,
  3193. results = [];
  3194. for ( ; (elem = this[i]); i++ ) {
  3195. results.push( elem );
  3196. }
  3197. return results;
  3198. };
  3199. }
  3200. /**
  3201. * For feature detection
  3202. * @param {Function} fn The function to test for native support
  3203. */
  3204. function isNative( fn ) {
  3205. return rnative.test( fn + "" );
  3206. }
  3207. /**
  3208. * Create key-value caches of limited size
  3209. * @returns {Function(string, Object)} Returns the Object data after storing it on itself with
  3210. * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
  3211. * deleting the oldest entry
  3212. */
  3213. function createCache() {
  3214. var cache,
  3215. keys = [];
  3216. return (cache = function( key, value ) {
  3217. // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
  3218. if ( keys.push( key += " " ) > Expr.cacheLength ) {
  3219. // Only keep the most recent entries
  3220. delete cache[ keys.shift() ];
  3221. }
  3222. return (cache[ key ] = value);
  3223. });
  3224. }
  3225. /**
  3226. * Mark a function for special use by Sizzle
  3227. * @param {Function} fn The function to mark
  3228. */
  3229. function markFunction( fn ) {
  3230. fn[ expando ] = true;
  3231. return fn;
  3232. }
  3233. /**
  3234. * Support testing using an element
  3235. * @param {Function} fn Passed the created div and expects a boolean result
  3236. */
  3237. function assert( fn ) {
  3238. var div = document.createElement("div");
  3239. try {
  3240. return fn( div );
  3241. } catch (e) {
  3242. return false;
  3243. } finally {
  3244. // release memory in IE
  3245. div = null;
  3246. }
  3247. }
  3248. function Sizzle( selector, context, results, seed ) {
  3249. var match, elem, m, nodeType,
  3250. // QSA vars
  3251. i, groups, old, nid, newContext, newSelector;
  3252. if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
  3253. setDocument( context );
  3254. }
  3255. context = context || document;
  3256. results = results || [];
  3257. if ( !selector || typeof selector !== "string" ) {
  3258. return results;
  3259. }
  3260. if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
  3261. return [];
  3262. }
  3263. if ( !documentIsXML && !seed ) {
  3264. // Shortcuts
  3265. if ( (match = rquickExpr.exec( selector )) ) {
  3266. // Speed-up: Sizzle("#ID")
  3267. if ( (m = match[1]) ) {
  3268. if ( nodeType === 9 ) {
  3269. elem = context.getElementById( m );
  3270. // Check parentNode to catch when Blackberry 4.6 returns
  3271. // nodes that are no longer in the document #6963
  3272. if ( elem && elem.parentNode ) {
  3273. // Handle the case where IE, Opera, and Webkit return items
  3274. // by name instead of ID
  3275. if ( elem.id === m ) {
  3276. results.push( elem );
  3277. return results;
  3278. }
  3279. } else {
  3280. return results;
  3281. }
  3282. } else {
  3283. // Context is not a document
  3284. if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
  3285. contains( context, elem ) && elem.id === m ) {
  3286. results.push( elem );
  3287. return results;
  3288. }
  3289. }
  3290. // Speed-up: Sizzle("TAG")
  3291. } else if ( match[2] ) {
  3292. push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
  3293. return results;
  3294. // Speed-up: Sizzle(".CLASS")
  3295. } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) {
  3296. push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
  3297. return results;
  3298. }
  3299. }
  3300. // QSA path
  3301. if ( support.qsa && !rbuggyQSA.test(selector) ) {
  3302. old = true;
  3303. nid = expando;
  3304. newContext = context;
  3305. newSelector = nodeType === 9 && selector;
  3306. // qSA works strangely on Element-rooted queries
  3307. // We can work around this by specifying an extra ID on the root
  3308. // and working up from there (Thanks to Andrew Dupont for the technique)
  3309. // IE 8 doesn't work on object elements
  3310. if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
  3311. groups = tokenize( selector );
  3312. if ( (old = context.getAttribute("id")) ) {
  3313. nid = old.replace( rescape, "\\$&" );
  3314. } else {
  3315. context.setAttribute( "id", nid );
  3316. }
  3317. nid = "[id='" + nid + "'] ";
  3318. i = groups.length;
  3319. while ( i-- ) {
  3320. groups[i] = nid + toSelector( groups[i] );
  3321. }
  3322. newContext = rsibling.test( selector ) && context.parentNode || context;
  3323. newSelector = groups.join(",");
  3324. }
  3325. if ( newSelector ) {
  3326. try {
  3327. push.apply( results, slice.call( newContext.querySelectorAll(
  3328. newSelector
  3329. ), 0 ) );
  3330. return results;
  3331. } catch(qsaError) {
  3332. } finally {
  3333. if ( !old ) {
  3334. context.removeAttribute("id");
  3335. }
  3336. }
  3337. }
  3338. }
  3339. }
  3340. // All others
  3341. return select( selector.replace( rtrim, "$1" ), context, results, seed );
  3342. }
  3343. /**
  3344. * Detect xml
  3345. * @param {Element|Object} elem An element or a document
  3346. */
  3347. isXML = Sizzle.isXML = function( elem ) {
  3348. // documentElement is verified for cases where it doesn't yet exist
  3349. // (such as loading iframes in IE - #4833)
  3350. var documentElement = elem && (elem.ownerDocument || elem).documentElement;
  3351. return documentElement ? documentElement.nodeName !== "HTML" : false;
  3352. };
  3353. /**
  3354. * Sets document-related variables once based on the current document
  3355. * @param {Element|Object} [doc] An element or document object to use to set the document
  3356. * @returns {Object} Returns the current document
  3357. */
  3358. setDocument = Sizzle.setDocument = function( node ) {
  3359. var doc = node ? node.ownerDocument || node : preferredDoc;
  3360. // If no document and documentElement is available, return
  3361. if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
  3362. return document;
  3363. }
  3364. // Set our document
  3365. document = doc;
  3366. docElem = doc.documentElement;
  3367. // Support tests
  3368. documentIsXML = isXML( doc );
  3369. // Check if getElementsByTagName("*") returns only elements
  3370. support.tagNameNoComments = assert(function( div ) {
  3371. div.appendChild( doc.createComment("") );
  3372. return !div.getElementsByTagName("*").length;
  3373. });
  3374. // Check if attributes should be retrieved by attribute nodes
  3375. support.attributes = assert(function( div ) {
  3376. div.innerHTML = "<select></select>";
  3377. var type = typeof div.lastChild.getAttribute("multiple");
  3378. // IE8 returns a string for some attributes even when not present
  3379. return type !== "boolean" && type !== "string";
  3380. });
  3381. // Check if getElementsByClassName can be trusted
  3382. support.getByClassName = assert(function( div ) {
  3383. // Opera can't find a second classname (in 9.6)
  3384. div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
  3385. if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
  3386. return false;
  3387. }
  3388. // Safari 3.2 caches class attributes and doesn't catch changes
  3389. div.lastChild.className = "e";
  3390. return div.getElementsByClassName("e").length === 2;
  3391. });
  3392. // Check if getElementById returns elements by name
  3393. // Check if getElementsByName privileges form controls or returns elements by ID
  3394. support.getByName = assert(function( div ) {
  3395. // Inject content
  3396. div.id = expando + 0;
  3397. div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
  3398. docElem.insertBefore( div, docElem.firstChild );
  3399. // Test
  3400. var pass = doc.getElementsByName &&
  3401. // buggy browsers will return fewer than the correct 2
  3402. doc.getElementsByName( expando ).length === 2 +
  3403. // buggy browsers will return more than the correct 0
  3404. doc.getElementsByName( expando + 0 ).length;
  3405. support.getIdNotName = !doc.getElementById( expando );
  3406. // Cleanup
  3407. docElem.removeChild( div );
  3408. return pass;
  3409. });
  3410. // IE6/7 return modified attributes
  3411. Expr.attrHandle = assert(function( div ) {
  3412. div.innerHTML = "<a href='#'></a>";
  3413. return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
  3414. div.firstChild.getAttribute("href") === "#";
  3415. }) ?
  3416. {} :
  3417. {
  3418. "href": function( elem ) {
  3419. return elem.getAttribute( "href", 2 );
  3420. },
  3421. "type": function( elem ) {
  3422. return elem.getAttribute("type");
  3423. }
  3424. };
  3425. // ID find and filter
  3426. if ( support.getIdNotName ) {
  3427. Expr.find["ID"] = function( id, context ) {
  3428. if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
  3429. var m = context.getElementById( id );
  3430. // Check parentNode to catch when Blackberry 4.6 returns
  3431. // nodes that are no longer in the document #6963
  3432. return m && m.parentNode ? [m] : [];
  3433. }
  3434. };
  3435. Expr.filter["ID"] = function( id ) {
  3436. var attrId = id.replace( runescape, funescape );
  3437. return function( elem ) {
  3438. return elem.getAttribute("id") === attrId;
  3439. };
  3440. };
  3441. } else {
  3442. Expr.find["ID"] = function( id, context ) {
  3443. if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
  3444. var m = context.getElementById( id );
  3445. return m ?
  3446. m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
  3447. [m] :
  3448. undefined :
  3449. [];
  3450. }
  3451. };
  3452. Expr.filter["ID"] = function( id ) {
  3453. var attrId = id.replace( runescape, funescape );
  3454. return function( elem ) {
  3455. var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
  3456. return node && node.value === attrId;
  3457. };
  3458. };
  3459. }
  3460. // Tag
  3461. Expr.find["TAG"] = support.tagNameNoComments ?
  3462. function( tag, context ) {
  3463. if ( typeof context.getElementsByTagName !== strundefined ) {
  3464. return context.getElementsByTagName( tag );
  3465. }
  3466. } :
  3467. function( tag, context ) {
  3468. var elem,
  3469. tmp = [],
  3470. i = 0,
  3471. results = context.getElementsByTagName( tag );
  3472. // Filter out possible comments
  3473. if ( tag === "*" ) {
  3474. for ( ; (elem = results[i]); i++ ) {
  3475. if ( elem.nodeType === 1 ) {
  3476. tmp.push( elem );
  3477. }
  3478. }
  3479. return tmp;
  3480. }
  3481. return results;
  3482. };
  3483. // Name
  3484. Expr.find["NAME"] = support.getByName && function( tag, context ) {
  3485. if ( typeof context.getElementsByName !== strundefined ) {
  3486. return context.getElementsByName( name );
  3487. }
  3488. };
  3489. // Class
  3490. Expr.find["CLASS"] = support.getByClassName && function( className, context ) {
  3491. if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) {
  3492. return context.getElementsByClassName( className );
  3493. }
  3494. };
  3495. // QSA and matchesSelector support
  3496. // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
  3497. rbuggyMatches = [];
  3498. // qSa(:focus) reports false when true (Chrome 21),
  3499. // no need to also add to buggyMatches since matches checks buggyQSA
  3500. // A support test would require too much code (would include document ready)
  3501. rbuggyQSA = [ ":focus" ];
  3502. if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
  3503. // Build QSA regex
  3504. // Regex strategy adopted from Diego Perini
  3505. assert(function( div ) {
  3506. // Select is set to empty string on purpose
  3507. // This is to test IE's treatment of not explictly
  3508. // setting a boolean content attribute,
  3509. // since its presence should be enough
  3510. // http://bugs.jquery.com/ticket/12359
  3511. div.innerHTML = "<select><option selected=''></option></select>";
  3512. // IE8 - Some boolean attributes are not treated correctly
  3513. if ( !div.querySelectorAll("[selected]").length ) {
  3514. rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
  3515. }
  3516. // Webkit/Opera - :checked should return selected option elements
  3517. // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
  3518. // IE8 throws error here and will not see later tests
  3519. if ( !div.querySelectorAll(":checked").length ) {
  3520. rbuggyQSA.push(":checked");
  3521. }
  3522. });
  3523. assert(function( div ) {
  3524. // Opera 10-12/IE8 - ^= $= *= and empty values
  3525. // Should not select anything
  3526. div.innerHTML = "<input type='hidden' i=''/>";
  3527. if ( div.querySelectorAll("[i^='']").length ) {
  3528. rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
  3529. }
  3530. // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
  3531. // IE8 throws error here and will not see later tests
  3532. if ( !div.querySelectorAll(":enabled").length ) {
  3533. rbuggyQSA.push( ":enabled", ":disabled" );
  3534. }
  3535. // Opera 10-11 does not throw on post-comma invalid pseudos
  3536. div.querySelectorAll("*,:x");
  3537. rbuggyQSA.push(",.*:");
  3538. });
  3539. }
  3540. if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector ||
  3541. docElem.mozMatchesSelector ||
  3542. docElem.webkitMatchesSelector ||
  3543. docElem.oMatchesSelector ||
  3544. docElem.msMatchesSelector) )) ) {
  3545. assert(function( div ) {
  3546. // Check to see if it's possible to do matchesSelector
  3547. // on a disconnected node (IE 9)
  3548. support.disconnectedMatch = matches.call( div, "div" );
  3549. // This should fail with an exception
  3550. // Gecko does not error, returns false instead
  3551. matches.call( div, "[s!='']:x" );
  3552. rbuggyMatches.push( "!=", pseudos );
  3553. });
  3554. }
  3555. rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
  3556. rbuggyMatches = new RegExp( rbuggyMatches.join("|") );
  3557. // Element contains another
  3558. // Purposefully does not implement inclusive descendent
  3559. // As in, an element does not contain itself
  3560. contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
  3561. function( a, b ) {
  3562. var adown = a.nodeType === 9 ? a.documentElement : a,
  3563. bup = b && b.parentNode;
  3564. return a === bup || !!( bup && bup.nodeType === 1 && (
  3565. adown.contains ?
  3566. adown.contains( bup ) :
  3567. a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
  3568. ));
  3569. } :
  3570. function( a, b ) {
  3571. if ( b ) {
  3572. while ( (b = b.parentNode) ) {
  3573. if ( b === a ) {
  3574. return true;
  3575. }
  3576. }
  3577. }
  3578. return false;
  3579. };
  3580. // Document order sorting
  3581. sortOrder = docElem.compareDocumentPosition ?
  3582. function( a, b ) {
  3583. var compare;
  3584. if ( a === b ) {
  3585. hasDuplicate = true;
  3586. return 0;
  3587. }
  3588. if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) {
  3589. if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) {
  3590. if ( a === doc || contains( preferredDoc, a ) ) {
  3591. return -1;
  3592. }
  3593. if ( b === doc || contains( preferredDoc, b ) ) {
  3594. return 1;
  3595. }
  3596. return 0;
  3597. }
  3598. return compare & 4 ? -1 : 1;
  3599. }
  3600. return a.compareDocumentPosition ? -1 : 1;
  3601. } :
  3602. function( a, b ) {
  3603. var cur,
  3604. i = 0,
  3605. aup = a.parentNode,
  3606. bup = b.parentNode,
  3607. ap = [ a ],
  3608. bp = [ b ];
  3609. // The nodes are identical, we can exit early
  3610. if ( a === b ) {
  3611. hasDuplicate = true;
  3612. return 0;
  3613. // Fallback to using sourceIndex (in IE) if it's available on both nodes
  3614. } else if ( a.sourceIndex && b.sourceIndex ) {
  3615. return ( ~b.sourceIndex || MAX_NEGATIVE ) - ( contains( preferredDoc, a ) && ~a.sourceIndex || MAX_NEGATIVE );
  3616. // Parentless nodes are either documents or disconnected
  3617. } else if ( !aup || !bup ) {
  3618. return a === doc ? -1 :
  3619. b === doc ? 1 :
  3620. aup ? -1 :
  3621. bup ? 1 :
  3622. 0;
  3623. // If the nodes are siblings, we can do a quick check
  3624. } else if ( aup === bup ) {
  3625. return siblingCheck( a, b );
  3626. }
  3627. // Otherwise we need full lists of their ancestors for comparison
  3628. cur = a;
  3629. while ( (cur = cur.parentNode) ) {
  3630. ap.unshift( cur );
  3631. }
  3632. cur = b;
  3633. while ( (cur = cur.parentNode) ) {
  3634. bp.unshift( cur );
  3635. }
  3636. // Walk down the tree looking for a discrepancy
  3637. while ( ap[i] === bp[i] ) {
  3638. i++;
  3639. }
  3640. return i ?
  3641. // Do a sibling check if the nodes have a common ancestor
  3642. siblingCheck( ap[i], bp[i] ) :
  3643. // Otherwise nodes in our document sort first
  3644. ap[i] === preferredDoc ? -1 :
  3645. bp[i] === preferredDoc ? 1 :
  3646. 0;
  3647. };
  3648. // Always assume the presence of duplicates if sort doesn't
  3649. // pass them to our comparison function (as in Google Chrome).
  3650. hasDuplicate = false;
  3651. [0, 0].sort( sortOrder );
  3652. support.detectDuplicates = hasDuplicate;
  3653. return document;
  3654. };
  3655. Sizzle.matches = function( expr, elements ) {
  3656. return Sizzle( expr, null, null, elements );
  3657. };
  3658. Sizzle.matchesSelector = function( elem, expr ) {
  3659. // Set document vars if needed
  3660. if ( ( elem.ownerDocument || elem ) !== document ) {
  3661. setDocument( elem );
  3662. }
  3663. // Make sure that attribute selectors are quoted
  3664. expr = expr.replace( rattributeQuotes, "='$1']" );
  3665. // rbuggyQSA always contains :focus, so no need for an existence check
  3666. if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) {
  3667. try {
  3668. var ret = matches.call( elem, expr );
  3669. // IE 9's matchesSelector returns false on disconnected nodes
  3670. if ( ret || support.disconnectedMatch ||
  3671. // As well, disconnected nodes are said to be in a document
  3672. // fragment in IE 9
  3673. elem.document && elem.document.nodeType !== 11 ) {
  3674. return ret;
  3675. }
  3676. } catch(e) {}
  3677. }
  3678. return Sizzle( expr, document, null, [elem] ).length > 0;
  3679. };
  3680. Sizzle.contains = function( context, elem ) {
  3681. // Set document vars if needed
  3682. if ( ( context.ownerDocument || context ) !== document ) {
  3683. setDocument( context );
  3684. }
  3685. return contains( context, elem );
  3686. };
  3687. Sizzle.attr = function( elem, name ) {
  3688. var val;
  3689. // Set document vars if needed
  3690. if ( ( elem.ownerDocument || elem ) !== document ) {
  3691. setDocument( elem );
  3692. }
  3693. if ( !documentIsXML ) {
  3694. name = name.toLowerCase();
  3695. }
  3696. if ( (val = Expr.attrHandle[ name ]) ) {
  3697. return val( elem );
  3698. }
  3699. if ( documentIsXML || support.attributes ) {
  3700. return elem.getAttribute( name );
  3701. }
  3702. return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
  3703. name :
  3704. val && val.specified ? val.value : null;
  3705. };
  3706. Sizzle.error = function( msg ) {
  3707. throw new Error( "Syntax error, unrecognized expression: " + msg );
  3708. };
  3709. // Document sorting and removing duplicates
  3710. Sizzle.uniqueSort = function( results ) {
  3711. var elem,
  3712. duplicates = [],
  3713. i = 1,
  3714. j = 0;
  3715. // Unless we *know* we can detect duplicates, assume their presence
  3716. hasDuplicate = !support.detectDuplicates;
  3717. results.sort( sortOrder );
  3718. if ( hasDuplicate ) {
  3719. for ( ; (elem = results[i]); i++ ) {
  3720. if ( elem === results[ i - 1 ] ) {
  3721. j = duplicates.push( i );
  3722. }
  3723. }
  3724. while ( j-- ) {
  3725. results.splice( duplicates[ j ], 1 );
  3726. }
  3727. }
  3728. return results;
  3729. };
  3730. function siblingCheck( a, b ) {
  3731. var cur = a && b && a.nextSibling;
  3732. for ( ; cur; cur = cur.nextSibling ) {
  3733. if ( cur === b ) {
  3734. return -1;
  3735. }
  3736. }
  3737. return a ? 1 : -1;
  3738. }
  3739. // Returns a function to use in pseudos for input types
  3740. function createInputPseudo( type ) {
  3741. return function( elem ) {
  3742. var name = elem.nodeName.toLowerCase();
  3743. return name === "input" && elem.type === type;
  3744. };
  3745. }
  3746. // Returns a function to use in pseudos for buttons
  3747. function createButtonPseudo( type ) {
  3748. return function( elem ) {
  3749. var name = elem.nodeName.toLowerCase();
  3750. return (name === "input" || name === "button") && elem.type === type;
  3751. };
  3752. }
  3753. // Returns a function to use in pseudos for positionals
  3754. function createPositionalPseudo( fn ) {
  3755. return markFunction(function( argument ) {
  3756. argument = +argument;
  3757. return markFunction(function( seed, matches ) {
  3758. var j,
  3759. matchIndexes = fn( [], seed.length, argument ),
  3760. i = matchIndexes.length;
  3761. // Match elements found at the specified indexes
  3762. while ( i-- ) {
  3763. if ( seed[ (j = matchIndexes[i]) ] ) {
  3764. seed[j] = !(matches[j] = seed[j]);
  3765. }
  3766. }
  3767. });
  3768. });
  3769. }
  3770. /**
  3771. * Utility function for retrieving the text value of an array of DOM nodes
  3772. * @param {Array|Element} elem
  3773. */
  3774. getText = Sizzle.getText = function( elem ) {
  3775. var node,
  3776. ret = "",
  3777. i = 0,
  3778. nodeType = elem.nodeType;
  3779. if ( !nodeType ) {
  3780. // If no nodeType, this is expected to be an array
  3781. for ( ; (node = elem[i]); i++ ) {
  3782. // Do not traverse comment nodes
  3783. ret += getText( node );
  3784. }
  3785. } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
  3786. // Use textContent for elements
  3787. // innerText usage removed for consistency of new lines (see #11153)
  3788. if ( typeof elem.textContent === "string" ) {
  3789. return elem.textContent;
  3790. } else {
  3791. // Traverse its children
  3792. for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
  3793. ret += getText( elem );
  3794. }
  3795. }
  3796. } else if ( nodeType === 3 || nodeType === 4 ) {
  3797. return elem.nodeValue;
  3798. }
  3799. // Do not include comment or processing instruction nodes
  3800. return ret;
  3801. };
  3802. Expr = Sizzle.selectors = {
  3803. // Can be adjusted by the user
  3804. cacheLength: 50,
  3805. createPseudo: markFunction,
  3806. match: matchExpr,
  3807. find: {},
  3808. relative: {
  3809. ">": { dir: "parentNode", first: true },
  3810. " ": { dir: "parentNode" },
  3811. "+": { dir: "previousSibling", first: true },
  3812. "~": { dir: "previousSibling" }
  3813. },
  3814. preFilter: {
  3815. "ATTR": function( match ) {
  3816. match[1] = match[1].replace( runescape, funescape );
  3817. // Move the given value to match[3] whether quoted or unquoted
  3818. match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
  3819. if ( match[2] === "~=" ) {
  3820. match[3] = " " + match[3] + " ";
  3821. }
  3822. return match.slice( 0, 4 );
  3823. },
  3824. "CHILD": function( match ) {
  3825. /* matches from matchExpr["CHILD"]
  3826. 1 type (only|nth|...)
  3827. 2 what (child|of-type)
  3828. 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
  3829. 4 xn-component of xn+y argument ([+-]?\d*n|)
  3830. 5 sign of xn-component
  3831. 6 x of xn-component
  3832. 7 sign of y-component
  3833. 8 y of y-component
  3834. */
  3835. match[1] = match[1].toLowerCase();
  3836. if ( match[1].slice( 0, 3 ) === "nth" ) {
  3837. // nth-* requires argument
  3838. if ( !match[3] ) {
  3839. Sizzle.error( match[0] );
  3840. }
  3841. // numeric x and y parameters for Expr.filter.CHILD
  3842. // remember that false/true cast respectively to 0/1
  3843. match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
  3844. match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
  3845. // other types prohibit arguments
  3846. } else if ( match[3] ) {
  3847. Sizzle.error( match[0] );
  3848. }
  3849. return match;
  3850. },
  3851. "PSEUDO": function( match ) {
  3852. var excess,
  3853. unquoted = !match[5] && match[2];
  3854. if ( matchExpr["CHILD"].test( match[0] ) ) {
  3855. return null;
  3856. }
  3857. // Accept quoted arguments as-is
  3858. if ( match[4] ) {
  3859. match[2] = match[4];
  3860. // Strip excess characters from unquoted arguments
  3861. } else if ( unquoted && rpseudo.test( unquoted ) &&
  3862. // Get excess from tokenize (recursively)
  3863. (excess = tokenize( unquoted, true )) &&
  3864. // advance to the next closing parenthesis
  3865. (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
  3866. // excess is a negative index
  3867. match[0] = match[0].slice( 0, excess );
  3868. match[2] = unquoted.slice( 0, excess );
  3869. }
  3870. // Return only captures needed by the pseudo filter method (type and argument)
  3871. return match.slice( 0, 3 );
  3872. }
  3873. },
  3874. filter: {
  3875. "TAG": function( nodeName ) {
  3876. if ( nodeName === "*" ) {
  3877. return function() { return true; };
  3878. }
  3879. nodeName = nodeName.replace( runescape, funescape ).toLowerCase();
  3880. return function( elem ) {
  3881. return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
  3882. };
  3883. },
  3884. "CLASS": function( className ) {
  3885. var pattern = classCache[ className + " " ];
  3886. return pattern ||
  3887. (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
  3888. classCache( className, function( elem ) {
  3889. return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
  3890. });
  3891. },
  3892. "ATTR": function( name, operator, check ) {
  3893. return function( elem ) {
  3894. var result = Sizzle.attr( elem, name );
  3895. if ( result == null ) {
  3896. return operator === "!=";
  3897. }
  3898. if ( !operator ) {
  3899. return true;
  3900. }
  3901. result += "";
  3902. return operator === "=" ? result === check :
  3903. operator === "!=" ? result !== check :
  3904. operator === "^=" ? check && result.indexOf( check ) === 0 :
  3905. operator === "*=" ? check && result.indexOf( check ) > -1 :
  3906. operator === "$=" ? check && result.substr( result.length - check.length ) === check :
  3907. operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
  3908. operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
  3909. false;
  3910. };
  3911. },
  3912. "CHILD": function( type, what, argument, first, last ) {
  3913. var simple = type.slice( 0, 3 ) !== "nth",
  3914. forward = type.slice( -4 ) !== "last",
  3915. ofType = what === "of-type";
  3916. return first === 1 && last === 0 ?
  3917. // Shortcut for :nth-*(n)
  3918. function( elem ) {
  3919. return !!elem.parentNode;
  3920. } :
  3921. function( elem, context, xml ) {
  3922. var cache, outerCache, node, diff, nodeIndex, start,
  3923. dir = simple !== forward ? "nextSibling" : "previousSibling",
  3924. parent = elem.parentNode,
  3925. name = ofType && elem.nodeName.toLowerCase(),
  3926. useCache = !xml && !ofType;
  3927. if ( parent ) {
  3928. // :(first|last|only)-(child|of-type)
  3929. if ( simple ) {
  3930. while ( dir ) {
  3931. node = elem;
  3932. while ( (node = node[ dir ]) ) {
  3933. if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
  3934. return false;
  3935. }
  3936. }
  3937. // Reverse direction for :only-* (if we haven't yet done so)
  3938. start = dir = type === "only" && !start && "nextSibling";
  3939. }
  3940. return true;
  3941. }
  3942. start = [ forward ? parent.firstChild : parent.lastChild ];
  3943. // non-xml :nth-child(...) stores cache data on `parent`
  3944. if ( forward && useCache ) {
  3945. // Seek `elem` from a previously-cached index
  3946. outerCache = parent[ expando ] || (parent[ expando ] = {});
  3947. cache = outerCache[ type ] || [];
  3948. nodeIndex = cache[0] === dirruns && cache[1];
  3949. diff = cache[0] === dirruns && cache[2];
  3950. node = nodeIndex && parent.childNodes[ nodeIndex ];
  3951. while ( (node = ++nodeIndex && node && node[ dir ] ||
  3952. // Fallback to seeking `elem` from the start
  3953. (diff = nodeIndex = 0) || start.pop()) ) {
  3954. // When found, cache indexes on `parent` and break
  3955. if ( node.nodeType === 1 && ++diff && node === elem ) {
  3956. outerCache[ type ] = [ dirruns, nodeIndex, diff ];
  3957. break;
  3958. }
  3959. }
  3960. // Use previously-cached element index if available
  3961. } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
  3962. diff = cache[1];
  3963. // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
  3964. } else {
  3965. // Use the same loop as above to seek `elem` from the start
  3966. while ( (node = ++nodeIndex && node && node[ dir ] ||
  3967. (diff = nodeIndex = 0) || start.pop()) ) {
  3968. if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
  3969. // Cache the index of each encountered element
  3970. if ( useCache ) {
  3971. (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
  3972. }
  3973. if ( node === elem ) {
  3974. break;
  3975. }
  3976. }
  3977. }
  3978. }
  3979. // Incorporate the offset, then check against cycle size
  3980. diff -= last;
  3981. return diff === first || ( diff % first === 0 && diff / first >= 0 );
  3982. }
  3983. };
  3984. },
  3985. "PSEUDO": function( pseudo, argument ) {
  3986. // pseudo-class names are case-insensitive
  3987. // http://www.w3.org/TR/selectors/#pseudo-classes
  3988. // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
  3989. // Remember that setFilters inherits from pseudos
  3990. var args,
  3991. fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
  3992. Sizzle.error( "unsupported pseudo: " + pseudo );
  3993. // The user may use createPseudo to indicate that
  3994. // arguments are needed to create the filter function
  3995. // just as Sizzle does
  3996. if ( fn[ expando ] ) {
  3997. return fn( argument );
  3998. }
  3999. // But maintain support for old signatures
  4000. if ( fn.length > 1 ) {
  4001. args = [ pseudo, pseudo, "", argument ];
  4002. return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
  4003. markFunction(function( seed, matches ) {
  4004. var idx,
  4005. matched = fn( seed, argument ),
  4006. i = matched.length;
  4007. while ( i-- ) {
  4008. idx = indexOf.call( seed, matched[i] );
  4009. seed[ idx ] = !( matches[ idx ] = matched[i] );
  4010. }
  4011. }) :
  4012. function( elem ) {
  4013. return fn( elem, 0, args );
  4014. };
  4015. }
  4016. return fn;
  4017. }
  4018. },
  4019. pseudos: {
  4020. // Potentially complex pseudos
  4021. "not": markFunction(function( selector ) {
  4022. // Trim the selector passed to compile
  4023. // to avoid treating leading and trailing
  4024. // spaces as combinators
  4025. var input = [],
  4026. results = [],
  4027. matcher = compile( selector.replace( rtrim, "$1" ) );
  4028. return matcher[ expando ] ?
  4029. markFunction(function( seed, matches, context, xml ) {
  4030. var elem,
  4031. unmatched = matcher( seed, null, xml, [] ),
  4032. i = seed.length;
  4033. // Match elements unmatched by `matcher`
  4034. while ( i-- ) {
  4035. if ( (elem = unmatched[i]) ) {
  4036. seed[i] = !(matches[i] = elem);
  4037. }
  4038. }
  4039. }) :
  4040. function( elem, context, xml ) {
  4041. input[0] = elem;
  4042. matcher( input, null, xml, results );
  4043. return !results.pop();
  4044. };
  4045. }),
  4046. "has": markFunction(function( selector ) {
  4047. return function( elem ) {
  4048. return Sizzle( selector, elem ).length > 0;
  4049. };
  4050. }),
  4051. "contains": markFunction(function( text ) {
  4052. return function( elem ) {
  4053. return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
  4054. };
  4055. }),
  4056. // "Whether an element is represented by a :lang() selector
  4057. // is based solely on the element's language value
  4058. // being equal to the identifier C,
  4059. // or beginning with the identifier C immediately followed by "-".
  4060. // The matching of C against the element's language value is performed case-insensitively.
  4061. // The identifier C does not have to be a valid language name."
  4062. // http://www.w3.org/TR/selectors/#lang-pseudo
  4063. "lang": markFunction( function( lang ) {
  4064. // lang value must be a valid identifider
  4065. if ( !ridentifier.test(lang || "") ) {
  4066. Sizzle.error( "unsupported lang: " + lang );
  4067. }
  4068. lang = lang.replace( runescape, funescape ).toLowerCase();
  4069. return function( elem ) {
  4070. var elemLang;
  4071. do {
  4072. if ( (elemLang = documentIsXML ?
  4073. elem.getAttribute("xml:lang") || elem.getAttribute("lang") :
  4074. elem.lang) ) {
  4075. elemLang = elemLang.toLowerCase();
  4076. return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
  4077. }
  4078. } while ( (elem = elem.parentNode) && elem.nodeType === 1 );
  4079. return false;
  4080. };
  4081. }),
  4082. // Miscellaneous
  4083. "target": function( elem ) {
  4084. var hash = window.location && window.location.hash;
  4085. return hash && hash.slice( 1 ) === elem.id;
  4086. },
  4087. "root": function( elem ) {
  4088. return elem === docElem;
  4089. },
  4090. "focus": function( elem ) {
  4091. return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
  4092. },
  4093. // Boolean properties
  4094. "enabled": function( elem ) {
  4095. return elem.disabled === false;
  4096. },
  4097. "disabled": function( elem ) {
  4098. return elem.disabled === true;
  4099. },
  4100. "checked": function( elem ) {
  4101. // In CSS3, :checked should return both checked and selected elements
  4102. // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
  4103. var nodeName = elem.nodeName.toLowerCase();
  4104. return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
  4105. },
  4106. "selected": function( elem ) {
  4107. // Accessing this property makes selected-by-default
  4108. // options in Safari work properly
  4109. if ( elem.parentNode ) {
  4110. elem.parentNode.selectedIndex;
  4111. }
  4112. return elem.selected === true;
  4113. },
  4114. // Contents
  4115. "empty": function( elem ) {
  4116. // http://www.w3.org/TR/selectors/#empty-pseudo
  4117. // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
  4118. // not comment, processing instructions, or others
  4119. // Thanks to Diego Perini for the nodeName shortcut
  4120. // Greater than "@" means alpha characters (specifically not starting with "#" or "?")
  4121. for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
  4122. if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
  4123. return false;
  4124. }
  4125. }
  4126. return true;
  4127. },
  4128. "parent": function( elem ) {
  4129. return !Expr.pseudos["empty"]( elem );
  4130. },
  4131. // Element/input types
  4132. "header": function( elem ) {
  4133. return rheader.test( elem.nodeName );
  4134. },
  4135. "input": function( elem ) {
  4136. return rinputs.test( elem.nodeName );
  4137. },
  4138. "button": function( elem ) {
  4139. var name = elem.nodeName.toLowerCase();
  4140. return name === "input" && elem.type === "button" || name === "button";
  4141. },
  4142. "text": function( elem ) {
  4143. var attr;
  4144. // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
  4145. // use getAttribute instead to test this case
  4146. return elem.nodeName.toLowerCase() === "input" &&
  4147. elem.type === "text" &&
  4148. ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
  4149. },
  4150. // Position-in-collection
  4151. "first": createPositionalPseudo(function() {
  4152. return [ 0 ];
  4153. }),
  4154. "last": createPositionalPseudo(function( matchIndexes, length ) {
  4155. return [ length - 1 ];
  4156. }),
  4157. "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
  4158. return [ argument < 0 ? argument + length : argument ];
  4159. }),
  4160. "even": createPositionalPseudo(function( matchIndexes, length ) {
  4161. var i = 0;
  4162. for ( ; i < length; i += 2 ) {
  4163. matchIndexes.push( i );
  4164. }
  4165. return matchIndexes;
  4166. }),
  4167. "odd": createPositionalPseudo(function( matchIndexes, length ) {
  4168. var i = 1;
  4169. for ( ; i < length; i += 2 ) {
  4170. matchIndexes.push( i );
  4171. }
  4172. return matchIndexes;
  4173. }),
  4174. "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
  4175. var i = argument < 0 ? argument + length : argument;
  4176. for ( ; --i >= 0; ) {
  4177. matchIndexes.push( i );
  4178. }
  4179. return matchIndexes;
  4180. }),
  4181. "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
  4182. var i = argument < 0 ? argument + length : argument;
  4183. for ( ; ++i < length; ) {
  4184. matchIndexes.push( i );
  4185. }
  4186. return matchIndexes;
  4187. })
  4188. }
  4189. };
  4190. // Add button/input type pseudos
  4191. for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
  4192. Expr.pseudos[ i ] = createInputPseudo( i );
  4193. }
  4194. for ( i in { submit: true, reset: true } ) {
  4195. Expr.pseudos[ i ] = createButtonPseudo( i );
  4196. }
  4197. function tokenize( selector, parseOnly ) {
  4198. var matched, match, tokens, type,
  4199. soFar, groups, preFilters,
  4200. cached = tokenCache[ selector + " " ];
  4201. if ( cached ) {
  4202. return parseOnly ? 0 : cached.slice( 0 );
  4203. }
  4204. soFar = selector;
  4205. groups = [];
  4206. preFilters = Expr.preFilter;
  4207. while ( soFar ) {
  4208. // Comma and first run
  4209. if ( !matched || (match = rcomma.exec( soFar )) ) {
  4210. if ( match ) {
  4211. // Don't consume trailing commas as valid
  4212. soFar = soFar.slice( match[0].length ) || soFar;
  4213. }
  4214. groups.push( tokens = [] );
  4215. }
  4216. matched = false;
  4217. // Combinators
  4218. if ( (match = rcombinators.exec( soFar )) ) {
  4219. matched = match.shift();
  4220. tokens.push( {
  4221. value: matched,
  4222. // Cast descendant combinators to space
  4223. type: match[0].replace( rtrim, " " )
  4224. } );
  4225. soFar = soFar.slice( matched.length );
  4226. }
  4227. // Filters
  4228. for ( type in Expr.filter ) {
  4229. if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
  4230. (match = preFilters[ type ]( match ))) ) {
  4231. matched = match.shift();
  4232. tokens.push( {
  4233. value: matched,
  4234. type: type,
  4235. matches: match
  4236. } );
  4237. soFar = soFar.slice( matched.length );
  4238. }
  4239. }
  4240. if ( !matched ) {
  4241. break;
  4242. }
  4243. }
  4244. // Return the length of the invalid excess
  4245. // if we're just parsing
  4246. // Otherwise, throw an error or return tokens
  4247. return parseOnly ?
  4248. soFar.length :
  4249. soFar ?
  4250. Sizzle.error( selector ) :
  4251. // Cache the tokens
  4252. tokenCache( selector, groups ).slice( 0 );
  4253. }
  4254. function toSelector( tokens ) {
  4255. var i = 0,
  4256. len = tokens.length,
  4257. selector = "";
  4258. for ( ; i < len; i++ ) {
  4259. selector += tokens[i].value;
  4260. }
  4261. return selector;
  4262. }
  4263. function addCombinator( matcher, combinator, base ) {
  4264. var dir = combinator.dir,
  4265. checkNonElements = base && combinator.dir === "parentNode",
  4266. doneName = done++;
  4267. return combinator.first ?
  4268. // Check against closest ancestor/preceding element
  4269. function( elem, context, xml ) {
  4270. while ( (elem = elem[ dir ]) ) {
  4271. if ( elem.nodeType === 1 || checkNonElements ) {
  4272. return matcher( elem, context, xml );
  4273. }
  4274. }
  4275. } :
  4276. // Check against all ancestor/preceding elements
  4277. function( elem, context, xml ) {
  4278. var data, cache, outerCache,
  4279. dirkey = dirruns + " " + doneName;
  4280. // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
  4281. if ( xml ) {
  4282. while ( (elem = elem[ dir ]) ) {
  4283. if ( elem.nodeType === 1 || checkNonElements ) {
  4284. if ( matcher( elem, context, xml ) ) {
  4285. return true;
  4286. }
  4287. }
  4288. }
  4289. } else {
  4290. while ( (elem = elem[ dir ]) ) {
  4291. if ( elem.nodeType === 1 || checkNonElements ) {
  4292. outerCache = elem[ expando ] || (elem[ expando ] = {});
  4293. if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
  4294. if ( (data = cache[1]) === true || data === cachedruns ) {
  4295. return data === true;
  4296. }
  4297. } else {
  4298. cache = outerCache[ dir ] = [ dirkey ];
  4299. cache[1] = matcher( elem, context, xml ) || cachedruns;
  4300. if ( cache[1] === true ) {
  4301. return true;
  4302. }
  4303. }
  4304. }
  4305. }
  4306. }
  4307. };
  4308. }
  4309. function elementMatcher( matchers ) {
  4310. return matchers.length > 1 ?
  4311. function( elem, context, xml ) {
  4312. var i = matchers.length;
  4313. while ( i-- ) {
  4314. if ( !matchers[i]( elem, context, xml ) ) {
  4315. return false;
  4316. }
  4317. }
  4318. return true;
  4319. } :
  4320. matchers[0];
  4321. }
  4322. function condense( unmatched, map, filter, context, xml ) {
  4323. var elem,
  4324. newUnmatched = [],
  4325. i = 0,
  4326. len = unmatched.length,
  4327. mapped = map != null;
  4328. for ( ; i < len; i++ ) {
  4329. if ( (elem = unmatched[i]) ) {
  4330. if ( !filter || filter( elem, context, xml ) ) {
  4331. newUnmatched.push( elem );
  4332. if ( mapped ) {
  4333. map.push( i );
  4334. }
  4335. }
  4336. }
  4337. }
  4338. return newUnmatched;
  4339. }
  4340. function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
  4341. if ( postFilter && !postFilter[ expando ] ) {
  4342. postFilter = setMatcher( postFilter );
  4343. }
  4344. if ( postFinder && !postFinder[ expando ] ) {
  4345. postFinder = setMatcher( postFinder, postSelector );
  4346. }
  4347. return markFunction(function( seed, results, context, xml ) {
  4348. var temp, i, elem,
  4349. preMap = [],
  4350. postMap = [],
  4351. preexisting = results.length,
  4352. // Get initial elements from seed or context
  4353. elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
  4354. // Prefilter to get matcher input, preserving a map for seed-results synchronization
  4355. matcherIn = preFilter && ( seed || !selector ) ?
  4356. condense( elems, preMap, preFilter, context, xml ) :
  4357. elems,
  4358. matcherOut = matcher ?
  4359. // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
  4360. postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
  4361. // ...intermediate processing is necessary
  4362. [] :
  4363. // ...otherwise use results directly
  4364. results :
  4365. matcherIn;
  4366. // Find primary matches
  4367. if ( matcher ) {
  4368. matcher( matcherIn, matcherOut, context, xml );
  4369. }
  4370. // Apply postFilter
  4371. if ( postFilter ) {
  4372. temp = condense( matcherOut, postMap );
  4373. postFilter( temp, [], context, xml );
  4374. // Un-match failing elements by moving them back to matcherIn
  4375. i = temp.length;
  4376. while ( i-- ) {
  4377. if ( (elem = temp[i]) ) {
  4378. matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
  4379. }
  4380. }
  4381. }
  4382. if ( seed ) {
  4383. if ( postFinder || preFilter ) {
  4384. if ( postFinder ) {
  4385. // Get the final matcherOut by condensing this intermediate into postFinder contexts
  4386. temp = [];
  4387. i = matcherOut.length;
  4388. while ( i-- ) {
  4389. if ( (elem = matcherOut[i]) ) {
  4390. // Restore matcherIn since elem is not yet a final match
  4391. temp.push( (matcherIn[i] = elem) );
  4392. }
  4393. }
  4394. postFinder( null, (matcherOut = []), temp, xml );
  4395. }
  4396. // Move matched elements from seed to results to keep them synchronized
  4397. i = matcherOut.length;
  4398. while ( i-- ) {
  4399. if ( (elem = matcherOut[i]) &&
  4400. (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
  4401. seed[temp] = !(results[temp] = elem);
  4402. }
  4403. }
  4404. }
  4405. // Add elements to results, through postFinder if defined
  4406. } else {
  4407. matcherOut = condense(
  4408. matcherOut === results ?
  4409. matcherOut.splice( preexisting, matcherOut.length ) :
  4410. matcherOut
  4411. );
  4412. if ( postFinder ) {
  4413. postFinder( null, results, matcherOut, xml );
  4414. } else {
  4415. push.apply( results, matcherOut );
  4416. }
  4417. }
  4418. });
  4419. }
  4420. function matcherFromTokens( tokens ) {
  4421. var checkContext, matcher, j,
  4422. len = tokens.length,
  4423. leadingRelative = Expr.relative[ tokens[0].type ],
  4424. implicitRelative = leadingRelative || Expr.relative[" "],
  4425. i = leadingRelative ? 1 : 0,
  4426. // The foundational matcher ensures that elements are reachable from top-level context(s)
  4427. matchContext = addCombinator( function( elem ) {
  4428. return elem === checkContext;
  4429. }, implicitRelative, true ),
  4430. matchAnyContext = addCombinator( function( elem ) {
  4431. return indexOf.call( checkContext, elem ) > -1;
  4432. }, implicitRelative, true ),
  4433. matchers = [ function( elem, context, xml ) {
  4434. return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
  4435. (checkContext = context).nodeType ?
  4436. matchContext( elem, context, xml ) :
  4437. matchAnyContext( elem, context, xml ) );
  4438. } ];
  4439. for ( ; i < len; i++ ) {
  4440. if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
  4441. matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
  4442. } else {
  4443. matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
  4444. // Return special upon seeing a positional matcher
  4445. if ( matcher[ expando ] ) {
  4446. // Find the next relative operator (if any) for proper handling
  4447. j = ++i;
  4448. for ( ; j < len; j++ ) {
  4449. if ( Expr.relative[ tokens[j].type ] ) {
  4450. break;
  4451. }
  4452. }
  4453. return setMatcher(
  4454. i > 1 && elementMatcher( matchers ),
  4455. i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ),
  4456. matcher,
  4457. i < j && matcherFromTokens( tokens.slice( i, j ) ),
  4458. j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
  4459. j < len && toSelector( tokens )
  4460. );
  4461. }
  4462. matchers.push( matcher );
  4463. }
  4464. }
  4465. return elementMatcher( matchers );
  4466. }
  4467. function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
  4468. // A counter to specify which element is currently being matched
  4469. var matcherCachedRuns = 0,
  4470. bySet = setMatchers.length > 0,
  4471. byElement = elementMatchers.length > 0,
  4472. superMatcher = function( seed, context, xml, results, expandContext ) {
  4473. var elem, j, matcher,
  4474. setMatched = [],
  4475. matchedCount = 0,
  4476. i = "0",
  4477. unmatched = seed && [],
  4478. outermost = expandContext != null,
  4479. contextBackup = outermostContext,
  4480. // We must always have either seed elements or context
  4481. elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
  4482. // Nested matchers should use non-integer dirruns
  4483. dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
  4484. if ( outermost ) {
  4485. outermostContext = context !== document && context;
  4486. cachedruns = matcherCachedRuns;
  4487. }
  4488. // Add elements passing elementMatchers directly to results
  4489. for ( ; (elem = elems[i]) != null; i++ ) {
  4490. if ( byElement && elem ) {
  4491. for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
  4492. if ( matcher( elem, context, xml ) ) {
  4493. results.push( elem );
  4494. break;
  4495. }
  4496. }
  4497. if ( outermost ) {
  4498. dirruns = dirrunsUnique;
  4499. cachedruns = ++matcherCachedRuns;
  4500. }
  4501. }
  4502. // Track unmatched elements for set filters
  4503. if ( bySet ) {
  4504. // They will have gone through all possible matchers
  4505. if ( (elem = !matcher && elem) ) {
  4506. matchedCount--;
  4507. }
  4508. // Lengthen the array for every element, matched or not
  4509. if ( seed ) {
  4510. unmatched.push( elem );
  4511. }
  4512. }
  4513. }
  4514. // Apply set filters to unmatched elements
  4515. // `i` starts as a string, so matchedCount would equal "00" if there are no elements
  4516. matchedCount += i;
  4517. if ( bySet && i !== matchedCount ) {
  4518. for ( j = 0; (matcher = setMatchers[j]); j++ ) {
  4519. matcher( unmatched, setMatched, context, xml );
  4520. }
  4521. if ( seed ) {
  4522. // Reintegrate element matches to eliminate the need for sorting
  4523. if ( matchedCount > 0 ) {
  4524. while ( i-- ) {
  4525. if ( !(unmatched[i] || setMatched[i]) ) {
  4526. setMatched[i] = pop.call( results );
  4527. }
  4528. }
  4529. }
  4530. // Discard index placeholder values to get only actual matches
  4531. setMatched = condense( setMatched );
  4532. }
  4533. // Add matches to results
  4534. push.apply( results, setMatched );
  4535. // Seedless set matches succeeding multiple successful matchers stipulate sorting
  4536. if ( outermost && !seed && setMatched.length > 0 &&
  4537. ( matchedCount + setMatchers.length ) > 1 ) {
  4538. Sizzle.uniqueSort( results );
  4539. }
  4540. }
  4541. // Override manipulation of globals by nested matchers
  4542. if ( outermost ) {
  4543. dirruns = dirrunsUnique;
  4544. outermostContext = contextBackup;
  4545. }
  4546. return unmatched;
  4547. };
  4548. return bySet ?
  4549. markFunction( superMatcher ) :
  4550. superMatcher;
  4551. }
  4552. compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
  4553. var i,
  4554. setMatchers = [],
  4555. elementMatchers = [],
  4556. cached = compilerCache[ selector + " " ];
  4557. if ( !cached ) {
  4558. // Generate a function of recursive functions that can be used to check each element
  4559. if ( !group ) {
  4560. group = tokenize( selector );
  4561. }
  4562. i = group.length;
  4563. while ( i-- ) {
  4564. cached = matcherFromTokens( group[i] );
  4565. if ( cached[ expando ] ) {
  4566. setMatchers.push( cached );
  4567. } else {
  4568. elementMatchers.push( cached );
  4569. }
  4570. }
  4571. // Cache the compiled function
  4572. cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
  4573. }
  4574. return cached;
  4575. };
  4576. function multipleContexts( selector, contexts, results ) {
  4577. var i = 0,
  4578. len = contexts.length;
  4579. for ( ; i < len; i++ ) {
  4580. Sizzle( selector, contexts[i], results );
  4581. }
  4582. return results;
  4583. }
  4584. function select( selector, context, results, seed ) {
  4585. var i, tokens, token, type, find,
  4586. match = tokenize( selector );
  4587. if ( !seed ) {
  4588. // Try to minimize operations if there is only one group
  4589. if ( match.length === 1 ) {
  4590. // Take a shortcut and set the context if the root selector is an ID
  4591. tokens = match[0] = match[0].slice( 0 );
  4592. if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
  4593. context.nodeType === 9 && !documentIsXML &&
  4594. Expr.relative[ tokens[1].type ] ) {
  4595. context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0];
  4596. if ( !context ) {
  4597. return results;
  4598. }
  4599. selector = selector.slice( tokens.shift().value.length );
  4600. }
  4601. // Fetch a seed set for right-to-left matching
  4602. for ( i = matchExpr["needsContext"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
  4603. token = tokens[i];
  4604. // Abort if we hit a combinator
  4605. if ( Expr.relative[ (type = token.type) ] ) {
  4606. break;
  4607. }
  4608. if ( (find = Expr.find[ type ]) ) {
  4609. // Search, expanding context for leading sibling combinators
  4610. if ( (seed = find(
  4611. token.matches[0].replace( runescape, funescape ),
  4612. rsibling.test( tokens[0].type ) && context.parentNode || context
  4613. )) ) {
  4614. // If seed is empty or no tokens remain, we can return early
  4615. tokens.splice( i, 1 );
  4616. selector = seed.length && toSelector( tokens );
  4617. if ( !selector ) {
  4618. push.apply( results, slice.call( seed, 0 ) );
  4619. return results;
  4620. }
  4621. break;
  4622. }
  4623. }
  4624. }
  4625. }
  4626. }
  4627. // Compile and execute a filtering function
  4628. // Provide `match` to avoid retokenization if we modified the selector above
  4629. compile( selector, match )(
  4630. seed,
  4631. context,
  4632. documentIsXML,
  4633. results,
  4634. rsibling.test( selector )
  4635. );
  4636. return results;
  4637. }
  4638. // Deprecated
  4639. Expr.pseudos["nth"] = Expr.pseudos["eq"];
  4640. // Easy API for creating new setFilters
  4641. function setFilters() {}
  4642. Expr.filters = setFilters.prototype = Expr.pseudos;
  4643. Expr.setFilters = new setFilters();
  4644. // Initialize with the default document
  4645. setDocument();
  4646. // Override sizzle attribute retrieval
  4647. Sizzle.attr = jQuery.attr;
  4648. jQuery.find = Sizzle;
  4649. jQuery.expr = Sizzle.selectors;
  4650. jQuery.expr[":"] = jQuery.expr.pseudos;
  4651. jQuery.unique = Sizzle.uniqueSort;
  4652. jQuery.text = Sizzle.getText;
  4653. jQuery.isXMLDoc = Sizzle.isXML;
  4654. jQuery.contains = Sizzle.contains;
  4655. })( window );
  4656. var runtil = /Until$/,
  4657. rparentsprev = /^(?:parents|prev(?:Until|All))/,
  4658. isSimple = /^.[^:#\[\.,]*$/,
  4659. rneedsContext = jQuery.expr.match.needsContext,
  4660. // methods guaranteed to produce a unique set when starting from a unique set
  4661. guaranteedUnique = {
  4662. children: true,
  4663. contents: true,
  4664. next: true,
  4665. prev: true
  4666. };
  4667. jQuery.fn.extend({
  4668. find: function( selector ) {
  4669. var i, ret, self;
  4670. if ( typeof selector !== "string" ) {
  4671. self = this;
  4672. return this.pushStack( jQuery( selector ).filter(function() {
  4673. for ( i = 0; i < self.length; i++ ) {
  4674. if ( jQuery.contains( self[ i ], this ) ) {
  4675. return true;
  4676. }
  4677. }
  4678. }) );
  4679. }
  4680. ret = [];
  4681. for ( i = 0; i < this.length; i++ ) {
  4682. jQuery.find( selector, this[ i ], ret );
  4683. }
  4684. // Needed because $( selector, context ) becomes $( context ).find( selector )
  4685. ret = this.pushStack( jQuery.unique( ret ) );
  4686. ret.selector = ( this.selector ? this.selector + " " : "" ) + selector;
  4687. return ret;
  4688. },
  4689. has: function( target ) {
  4690. var i,
  4691. targets = jQuery( target, this ),
  4692. len = targets.length;
  4693. return this.filter(function() {
  4694. for ( i = 0; i < len; i++ ) {
  4695. if ( jQuery.contains( this, targets[i] ) ) {
  4696. return true;
  4697. }
  4698. }
  4699. });
  4700. },
  4701. not: function( selector ) {
  4702. return this.pushStack( winnow(this, selector, false) );
  4703. },
  4704. filter: function( selector ) {
  4705. return this.pushStack( winnow(this, selector, true) );
  4706. },
  4707. is: function( selector ) {
  4708. return !!selector && (
  4709. typeof selector === "string" ?
  4710. // If this is a positional/relative selector, check membership in the returned set
  4711. // so $("p:first").is("p:last") won't return true for a doc with two "p".
  4712. rneedsContext.test( selector ) ?
  4713. jQuery( selector, this.context ).index( this[0] ) >= 0 :
  4714. jQuery.filter( selector, this ).length > 0 :
  4715. this.filter( selector ).length > 0 );
  4716. },
  4717. closest: function( selectors, context ) {
  4718. var cur,
  4719. i = 0,
  4720. l = this.length,
  4721. ret = [],
  4722. pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
  4723. jQuery( selectors, context || this.context ) :
  4724. 0;
  4725. for ( ; i < l; i++ ) {
  4726. cur = this[i];
  4727. while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
  4728. if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
  4729. ret.push( cur );
  4730. break;
  4731. }
  4732. cur = cur.parentNode;
  4733. }
  4734. }
  4735. return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
  4736. },
  4737. // Determine the position of an element within
  4738. // the matched set of elements
  4739. index: function( elem ) {
  4740. // No argument, return index in parent
  4741. if ( !elem ) {
  4742. return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
  4743. }
  4744. // index in selector
  4745. if ( typeof elem === "string" ) {
  4746. return jQuery.inArray( this[0], jQuery( elem ) );
  4747. }
  4748. // Locate the position of the desired element
  4749. return jQuery.inArray(
  4750. // If it receives a jQuery object, the first element is used
  4751. elem.jquery ? elem[0] : elem, this );
  4752. },
  4753. add: function( selector, context ) {
  4754. var set = typeof selector === "string" ?
  4755. jQuery( selector, context ) :
  4756. jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
  4757. all = jQuery.merge( this.get(), set );
  4758. return this.pushStack( jQuery.unique(all) );
  4759. },
  4760. addBack: function( selector ) {
  4761. return this.add( selector == null ?
  4762. this.prevObject : this.prevObject.filter(selector)
  4763. );
  4764. }
  4765. });
  4766. jQuery.fn.andSelf = jQuery.fn.addBack;
  4767. function sibling( cur, dir ) {
  4768. do {
  4769. cur = cur[ dir ];
  4770. } while ( cur && cur.nodeType !== 1 );
  4771. return cur;
  4772. }
  4773. jQuery.each({
  4774. parent: function( elem ) {
  4775. var parent = elem.parentNode;
  4776. return parent && parent.nodeType !== 11 ? parent : null;
  4777. },
  4778. parents: function( elem ) {
  4779. return jQuery.dir( elem, "parentNode" );
  4780. },
  4781. parentsUntil: function( elem, i, until ) {
  4782. return jQuery.dir( elem, "parentNode", until );
  4783. },
  4784. next: function( elem ) {
  4785. return sibling( elem, "nextSibling" );
  4786. },
  4787. prev: function( elem ) {
  4788. return sibling( elem, "previousSibling" );
  4789. },
  4790. nextAll: function( elem ) {
  4791. return jQuery.dir( elem, "nextSibling" );
  4792. },
  4793. prevAll: function( elem ) {
  4794. return jQuery.dir( elem, "previousSibling" );
  4795. },
  4796. nextUntil: function( elem, i, until ) {
  4797. return jQuery.dir( elem, "nextSibling", until );
  4798. },
  4799. prevUntil: function( elem, i, until ) {
  4800. return jQuery.dir( elem, "previousSibling", until );
  4801. },
  4802. siblings: function( elem ) {
  4803. return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
  4804. },
  4805. children: function( elem ) {
  4806. return jQuery.sibling( elem.firstChild );
  4807. },
  4808. contents: function( elem ) {
  4809. return jQuery.nodeName( elem, "iframe" ) ?
  4810. elem.contentDocument || elem.contentWindow.document :
  4811. jQuery.merge( [], elem.childNodes );
  4812. }
  4813. }, function( name, fn ) {
  4814. jQuery.fn[ name ] = function( until, selector ) {
  4815. var ret = jQuery.map( this, fn, until );
  4816. if ( !runtil.test( name ) ) {
  4817. selector = until;
  4818. }
  4819. if ( selector && typeof selector === "string" ) {
  4820. ret = jQuery.filter( selector, ret );
  4821. }
  4822. ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
  4823. if ( this.length > 1 && rparentsprev.test( name ) ) {
  4824. ret = ret.reverse();
  4825. }
  4826. return this.pushStack( ret );
  4827. };
  4828. });
  4829. jQuery.extend({
  4830. filter: function( expr, elems, not ) {
  4831. if ( not ) {
  4832. expr = ":not(" + expr + ")";
  4833. }
  4834. return elems.length === 1 ?
  4835. jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
  4836. jQuery.find.matches(expr, elems);
  4837. },
  4838. dir: function( elem, dir, until ) {
  4839. var matched = [],
  4840. cur = elem[ dir ];
  4841. while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
  4842. if ( cur.nodeType === 1 ) {
  4843. matched.push( cur );
  4844. }
  4845. cur = cur[dir];
  4846. }
  4847. return matched;
  4848. },
  4849. sibling: function( n, elem ) {
  4850. var r = [];
  4851. for ( ; n; n = n.nextSibling ) {
  4852. if ( n.nodeType === 1 && n !== elem ) {
  4853. r.push( n );
  4854. }
  4855. }
  4856. return r;
  4857. }
  4858. });
  4859. // Implement the identical functionality for filter and not
  4860. function winnow( elements, qualifier, keep ) {
  4861. // Can't pass null or undefined to indexOf in Firefox 4
  4862. // Set to 0 to skip string check
  4863. qualifier = qualifier || 0;
  4864. if ( jQuery.isFunction( qualifier ) ) {
  4865. return jQuery.grep(elements, function( elem, i ) {
  4866. var retVal = !!qualifier.call( elem, i, elem );
  4867. return retVal === keep;
  4868. });
  4869. } else if ( qualifier.nodeType ) {
  4870. return jQuery.grep(elements, function( elem ) {
  4871. return ( elem === qualifier ) === keep;
  4872. });
  4873. } else if ( typeof qualifier === "string" ) {
  4874. var filtered = jQuery.grep(elements, function( elem ) {
  4875. return elem.nodeType === 1;
  4876. });
  4877. if ( isSimple.test( qualifier ) ) {
  4878. return jQuery.filter(qualifier, filtered, !keep);
  4879. } else {
  4880. qualifier = jQuery.filter( qualifier, filtered );
  4881. }
  4882. }
  4883. return jQuery.grep(elements, function( elem ) {
  4884. return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
  4885. });
  4886. }
  4887. function createSafeFragment( document ) {
  4888. var list = nodeNames.split( "|" ),
  4889. safeFrag = document.createDocumentFragment();
  4890. if ( safeFrag.createElement ) {
  4891. while ( list.length ) {
  4892. safeFrag.createElement(
  4893. list.pop()
  4894. );
  4895. }
  4896. }
  4897. return safeFrag;
  4898. }
  4899. var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
  4900. "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
  4901. rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
  4902. rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
  4903. rleadingWhitespace = /^\s+/,
  4904. rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
  4905. rtagName = /<([\w:]+)/,
  4906. rtbody = /<tbody/i,
  4907. rhtml = /<|&#?\w+;/,
  4908. rnoInnerhtml = /<(?:script|style|link)/i,
  4909. manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
  4910. // checked="checked" or checked
  4911. rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
  4912. rscriptType = /^$|\/(?:java|ecma)script/i,
  4913. rscriptTypeMasked = /^true\/(.*)/,
  4914. rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
  4915. // We have to close these tags to support XHTML (#13200)
  4916. wrapMap = {
  4917. option: [ 1, "<select multiple='multiple'>", "</select>" ],
  4918. legend: [ 1, "<fieldset>", "</fieldset>" ],
  4919. area: [ 1, "<map>", "</map>" ],
  4920. param: [ 1, "<object>", "</object>" ],
  4921. thead: [ 1, "<table>", "</table>" ],
  4922. tr: [ 2, "<table><tbody>", "</tbody></table>" ],
  4923. col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
  4924. td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
  4925. // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
  4926. // unless wrapped in a div with non-breaking characters in front of it.
  4927. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
  4928. },
  4929. safeFragment = createSafeFragment( document ),
  4930. fragmentDiv = safeFragment.appendChild( document.createElement("div") );
  4931. wrapMap.optgroup = wrapMap.option;
  4932. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  4933. wrapMap.th = wrapMap.td;
  4934. jQuery.fn.extend({
  4935. text: function( value ) {
  4936. return jQuery.access( this, function( value ) {
  4937. return value === undefined ?
  4938. jQuery.text( this ) :
  4939. this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
  4940. }, null, value, arguments.length );
  4941. },
  4942. wrapAll: function( html ) {
  4943. if ( jQuery.isFunction( html ) ) {
  4944. return this.each(function(i) {
  4945. jQuery(this).wrapAll( html.call(this, i) );
  4946. });
  4947. }
  4948. if ( this[0] ) {
  4949. // The elements to wrap the target around
  4950. var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
  4951. if ( this[0].parentNode ) {
  4952. wrap.insertBefore( this[0] );
  4953. }
  4954. wrap.map(function() {
  4955. var elem = this;
  4956. while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
  4957. elem = elem.firstChild;
  4958. }
  4959. return elem;
  4960. }).append( this );
  4961. }
  4962. return this;
  4963. },
  4964. wrapInner: function( html ) {
  4965. if ( jQuery.isFunction( html ) ) {
  4966. return this.each(function(i) {
  4967. jQuery(this).wrapInner( html.call(this, i) );
  4968. });
  4969. }
  4970. return this.each(function() {
  4971. var self = jQuery( this ),
  4972. contents = self.contents();
  4973. if ( contents.length ) {
  4974. contents.wrapAll( html );
  4975. } else {
  4976. self.append( html );
  4977. }
  4978. });
  4979. },
  4980. wrap: function( html ) {
  4981. var isFunction = jQuery.isFunction( html );
  4982. return this.each(function(i) {
  4983. jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
  4984. });
  4985. },
  4986. unwrap: function() {
  4987. return this.parent().each(function() {
  4988. if ( !jQuery.nodeName( this, "body" ) ) {
  4989. jQuery( this ).replaceWith( this.childNodes );
  4990. }
  4991. }).end();
  4992. },
  4993. append: function() {
  4994. return this.domManip(arguments, true, function( elem ) {
  4995. if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
  4996. this.appendChild( elem );
  4997. }
  4998. });
  4999. },
  5000. prepend: function() {
  5001. return this.domManip(arguments, true, function( elem ) {
  5002. if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
  5003. this.insertBefore( elem, this.firstChild );
  5004. }
  5005. });
  5006. },
  5007. before: function() {
  5008. return this.domManip( arguments, false, function( elem ) {
  5009. if ( this.parentNode ) {
  5010. this.parentNode.insertBefore( elem, this );
  5011. }
  5012. });
  5013. },
  5014. after: function() {
  5015. return this.domManip( arguments, false, function( elem ) {
  5016. if ( this.parentNode ) {
  5017. this.parentNode.insertBefore( elem, this.nextSibling );
  5018. }
  5019. });
  5020. },
  5021. // keepData is for internal use only--do not document
  5022. remove: function( selector, keepData ) {
  5023. var elem,
  5024. i = 0;
  5025. for ( ; (elem = this[i]) != null; i++ ) {
  5026. if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) {
  5027. if ( !keepData && elem.nodeType === 1 ) {
  5028. jQuery.cleanData( getAll( elem ) );
  5029. }
  5030. if ( elem.parentNode ) {
  5031. if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
  5032. setGlobalEval( getAll( elem, "script" ) );
  5033. }
  5034. elem.parentNode.removeChild( elem );
  5035. }
  5036. }
  5037. }
  5038. return this;
  5039. },
  5040. empty: function() {
  5041. var elem,
  5042. i = 0;
  5043. for ( ; (elem = this[i]) != null; i++ ) {
  5044. // Remove element nodes and prevent memory leaks
  5045. if ( elem.nodeType === 1 ) {
  5046. jQuery.cleanData( getAll( elem, false ) );
  5047. }
  5048. // Remove any remaining nodes
  5049. while ( elem.firstChild ) {
  5050. elem.removeChild( elem.firstChild );
  5051. }
  5052. // If this is a select, ensure that it displays empty (#12336)
  5053. // Support: IE<9
  5054. if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
  5055. elem.options.length = 0;
  5056. }
  5057. }
  5058. return this;
  5059. },
  5060. clone: function( dataAndEvents, deepDataAndEvents ) {
  5061. dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
  5062. deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
  5063. return this.map( function () {
  5064. return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
  5065. });
  5066. },
  5067. html: function( value ) {
  5068. return jQuery.access( this, function( value ) {
  5069. var elem = this[0] || {},
  5070. i = 0,
  5071. l = this.length;
  5072. if ( value === undefined ) {
  5073. return elem.nodeType === 1 ?
  5074. elem.innerHTML.replace( rinlinejQuery, "" ) :
  5075. undefined;
  5076. }
  5077. // See if we can take a shortcut and just use innerHTML
  5078. if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
  5079. ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
  5080. ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
  5081. !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
  5082. value = value.replace( rxhtmlTag, "<$1></$2>" );
  5083. try {
  5084. for (; i < l; i++ ) {
  5085. // Remove element nodes and prevent memory leaks
  5086. elem = this[i] || {};
  5087. if ( elem.nodeType === 1 ) {
  5088. jQuery.cleanData( getAll( elem, false ) );
  5089. elem.innerHTML = value;
  5090. }
  5091. }
  5092. elem = 0;
  5093. // If using innerHTML throws an exception, use the fallback method
  5094. } catch(e) {}
  5095. }
  5096. if ( elem ) {
  5097. this.empty().append( value );
  5098. }
  5099. }, null, value, arguments.length );
  5100. },
  5101. replaceWith: function( value ) {
  5102. var isFunc = jQuery.isFunction( value );
  5103. // Make sure that the elements are removed from the DOM before they are inserted
  5104. // this can help fix replacing a parent with child elements
  5105. if ( !isFunc && typeof value !== "string" ) {
  5106. value = jQuery( value ).not( this ).detach();
  5107. }
  5108. return this.domManip( [ value ], true, function( elem ) {
  5109. var next = this.nextSibling,
  5110. parent = this.parentNode;
  5111. if ( parent && this.nodeType === 1 || this.nodeType === 11 ) {
  5112. jQuery( this ).remove();
  5113. if ( next ) {
  5114. next.parentNode.insertBefore( elem, next );
  5115. } else {
  5116. parent.appendChild( elem );
  5117. }
  5118. }
  5119. });
  5120. },
  5121. detach: function( selector ) {
  5122. return this.remove( selector, true );
  5123. },
  5124. domManip: function( args, table, callback ) {
  5125. // Flatten any nested arrays
  5126. args = core_concat.apply( [], args );
  5127. var fragment, first, scripts, hasScripts, node, doc,
  5128. i = 0,
  5129. l = this.length,
  5130. set = this,
  5131. iNoClone = l - 1,
  5132. value = args[0],
  5133. isFunction = jQuery.isFunction( value );
  5134. // We can't cloneNode fragments that contain checked, in WebKit
  5135. if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
  5136. return this.each(function( index ) {
  5137. var self = set.eq( index );
  5138. if ( isFunction ) {
  5139. args[0] = value.call( this, index, table ? self.html() : undefined );
  5140. }
  5141. self.domManip( args, table, callback );
  5142. });
  5143. }
  5144. if ( l ) {
  5145. fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
  5146. first = fragment.firstChild;
  5147. if ( fragment.childNodes.length === 1 ) {
  5148. fragment = first;
  5149. }
  5150. if ( first ) {
  5151. table = table && jQuery.nodeName( first, "tr" );
  5152. scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
  5153. hasScripts = scripts.length;
  5154. // Use the original fragment for the last item instead of the first because it can end up
  5155. // being emptied incorrectly in certain situations (#8070).
  5156. for ( ; i < l; i++ ) {
  5157. node = fragment;
  5158. if ( i !== iNoClone ) {
  5159. node = jQuery.clone( node, true, true );
  5160. // Keep references to cloned scripts for later restoration
  5161. if ( hasScripts ) {
  5162. jQuery.merge( scripts, getAll( node, "script" ) );
  5163. }
  5164. }
  5165. callback.call(
  5166. table && jQuery.nodeName( this[i], "table" ) ?
  5167. findOrAppend( this[i], "tbody" ) :
  5168. this[i],
  5169. node,
  5170. i
  5171. );
  5172. }
  5173. if ( hasScripts ) {
  5174. doc = scripts[ scripts.length - 1 ].ownerDocument;
  5175. // Reenable scripts
  5176. jQuery.map( scripts, restoreScript );
  5177. // Evaluate executable scripts on first document insertion
  5178. for ( i = 0; i < hasScripts; i++ ) {
  5179. node = scripts[ i ];
  5180. if ( rscriptType.test( node.type || "" ) &&
  5181. !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
  5182. if ( node.src ) {
  5183. // Hope ajax is available...
  5184. jQuery.ajax({
  5185. url: node.src,
  5186. type: "GET",
  5187. dataType: "script",
  5188. async: false,
  5189. global: false,
  5190. "throws": true
  5191. });
  5192. } else {
  5193. jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
  5194. }
  5195. }
  5196. }
  5197. }
  5198. // Fix #11809: Avoid leaking memory
  5199. fragment = first = null;
  5200. }
  5201. }
  5202. return this;
  5203. }
  5204. });
  5205. function findOrAppend( elem, tag ) {
  5206. return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
  5207. }
  5208. // Replace/restore the type attribute of script elements for safe DOM manipulation
  5209. function disableScript( elem ) {
  5210. var attr = elem.getAttributeNode("type");
  5211. elem.type = ( attr && attr.specified ) + "/" + elem.type;
  5212. return elem;
  5213. }
  5214. function restoreScript( elem ) {
  5215. var match = rscriptTypeMasked.exec( elem.type );
  5216. if ( match ) {
  5217. elem.type = match[1];
  5218. } else {
  5219. elem.removeAttribute("type");
  5220. }
  5221. return elem;
  5222. }
  5223. // Mark scripts as having already been evaluated
  5224. function setGlobalEval( elems, refElements ) {
  5225. var elem,
  5226. i = 0;
  5227. for ( ; (elem = elems[i]) != null; i++ ) {
  5228. jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
  5229. }
  5230. }
  5231. function cloneCopyEvent( src, dest ) {
  5232. if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
  5233. return;
  5234. }
  5235. var type, i, l,
  5236. oldData = jQuery._data( src ),
  5237. curData = jQuery._data( dest, oldData ),
  5238. events = oldData.events;
  5239. if ( events ) {
  5240. delete curData.handle;
  5241. curData.events = {};
  5242. for ( type in events ) {
  5243. for ( i = 0, l = events[ type ].length; i < l; i++ ) {
  5244. jQuery.event.add( dest, type, events[ type ][ i ] );
  5245. }
  5246. }
  5247. }
  5248. // make the cloned public data object a copy from the original
  5249. if ( curData.data ) {
  5250. curData.data = jQuery.extend( {}, curData.data );
  5251. }
  5252. }
  5253. function fixCloneNodeIssues( src, dest ) {
  5254. var nodeName, data, e;
  5255. // We do not need to do anything for non-Elements
  5256. if ( dest.nodeType !== 1 ) {
  5257. return;
  5258. }
  5259. nodeName = dest.nodeName.toLowerCase();
  5260. // IE6-8 copies events bound via attachEvent when using cloneNode.
  5261. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
  5262. data = jQuery._data( dest );
  5263. for ( e in data.events ) {
  5264. jQuery.removeEvent( dest, e, data.handle );
  5265. }
  5266. // Event data gets referenced instead of copied if the expando gets copied too
  5267. dest.removeAttribute( jQuery.expando );
  5268. }
  5269. // IE blanks contents when cloning scripts, and tries to evaluate newly-set text
  5270. if ( nodeName === "script" && dest.text !== src.text ) {
  5271. disableScript( dest ).text = src.text;
  5272. restoreScript( dest );
  5273. // IE6-10 improperly clones children of object elements using classid.
  5274. // IE10 throws NoModificationAllowedError if parent is null, #12132.
  5275. } else if ( nodeName === "object" ) {
  5276. if ( dest.parentNode ) {
  5277. dest.outerHTML = src.outerHTML;
  5278. }
  5279. // This path appears unavoidable for IE9. When cloning an object
  5280. // element in IE9, the outerHTML strategy above is not sufficient.
  5281. // If the src has innerHTML and the destination does not,
  5282. // copy the src.innerHTML into the dest.innerHTML. #10324
  5283. if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
  5284. dest.innerHTML = src.innerHTML;
  5285. }
  5286. } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
  5287. // IE6-8 fails to persist the checked state of a cloned checkbox
  5288. // or radio button. Worse, IE6-7 fail to give the cloned element
  5289. // a checked appearance if the defaultChecked value isn't also set
  5290. dest.defaultChecked = dest.checked = src.checked;
  5291. // IE6-7 get confused and end up setting the value of a cloned
  5292. // checkbox/radio button to an empty string instead of "on"
  5293. if ( dest.value !== src.value ) {
  5294. dest.value = src.value;
  5295. }
  5296. // IE6-8 fails to return the selected option to the default selected
  5297. // state when cloning options
  5298. } else if ( nodeName === "option" ) {
  5299. dest.defaultSelected = dest.selected = src.defaultSelected;
  5300. // IE6-8 fails to set the defaultValue to the correct value when
  5301. // cloning other types of input fields
  5302. } else if ( nodeName === "input" || nodeName === "textarea" ) {
  5303. dest.defaultValue = src.defaultValue;
  5304. }
  5305. }
  5306. jQuery.each({
  5307. appendTo: "append",
  5308. prependTo: "prepend",
  5309. insertBefore: "before",
  5310. insertAfter: "after",
  5311. replaceAll: "replaceWith"
  5312. }, function( name, original ) {
  5313. jQuery.fn[ name ] = function( selector ) {
  5314. var elems,
  5315. i = 0,
  5316. ret = [],
  5317. insert = jQuery( selector ),
  5318. last = insert.length - 1;
  5319. for ( ; i <= last; i++ ) {
  5320. elems = i === last ? this : this.clone(true);
  5321. jQuery( insert[i] )[ original ]( elems );
  5322. // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
  5323. core_push.apply( ret, elems.get() );
  5324. }
  5325. return this.pushStack( ret );
  5326. };
  5327. });
  5328. function getAll( context, tag ) {
  5329. var elems, elem,
  5330. i = 0,
  5331. found = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( tag || "*" ) :
  5332. typeof context.querySelectorAll !== "undefined" ? context.querySelectorAll( tag || "*" ) :
  5333. undefined;
  5334. if ( !found ) {
  5335. for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
  5336. if ( !tag || jQuery.nodeName( elem, tag ) ) {
  5337. found.push( elem );
  5338. } else {
  5339. jQuery.merge( found, getAll( elem, tag ) );
  5340. }
  5341. }
  5342. }
  5343. return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
  5344. jQuery.merge( [ context ], found ) :
  5345. found;
  5346. }
  5347. // Used in buildFragment, fixes the defaultChecked property
  5348. function fixDefaultChecked( elem ) {
  5349. if ( manipulation_rcheckableType.test( elem.type ) ) {
  5350. elem.defaultChecked = elem.checked;
  5351. }
  5352. }
  5353. jQuery.extend({
  5354. clone: function( elem, dataAndEvents, deepDataAndEvents ) {
  5355. var destElements, srcElements, node, i, clone,
  5356. inPage = jQuery.contains( elem.ownerDocument, elem );
  5357. if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
  5358. clone = elem.cloneNode( true );
  5359. // IE<=8 does not properly clone detached, unknown element nodes
  5360. } else {
  5361. fragmentDiv.innerHTML = elem.outerHTML;
  5362. fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
  5363. }
  5364. if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
  5365. (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
  5366. // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
  5367. destElements = getAll( clone );
  5368. srcElements = getAll( elem );
  5369. // Fix all IE cloning issues
  5370. for ( i = 0; (node = srcElements[i]) != null; ++i ) {
  5371. // Ensure that the destination node is not null; Fixes #9587
  5372. if ( destElements[i] ) {
  5373. fixCloneNodeIssues( node, destElements[i] );
  5374. }
  5375. }
  5376. }
  5377. // Copy the events from the original to the clone
  5378. if ( dataAndEvents ) {
  5379. if ( deepDataAndEvents ) {
  5380. srcElements = srcElements || getAll( elem );
  5381. destElements = destElements || getAll( clone );
  5382. for ( i = 0; (node = srcElements[i]) != null; i++ ) {
  5383. cloneCopyEvent( node, destElements[i] );
  5384. }
  5385. } else {
  5386. cloneCopyEvent( elem, clone );
  5387. }
  5388. }
  5389. // Preserve script evaluation history
  5390. destElements = getAll( clone, "script" );
  5391. if ( destElements.length > 0 ) {
  5392. setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
  5393. }
  5394. destElements = srcElements = node = null;
  5395. // Return the cloned set
  5396. return clone;
  5397. },
  5398. buildFragment: function( elems, context, scripts, selection ) {
  5399. var contains, elem, tag, tmp, wrap, tbody, j,
  5400. l = elems.length,
  5401. // Ensure a safe fragment
  5402. safe = createSafeFragment( context ),
  5403. nodes = [],
  5404. i = 0;
  5405. for ( ; i < l; i++ ) {
  5406. elem = elems[ i ];
  5407. if ( elem || elem === 0 ) {
  5408. // Add nodes directly
  5409. if ( jQuery.type( elem ) === "object" ) {
  5410. jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
  5411. // Convert non-html into a text node
  5412. } else if ( !rhtml.test( elem ) ) {
  5413. nodes.push( context.createTextNode( elem ) );
  5414. // Convert html into DOM nodes
  5415. } else {
  5416. tmp = tmp || safe.appendChild( context.createElement("div") );
  5417. // Deserialize a standard representation
  5418. tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
  5419. wrap = wrapMap[ tag ] || wrapMap._default;
  5420. tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
  5421. // Descend through wrappers to the right content
  5422. j = wrap[0];
  5423. while ( j-- ) {
  5424. tmp = tmp.lastChild;
  5425. }
  5426. // Manually add leading whitespace removed by IE
  5427. if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
  5428. nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
  5429. }
  5430. // Remove IE's autoinserted <tbody> from table fragments
  5431. if ( !jQuery.support.tbody ) {
  5432. // String was a <table>, *may* have spurious <tbody>
  5433. elem = tag === "table" && !rtbody.test( elem ) ?
  5434. tmp.firstChild :
  5435. // String was a bare <thead> or <tfoot>
  5436. wrap[1] === "<table>" && !rtbody.test( elem ) ?
  5437. tmp :
  5438. 0;
  5439. j = elem && elem.childNodes.length;
  5440. while ( j-- ) {
  5441. if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
  5442. elem.removeChild( tbody );
  5443. }
  5444. }
  5445. }
  5446. jQuery.merge( nodes, tmp.childNodes );
  5447. // Fix #12392 for WebKit and IE > 9
  5448. tmp.textContent = "";
  5449. // Fix #12392 for oldIE
  5450. while ( tmp.firstChild ) {
  5451. tmp.removeChild( tmp.firstChild );
  5452. }
  5453. // Remember the top-level container for proper cleanup
  5454. tmp = safe.lastChild;
  5455. }
  5456. }
  5457. }
  5458. // Fix #11356: Clear elements from fragment
  5459. if ( tmp ) {
  5460. safe.removeChild( tmp );
  5461. }
  5462. // Reset defaultChecked for any radios and checkboxes
  5463. // about to be appended to the DOM in IE 6/7 (#8060)
  5464. if ( !jQuery.support.appendChecked ) {
  5465. jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
  5466. }
  5467. i = 0;
  5468. while ( (elem = nodes[ i++ ]) ) {
  5469. // #4087 - If origin and destination elements are the same, and this is
  5470. // that element, do not do anything
  5471. if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
  5472. continue;
  5473. }
  5474. contains = jQuery.contains( elem.ownerDocument, elem );
  5475. // Append to fragment
  5476. tmp = getAll( safe.appendChild( elem ), "script" );
  5477. // Preserve script evaluation history
  5478. if ( contains ) {
  5479. setGlobalEval( tmp );
  5480. }
  5481. // Capture executables
  5482. if ( scripts ) {
  5483. j = 0;
  5484. while ( (elem = tmp[ j++ ]) ) {
  5485. if ( rscriptType.test( elem.type || "" ) ) {
  5486. scripts.push( elem );
  5487. }
  5488. }
  5489. }
  5490. }
  5491. tmp = null;
  5492. return safe;
  5493. },
  5494. cleanData: function( elems, /* internal */ acceptData ) {
  5495. var data, id, elem, type,
  5496. i = 0,
  5497. internalKey = jQuery.expando,
  5498. cache = jQuery.cache,
  5499. deleteExpando = jQuery.support.deleteExpando,
  5500. special = jQuery.event.special;
  5501. for ( ; (elem = elems[i]) != null; i++ ) {
  5502. if ( acceptData || jQuery.acceptData( elem ) ) {
  5503. id = elem[ internalKey ];
  5504. data = id && cache[ id ];
  5505. if ( data ) {
  5506. if ( data.events ) {
  5507. for ( type in data.events ) {
  5508. if ( special[ type ] ) {
  5509. jQuery.event.remove( elem, type );
  5510. // This is a shortcut to avoid jQuery.event.remove's overhead
  5511. } else {
  5512. jQuery.removeEvent( elem, type, data.handle );
  5513. }
  5514. }
  5515. }
  5516. // Remove cache only if it was not already removed by jQuery.event.remove
  5517. if ( cache[ id ] ) {
  5518. delete cache[ id ];
  5519. // IE does not allow us to delete expando properties from nodes,
  5520. // nor does it have a removeAttribute function on Document nodes;
  5521. // we must handle all of these cases
  5522. if ( deleteExpando ) {
  5523. delete elem[ internalKey ];
  5524. } else if ( typeof elem.removeAttribute !== "undefined" ) {
  5525. elem.removeAttribute( internalKey );
  5526. } else {
  5527. elem[ internalKey ] = null;
  5528. }
  5529. core_deletedIds.push( id );
  5530. }
  5531. }
  5532. }
  5533. }
  5534. }
  5535. });
  5536. var curCSS, getStyles, iframe,
  5537. ralpha = /alpha\([^)]*\)/i,
  5538. ropacity = /opacity\s*=\s*([^)]*)/,
  5539. rposition = /^(top|right|bottom|left)$/,
  5540. // swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
  5541. // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
  5542. rdisplayswap = /^(none|table(?!-c[ea]).+)/,
  5543. rmargin = /^margin/,
  5544. rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
  5545. rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
  5546. rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
  5547. elemdisplay = { BODY: "block" },
  5548. cssShow = { position: "absolute", visibility: "hidden", display: "block" },
  5549. cssNormalTransform = {
  5550. letterSpacing: 0,
  5551. fontWeight: 400
  5552. },
  5553. cssExpand = [ "Top", "Right", "Bottom", "Left" ],
  5554. cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
  5555. // return a css property mapped to a potentially vendor prefixed property
  5556. function vendorPropName( style, name ) {
  5557. // shortcut for names that are not vendor prefixed
  5558. if ( name in style ) {
  5559. return name;
  5560. }
  5561. // check for vendor prefixed names
  5562. var capName = name.charAt(0).toUpperCase() + name.slice(1),
  5563. origName = name,
  5564. i = cssPrefixes.length;
  5565. while ( i-- ) {
  5566. name = cssPrefixes[ i ] + capName;
  5567. if ( name in style ) {
  5568. return name;
  5569. }
  5570. }
  5571. return origName;
  5572. }
  5573. function isHidden( elem, el ) {
  5574. // isHidden might be called from jQuery#filter function;
  5575. // in that case, element will be second argument
  5576. elem = el || elem;
  5577. return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
  5578. }
  5579. function showHide( elements, show ) {
  5580. var elem,
  5581. values = [],
  5582. index = 0,
  5583. length = elements.length;
  5584. for ( ; index < length; index++ ) {
  5585. elem = elements[ index ];
  5586. if ( !elem.style ) {
  5587. continue;
  5588. }
  5589. values[ index ] = jQuery._data( elem, "olddisplay" );
  5590. if ( show ) {
  5591. // Reset the inline display of this element to learn if it is
  5592. // being hidden by cascaded rules or not
  5593. if ( !values[ index ] && elem.style.display === "none" ) {
  5594. elem.style.display = "";
  5595. }
  5596. // Set elements which have been overridden with display: none
  5597. // in a stylesheet to whatever the default browser style is
  5598. // for such an element
  5599. if ( elem.style.display === "" && isHidden( elem ) ) {
  5600. values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
  5601. }
  5602. } else if ( !values[ index ] && !isHidden( elem ) ) {
  5603. jQuery._data( elem, "olddisplay", jQuery.css( elem, "display" ) );
  5604. }
  5605. }
  5606. // Set the display of most of the elements in a second loop
  5607. // to avoid the constant reflow
  5608. for ( index = 0; index < length; index++ ) {
  5609. elem = elements[ index ];
  5610. if ( !elem.style ) {
  5611. continue;
  5612. }
  5613. if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
  5614. elem.style.display = show ? values[ index ] || "" : "none";
  5615. }
  5616. }
  5617. return elements;
  5618. }
  5619. jQuery.fn.extend({
  5620. css: function( name, value ) {
  5621. return jQuery.access( this, function( elem, name, value ) {
  5622. var styles, len,
  5623. map = {},
  5624. i = 0;
  5625. if ( jQuery.isArray( name ) ) {
  5626. styles = getStyles( elem );
  5627. len = name.length;
  5628. for ( ; i < len; i++ ) {
  5629. map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
  5630. }
  5631. return map;
  5632. }
  5633. return value !== undefined ?
  5634. jQuery.style( elem, name, value ) :
  5635. jQuery.css( elem, name );
  5636. }, name, value, arguments.length > 1 );
  5637. },
  5638. show: function() {
  5639. return showHide( this, true );
  5640. },
  5641. hide: function() {
  5642. return showHide( this );
  5643. },
  5644. toggle: function( state ) {
  5645. var bool = typeof state === "boolean";
  5646. return this.each(function() {
  5647. if ( bool ? state : isHidden( this ) ) {
  5648. jQuery( this ).show();
  5649. } else {
  5650. jQuery( this ).hide();
  5651. }
  5652. });
  5653. }
  5654. });
  5655. jQuery.extend({
  5656. // Add in style property hooks for overriding the default
  5657. // behavior of getting and setting a style property
  5658. cssHooks: {
  5659. opacity: {
  5660. get: function( elem, computed ) {
  5661. if ( computed ) {
  5662. // We should always get a number back from opacity
  5663. var ret = curCSS( elem, "opacity" );
  5664. return ret === "" ? "1" : ret;
  5665. }
  5666. }
  5667. }
  5668. },
  5669. // Exclude the following css properties to add px
  5670. cssNumber: {
  5671. "columnCount": true,
  5672. "fillOpacity": true,
  5673. "fontWeight": true,
  5674. "lineHeight": true,
  5675. "opacity": true,
  5676. "orphans": true,
  5677. "widows": true,
  5678. "zIndex": true,
  5679. "zoom": true
  5680. },
  5681. // Add in properties whose names you wish to fix before
  5682. // setting or getting the value
  5683. cssProps: {
  5684. // normalize float css property
  5685. "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
  5686. },
  5687. // Get and set the style property on a DOM Node
  5688. style: function( elem, name, value, extra ) {
  5689. // Don't set styles on text and comment nodes
  5690. if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
  5691. return;
  5692. }
  5693. // Make sure that we're working with the right name
  5694. var ret, type, hooks,
  5695. origName = jQuery.camelCase( name ),
  5696. style = elem.style;
  5697. name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
  5698. // gets hook for the prefixed version
  5699. // followed by the unprefixed version
  5700. hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
  5701. // Check if we're setting a value
  5702. if ( value !== undefined ) {
  5703. type = typeof value;
  5704. // convert relative number strings (+= or -=) to relative numbers. #7345
  5705. if ( type === "string" && (ret = rrelNum.exec( value )) ) {
  5706. value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
  5707. // Fixes bug #9237
  5708. type = "number";
  5709. }
  5710. // Make sure that NaN and null values aren't set. See: #7116
  5711. if ( value == null || type === "number" && isNaN( value ) ) {
  5712. return;
  5713. }
  5714. // If a number was passed in, add 'px' to the (except for certain CSS properties)
  5715. if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
  5716. value += "px";
  5717. }
  5718. // Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
  5719. // but it would mean to define eight (for every problematic property) identical functions
  5720. if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
  5721. style[ name ] = "inherit";
  5722. }
  5723. // If a hook was provided, use that value, otherwise just set the specified value
  5724. if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
  5725. // Wrapped to prevent IE from throwing errors when 'invalid' values are provided
  5726. // Fixes bug #5509
  5727. try {
  5728. style[ name ] = value;
  5729. } catch(e) {}
  5730. }
  5731. } else {
  5732. // If a hook was provided get the non-computed value from there
  5733. if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
  5734. return ret;
  5735. }
  5736. // Otherwise just get the value from the style object
  5737. return style[ name ];
  5738. }
  5739. },
  5740. css: function( elem, name, extra, styles ) {
  5741. var val, num, hooks,
  5742. origName = jQuery.camelCase( name );
  5743. // Make sure that we're working with the right name
  5744. name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
  5745. // gets hook for the prefixed version
  5746. // followed by the unprefixed version
  5747. hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
  5748. // If a hook was provided get the computed value from there
  5749. if ( hooks && "get" in hooks ) {
  5750. val = hooks.get( elem, true, extra );
  5751. }
  5752. // Otherwise, if a way to get the computed value exists, use that
  5753. if ( val === undefined ) {
  5754. val = curCSS( elem, name, styles );
  5755. }
  5756. //convert "normal" to computed value
  5757. if ( val === "normal" && name in cssNormalTransform ) {
  5758. val = cssNormalTransform[ name ];
  5759. }
  5760. // Return, converting to number if forced or a qualifier was provided and val looks numeric
  5761. if ( extra ) {
  5762. num = parseFloat( val );
  5763. return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
  5764. }
  5765. return val;
  5766. },
  5767. // A method for quickly swapping in/out CSS properties to get correct calculations
  5768. swap: function( elem, options, callback, args ) {
  5769. var ret, name,
  5770. old = {};
  5771. // Remember the old values, and insert the new ones
  5772. for ( name in options ) {
  5773. old[ name ] = elem.style[ name ];
  5774. elem.style[ name ] = options[ name ];
  5775. }
  5776. ret = callback.apply( elem, args || [] );
  5777. // Revert the old values
  5778. for ( name in options ) {
  5779. elem.style[ name ] = old[ name ];
  5780. }
  5781. return ret;
  5782. }
  5783. });
  5784. // NOTE: we've included the "window" in window.getComputedStyle
  5785. // because jsdom on node.js will break without it.
  5786. if ( window.getComputedStyle ) {
  5787. getStyles = function( elem ) {
  5788. return window.getComputedStyle( elem, null );
  5789. };
  5790. curCSS = function( elem, name, _computed ) {
  5791. var width, minWidth, maxWidth,
  5792. computed = _computed || getStyles( elem ),
  5793. // getPropertyValue is only needed for .css('filter') in IE9, see #12537
  5794. ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
  5795. style = elem.style;
  5796. if ( computed ) {
  5797. if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
  5798. ret = jQuery.style( elem, name );
  5799. }
  5800. // A tribute to the "awesome hack by Dean Edwards"
  5801. // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
  5802. // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
  5803. // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
  5804. if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
  5805. // Remember the original values
  5806. width = style.width;
  5807. minWidth = style.minWidth;
  5808. maxWidth = style.maxWidth;
  5809. // Put in the new values to get a computed value out
  5810. style.minWidth = style.maxWidth = style.width = ret;
  5811. ret = computed.width;
  5812. // Revert the changed values
  5813. style.width = width;
  5814. style.minWidth = minWidth;
  5815. style.maxWidth = maxWidth;
  5816. }
  5817. }
  5818. return ret;
  5819. };
  5820. } else if ( document.documentElement.currentStyle ) {
  5821. getStyles = function( elem ) {
  5822. return elem.currentStyle;
  5823. };
  5824. curCSS = function( elem, name, _computed ) {
  5825. var left, rs, rsLeft,
  5826. computed = _computed || getStyles( elem ),
  5827. ret = computed ? computed[ name ] : undefined,
  5828. style = elem.style;
  5829. // Avoid setting ret to empty string here
  5830. // so we don't default to auto
  5831. if ( ret == null && style && style[ name ] ) {
  5832. ret = style[ name ];
  5833. }
  5834. // From the awesome hack by Dean Edwards
  5835. // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
  5836. // If we're not dealing with a regular pixel number
  5837. // but a number that has a weird ending, we need to convert it to pixels
  5838. // but not position css attributes, as those are proportional to the parent element instead
  5839. // and we can't measure the parent instead because it might trigger a "stacking dolls" problem
  5840. if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
  5841. // Remember the original values
  5842. left = style.left;
  5843. rs = elem.runtimeStyle;
  5844. rsLeft = rs && rs.left;
  5845. // Put in the new values to get a computed value out
  5846. if ( rsLeft ) {
  5847. rs.left = elem.currentStyle.left;
  5848. }
  5849. style.left = name === "fontSize" ? "1em" : ret;
  5850. ret = style.pixelLeft + "px";
  5851. // Revert the changed values
  5852. style.left = left;
  5853. if ( rsLeft ) {
  5854. rs.left = rsLeft;
  5855. }
  5856. }
  5857. return ret === "" ? "auto" : ret;
  5858. };
  5859. }
  5860. function setPositiveNumber( elem, value, subtract ) {
  5861. var matches = rnumsplit.exec( value );
  5862. return matches ?
  5863. // Guard against undefined "subtract", e.g., when used as in cssHooks
  5864. Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
  5865. value;
  5866. }
  5867. function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
  5868. var i = extra === ( isBorderBox ? "border" : "content" ) ?
  5869. // If we already have the right measurement, avoid augmentation
  5870. 4 :
  5871. // Otherwise initialize for horizontal or vertical properties
  5872. name === "width" ? 1 : 0,
  5873. val = 0;
  5874. for ( ; i < 4; i += 2 ) {
  5875. // both box models exclude margin, so add it if we want it
  5876. if ( extra === "margin" ) {
  5877. val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
  5878. }
  5879. if ( isBorderBox ) {
  5880. // border-box includes padding, so remove it if we want content
  5881. if ( extra === "content" ) {
  5882. val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
  5883. }
  5884. // at this point, extra isn't border nor margin, so remove border
  5885. if ( extra !== "margin" ) {
  5886. val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
  5887. }
  5888. } else {
  5889. // at this point, extra isn't content, so add padding
  5890. val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
  5891. // at this point, extra isn't content nor padding, so add border
  5892. if ( extra !== "padding" ) {
  5893. val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
  5894. }
  5895. }
  5896. }
  5897. return val;
  5898. }
  5899. function getWidthOrHeight( elem, name, extra ) {
  5900. // Start with offset property, which is equivalent to the border-box value
  5901. var valueIsBorderBox = true,
  5902. val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
  5903. styles = getStyles( elem ),
  5904. isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
  5905. // some non-html elements return undefined for offsetWidth, so check for null/undefined
  5906. // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
  5907. // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
  5908. if ( val <= 0 || val == null ) {
  5909. // Fall back to computed then uncomputed css if necessary
  5910. val = curCSS( elem, name, styles );
  5911. if ( val < 0 || val == null ) {
  5912. val = elem.style[ name ];
  5913. }
  5914. // Computed unit is not pixels. Stop here and return.
  5915. if ( rnumnonpx.test(val) ) {
  5916. return val;
  5917. }
  5918. // we need the check for style in case a browser which returns unreliable values
  5919. // for getComputedStyle silently falls back to the reliable elem.style
  5920. valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
  5921. // Normalize "", auto, and prepare for extra
  5922. val = parseFloat( val ) || 0;
  5923. }
  5924. // use the active box-sizing model to add/subtract irrelevant styles
  5925. return ( val +
  5926. augmentWidthOrHeight(
  5927. elem,
  5928. name,
  5929. extra || ( isBorderBox ? "border" : "content" ),
  5930. valueIsBorderBox,
  5931. styles
  5932. )
  5933. ) + "px";
  5934. }
  5935. // Try to determine the default display value of an element
  5936. function css_defaultDisplay( nodeName ) {
  5937. var doc = document,
  5938. display = elemdisplay[ nodeName ];
  5939. if ( !display ) {
  5940. display = actualDisplay( nodeName, doc );
  5941. // If the simple way fails, read from inside an iframe
  5942. if ( display === "none" || !display ) {
  5943. // Use the already-created iframe if possible
  5944. iframe = ( iframe ||
  5945. jQuery("<iframe frameborder='0' width='0' height='0'/>")
  5946. .css( "cssText", "display:block !important" )
  5947. ).appendTo( doc.documentElement );
  5948. // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
  5949. doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
  5950. doc.write("<!doctype html><html><body>");
  5951. doc.close();
  5952. display = actualDisplay( nodeName, doc );
  5953. iframe.detach();
  5954. }
  5955. // Store the correct default display
  5956. elemdisplay[ nodeName ] = display;
  5957. }
  5958. return display;
  5959. }
  5960. // Called ONLY from within css_defaultDisplay
  5961. function actualDisplay( name, doc ) {
  5962. var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
  5963. display = jQuery.css( elem[0], "display" );
  5964. elem.remove();
  5965. return display;
  5966. }
  5967. jQuery.each([ "height", "width" ], function( i, name ) {
  5968. jQuery.cssHooks[ name ] = {
  5969. get: function( elem, computed, extra ) {
  5970. if ( computed ) {
  5971. // certain elements can have dimension info if we invisibly show them
  5972. // however, it must have a current display style that would benefit from this
  5973. return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
  5974. jQuery.swap( elem, cssShow, function() {
  5975. return getWidthOrHeight( elem, name, extra );
  5976. }) :
  5977. getWidthOrHeight( elem, name, extra );
  5978. }
  5979. },
  5980. set: function( elem, value, extra ) {
  5981. var styles = extra && getStyles( elem );
  5982. return setPositiveNumber( elem, value, extra ?
  5983. augmentWidthOrHeight(
  5984. elem,
  5985. name,
  5986. extra,
  5987. jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
  5988. styles
  5989. ) : 0
  5990. );
  5991. }
  5992. };
  5993. });
  5994. if ( !jQuery.support.opacity ) {
  5995. jQuery.cssHooks.opacity = {
  5996. get: function( elem, computed ) {
  5997. // IE uses filters for opacity
  5998. return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
  5999. ( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
  6000. computed ? "1" : "";
  6001. },
  6002. set: function( elem, value ) {
  6003. var style = elem.style,
  6004. currentStyle = elem.currentStyle,
  6005. opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
  6006. filter = currentStyle && currentStyle.filter || style.filter || "";
  6007. // IE has trouble with opacity if it does not have layout
  6008. // Force it by setting the zoom level
  6009. style.zoom = 1;
  6010. // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
  6011. // if value === "", then remove inline opacity #12685
  6012. if ( ( value >= 1 || value === "" ) &&
  6013. jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
  6014. style.removeAttribute ) {
  6015. // Setting style.filter to null, "" & " " still leave "filter:" in the cssText
  6016. // if "filter:" is present at all, clearType is disabled, we want to avoid this
  6017. // style.removeAttribute is IE Only, but so apparently is this code path...
  6018. style.removeAttribute( "filter" );
  6019. // if there is no filter style applied in a css rule or unset inline opacity, we are done
  6020. if ( value === "" || currentStyle && !currentStyle.filter ) {
  6021. return;
  6022. }
  6023. }
  6024. // otherwise, set new filter values
  6025. style.filter = ralpha.test( filter ) ?
  6026. filter.replace( ralpha, opacity ) :
  6027. filter + " " + opacity;
  6028. }
  6029. };
  6030. }
  6031. // These hooks cannot be added until DOM ready because the support test
  6032. // for it is not run until after DOM ready
  6033. jQuery(function() {
  6034. if ( !jQuery.support.reliableMarginRight ) {
  6035. jQuery.cssHooks.marginRight = {
  6036. get: function( elem, computed ) {
  6037. if ( computed ) {
  6038. // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
  6039. // Work around by temporarily setting element display to inline-block
  6040. return jQuery.swap( elem, { "display": "inline-block" },
  6041. curCSS, [ elem, "marginRight" ] );
  6042. }
  6043. }
  6044. };
  6045. }
  6046. // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
  6047. // getComputedStyle returns percent when specified for top/left/bottom/right
  6048. // rather than make the css module depend on the offset module, we just check for it here
  6049. if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
  6050. jQuery.each( [ "top", "left" ], function( i, prop ) {
  6051. jQuery.cssHooks[ prop ] = {
  6052. get: function( elem, computed ) {
  6053. if ( computed ) {
  6054. computed = curCSS( elem, prop );
  6055. // if curCSS returns percentage, fallback to offset
  6056. return rnumnonpx.test( computed ) ?
  6057. jQuery( elem ).position()[ prop ] + "px" :
  6058. computed;
  6059. }
  6060. }
  6061. };
  6062. });
  6063. }
  6064. });
  6065. if ( jQuery.expr && jQuery.expr.filters ) {
  6066. jQuery.expr.filters.hidden = function( elem ) {
  6067. return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
  6068. };
  6069. jQuery.expr.filters.visible = function( elem ) {
  6070. return !jQuery.expr.filters.hidden( elem );
  6071. };
  6072. }
  6073. // These hooks are used by animate to expand properties
  6074. jQuery.each({
  6075. margin: "",
  6076. padding: "",
  6077. border: "Width"
  6078. }, function( prefix, suffix ) {
  6079. jQuery.cssHooks[ prefix + suffix ] = {
  6080. expand: function( value ) {
  6081. var i = 0,
  6082. expanded = {},
  6083. // assumes a single number if not a string
  6084. parts = typeof value === "string" ? value.split(" ") : [ value ];
  6085. for ( ; i < 4; i++ ) {
  6086. expanded[ prefix + cssExpand[ i ] + suffix ] =
  6087. parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
  6088. }
  6089. return expanded;
  6090. }
  6091. };
  6092. if ( !rmargin.test( prefix ) ) {
  6093. jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
  6094. }
  6095. });
  6096. var r20 = /%20/g,
  6097. rbracket = /\[\]$/,
  6098. rCRLF = /\r?\n/g,
  6099. rsubmitterTypes = /^(?:submit|button|image|reset)$/i,
  6100. rsubmittable = /^(?:input|select|textarea|keygen)/i;
  6101. jQuery.fn.extend({
  6102. serialize: function() {
  6103. return jQuery.param( this.serializeArray() );
  6104. },
  6105. serializeArray: function() {
  6106. return this.map(function(){
  6107. // Can add propHook for "elements" to filter or add form elements
  6108. var elements = jQuery.prop( this, "elements" );
  6109. return elements ? jQuery.makeArray( elements ) : this;
  6110. })
  6111. .filter(function(){
  6112. var type = this.type;
  6113. // Use .is(":disabled") so that fieldset[disabled] works
  6114. return this.name && !jQuery( this ).is( ":disabled" ) &&
  6115. rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
  6116. ( this.checked || !manipulation_rcheckableType.test( type ) );
  6117. })
  6118. .map(function( i, elem ){
  6119. var val = jQuery( this ).val();
  6120. return val == null ?
  6121. null :
  6122. jQuery.isArray( val ) ?
  6123. jQuery.map( val, function( val ){
  6124. return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
  6125. }) :
  6126. { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
  6127. }).get();
  6128. }
  6129. });
  6130. //Serialize an array of form elements or a set of
  6131. //key/values into a query string
  6132. jQuery.param = function( a, traditional ) {
  6133. var prefix,
  6134. s = [],
  6135. add = function( key, value ) {
  6136. // If value is a function, invoke it and return its value
  6137. value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
  6138. s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
  6139. };
  6140. // Set traditional to true for jQuery <= 1.3.2 behavior.
  6141. if ( traditional === undefined ) {
  6142. traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
  6143. }
  6144. // If an array was passed in, assume that it is an array of form elements.
  6145. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
  6146. // Serialize the form elements
  6147. jQuery.each( a, function() {
  6148. add( this.name, this.value );
  6149. });
  6150. } else {
  6151. // If traditional, encode the "old" way (the way 1.3.2 or older
  6152. // did it), otherwise encode params recursively.
  6153. for ( prefix in a ) {
  6154. buildParams( prefix, a[ prefix ], traditional, add );
  6155. }
  6156. }
  6157. // Return the resulting serialization
  6158. return s.join( "&" ).replace( r20, "+" );
  6159. };
  6160. function buildParams( prefix, obj, traditional, add ) {
  6161. var name;
  6162. if ( jQuery.isArray( obj ) ) {
  6163. // Serialize array item.
  6164. jQuery.each( obj, function( i, v ) {
  6165. if ( traditional || rbracket.test( prefix ) ) {
  6166. // Treat each array item as a scalar.
  6167. add( prefix, v );
  6168. } else {
  6169. // Item is non-scalar (array or object), encode its numeric index.
  6170. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
  6171. }
  6172. });
  6173. } else if ( !traditional && jQuery.type( obj ) === "object" ) {
  6174. // Serialize object item.
  6175. for ( name in obj ) {
  6176. buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
  6177. }
  6178. } else {
  6179. // Serialize scalar item.
  6180. add( prefix, obj );
  6181. }
  6182. }
  6183. var
  6184. // Document location
  6185. ajaxLocParts,
  6186. ajaxLocation,
  6187. ajax_nonce = jQuery.now(),
  6188. ajax_rquery = /\?/,
  6189. rhash = /#.*$/,
  6190. rts = /([?&])_=[^&]*/,
  6191. rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
  6192. // #7653, #8125, #8152: local protocol detection
  6193. rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
  6194. rnoContent = /^(?:GET|HEAD)$/,
  6195. rprotocol = /^\/\//,
  6196. rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
  6197. // Keep a copy of the old load method
  6198. _load = jQuery.fn.load,
  6199. /* Prefilters
  6200. * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
  6201. * 2) These are called:
  6202. * - BEFORE asking for a transport
  6203. * - AFTER param serialization (s.data is a string if s.processData is true)
  6204. * 3) key is the dataType
  6205. * 4) the catchall symbol "*" can be used
  6206. * 5) execution will start with transport dataType and THEN continue down to "*" if needed
  6207. */
  6208. prefilters = {},
  6209. /* Transports bindings
  6210. * 1) key is the dataType
  6211. * 2) the catchall symbol "*" can be used
  6212. * 3) selection will start with transport dataType and THEN go to "*" if needed
  6213. */
  6214. transports = {},
  6215. // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
  6216. allTypes = "*/".concat("*");
  6217. // #8138, IE may throw an exception when accessing
  6218. // a field from window.location if document.domain has been set
  6219. try {
  6220. ajaxLocation = location.href;
  6221. } catch( e ) {
  6222. // Use the href attribute of an A element
  6223. // since IE will modify it given document.location
  6224. ajaxLocation = document.createElement( "a" );
  6225. ajaxLocation.href = "";
  6226. ajaxLocation = ajaxLocation.href;
  6227. }
  6228. // Segment location into parts
  6229. ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
  6230. // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
  6231. function addToPrefiltersOrTransports( structure ) {
  6232. // dataTypeExpression is optional and defaults to "*"
  6233. return function( dataTypeExpression, func ) {
  6234. if ( typeof dataTypeExpression !== "string" ) {
  6235. func = dataTypeExpression;
  6236. dataTypeExpression = "*";
  6237. }
  6238. var dataType,
  6239. i = 0,
  6240. dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
  6241. if ( jQuery.isFunction( func ) ) {
  6242. // For each dataType in the dataTypeExpression
  6243. while ( (dataType = dataTypes[i++]) ) {
  6244. // Prepend if requested
  6245. if ( dataType[0] === "+" ) {
  6246. dataType = dataType.slice( 1 ) || "*";
  6247. (structure[ dataType ] = structure[ dataType ] || []).unshift( func );
  6248. // Otherwise append
  6249. } else {
  6250. (structure[ dataType ] = structure[ dataType ] || []).push( func );
  6251. }
  6252. }
  6253. }
  6254. };
  6255. }
  6256. // Base inspection function for prefilters and transports
  6257. function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
  6258. var inspected = {},
  6259. seekingTransport = ( structure === transports );
  6260. function inspect( dataType ) {
  6261. var selected;
  6262. inspected[ dataType ] = true;
  6263. jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
  6264. var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
  6265. if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
  6266. options.dataTypes.unshift( dataTypeOrTransport );
  6267. inspect( dataTypeOrTransport );
  6268. return false;
  6269. } else if ( seekingTransport ) {
  6270. return !( selected = dataTypeOrTransport );
  6271. }
  6272. });
  6273. return selected;
  6274. }
  6275. return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
  6276. }
  6277. // A special extend for ajax options
  6278. // that takes "flat" options (not to be deep extended)
  6279. // Fixes #9887
  6280. function ajaxExtend( target, src ) {
  6281. var key, deep,
  6282. flatOptions = jQuery.ajaxSettings.flatOptions || {};
  6283. for ( key in src ) {
  6284. if ( src[ key ] !== undefined ) {
  6285. ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
  6286. }
  6287. }
  6288. if ( deep ) {
  6289. jQuery.extend( true, target, deep );
  6290. }
  6291. return target;
  6292. }
  6293. jQuery.fn.load = function( url, params, callback ) {
  6294. if ( typeof url !== "string" && _load ) {
  6295. return _load.apply( this, arguments );
  6296. }
  6297. var selector, type, response,
  6298. self = this,
  6299. off = url.indexOf(" ");
  6300. if ( off >= 0 ) {
  6301. selector = url.slice( off, url.length );
  6302. url = url.slice( 0, off );
  6303. }
  6304. // If it's a function
  6305. if ( jQuery.isFunction( params ) ) {
  6306. // We assume that it's the callback
  6307. callback = params;
  6308. params = undefined;
  6309. // Otherwise, build a param string
  6310. } else if ( params && typeof params === "object" ) {
  6311. type = "POST";
  6312. }
  6313. // If we have elements to modify, make the request
  6314. if ( self.length > 0 ) {
  6315. jQuery.ajax({
  6316. url: url,
  6317. // if "type" variable is undefined, then "GET" method will be used
  6318. type: type,
  6319. dataType: "html",
  6320. data: params
  6321. }).done(function( responseText ) {
  6322. // Save response for use in complete callback
  6323. response = arguments;
  6324. self.html( selector ?
  6325. // If a selector was specified, locate the right elements in a dummy div
  6326. // Exclude scripts to avoid IE 'Permission Denied' errors
  6327. jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
  6328. // Otherwise use the full result
  6329. responseText );
  6330. }).complete( callback && function( jqXHR, status ) {
  6331. self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
  6332. });
  6333. }
  6334. return this;
  6335. };
  6336. // Attach a bunch of functions for handling common AJAX events
  6337. jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
  6338. jQuery.fn[ type ] = function( fn ){
  6339. return this.on( type, fn );
  6340. };
  6341. });
  6342. jQuery.each( [ "get", "post" ], function( i, method ) {
  6343. jQuery[ method ] = function( url, data, callback, type ) {
  6344. // shift arguments if data argument was omitted
  6345. if ( jQuery.isFunction( data ) ) {
  6346. type = type || callback;
  6347. callback = data;
  6348. data = undefined;
  6349. }
  6350. return jQuery.ajax({
  6351. url: url,
  6352. type: method,
  6353. dataType: type,
  6354. data: data,
  6355. success: callback
  6356. });
  6357. };
  6358. });
  6359. jQuery.extend({
  6360. // Counter for holding the number of active queries
  6361. active: 0,
  6362. // Last-Modified header cache for next request
  6363. lastModified: {},
  6364. etag: {},
  6365. ajaxSettings: {
  6366. url: ajaxLocation,
  6367. type: "GET",
  6368. isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
  6369. global: true,
  6370. processData: true,
  6371. async: true,
  6372. contentType: "application/x-www-form-urlencoded; charset=UTF-8",
  6373. /*
  6374. timeout: 0,
  6375. data: null,
  6376. dataType: null,
  6377. username: null,
  6378. password: null,
  6379. cache: null,
  6380. throws: false,
  6381. traditional: false,
  6382. headers: {},
  6383. */
  6384. accepts: {
  6385. "*": allTypes,
  6386. text: "text/plain",
  6387. html: "text/html",
  6388. xml: "application/xml, text/xml",
  6389. json: "application/json, text/javascript"
  6390. },
  6391. contents: {
  6392. xml: /xml/,
  6393. html: /html/,
  6394. json: /json/
  6395. },
  6396. responseFields: {
  6397. xml: "responseXML",
  6398. text: "responseText"
  6399. },
  6400. // Data converters
  6401. // Keys separate source (or catchall "*") and destination types with a single space
  6402. converters: {
  6403. // Convert anything to text
  6404. "* text": window.String,
  6405. // Text to html (true = no transformation)
  6406. "text html": true,
  6407. // Evaluate text as a json expression
  6408. "text json": jQuery.parseJSON,
  6409. // Parse text as xml
  6410. "text xml": jQuery.parseXML
  6411. },
  6412. // For options that shouldn't be deep extended:
  6413. // you can add your own custom options here if
  6414. // and when you create one that shouldn't be
  6415. // deep extended (see ajaxExtend)
  6416. flatOptions: {
  6417. url: true,
  6418. context: true
  6419. }
  6420. },
  6421. // Creates a full fledged settings object into target
  6422. // with both ajaxSettings and settings fields.
  6423. // If target is omitted, writes into ajaxSettings.
  6424. ajaxSetup: function( target, settings ) {
  6425. return settings ?
  6426. // Building a settings object
  6427. ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
  6428. // Extending ajaxSettings
  6429. ajaxExtend( jQuery.ajaxSettings, target );
  6430. },
  6431. ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
  6432. ajaxTransport: addToPrefiltersOrTransports( transports ),
  6433. // Main method
  6434. ajax: function( url, options ) {
  6435. // If url is an object, simulate pre-1.5 signature
  6436. if ( typeof url === "object" ) {
  6437. options = url;
  6438. url = undefined;
  6439. }
  6440. // Force options to be an object
  6441. options = options || {};
  6442. var transport,
  6443. // URL without anti-cache param
  6444. cacheURL,
  6445. // Response headers
  6446. responseHeadersString,
  6447. responseHeaders,
  6448. // timeout handle
  6449. timeoutTimer,
  6450. // Cross-domain detection vars
  6451. parts,
  6452. // To know if global events are to be dispatched
  6453. fireGlobals,
  6454. // Loop variable
  6455. i,
  6456. // Create the final options object
  6457. s = jQuery.ajaxSetup( {}, options ),
  6458. // Callbacks context
  6459. callbackContext = s.context || s,
  6460. // Context for global events is callbackContext if it is a DOM node or jQuery collection
  6461. globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
  6462. jQuery( callbackContext ) :
  6463. jQuery.event,
  6464. // Deferreds
  6465. deferred = jQuery.Deferred(),
  6466. completeDeferred = jQuery.Callbacks("once memory"),
  6467. // Status-dependent callbacks
  6468. statusCode = s.statusCode || {},
  6469. // Headers (they are sent all at once)
  6470. requestHeaders = {},
  6471. requestHeadersNames = {},
  6472. // The jqXHR state
  6473. state = 0,
  6474. // Default abort message
  6475. strAbort = "canceled",
  6476. // Fake xhr
  6477. jqXHR = {
  6478. readyState: 0,
  6479. // Builds headers hashtable if needed
  6480. getResponseHeader: function( key ) {
  6481. var match;
  6482. if ( state === 2 ) {
  6483. if ( !responseHeaders ) {
  6484. responseHeaders = {};
  6485. while ( (match = rheaders.exec( responseHeadersString )) ) {
  6486. responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
  6487. }
  6488. }
  6489. match = responseHeaders[ key.toLowerCase() ];
  6490. }
  6491. return match == null ? null : match;
  6492. },
  6493. // Raw string
  6494. getAllResponseHeaders: function() {
  6495. return state === 2 ? responseHeadersString : null;
  6496. },
  6497. // Caches the header
  6498. setRequestHeader: function( name, value ) {
  6499. var lname = name.toLowerCase();
  6500. if ( !state ) {
  6501. name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
  6502. requestHeaders[ name ] = value;
  6503. }
  6504. return this;
  6505. },
  6506. // Overrides response content-type header
  6507. overrideMimeType: function( type ) {
  6508. if ( !state ) {
  6509. s.mimeType = type;
  6510. }
  6511. return this;
  6512. },
  6513. // Status-dependent callbacks
  6514. statusCode: function( map ) {
  6515. var code;
  6516. if ( map ) {
  6517. if ( state < 2 ) {
  6518. for ( code in map ) {
  6519. // Lazy-add the new callback in a way that preserves old ones
  6520. statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
  6521. }
  6522. } else {
  6523. // Execute the appropriate callbacks
  6524. jqXHR.always( map[ jqXHR.status ] );
  6525. }
  6526. }
  6527. return this;
  6528. },
  6529. // Cancel the request
  6530. abort: function( statusText ) {
  6531. var finalText = statusText || strAbort;
  6532. if ( transport ) {
  6533. transport.abort( finalText );
  6534. }
  6535. done( 0, finalText );
  6536. return this;
  6537. }
  6538. };
  6539. // Attach deferreds
  6540. deferred.promise( jqXHR ).complete = completeDeferred.add;
  6541. jqXHR.success = jqXHR.done;
  6542. jqXHR.error = jqXHR.fail;
  6543. // Remove hash character (#7531: and string promotion)
  6544. // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
  6545. // Handle falsy url in the settings object (#10093: consistency with old signature)
  6546. // We also use the url parameter if available
  6547. s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
  6548. // Alias method option to type as per ticket #12004
  6549. s.type = options.method || options.type || s.method || s.type;
  6550. // Extract dataTypes list
  6551. s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
  6552. // A cross-domain request is in order when we have a protocol:host:port mismatch
  6553. if ( s.crossDomain == null ) {
  6554. parts = rurl.exec( s.url.toLowerCase() );
  6555. s.crossDomain = !!( parts &&
  6556. ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
  6557. ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
  6558. ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
  6559. );
  6560. }
  6561. // Convert data if not already a string
  6562. if ( s.data && s.processData && typeof s.data !== "string" ) {
  6563. s.data = jQuery.param( s.data, s.traditional );
  6564. }
  6565. // Apply prefilters
  6566. inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
  6567. // If request was aborted inside a prefilter, stop there
  6568. if ( state === 2 ) {
  6569. return jqXHR;
  6570. }
  6571. // We can fire global events as of now if asked to
  6572. fireGlobals = s.global;
  6573. // Watch for a new set of requests
  6574. if ( fireGlobals && jQuery.active++ === 0 ) {
  6575. jQuery.event.trigger("ajaxStart");
  6576. }
  6577. // Uppercase the type
  6578. s.type = s.type.toUpperCase();
  6579. // Determine if request has content
  6580. s.hasContent = !rnoContent.test( s.type );
  6581. // Save the URL in case we're toying with the If-Modified-Since
  6582. // and/or If-None-Match header later on
  6583. cacheURL = s.url;
  6584. // More options handling for requests with no content
  6585. if ( !s.hasContent ) {
  6586. // If data is available, append data to url
  6587. if ( s.data ) {
  6588. cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
  6589. // #9682: remove data so that it's not used in an eventual retry
  6590. delete s.data;
  6591. }
  6592. // Add anti-cache in url if needed
  6593. if ( s.cache === false ) {
  6594. s.url = rts.test( cacheURL ) ?
  6595. // If there is already a '_' parameter, set its value
  6596. cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
  6597. // Otherwise add one to the end
  6598. cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
  6599. }
  6600. }
  6601. // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
  6602. if ( s.ifModified ) {
  6603. if ( jQuery.lastModified[ cacheURL ] ) {
  6604. jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
  6605. }
  6606. if ( jQuery.etag[ cacheURL ] ) {
  6607. jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
  6608. }
  6609. }
  6610. // Set the correct header, if data is being sent
  6611. if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
  6612. jqXHR.setRequestHeader( "Content-Type", s.contentType );
  6613. }
  6614. // Set the Accepts header for the server, depending on the dataType
  6615. jqXHR.setRequestHeader(
  6616. "Accept",
  6617. s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
  6618. s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
  6619. s.accepts[ "*" ]
  6620. );
  6621. // Check for headers option
  6622. for ( i in s.headers ) {
  6623. jqXHR.setRequestHeader( i, s.headers[ i ] );
  6624. }
  6625. // Allow custom headers/mimetypes and early abort
  6626. if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
  6627. // Abort if not done already and return
  6628. return jqXHR.abort();
  6629. }
  6630. // aborting is no longer a cancellation
  6631. strAbort = "abort";
  6632. // Install callbacks on deferreds
  6633. for ( i in { success: 1, error: 1, complete: 1 } ) {
  6634. jqXHR[ i ]( s[ i ] );
  6635. }
  6636. // Get transport
  6637. transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
  6638. // If no transport, we auto-abort
  6639. if ( !transport ) {
  6640. done( -1, "No Transport" );
  6641. } else {
  6642. jqXHR.readyState = 1;
  6643. // Send global event
  6644. if ( fireGlobals ) {
  6645. globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
  6646. }
  6647. // Timeout
  6648. if ( s.async && s.timeout > 0 ) {
  6649. timeoutTimer = setTimeout(function() {
  6650. jqXHR.abort("timeout");
  6651. }, s.timeout );
  6652. }
  6653. try {
  6654. state = 1;
  6655. transport.send( requestHeaders, done );
  6656. } catch ( e ) {
  6657. // Propagate exception as error if not done
  6658. if ( state < 2 ) {
  6659. done( -1, e );
  6660. // Simply rethrow otherwise
  6661. } else {
  6662. throw e;
  6663. }
  6664. }
  6665. }
  6666. // Callback for when everything is done
  6667. function done( status, nativeStatusText, responses, headers ) {
  6668. var isSuccess, success, error, response, modified,
  6669. statusText = nativeStatusText;
  6670. // Called once
  6671. if ( state === 2 ) {
  6672. return;
  6673. }
  6674. // State is "done" now
  6675. state = 2;
  6676. // Clear timeout if it exists
  6677. if ( timeoutTimer ) {
  6678. clearTimeout( timeoutTimer );
  6679. }
  6680. // Dereference transport for early garbage collection
  6681. // (no matter how long the jqXHR object will be used)
  6682. transport = undefined;
  6683. // Cache response headers
  6684. responseHeadersString = headers || "";
  6685. // Set readyState
  6686. jqXHR.readyState = status > 0 ? 4 : 0;
  6687. // Get response data
  6688. if ( responses ) {
  6689. response = ajaxHandleResponses( s, jqXHR, responses );
  6690. }
  6691. // If successful, handle type chaining
  6692. if ( status >= 200 && status < 300 || status === 304 ) {
  6693. // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
  6694. if ( s.ifModified ) {
  6695. modified = jqXHR.getResponseHeader("Last-Modified");
  6696. if ( modified ) {
  6697. jQuery.lastModified[ cacheURL ] = modified;
  6698. }
  6699. modified = jqXHR.getResponseHeader("etag");
  6700. if ( modified ) {
  6701. jQuery.etag[ cacheURL ] = modified;
  6702. }
  6703. }
  6704. // If not modified
  6705. if ( status === 304 ) {
  6706. isSuccess = true;
  6707. statusText = "notmodified";
  6708. // If we have data
  6709. } else {
  6710. isSuccess = ajaxConvert( s, response );
  6711. statusText = isSuccess.state;
  6712. success = isSuccess.data;
  6713. error = isSuccess.error;
  6714. isSuccess = !error;
  6715. }
  6716. } else {
  6717. // We extract error from statusText
  6718. // then normalize statusText and status for non-aborts
  6719. error = statusText;
  6720. if ( status || !statusText ) {
  6721. statusText = "error";
  6722. if ( status < 0 ) {
  6723. status = 0;
  6724. }
  6725. }
  6726. }
  6727. // Set data for the fake xhr object
  6728. jqXHR.status = status;
  6729. jqXHR.statusText = ( nativeStatusText || statusText ) + "";
  6730. // Success/Error
  6731. if ( isSuccess ) {
  6732. deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
  6733. } else {
  6734. deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
  6735. }
  6736. // Status-dependent callbacks
  6737. jqXHR.statusCode( statusCode );
  6738. statusCode = undefined;
  6739. if ( fireGlobals ) {
  6740. globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
  6741. [ jqXHR, s, isSuccess ? success : error ] );
  6742. }
  6743. // Complete
  6744. completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
  6745. if ( fireGlobals ) {
  6746. globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
  6747. // Handle the global AJAX counter
  6748. if ( !( --jQuery.active ) ) {
  6749. jQuery.event.trigger("ajaxStop");
  6750. }
  6751. }
  6752. }
  6753. return jqXHR;
  6754. },
  6755. getScript: function( url, callback ) {
  6756. return jQuery.get( url, undefined, callback, "script" );
  6757. },
  6758. getJSON: function( url, data, callback ) {
  6759. return jQuery.get( url, data, callback, "json" );
  6760. }
  6761. });
  6762. /* Handles responses to an ajax request:
  6763. * - sets all responseXXX fields accordingly
  6764. * - finds the right dataType (mediates between content-type and expected dataType)
  6765. * - returns the corresponding response
  6766. */
  6767. function ajaxHandleResponses( s, jqXHR, responses ) {
  6768. var ct, type, finalDataType, firstDataType,
  6769. contents = s.contents,
  6770. dataTypes = s.dataTypes,
  6771. responseFields = s.responseFields;
  6772. // Fill responseXXX fields
  6773. for ( type in responseFields ) {
  6774. if ( type in responses ) {
  6775. jqXHR[ responseFields[type] ] = responses[ type ];
  6776. }
  6777. }
  6778. // Remove auto dataType and get content-type in the process
  6779. while( dataTypes[ 0 ] === "*" ) {
  6780. dataTypes.shift();
  6781. if ( ct === undefined ) {
  6782. ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
  6783. }
  6784. }
  6785. // Check if we're dealing with a known content-type
  6786. if ( ct ) {
  6787. for ( type in contents ) {
  6788. if ( contents[ type ] && contents[ type ].test( ct ) ) {
  6789. dataTypes.unshift( type );
  6790. break;
  6791. }
  6792. }
  6793. }
  6794. // Check to see if we have a response for the expected dataType
  6795. if ( dataTypes[ 0 ] in responses ) {
  6796. finalDataType = dataTypes[ 0 ];
  6797. } else {
  6798. // Try convertible dataTypes
  6799. for ( type in responses ) {
  6800. if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
  6801. finalDataType = type;
  6802. break;
  6803. }
  6804. if ( !firstDataType ) {
  6805. firstDataType = type;
  6806. }
  6807. }
  6808. // Or just use first one
  6809. finalDataType = finalDataType || firstDataType;
  6810. }
  6811. // If we found a dataType
  6812. // We add the dataType to the list if needed
  6813. // and return the corresponding response
  6814. if ( finalDataType ) {
  6815. if ( finalDataType !== dataTypes[ 0 ] ) {
  6816. dataTypes.unshift( finalDataType );
  6817. }
  6818. return responses[ finalDataType ];
  6819. }
  6820. }
  6821. // Chain conversions given the request and the original response
  6822. function ajaxConvert( s, response ) {
  6823. var conv, conv2, current, tmp,
  6824. converters = {},
  6825. i = 0,
  6826. // Work with a copy of dataTypes in case we need to modify it for conversion
  6827. dataTypes = s.dataTypes.slice(),
  6828. prev = dataTypes[ 0 ];
  6829. // Apply the dataFilter if provided
  6830. if ( s.dataFilter ) {
  6831. response = s.dataFilter( response, s.dataType );
  6832. }
  6833. // Create converters map with lowercased keys
  6834. if ( dataTypes[ 1 ] ) {
  6835. for ( conv in s.converters ) {
  6836. converters[ conv.toLowerCase() ] = s.converters[ conv ];
  6837. }
  6838. }
  6839. // Convert to each sequential dataType, tolerating list modification
  6840. for ( ; (current = dataTypes[++i]); ) {
  6841. // There's only work to do if current dataType is non-auto
  6842. if ( current !== "*" ) {
  6843. // Convert response if prev dataType is non-auto and differs from current
  6844. if ( prev !== "*" && prev !== current ) {
  6845. // Seek a direct converter
  6846. conv = converters[ prev + " " + current ] || converters[ "* " + current ];
  6847. // If none found, seek a pair
  6848. if ( !conv ) {
  6849. for ( conv2 in converters ) {
  6850. // If conv2 outputs current
  6851. tmp = conv2.split(" ");
  6852. if ( tmp[ 1 ] === current ) {
  6853. // If prev can be converted to accepted input
  6854. conv = converters[ prev + " " + tmp[ 0 ] ] ||
  6855. converters[ "* " + tmp[ 0 ] ];
  6856. if ( conv ) {
  6857. // Condense equivalence converters
  6858. if ( conv === true ) {
  6859. conv = converters[ conv2 ];
  6860. // Otherwise, insert the intermediate dataType
  6861. } else if ( converters[ conv2 ] !== true ) {
  6862. current = tmp[ 0 ];
  6863. dataTypes.splice( i--, 0, current );
  6864. }
  6865. break;
  6866. }
  6867. }
  6868. }
  6869. }
  6870. // Apply converter (if not an equivalence)
  6871. if ( conv !== true ) {
  6872. // Unless errors are allowed to bubble, catch and return them
  6873. if ( conv && s["throws"] ) {
  6874. response = conv( response );
  6875. } else {
  6876. try {
  6877. response = conv( response );
  6878. } catch ( e ) {
  6879. return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
  6880. }
  6881. }
  6882. }
  6883. }
  6884. // Update prev for next iteration
  6885. prev = current;
  6886. }
  6887. }
  6888. return { state: "success", data: response };
  6889. }
  6890. // Install script dataType
  6891. jQuery.ajaxSetup({
  6892. accepts: {
  6893. script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
  6894. },
  6895. contents: {
  6896. script: /(?:java|ecma)script/
  6897. },
  6898. converters: {
  6899. "text script": function( text ) {
  6900. jQuery.globalEval( text );
  6901. return text;
  6902. }
  6903. }
  6904. });
  6905. // Handle cache's special case and global
  6906. jQuery.ajaxPrefilter( "script", function( s ) {
  6907. if ( s.cache === undefined ) {
  6908. s.cache = false;
  6909. }
  6910. if ( s.crossDomain ) {
  6911. s.type = "GET";
  6912. s.global = false;
  6913. }
  6914. });
  6915. // Bind script tag hack transport
  6916. jQuery.ajaxTransport( "script", function(s) {
  6917. // This transport only deals with cross domain requests
  6918. if ( s.crossDomain ) {
  6919. var script,
  6920. head = document.head || jQuery("head")[0] || document.documentElement;
  6921. return {
  6922. send: function( _, callback ) {
  6923. script = document.createElement("script");
  6924. script.async = true;
  6925. if ( s.scriptCharset ) {
  6926. script.charset = s.scriptCharset;
  6927. }
  6928. script.src = s.url;
  6929. // Attach handlers for all browsers
  6930. script.onload = script.onreadystatechange = function( _, isAbort ) {
  6931. if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
  6932. // Handle memory leak in IE
  6933. script.onload = script.onreadystatechange = null;
  6934. // Remove the script
  6935. if ( script.parentNode ) {
  6936. script.parentNode.removeChild( script );
  6937. }
  6938. // Dereference the script
  6939. script = null;
  6940. // Callback if not abort
  6941. if ( !isAbort ) {
  6942. callback( 200, "success" );
  6943. }
  6944. }
  6945. };
  6946. // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
  6947. // Use native DOM manipulation to avoid our domManip AJAX trickery
  6948. head.insertBefore( script, head.firstChild );
  6949. },
  6950. abort: function() {
  6951. if ( script ) {
  6952. script.onload( undefined, true );
  6953. }
  6954. }
  6955. };
  6956. }
  6957. });
  6958. var oldCallbacks = [],
  6959. rjsonp = /(=)\?(?=&|$)|\?\?/;
  6960. // Default jsonp settings
  6961. jQuery.ajaxSetup({
  6962. jsonp: "callback",
  6963. jsonpCallback: function() {
  6964. var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
  6965. this[ callback ] = true;
  6966. return callback;
  6967. }
  6968. });
  6969. // Detect, normalize options and install callbacks for jsonp requests
  6970. jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
  6971. var callbackName, overwritten, responseContainer,
  6972. jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
  6973. "url" :
  6974. typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
  6975. );
  6976. // Handle iff the expected data type is "jsonp" or we have a parameter to set
  6977. if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
  6978. // Get callback name, remembering preexisting value associated with it
  6979. callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
  6980. s.jsonpCallback() :
  6981. s.jsonpCallback;
  6982. // Insert callback into url or form data
  6983. if ( jsonProp ) {
  6984. s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
  6985. } else if ( s.jsonp !== false ) {
  6986. s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
  6987. }
  6988. // Use data converter to retrieve json after script execution
  6989. s.converters["script json"] = function() {
  6990. if ( !responseContainer ) {
  6991. jQuery.error( callbackName + " was not called" );
  6992. }
  6993. return responseContainer[ 0 ];
  6994. };
  6995. // force json dataType
  6996. s.dataTypes[ 0 ] = "json";
  6997. // Install callback
  6998. overwritten = window[ callbackName ];
  6999. window[ callbackName ] = function() {
  7000. responseContainer = arguments;
  7001. };
  7002. // Clean-up function (fires after converters)
  7003. jqXHR.always(function() {
  7004. // Restore preexisting value
  7005. window[ callbackName ] = overwritten;
  7006. // Save back as free
  7007. if ( s[ callbackName ] ) {
  7008. // make sure that re-using the options doesn't screw things around
  7009. s.jsonpCallback = originalSettings.jsonpCallback;
  7010. // save the callback name for future use
  7011. oldCallbacks.push( callbackName );
  7012. }
  7013. // Call if it was a function and we have a response
  7014. if ( responseContainer && jQuery.isFunction( overwritten ) ) {
  7015. overwritten( responseContainer[ 0 ] );
  7016. }
  7017. responseContainer = overwritten = undefined;
  7018. });
  7019. // Delegate to script
  7020. return "script";
  7021. }
  7022. });
  7023. var xhrCallbacks, xhrSupported,
  7024. xhrId = 0,
  7025. // #5280: Internet Explorer will keep connections alive if we don't abort on unload
  7026. xhrOnUnloadAbort = window.ActiveXObject && function() {
  7027. // Abort all pending requests
  7028. var key;
  7029. for ( key in xhrCallbacks ) {
  7030. xhrCallbacks[ key ]( undefined, true );
  7031. }
  7032. };
  7033. // Functions to create xhrs
  7034. function createStandardXHR() {
  7035. try {
  7036. return new window.XMLHttpRequest();
  7037. } catch( e ) {}
  7038. }
  7039. function createActiveXHR() {
  7040. try {
  7041. return new window.ActiveXObject("Microsoft.XMLHTTP");
  7042. } catch( e ) {}
  7043. }
  7044. // Create the request object
  7045. // (This is still attached to ajaxSettings for backward compatibility)
  7046. jQuery.ajaxSettings.xhr = window.ActiveXObject ?
  7047. /* Microsoft failed to properly
  7048. * implement the XMLHttpRequest in IE7 (can't request local files),
  7049. * so we use the ActiveXObject when it is available
  7050. * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
  7051. * we need a fallback.
  7052. */
  7053. function() {
  7054. return !this.isLocal && createStandardXHR() || createActiveXHR();
  7055. } :
  7056. // For all other browsers, use the standard XMLHttpRequest object
  7057. createStandardXHR;
  7058. // Determine support properties
  7059. xhrSupported = jQuery.ajaxSettings.xhr();
  7060. jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
  7061. xhrSupported = jQuery.support.ajax = !!xhrSupported;
  7062. // Create transport if the browser can provide an xhr
  7063. if ( xhrSupported ) {
  7064. jQuery.ajaxTransport(function( s ) {
  7065. // Cross domain only allowed if supported through XMLHttpRequest
  7066. if ( !s.crossDomain || jQuery.support.cors ) {
  7067. var callback;
  7068. return {
  7069. send: function( headers, complete ) {
  7070. // Get a new xhr
  7071. var handle, i,
  7072. xhr = s.xhr();
  7073. // Open the socket
  7074. // Passing null username, generates a login popup on Opera (#2865)
  7075. if ( s.username ) {
  7076. xhr.open( s.type, s.url, s.async, s.username, s.password );
  7077. } else {
  7078. xhr.open( s.type, s.url, s.async );
  7079. }
  7080. // Apply custom fields if provided
  7081. if ( s.xhrFields ) {
  7082. for ( i in s.xhrFields ) {
  7083. xhr[ i ] = s.xhrFields[ i ];
  7084. }
  7085. }
  7086. // Override mime type if needed
  7087. if ( s.mimeType && xhr.overrideMimeType ) {
  7088. xhr.overrideMimeType( s.mimeType );
  7089. }
  7090. // X-Requested-With header
  7091. // For cross-domain requests, seeing as conditions for a preflight are
  7092. // akin to a jigsaw puzzle, we simply never set it to be sure.
  7093. // (it can always be set on a per-request basis or even using ajaxSetup)
  7094. // For same-domain requests, won't change header if already provided.
  7095. if ( !s.crossDomain && !headers["X-Requested-With"] ) {
  7096. headers["X-Requested-With"] = "XMLHttpRequest";
  7097. }
  7098. // Need an extra try/catch for cross domain requests in Firefox 3
  7099. try {
  7100. for ( i in headers ) {
  7101. xhr.setRequestHeader( i, headers[ i ] );
  7102. }
  7103. } catch( err ) {}
  7104. // Do send the request
  7105. // This may raise an exception which is actually
  7106. // handled in jQuery.ajax (so no try/catch here)
  7107. xhr.send( ( s.hasContent && s.data ) || null );
  7108. // Listener
  7109. callback = function( _, isAbort ) {
  7110. var status,
  7111. statusText,
  7112. responseHeaders,
  7113. responses,
  7114. xml;
  7115. // Firefox throws exceptions when accessing properties
  7116. // of an xhr when a network error occurred
  7117. // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
  7118. try {
  7119. // Was never called and is aborted or complete
  7120. if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
  7121. // Only called once
  7122. callback = undefined;
  7123. // Do not keep as active anymore
  7124. if ( handle ) {
  7125. xhr.onreadystatechange = jQuery.noop;
  7126. if ( xhrOnUnloadAbort ) {
  7127. delete xhrCallbacks[ handle ];
  7128. }
  7129. }
  7130. // If it's an abort
  7131. if ( isAbort ) {
  7132. // Abort it manually if needed
  7133. if ( xhr.readyState !== 4 ) {
  7134. xhr.abort();
  7135. }
  7136. } else {
  7137. responses = {};
  7138. status = xhr.status;
  7139. xml = xhr.responseXML;
  7140. responseHeaders = xhr.getAllResponseHeaders();
  7141. // Construct response list
  7142. if ( xml && xml.documentElement /* #4958 */ ) {
  7143. responses.xml = xml;
  7144. }
  7145. // When requesting binary data, IE6-9 will throw an exception
  7146. // on any attempt to access responseText (#11426)
  7147. if ( typeof xhr.responseText === "string" ) {
  7148. responses.text = xhr.responseText;
  7149. }
  7150. // Firefox throws an exception when accessing
  7151. // statusText for faulty cross-domain requests
  7152. try {
  7153. statusText = xhr.statusText;
  7154. } catch( e ) {
  7155. // We normalize with Webkit giving an empty statusText
  7156. statusText = "";
  7157. }
  7158. // Filter status for non standard behaviors
  7159. // If the request is local and we have data: assume a success
  7160. // (success with no data won't get notified, that's the best we
  7161. // can do given current implementations)
  7162. if ( !status && s.isLocal && !s.crossDomain ) {
  7163. status = responses.text ? 200 : 404;
  7164. // IE - #1450: sometimes returns 1223 when it should be 204
  7165. } else if ( status === 1223 ) {
  7166. status = 204;
  7167. }
  7168. }
  7169. }
  7170. } catch( firefoxAccessException ) {
  7171. if ( !isAbort ) {
  7172. complete( -1, firefoxAccessException );
  7173. }
  7174. }
  7175. // Call complete if needed
  7176. if ( responses ) {
  7177. complete( status, statusText, responses, responseHeaders );
  7178. }
  7179. };
  7180. if ( !s.async ) {
  7181. // if we're in sync mode we fire the callback
  7182. callback();
  7183. } else if ( xhr.readyState === 4 ) {
  7184. // (IE6 & IE7) if it's in cache and has been
  7185. // retrieved directly we need to fire the callback
  7186. setTimeout( callback );
  7187. } else {
  7188. handle = ++xhrId;
  7189. if ( xhrOnUnloadAbort ) {
  7190. // Create the active xhrs callbacks list if needed
  7191. // and attach the unload handler
  7192. if ( !xhrCallbacks ) {
  7193. xhrCallbacks = {};
  7194. jQuery( window ).unload( xhrOnUnloadAbort );
  7195. }
  7196. // Add to list of active xhrs callbacks
  7197. xhrCallbacks[ handle ] = callback;
  7198. }
  7199. xhr.onreadystatechange = callback;
  7200. }
  7201. },
  7202. abort: function() {
  7203. if ( callback ) {
  7204. callback( undefined, true );
  7205. }
  7206. }
  7207. };
  7208. }
  7209. });
  7210. }
  7211. var fxNow, timerId,
  7212. rfxtypes = /^(?:toggle|show|hide)$/,
  7213. rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
  7214. rrun = /queueHooks$/,
  7215. animationPrefilters = [ defaultPrefilter ],
  7216. tweeners = {
  7217. "*": [function( prop, value ) {
  7218. var end, unit,
  7219. tween = this.createTween( prop, value ),
  7220. parts = rfxnum.exec( value ),
  7221. target = tween.cur(),
  7222. start = +target || 0,
  7223. scale = 1,
  7224. maxIterations = 20;
  7225. if ( parts ) {
  7226. end = +parts[2];
  7227. unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
  7228. // We need to compute starting value
  7229. if ( unit !== "px" && start ) {
  7230. // Iteratively approximate from a nonzero starting point
  7231. // Prefer the current property, because this process will be trivial if it uses the same units
  7232. // Fallback to end or a simple constant
  7233. start = jQuery.css( tween.elem, prop, true ) || end || 1;
  7234. do {
  7235. // If previous iteration zeroed out, double until we get *something*
  7236. // Use a string for doubling factor so we don't accidentally see scale as unchanged below
  7237. scale = scale || ".5";
  7238. // Adjust and apply
  7239. start = start / scale;
  7240. jQuery.style( tween.elem, prop, start + unit );
  7241. // Update scale, tolerating zero or NaN from tween.cur()
  7242. // And breaking the loop if scale is unchanged or perfect, or if we've just had enough
  7243. } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
  7244. }
  7245. tween.unit = unit;
  7246. tween.start = start;
  7247. // If a +=/-= token was provided, we're doing a relative animation
  7248. tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
  7249. }
  7250. return tween;
  7251. }]
  7252. };
  7253. // Animations created synchronously will run synchronously
  7254. function createFxNow() {
  7255. setTimeout(function() {
  7256. fxNow = undefined;
  7257. });
  7258. return ( fxNow = jQuery.now() );
  7259. }
  7260. function createTweens( animation, props ) {
  7261. jQuery.each( props, function( prop, value ) {
  7262. var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
  7263. index = 0,
  7264. length = collection.length;
  7265. for ( ; index < length; index++ ) {
  7266. if ( collection[ index ].call( animation, prop, value ) ) {
  7267. // we're done with this property
  7268. return;
  7269. }
  7270. }
  7271. });
  7272. }
  7273. function Animation( elem, properties, options ) {
  7274. var result,
  7275. stopped,
  7276. index = 0,
  7277. length = animationPrefilters.length,
  7278. deferred = jQuery.Deferred().always( function() {
  7279. // don't match elem in the :animated selector
  7280. delete tick.elem;
  7281. }),
  7282. tick = function() {
  7283. if ( stopped ) {
  7284. return false;
  7285. }
  7286. var currentTime = fxNow || createFxNow(),
  7287. remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
  7288. // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
  7289. temp = remaining / animation.duration || 0,
  7290. percent = 1 - temp,
  7291. index = 0,
  7292. length = animation.tweens.length;
  7293. for ( ; index < length ; index++ ) {
  7294. animation.tweens[ index ].run( percent );
  7295. }
  7296. deferred.notifyWith( elem, [ animation, percent, remaining ]);
  7297. if ( percent < 1 && length ) {
  7298. return remaining;
  7299. } else {
  7300. deferred.resolveWith( elem, [ animation ] );
  7301. return false;
  7302. }
  7303. },
  7304. animation = deferred.promise({
  7305. elem: elem,
  7306. props: jQuery.extend( {}, properties ),
  7307. opts: jQuery.extend( true, { specialEasing: {} }, options ),
  7308. originalProperties: properties,
  7309. originalOptions: options,
  7310. startTime: fxNow || createFxNow(),
  7311. duration: options.duration,
  7312. tweens: [],
  7313. createTween: function( prop, end ) {
  7314. var tween = jQuery.Tween( elem, animation.opts, prop, end,
  7315. animation.opts.specialEasing[ prop ] || animation.opts.easing );
  7316. animation.tweens.push( tween );
  7317. return tween;
  7318. },
  7319. stop: function( gotoEnd ) {
  7320. var index = 0,
  7321. // if we are going to the end, we want to run all the tweens
  7322. // otherwise we skip this part
  7323. length = gotoEnd ? animation.tweens.length : 0;
  7324. if ( stopped ) {
  7325. return this;
  7326. }
  7327. stopped = true;
  7328. for ( ; index < length ; index++ ) {
  7329. animation.tweens[ index ].run( 1 );
  7330. }
  7331. // resolve when we played the last frame
  7332. // otherwise, reject
  7333. if ( gotoEnd ) {
  7334. deferred.resolveWith( elem, [ animation, gotoEnd ] );
  7335. } else {
  7336. deferred.rejectWith( elem, [ animation, gotoEnd ] );
  7337. }
  7338. return this;
  7339. }
  7340. }),
  7341. props = animation.props;
  7342. propFilter( props, animation.opts.specialEasing );
  7343. for ( ; index < length ; index++ ) {
  7344. result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
  7345. if ( result ) {
  7346. return result;
  7347. }
  7348. }
  7349. createTweens( animation, props );
  7350. if ( jQuery.isFunction( animation.opts.start ) ) {
  7351. animation.opts.start.call( elem, animation );
  7352. }
  7353. jQuery.fx.timer(
  7354. jQuery.extend( tick, {
  7355. elem: elem,
  7356. anim: animation,
  7357. queue: animation.opts.queue
  7358. })
  7359. );
  7360. // attach callbacks from options
  7361. return animation.progress( animation.opts.progress )
  7362. .done( animation.opts.done, animation.opts.complete )
  7363. .fail( animation.opts.fail )
  7364. .always( animation.opts.always );
  7365. }
  7366. function propFilter( props, specialEasing ) {
  7367. var index, name, easing, value, hooks;
  7368. // camelCase, specialEasing and expand cssHook pass
  7369. for ( index in props ) {
  7370. name = jQuery.camelCase( index );
  7371. easing = specialEasing[ name ];
  7372. value = props[ index ];
  7373. if ( jQuery.isArray( value ) ) {
  7374. easing = value[ 1 ];
  7375. value = props[ index ] = value[ 0 ];
  7376. }
  7377. if ( index !== name ) {
  7378. props[ name ] = value;
  7379. delete props[ index ];
  7380. }
  7381. hooks = jQuery.cssHooks[ name ];
  7382. if ( hooks && "expand" in hooks ) {
  7383. value = hooks.expand( value );
  7384. delete props[ name ];
  7385. // not quite $.extend, this wont overwrite keys already present.
  7386. // also - reusing 'index' from above because we have the correct "name"
  7387. for ( index in value ) {
  7388. if ( !( index in props ) ) {
  7389. props[ index ] = value[ index ];
  7390. specialEasing[ index ] = easing;
  7391. }
  7392. }
  7393. } else {
  7394. specialEasing[ name ] = easing;
  7395. }
  7396. }
  7397. }
  7398. jQuery.Animation = jQuery.extend( Animation, {
  7399. tweener: function( props, callback ) {
  7400. if ( jQuery.isFunction( props ) ) {
  7401. callback = props;
  7402. props = [ "*" ];
  7403. } else {
  7404. props = props.split(" ");
  7405. }
  7406. var prop,
  7407. index = 0,
  7408. length = props.length;
  7409. for ( ; index < length ; index++ ) {
  7410. prop = props[ index ];
  7411. tweeners[ prop ] = tweeners[ prop ] || [];
  7412. tweeners[ prop ].unshift( callback );
  7413. }
  7414. },
  7415. prefilter: function( callback, prepend ) {
  7416. if ( prepend ) {
  7417. animationPrefilters.unshift( callback );
  7418. } else {
  7419. animationPrefilters.push( callback );
  7420. }
  7421. }
  7422. });
  7423. function defaultPrefilter( elem, props, opts ) {
  7424. /*jshint validthis:true */
  7425. var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire,
  7426. anim = this,
  7427. style = elem.style,
  7428. orig = {},
  7429. handled = [],
  7430. hidden = elem.nodeType && isHidden( elem );
  7431. // handle queue: false promises
  7432. if ( !opts.queue ) {
  7433. hooks = jQuery._queueHooks( elem, "fx" );
  7434. if ( hooks.unqueued == null ) {
  7435. hooks.unqueued = 0;
  7436. oldfire = hooks.empty.fire;
  7437. hooks.empty.fire = function() {
  7438. if ( !hooks.unqueued ) {
  7439. oldfire();
  7440. }
  7441. };
  7442. }
  7443. hooks.unqueued++;
  7444. anim.always(function() {
  7445. // doing this makes sure that the complete handler will be called
  7446. // before this completes
  7447. anim.always(function() {
  7448. hooks.unqueued--;
  7449. if ( !jQuery.queue( elem, "fx" ).length ) {
  7450. hooks.empty.fire();
  7451. }
  7452. });
  7453. });
  7454. }
  7455. // height/width overflow pass
  7456. if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
  7457. // Make sure that nothing sneaks out
  7458. // Record all 3 overflow attributes because IE does not
  7459. // change the overflow attribute when overflowX and
  7460. // overflowY are set to the same value
  7461. opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
  7462. // Set display property to inline-block for height/width
  7463. // animations on inline elements that are having width/height animated
  7464. if ( jQuery.css( elem, "display" ) === "inline" &&
  7465. jQuery.css( elem, "float" ) === "none" ) {
  7466. // inline-level elements accept inline-block;
  7467. // block-level elements need to be inline with layout
  7468. if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
  7469. style.display = "inline-block";
  7470. } else {
  7471. style.zoom = 1;
  7472. }
  7473. }
  7474. }
  7475. if ( opts.overflow ) {
  7476. style.overflow = "hidden";
  7477. if ( !jQuery.support.shrinkWrapBlocks ) {
  7478. anim.done(function() {
  7479. style.overflow = opts.overflow[ 0 ];
  7480. style.overflowX = opts.overflow[ 1 ];
  7481. style.overflowY = opts.overflow[ 2 ];
  7482. });
  7483. }
  7484. }
  7485. // show/hide pass
  7486. for ( index in props ) {
  7487. value = props[ index ];
  7488. if ( rfxtypes.exec( value ) ) {
  7489. delete props[ index ];
  7490. toggle = toggle || value === "toggle";
  7491. if ( value === ( hidden ? "hide" : "show" ) ) {
  7492. continue;
  7493. }
  7494. handled.push( index );
  7495. }
  7496. }
  7497. length = handled.length;
  7498. if ( length ) {
  7499. dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
  7500. if ( "hidden" in dataShow ) {
  7501. hidden = dataShow.hidden;
  7502. }
  7503. // store state if its toggle - enables .stop().toggle() to "reverse"
  7504. if ( toggle ) {
  7505. dataShow.hidden = !hidden;
  7506. }
  7507. if ( hidden ) {
  7508. jQuery( elem ).show();
  7509. } else {
  7510. anim.done(function() {
  7511. jQuery( elem ).hide();
  7512. });
  7513. }
  7514. anim.done(function() {
  7515. var prop;
  7516. jQuery._removeData( elem, "fxshow" );
  7517. for ( prop in orig ) {
  7518. jQuery.style( elem, prop, orig[ prop ] );
  7519. }
  7520. });
  7521. for ( index = 0 ; index < length ; index++ ) {
  7522. prop = handled[ index ];
  7523. tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
  7524. orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
  7525. if ( !( prop in dataShow ) ) {
  7526. dataShow[ prop ] = tween.start;
  7527. if ( hidden ) {
  7528. tween.end = tween.start;
  7529. tween.start = prop === "width" || prop === "height" ? 1 : 0;
  7530. }
  7531. }
  7532. }
  7533. }
  7534. }
  7535. function Tween( elem, options, prop, end, easing ) {
  7536. return new Tween.prototype.init( elem, options, prop, end, easing );
  7537. }
  7538. jQuery.Tween = Tween;
  7539. Tween.prototype = {
  7540. constructor: Tween,
  7541. init: function( elem, options, prop, end, easing, unit ) {
  7542. this.elem = elem;
  7543. this.prop = prop;
  7544. this.easing = easing || "swing";
  7545. this.options = options;
  7546. this.start = this.now = this.cur();
  7547. this.end = end;
  7548. this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
  7549. },
  7550. cur: function() {
  7551. var hooks = Tween.propHooks[ this.prop ];
  7552. return hooks && hooks.get ?
  7553. hooks.get( this ) :
  7554. Tween.propHooks._default.get( this );
  7555. },
  7556. run: function( percent ) {
  7557. var eased,
  7558. hooks = Tween.propHooks[ this.prop ];
  7559. if ( this.options.duration ) {
  7560. this.pos = eased = jQuery.easing[ this.easing ](
  7561. percent, this.options.duration * percent, 0, 1, this.options.duration
  7562. );
  7563. } else {
  7564. this.pos = eased = percent;
  7565. }
  7566. this.now = ( this.end - this.start ) * eased + this.start;
  7567. if ( this.options.step ) {
  7568. this.options.step.call( this.elem, this.now, this );
  7569. }
  7570. if ( hooks && hooks.set ) {
  7571. hooks.set( this );
  7572. } else {
  7573. Tween.propHooks._default.set( this );
  7574. }
  7575. return this;
  7576. }
  7577. };
  7578. Tween.prototype.init.prototype = Tween.prototype;
  7579. Tween.propHooks = {
  7580. _default: {
  7581. get: function( tween ) {
  7582. var result;
  7583. if ( tween.elem[ tween.prop ] != null &&
  7584. (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
  7585. return tween.elem[ tween.prop ];
  7586. }
  7587. // passing a non empty string as a 3rd parameter to .css will automatically
  7588. // attempt a parseFloat and fallback to a string if the parse fails
  7589. // so, simple values such as "10px" are parsed to Float.
  7590. // complex values such as "rotate(1rad)" are returned as is.
  7591. result = jQuery.css( tween.elem, tween.prop, "auto" );
  7592. // Empty strings, null, undefined and "auto" are converted to 0.
  7593. return !result || result === "auto" ? 0 : result;
  7594. },
  7595. set: function( tween ) {
  7596. // use step hook for back compat - use cssHook if its there - use .style if its
  7597. // available and use plain properties where available
  7598. if ( jQuery.fx.step[ tween.prop ] ) {
  7599. jQuery.fx.step[ tween.prop ]( tween );
  7600. } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
  7601. jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
  7602. } else {
  7603. tween.elem[ tween.prop ] = tween.now;
  7604. }
  7605. }
  7606. }
  7607. };
  7608. // Remove in 2.0 - this supports IE8's panic based approach
  7609. // to setting things on disconnected nodes
  7610. Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
  7611. set: function( tween ) {
  7612. if ( tween.elem.nodeType && tween.elem.parentNode ) {
  7613. tween.elem[ tween.prop ] = tween.now;
  7614. }
  7615. }
  7616. };
  7617. jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
  7618. var cssFn = jQuery.fn[ name ];
  7619. jQuery.fn[ name ] = function( speed, easing, callback ) {
  7620. return speed == null || typeof speed === "boolean" ?
  7621. cssFn.apply( this, arguments ) :
  7622. this.animate( genFx( name, true ), speed, easing, callback );
  7623. };
  7624. });
  7625. jQuery.fn.extend({
  7626. fadeTo: function( speed, to, easing, callback ) {
  7627. // show any hidden elements after setting opacity to 0
  7628. return this.filter( isHidden ).css( "opacity", 0 ).show()
  7629. // animate to the value specified
  7630. .end().animate({ opacity: to }, speed, easing, callback );
  7631. },
  7632. animate: function( prop, speed, easing, callback ) {
  7633. var empty = jQuery.isEmptyObject( prop ),
  7634. optall = jQuery.speed( speed, easing, callback ),
  7635. doAnimation = function() {
  7636. // Operate on a copy of prop so per-property easing won't be lost
  7637. var anim = Animation( this, jQuery.extend( {}, prop ), optall );
  7638. doAnimation.finish = function() {
  7639. anim.stop( true );
  7640. };
  7641. // Empty animations, or finishing resolves immediately
  7642. if ( empty || jQuery._data( this, "finish" ) ) {
  7643. anim.stop( true );
  7644. }
  7645. };
  7646. doAnimation.finish = doAnimation;
  7647. return empty || optall.queue === false ?
  7648. this.each( doAnimation ) :
  7649. this.queue( optall.queue, doAnimation );
  7650. },
  7651. stop: function( type, clearQueue, gotoEnd ) {
  7652. var stopQueue = function( hooks ) {
  7653. var stop = hooks.stop;
  7654. delete hooks.stop;
  7655. stop( gotoEnd );
  7656. };
  7657. if ( typeof type !== "string" ) {
  7658. gotoEnd = clearQueue;
  7659. clearQueue = type;
  7660. type = undefined;
  7661. }
  7662. if ( clearQueue && type !== false ) {
  7663. this.queue( type || "fx", [] );
  7664. }
  7665. return this.each(function() {
  7666. var dequeue = true,
  7667. index = type != null && type + "queueHooks",
  7668. timers = jQuery.timers,
  7669. data = jQuery._data( this );
  7670. if ( index ) {
  7671. if ( data[ index ] && data[ index ].stop ) {
  7672. stopQueue( data[ index ] );
  7673. }
  7674. } else {
  7675. for ( index in data ) {
  7676. if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
  7677. stopQueue( data[ index ] );
  7678. }
  7679. }
  7680. }
  7681. for ( index = timers.length; index--; ) {
  7682. if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
  7683. timers[ index ].anim.stop( gotoEnd );
  7684. dequeue = false;
  7685. timers.splice( index, 1 );
  7686. }
  7687. }
  7688. // start the next in the queue if the last step wasn't forced
  7689. // timers currently will call their complete callbacks, which will dequeue
  7690. // but only if they were gotoEnd
  7691. if ( dequeue || !gotoEnd ) {
  7692. jQuery.dequeue( this, type );
  7693. }
  7694. });
  7695. },
  7696. finish: function( type ) {
  7697. if ( type !== false ) {
  7698. type = type || "fx";
  7699. }
  7700. return this.each(function() {
  7701. var index,
  7702. data = jQuery._data( this ),
  7703. queue = data[ type + "queue" ],
  7704. hooks = data[ type + "queueHooks" ],
  7705. timers = jQuery.timers,
  7706. length = queue ? queue.length : 0;
  7707. // enable finishing flag on private data
  7708. data.finish = true;
  7709. // empty the queue first
  7710. jQuery.queue( this, type, [] );
  7711. if ( hooks && hooks.cur && hooks.cur.finish ) {
  7712. hooks.cur.finish.call( this );
  7713. }
  7714. // look for any active animations, and finish them
  7715. for ( index = timers.length; index--; ) {
  7716. if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
  7717. timers[ index ].anim.stop( true );
  7718. timers.splice( index, 1 );
  7719. }
  7720. }
  7721. // look for any animations in the old queue and finish them
  7722. for ( index = 0; index < length; index++ ) {
  7723. if ( queue[ index ] && queue[ index ].finish ) {
  7724. queue[ index ].finish.call( this );
  7725. }
  7726. }
  7727. // turn off finishing flag
  7728. delete data.finish;
  7729. });
  7730. }
  7731. });
  7732. // Generate parameters to create a standard animation
  7733. function genFx( type, includeWidth ) {
  7734. var which,
  7735. attrs = { height: type },
  7736. i = 0;
  7737. // if we include width, step value is 1 to do all cssExpand values,
  7738. // if we don't include width, step value is 2 to skip over Left and Right
  7739. includeWidth = includeWidth? 1 : 0;
  7740. for( ; i < 4 ; i += 2 - includeWidth ) {
  7741. which = cssExpand[ i ];
  7742. attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
  7743. }
  7744. if ( includeWidth ) {
  7745. attrs.opacity = attrs.width = type;
  7746. }
  7747. return attrs;
  7748. }
  7749. // Generate shortcuts for custom animations
  7750. jQuery.each({
  7751. slideDown: genFx("show"),
  7752. slideUp: genFx("hide"),
  7753. slideToggle: genFx("toggle"),
  7754. fadeIn: { opacity: "show" },
  7755. fadeOut: { opacity: "hide" },
  7756. fadeToggle: { opacity: "toggle" }
  7757. }, function( name, props ) {
  7758. jQuery.fn[ name ] = function( speed, easing, callback ) {
  7759. return this.animate( props, speed, easing, callback );
  7760. };
  7761. });
  7762. jQuery.speed = function( speed, easing, fn ) {
  7763. var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
  7764. complete: fn || !fn && easing ||
  7765. jQuery.isFunction( speed ) && speed,
  7766. duration: speed,
  7767. easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
  7768. };
  7769. opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
  7770. opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
  7771. // normalize opt.queue - true/undefined/null -> "fx"
  7772. if ( opt.queue == null || opt.queue === true ) {
  7773. opt.queue = "fx";
  7774. }
  7775. // Queueing
  7776. opt.old = opt.complete;
  7777. opt.complete = function() {
  7778. if ( jQuery.isFunction( opt.old ) ) {
  7779. opt.old.call( this );
  7780. }
  7781. if ( opt.queue ) {
  7782. jQuery.dequeue( this, opt.queue );
  7783. }
  7784. };
  7785. return opt;
  7786. };
  7787. jQuery.easing = {
  7788. linear: function( p ) {
  7789. return p;
  7790. },
  7791. swing: function( p ) {
  7792. return 0.5 - Math.cos( p*Math.PI ) / 2;
  7793. }
  7794. };
  7795. jQuery.timers = [];
  7796. jQuery.fx = Tween.prototype.init;
  7797. jQuery.fx.tick = function() {
  7798. var timer,
  7799. timers = jQuery.timers,
  7800. i = 0;
  7801. fxNow = jQuery.now();
  7802. for ( ; i < timers.length; i++ ) {
  7803. timer = timers[ i ];
  7804. // Checks the timer has not already been removed
  7805. if ( !timer() && timers[ i ] === timer ) {
  7806. timers.splice( i--, 1 );
  7807. }
  7808. }
  7809. if ( !timers.length ) {
  7810. jQuery.fx.stop();
  7811. }
  7812. fxNow = undefined;
  7813. };
  7814. jQuery.fx.timer = function( timer ) {
  7815. if ( timer() && jQuery.timers.push( timer ) ) {
  7816. jQuery.fx.start();
  7817. }
  7818. };
  7819. jQuery.fx.interval = 13;
  7820. jQuery.fx.start = function() {
  7821. if ( !timerId ) {
  7822. timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
  7823. }
  7824. };
  7825. jQuery.fx.stop = function() {
  7826. clearInterval( timerId );
  7827. timerId = null;
  7828. };
  7829. jQuery.fx.speeds = {
  7830. slow: 600,
  7831. fast: 200,
  7832. // Default speed
  7833. _default: 400
  7834. };
  7835. // Back Compat <1.8 extension point
  7836. jQuery.fx.step = {};
  7837. if ( jQuery.expr && jQuery.expr.filters ) {
  7838. jQuery.expr.filters.animated = function( elem ) {
  7839. return jQuery.grep(jQuery.timers, function( fn ) {
  7840. return elem === fn.elem;
  7841. }).length;
  7842. };
  7843. }
  7844. jQuery.fn.offset = function( options ) {
  7845. if ( arguments.length ) {
  7846. return options === undefined ?
  7847. this :
  7848. this.each(function( i ) {
  7849. jQuery.offset.setOffset( this, options, i );
  7850. });
  7851. }
  7852. var docElem, win,
  7853. box = { top: 0, left: 0 },
  7854. elem = this[ 0 ],
  7855. doc = elem && elem.ownerDocument;
  7856. if ( !doc ) {
  7857. return;
  7858. }
  7859. docElem = doc.documentElement;
  7860. // Make sure it's not a disconnected DOM node
  7861. if ( !jQuery.contains( docElem, elem ) ) {
  7862. return box;
  7863. }
  7864. // If we don't have gBCR, just use 0,0 rather than error
  7865. // BlackBerry 5, iOS 3 (original iPhone)
  7866. if ( typeof elem.getBoundingClientRect !== "undefined" ) {
  7867. box = elem.getBoundingClientRect();
  7868. }
  7869. win = getWindow( doc );
  7870. return {
  7871. top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
  7872. left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
  7873. };
  7874. };
  7875. jQuery.offset = {
  7876. setOffset: function( elem, options, i ) {
  7877. var position = jQuery.css( elem, "position" );
  7878. // set position first, in-case top/left are set even on static elem
  7879. if ( position === "static" ) {
  7880. elem.style.position = "relative";
  7881. }
  7882. var curElem = jQuery( elem ),
  7883. curOffset = curElem.offset(),
  7884. curCSSTop = jQuery.css( elem, "top" ),
  7885. curCSSLeft = jQuery.css( elem, "left" ),
  7886. calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
  7887. props = {}, curPosition = {}, curTop, curLeft;
  7888. // need to be able to calculate position if either top or left is auto and position is either absolute or fixed
  7889. if ( calculatePosition ) {
  7890. curPosition = curElem.position();
  7891. curTop = curPosition.top;
  7892. curLeft = curPosition.left;
  7893. } else {
  7894. curTop = parseFloat( curCSSTop ) || 0;
  7895. curLeft = parseFloat( curCSSLeft ) || 0;
  7896. }
  7897. if ( jQuery.isFunction( options ) ) {
  7898. options = options.call( elem, i, curOffset );
  7899. }
  7900. if ( options.top != null ) {
  7901. props.top = ( options.top - curOffset.top ) + curTop;
  7902. }
  7903. if ( options.left != null ) {
  7904. props.left = ( options.left - curOffset.left ) + curLeft;
  7905. }
  7906. if ( "using" in options ) {
  7907. options.using.call( elem, props );
  7908. } else {
  7909. curElem.css( props );
  7910. }
  7911. }
  7912. };
  7913. jQuery.fn.extend({
  7914. position: function() {
  7915. if ( !this[ 0 ] ) {
  7916. return;
  7917. }
  7918. var offsetParent, offset,
  7919. parentOffset = { top: 0, left: 0 },
  7920. elem = this[ 0 ];
  7921. // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
  7922. if ( jQuery.css( elem, "position" ) === "fixed" ) {
  7923. // we assume that getBoundingClientRect is available when computed position is fixed
  7924. offset = elem.getBoundingClientRect();
  7925. } else {
  7926. // Get *real* offsetParent
  7927. offsetParent = this.offsetParent();
  7928. // Get correct offsets
  7929. offset = this.offset();
  7930. if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
  7931. parentOffset = offsetParent.offset();
  7932. }
  7933. // Add offsetParent borders
  7934. parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
  7935. parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
  7936. }
  7937. // Subtract parent offsets and element margins
  7938. // note: when an element has margin: auto the offsetLeft and marginLeft
  7939. // are the same in Safari causing offset.left to incorrectly be 0
  7940. return {
  7941. top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
  7942. left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
  7943. };
  7944. },
  7945. offsetParent: function() {
  7946. return this.map(function() {
  7947. var offsetParent = this.offsetParent || document.documentElement;
  7948. while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
  7949. offsetParent = offsetParent.offsetParent;
  7950. }
  7951. return offsetParent || document.documentElement;
  7952. });
  7953. }
  7954. });
  7955. // Create scrollLeft and scrollTop methods
  7956. jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
  7957. var top = /Y/.test( prop );
  7958. jQuery.fn[ method ] = function( val ) {
  7959. return jQuery.access( this, function( elem, method, val ) {
  7960. var win = getWindow( elem );
  7961. if ( val === undefined ) {
  7962. return win ? (prop in win) ? win[ prop ] :
  7963. win.document.documentElement[ method ] :
  7964. elem[ method ];
  7965. }
  7966. if ( win ) {
  7967. win.scrollTo(
  7968. !top ? val : jQuery( win ).scrollLeft(),
  7969. top ? val : jQuery( win ).scrollTop()
  7970. );
  7971. } else {
  7972. elem[ method ] = val;
  7973. }
  7974. }, method, val, arguments.length, null );
  7975. };
  7976. });
  7977. function getWindow( elem ) {
  7978. return jQuery.isWindow( elem ) ?
  7979. elem :
  7980. elem.nodeType === 9 ?
  7981. elem.defaultView || elem.parentWindow :
  7982. false;
  7983. }
  7984. // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
  7985. jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
  7986. jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
  7987. // margin is only for outerHeight, outerWidth
  7988. jQuery.fn[ funcName ] = function( margin, value ) {
  7989. var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
  7990. extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
  7991. return jQuery.access( this, function( elem, type, value ) {
  7992. var doc;
  7993. if ( jQuery.isWindow( elem ) ) {
  7994. // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
  7995. // isn't a whole lot we can do. See pull request at this URL for discussion:
  7996. // https://github.com/jquery/jquery/pull/764
  7997. return elem.document.documentElement[ "client" + name ];
  7998. }
  7999. // Get document width or height
  8000. if ( elem.nodeType === 9 ) {
  8001. doc = elem.documentElement;
  8002. // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
  8003. // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
  8004. return Math.max(
  8005. elem.body[ "scroll" + name ], doc[ "scroll" + name ],
  8006. elem.body[ "offset" + name ], doc[ "offset" + name ],
  8007. doc[ "client" + name ]
  8008. );
  8009. }
  8010. return value === undefined ?
  8011. // Get width or height on the element, requesting but not forcing parseFloat
  8012. jQuery.css( elem, type, extra ) :
  8013. // Set width or height on the element
  8014. jQuery.style( elem, type, value, extra );
  8015. }, type, chainable ? margin : undefined, chainable, null );
  8016. };
  8017. });
  8018. });
  8019. // Limit scope pollution from any deprecated API
  8020. // (function() {
  8021. // })();
  8022. // Expose jQuery to the global object
  8023. window.jQuery = window.$ = jQuery;
  8024. // Expose jQuery as an AMD module, but only for AMD loaders that
  8025. // understand the issues with loading multiple versions of jQuery
  8026. // in a page that all might call define(). The loader will indicate
  8027. // they have special allowances for multiple jQuery versions by
  8028. // specifying define.amd.jQuery = true. Register as a named module,
  8029. // since jQuery can be concatenated with other files that may use define,
  8030. // but not use a proper concatenation script that understands anonymous
  8031. // AMD modules. A named AMD is safest and most robust way to register.
  8032. // Lowercase jquery is used because AMD module names are derived from
  8033. // file names, and jQuery is normally delivered in a lowercase file name.
  8034. // Do this after creating the global so that if an AMD module wants to call
  8035. // noConflict to hide this version of jQuery, it will work.
  8036. if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
  8037. define( "jquery", [], function () { return jQuery; } );
  8038. }
  8039. })( window );
  8040. // lib/handlebars/base.js
  8041. /*jshint eqnull:true*/
  8042. this.Handlebars = {};
  8043. (function(Handlebars) {
  8044. Handlebars.VERSION = "1.0.rc.1";
  8045. Handlebars.helpers = {};
  8046. Handlebars.partials = {};
  8047. Handlebars.registerHelper = function(name, fn, inverse) {
  8048. if(inverse) { fn.not = inverse; }
  8049. this.helpers[name] = fn;
  8050. };
  8051. Handlebars.registerPartial = function(name, str) {
  8052. this.partials[name] = str;
  8053. };
  8054. Handlebars.registerHelper('helperMissing', function(arg) {
  8055. if(arguments.length === 2) {
  8056. return undefined;
  8057. } else {
  8058. throw new Error("Could not find property '" + arg + "'");
  8059. }
  8060. });
  8061. var toString = Object.prototype.toString, functionType = "[object Function]";
  8062. Handlebars.registerHelper('blockHelperMissing', function(context, options) {
  8063. var inverse = options.inverse || function() {}, fn = options.fn;
  8064. var ret = "";
  8065. var type = toString.call(context);
  8066. if(type === functionType) { context = context.call(this); }
  8067. if(context === true) {
  8068. return fn(this);
  8069. } else if(context === false || context == null) {
  8070. return inverse(this);
  8071. } else if(type === "[object Array]") {
  8072. if(context.length > 0) {
  8073. return Handlebars.helpers.each(context, options);
  8074. } else {
  8075. return inverse(this);
  8076. }
  8077. } else {
  8078. return fn(context);
  8079. }
  8080. });
  8081. Handlebars.K = function() {};
  8082. Handlebars.createFrame = Object.create || function(object) {
  8083. Handlebars.K.prototype = object;
  8084. var obj = new Handlebars.K();
  8085. Handlebars.K.prototype = null;
  8086. return obj;
  8087. };
  8088. Handlebars.registerHelper('each', function(context, options) {
  8089. var fn = options.fn, inverse = options.inverse;
  8090. var ret = "", data;
  8091. if (options.data) {
  8092. data = Handlebars.createFrame(options.data);
  8093. }
  8094. if(context && context.length > 0) {
  8095. for(var i=0, j=context.length; i<j; i++) {
  8096. if (data) { data.index = i; }
  8097. ret = ret + fn(context[i], { data: data });
  8098. }
  8099. } else {
  8100. ret = inverse(this);
  8101. }
  8102. return ret;
  8103. });
  8104. Handlebars.registerHelper('if', function(context, options) {
  8105. var type = toString.call(context);
  8106. if(type === functionType) { context = context.call(this); }
  8107. if(!context || Handlebars.Utils.isEmpty(context)) {
  8108. return options.inverse(this);
  8109. } else {
  8110. return options.fn(this);
  8111. }
  8112. });
  8113. Handlebars.registerHelper('unless', function(context, options) {
  8114. var fn = options.fn, inverse = options.inverse;
  8115. options.fn = inverse;
  8116. options.inverse = fn;
  8117. return Handlebars.helpers['if'].call(this, context, options);
  8118. });
  8119. Handlebars.registerHelper('with', function(context, options) {
  8120. return options.fn(context);
  8121. });
  8122. Handlebars.registerHelper('log', function(context) {
  8123. Handlebars.log(context);
  8124. });
  8125. }(this.Handlebars));
  8126. ;
  8127. // lib/handlebars/compiler/parser.js
  8128. /* Jison generated parser */
  8129. var handlebars = (function(){
  8130. var parser = {trace: function trace() { },
  8131. yy: {},
  8132. symbols_: {"error":2,"root":3,"program":4,"EOF":5,"statements":6,"simpleInverse":7,"statement":8,"openInverse":9,"closeBlock":10,"openBlock":11,"mustache":12,"partial":13,"CONTENT":14,"COMMENT":15,"OPEN_BLOCK":16,"inMustache":17,"CLOSE":18,"OPEN_INVERSE":19,"OPEN_ENDBLOCK":20,"path":21,"OPEN":22,"OPEN_UNESCAPED":23,"OPEN_PARTIAL":24,"params":25,"hash":26,"DATA":27,"param":28,"STRING":29,"INTEGER":30,"BOOLEAN":31,"hashSegments":32,"hashSegment":33,"ID":34,"EQUALS":35,"pathSegments":36,"SEP":37,"$accept":0,"$end":1},
  8133. terminals_: {2:"error",5:"EOF",14:"CONTENT",15:"COMMENT",16:"OPEN_BLOCK",18:"CLOSE",19:"OPEN_INVERSE",20:"OPEN_ENDBLOCK",22:"OPEN",23:"OPEN_UNESCAPED",24:"OPEN_PARTIAL",27:"DATA",29:"STRING",30:"INTEGER",31:"BOOLEAN",34:"ID",35:"EQUALS",37:"SEP"},
  8134. productions_: [0,[3,2],[4,3],[4,1],[4,0],[6,1],[6,2],[8,3],[8,3],[8,1],[8,1],[8,1],[8,1],[11,3],[9,3],[10,3],[12,3],[12,3],[13,3],[13,4],[7,2],[17,3],[17,2],[17,2],[17,1],[17,1],[25,2],[25,1],[28,1],[28,1],[28,1],[28,1],[28,1],[26,1],[32,2],[32,1],[33,3],[33,3],[33,3],[33,3],[33,3],[21,1],[36,3],[36,1]],
  8135. performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) {
  8136. var $0 = $$.length - 1;
  8137. switch (yystate) {
  8138. case 1: return $$[$0-1];
  8139. break;
  8140. case 2: this.$ = new yy.ProgramNode($$[$0-2], $$[$0]);
  8141. break;
  8142. case 3: this.$ = new yy.ProgramNode($$[$0]);
  8143. break;
  8144. case 4: this.$ = new yy.ProgramNode([]);
  8145. break;
  8146. case 5: this.$ = [$$[$0]];
  8147. break;
  8148. case 6: $$[$0-1].push($$[$0]); this.$ = $$[$0-1];
  8149. break;
  8150. case 7: this.$ = new yy.BlockNode($$[$0-2], $$[$0-1].inverse, $$[$0-1], $$[$0]);
  8151. break;
  8152. case 8: this.$ = new yy.BlockNode($$[$0-2], $$[$0-1], $$[$0-1].inverse, $$[$0]);
  8153. break;
  8154. case 9: this.$ = $$[$0];
  8155. break;
  8156. case 10: this.$ = $$[$0];
  8157. break;
  8158. case 11: this.$ = new yy.ContentNode($$[$0]);
  8159. break;
  8160. case 12: this.$ = new yy.CommentNode($$[$0]);
  8161. break;
  8162. case 13: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1]);
  8163. break;
  8164. case 14: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1]);
  8165. break;
  8166. case 15: this.$ = $$[$0-1];
  8167. break;
  8168. case 16: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1]);
  8169. break;
  8170. case 17: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1], true);
  8171. break;
  8172. case 18: this.$ = new yy.PartialNode($$[$0-1]);
  8173. break;
  8174. case 19: this.$ = new yy.PartialNode($$[$0-2], $$[$0-1]);
  8175. break;
  8176. case 20:
  8177. break;
  8178. case 21: this.$ = [[$$[$0-2]].concat($$[$0-1]), $$[$0]];
  8179. break;
  8180. case 22: this.$ = [[$$[$0-1]].concat($$[$0]), null];
  8181. break;
  8182. case 23: this.$ = [[$$[$0-1]], $$[$0]];
  8183. break;
  8184. case 24: this.$ = [[$$[$0]], null];
  8185. break;
  8186. case 25: this.$ = [[new yy.DataNode($$[$0])], null];
  8187. break;
  8188. case 26: $$[$0-1].push($$[$0]); this.$ = $$[$0-1];
  8189. break;
  8190. case 27: this.$ = [$$[$0]];
  8191. break;
  8192. case 28: this.$ = $$[$0];
  8193. break;
  8194. case 29: this.$ = new yy.StringNode($$[$0]);
  8195. break;
  8196. case 30: this.$ = new yy.IntegerNode($$[$0]);
  8197. break;
  8198. case 31: this.$ = new yy.BooleanNode($$[$0]);
  8199. break;
  8200. case 32: this.$ = new yy.DataNode($$[$0]);
  8201. break;
  8202. case 33: this.$ = new yy.HashNode($$[$0]);
  8203. break;
  8204. case 34: $$[$0-1].push($$[$0]); this.$ = $$[$0-1];
  8205. break;
  8206. case 35: this.$ = [$$[$0]];
  8207. break;
  8208. case 36: this.$ = [$$[$0-2], $$[$0]];
  8209. break;
  8210. case 37: this.$ = [$$[$0-2], new yy.StringNode($$[$0])];
  8211. break;
  8212. case 38: this.$ = [$$[$0-2], new yy.IntegerNode($$[$0])];
  8213. break;
  8214. case 39: this.$ = [$$[$0-2], new yy.BooleanNode($$[$0])];
  8215. break;
  8216. case 40: this.$ = [$$[$0-2], new yy.DataNode($$[$0])];
  8217. break;
  8218. case 41: this.$ = new yy.IdNode($$[$0]);
  8219. break;
  8220. case 42: $$[$0-2].push($$[$0]); this.$ = $$[$0-2];
  8221. break;
  8222. case 43: this.$ = [$$[$0]];
  8223. break;
  8224. }
  8225. },
  8226. table: [{3:1,4:2,5:[2,4],6:3,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],24:[1,15]},{1:[3]},{5:[1,16]},{5:[2,3],7:17,8:18,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,19],20:[2,3],22:[1,13],23:[1,14],24:[1,15]},{5:[2,5],14:[2,5],15:[2,5],16:[2,5],19:[2,5],20:[2,5],22:[2,5],23:[2,5],24:[2,5]},{4:20,6:3,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,4],22:[1,13],23:[1,14],24:[1,15]},{4:21,6:3,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,4],22:[1,13],23:[1,14],24:[1,15]},{5:[2,9],14:[2,9],15:[2,9],16:[2,9],19:[2,9],20:[2,9],22:[2,9],23:[2,9],24:[2,9]},{5:[2,10],14:[2,10],15:[2,10],16:[2,10],19:[2,10],20:[2,10],22:[2,10],23:[2,10],24:[2,10]},{5:[2,11],14:[2,11],15:[2,11],16:[2,11],19:[2,11],20:[2,11],22:[2,11],23:[2,11],24:[2,11]},{5:[2,12],14:[2,12],15:[2,12],16:[2,12],19:[2,12],20:[2,12],22:[2,12],23:[2,12],24:[2,12]},{17:22,21:23,27:[1,24],34:[1,26],36:25},{17:27,21:23,27:[1,24],34:[1,26],36:25},{17:28,21:23,27:[1,24],34:[1,26],36:25},{17:29,21:23,27:[1,24],34:[1,26],36:25},{21:30,34:[1,26],36:25},{1:[2,1]},{6:31,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],24:[1,15]},{5:[2,6],14:[2,6],15:[2,6],16:[2,6],19:[2,6],20:[2,6],22:[2,6],23:[2,6],24:[2,6]},{17:22,18:[1,32],21:23,27:[1,24],34:[1,26],36:25},{10:33,20:[1,34]},{10:35,20:[1,34]},{18:[1,36]},{18:[2,24],21:41,25:37,26:38,27:[1,45],28:39,29:[1,42],30:[1,43],31:[1,44],32:40,33:46,34:[1,47],36:25},{18:[2,25]},{18:[2,41],27:[2,41],29:[2,41],30:[2,41],31:[2,41],34:[2,41],37:[1,48]},{18:[2,43],27:[2,43],29:[2,43],30:[2,43],31:[2,43],34:[2,43],37:[2,43]},{18:[1,49]},{18:[1,50]},{18:[1,51]},{18:[1,52],21:53,34:[1,26],36:25},{5:[2,2],8:18,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,2],22:[1,13],23:[1,14],24:[1,15]},{14:[2,20],15:[2,20],16:[2,20],19:[2,20],22:[2,20],23:[2,20],24:[2,20]},{5:[2,7],14:[2,7],15:[2,7],16:[2,7],19:[2,7],20:[2,7],22:[2,7],23:[2,7],24:[2,7]},{21:54,34:[1,26],36:25},{5:[2,8],14:[2,8],15:[2,8],16:[2,8],19:[2,8],20:[2,8],22:[2,8],23:[2,8],24:[2,8]},{14:[2,14],15:[2,14],16:[2,14],19:[2,14],20:[2,14],22:[2,14],23:[2,14],24:[2,14]},{18:[2,22],21:41,26:55,27:[1,45],28:56,29:[1,42],30:[1,43],31:[1,44],32:40,33:46,34:[1,47],36:25},{18:[2,23]},{18:[2,27],27:[2,27],29:[2,27],30:[2,27],31:[2,27],34:[2,27]},{18:[2,33],33:57,34:[1,58]},{18:[2,28],27:[2,28],29:[2,28],30:[2,28],31:[2,28],34:[2,28]},{18:[2,29],27:[2,29],29:[2,29],30:[2,29],31:[2,29],34:[2,29]},{18:[2,30],27:[2,30],29:[2,30],30:[2,30],31:[2,30],34:[2,30]},{18:[2,31],27:[2,31],29:[2,31],30:[2,31],31:[2,31],34:[2,31]},{18:[2,32],27:[2,32],29:[2,32],30:[2,32],31:[2,32],34:[2,32]},{18:[2,35],34:[2,35]},{18:[2,43],27:[2,43],29:[2,43],30:[2,43],31:[2,43],34:[2,43],35:[1,59],37:[2,43]},{34:[1,60]},{14:[2,13],15:[2,13],16:[2,13],19:[2,13],20:[2,13],22:[2,13],23:[2,13],24:[2,13]},{5:[2,16],14:[2,16],15:[2,16],16:[2,16],19:[2,16],20:[2,16],22:[2,16],23:[2,16],24:[2,16]},{5:[2,17],14:[2,17],15:[2,17],16:[2,17],19:[2,17],20:[2,17],22:[2,17],23:[2,17],24:[2,17]},{5:[2,18],14:[2,18],15:[2,18],16:[2,18],19:[2,18],20:[2,18],22:[2,18],23:[2,18],24:[2,18]},{18:[1,61]},{18:[1,62]},{18:[2,21]},{18:[2,26],27:[2,26],29:[2,26],30:[2,26],31:[2,26],34:[2,26]},{18:[2,34],34:[2,34]},{35:[1,59]},{21:63,27:[1,67],29:[1,64],30:[1,65],31:[1,66],34:[1,26],36:25},{18:[2,42],27:[2,42],29:[2,42],30:[2,42],31:[2,42],34:[2,42],37:[2,42]},{5:[2,19],14:[2,19],15:[2,19],16:[2,19],19:[2,19],20:[2,19],22:[2,19],23:[2,19],24:[2,19]},{5:[2,15],14:[2,15],15:[2,15],16:[2,15],19:[2,15],20:[2,15],22:[2,15],23:[2,15],24:[2,15]},{18:[2,36],34:[2,36]},{18:[2,37],34:[2,37]},{18:[2,38],34:[2,38]},{18:[2,39],34:[2,39]},{18:[2,40],34:[2,40]}],
  8227. defaultActions: {16:[2,1],24:[2,25],38:[2,23],55:[2,21]},
  8228. parseError: function parseError(str, hash) {
  8229. throw new Error(str);
  8230. },
  8231. parse: function parse(input) {
  8232. var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;
  8233. this.lexer.setInput(input);
  8234. this.lexer.yy = this.yy;
  8235. this.yy.lexer = this.lexer;
  8236. this.yy.parser = this;
  8237. if (typeof this.lexer.yylloc == "undefined")
  8238. this.lexer.yylloc = {};
  8239. var yyloc = this.lexer.yylloc;
  8240. lstack.push(yyloc);
  8241. var ranges = this.lexer.options && this.lexer.options.ranges;
  8242. if (typeof this.yy.parseError === "function")
  8243. this.parseError = this.yy.parseError;
  8244. function popStack(n) {
  8245. stack.length = stack.length - 2 * n;
  8246. vstack.length = vstack.length - n;
  8247. lstack.length = lstack.length - n;
  8248. }
  8249. function lex() {
  8250. var token;
  8251. token = self.lexer.lex() || 1;
  8252. if (typeof token !== "number") {
  8253. token = self.symbols_[token] || token;
  8254. }
  8255. return token;
  8256. }
  8257. var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;
  8258. while (true) {
  8259. state = stack[stack.length - 1];
  8260. if (this.defaultActions[state]) {
  8261. action = this.defaultActions[state];
  8262. } else {
  8263. if (symbol === null || typeof symbol == "undefined") {
  8264. symbol = lex();
  8265. }
  8266. action = table[state] && table[state][symbol];
  8267. }
  8268. if (typeof action === "undefined" || !action.length || !action[0]) {
  8269. var errStr = "";
  8270. if (!recovering) {
  8271. expected = [];
  8272. for (p in table[state])
  8273. if (this.terminals_[p] && p > 2) {
  8274. expected.push("'" + this.terminals_[p] + "'");
  8275. }
  8276. if (this.lexer.showPosition) {
  8277. errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
  8278. } else {
  8279. errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'");
  8280. }
  8281. this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected});
  8282. }
  8283. }
  8284. if (action[0] instanceof Array && action.length > 1) {
  8285. throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
  8286. }
  8287. switch (action[0]) {
  8288. case 1:
  8289. stack.push(symbol);
  8290. vstack.push(this.lexer.yytext);
  8291. lstack.push(this.lexer.yylloc);
  8292. stack.push(action[1]);
  8293. symbol = null;
  8294. if (!preErrorSymbol) {
  8295. yyleng = this.lexer.yyleng;
  8296. yytext = this.lexer.yytext;
  8297. yylineno = this.lexer.yylineno;
  8298. yyloc = this.lexer.yylloc;
  8299. if (recovering > 0)
  8300. recovering--;
  8301. } else {
  8302. symbol = preErrorSymbol;
  8303. preErrorSymbol = null;
  8304. }
  8305. break;
  8306. case 2:
  8307. len = this.productions_[action[1]][1];
  8308. yyval.$ = vstack[vstack.length - len];
  8309. yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column};
  8310. if (ranges) {
  8311. yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
  8312. }
  8313. r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
  8314. if (typeof r !== "undefined") {
  8315. return r;
  8316. }
  8317. if (len) {
  8318. stack = stack.slice(0, -1 * len * 2);
  8319. vstack = vstack.slice(0, -1 * len);
  8320. lstack = lstack.slice(0, -1 * len);
  8321. }
  8322. stack.push(this.productions_[action[1]][0]);
  8323. vstack.push(yyval.$);
  8324. lstack.push(yyval._$);
  8325. newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
  8326. stack.push(newState);
  8327. break;
  8328. case 3:
  8329. return true;
  8330. }
  8331. }
  8332. return true;
  8333. }
  8334. };
  8335. /* Jison generated lexer */
  8336. var lexer = (function(){
  8337. var lexer = ({EOF:1,
  8338. parseError:function parseError(str, hash) {
  8339. if (this.yy.parser) {
  8340. this.yy.parser.parseError(str, hash);
  8341. } else {
  8342. throw new Error(str);
  8343. }
  8344. },
  8345. setInput:function (input) {
  8346. this._input = input;
  8347. this._more = this._less = this.done = false;
  8348. this.yylineno = this.yyleng = 0;
  8349. this.yytext = this.matched = this.match = '';
  8350. this.conditionStack = ['INITIAL'];
  8351. this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0};
  8352. if (this.options.ranges) this.yylloc.range = [0,0];
  8353. this.offset = 0;
  8354. return this;
  8355. },
  8356. input:function () {
  8357. var ch = this._input[0];
  8358. this.yytext += ch;
  8359. this.yyleng++;
  8360. this.offset++;
  8361. this.match += ch;
  8362. this.matched += ch;
  8363. var lines = ch.match(/(?:\r\n?|\n).*/g);
  8364. if (lines) {
  8365. this.yylineno++;
  8366. this.yylloc.last_line++;
  8367. } else {
  8368. this.yylloc.last_column++;
  8369. }
  8370. if (this.options.ranges) this.yylloc.range[1]++;
  8371. this._input = this._input.slice(1);
  8372. return ch;
  8373. },
  8374. unput:function (ch) {
  8375. var len = ch.length;
  8376. var lines = ch.split(/(?:\r\n?|\n)/g);
  8377. this._input = ch + this._input;
  8378. this.yytext = this.yytext.substr(0, this.yytext.length-len-1);
  8379. //this.yyleng -= len;
  8380. this.offset -= len;
  8381. var oldLines = this.match.split(/(?:\r\n?|\n)/g);
  8382. this.match = this.match.substr(0, this.match.length-1);
  8383. this.matched = this.matched.substr(0, this.matched.length-1);
  8384. if (lines.length-1) this.yylineno -= lines.length-1;
  8385. var r = this.yylloc.range;
  8386. this.yylloc = {first_line: this.yylloc.first_line,
  8387. last_line: this.yylineno+1,
  8388. first_column: this.yylloc.first_column,
  8389. last_column: lines ?
  8390. (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length:
  8391. this.yylloc.first_column - len
  8392. };
  8393. if (this.options.ranges) {
  8394. this.yylloc.range = [r[0], r[0] + this.yyleng - len];
  8395. }
  8396. return this;
  8397. },
  8398. more:function () {
  8399. this._more = true;
  8400. return this;
  8401. },
  8402. less:function (n) {
  8403. this.unput(this.match.slice(n));
  8404. },
  8405. pastInput:function () {
  8406. var past = this.matched.substr(0, this.matched.length - this.match.length);
  8407. return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, "");
  8408. },
  8409. upcomingInput:function () {
  8410. var next = this.match;
  8411. if (next.length < 20) {
  8412. next += this._input.substr(0, 20-next.length);
  8413. }
  8414. return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, "");
  8415. },
  8416. showPosition:function () {
  8417. var pre = this.pastInput();
  8418. var c = new Array(pre.length + 1).join("-");
  8419. return pre + this.upcomingInput() + "\n" + c+"^";
  8420. },
  8421. next:function () {
  8422. if (this.done) {
  8423. return this.EOF;
  8424. }
  8425. if (!this._input) this.done = true;
  8426. var token,
  8427. match,
  8428. tempMatch,
  8429. index,
  8430. col,
  8431. lines;
  8432. if (!this._more) {
  8433. this.yytext = '';
  8434. this.match = '';
  8435. }
  8436. var rules = this._currentRules();
  8437. for (var i=0;i < rules.length; i++) {
  8438. tempMatch = this._input.match(this.rules[rules[i]]);
  8439. if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
  8440. match = tempMatch;
  8441. index = i;
  8442. if (!this.options.flex) break;
  8443. }
  8444. }
  8445. if (match) {
  8446. lines = match[0].match(/(?:\r\n?|\n).*/g);
  8447. if (lines) this.yylineno += lines.length;
  8448. this.yylloc = {first_line: this.yylloc.last_line,
  8449. last_line: this.yylineno+1,
  8450. first_column: this.yylloc.last_column,
  8451. last_column: lines ? lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length};
  8452. this.yytext += match[0];
  8453. this.match += match[0];
  8454. this.matches = match;
  8455. this.yyleng = this.yytext.length;
  8456. if (this.options.ranges) {
  8457. this.yylloc.range = [this.offset, this.offset += this.yyleng];
  8458. }
  8459. this._more = false;
  8460. this._input = this._input.slice(match[0].length);
  8461. this.matched += match[0];
  8462. token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]);
  8463. if (this.done && this._input) this.done = false;
  8464. if (token) return token;
  8465. else return;
  8466. }
  8467. if (this._input === "") {
  8468. return this.EOF;
  8469. } else {
  8470. return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(),
  8471. {text: "", token: null, line: this.yylineno});
  8472. }
  8473. },
  8474. lex:function lex() {
  8475. var r = this.next();
  8476. if (typeof r !== 'undefined') {
  8477. return r;
  8478. } else {
  8479. return this.lex();
  8480. }
  8481. },
  8482. begin:function begin(condition) {
  8483. this.conditionStack.push(condition);
  8484. },
  8485. popState:function popState() {
  8486. return this.conditionStack.pop();
  8487. },
  8488. _currentRules:function _currentRules() {
  8489. return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules;
  8490. },
  8491. topState:function () {
  8492. return this.conditionStack[this.conditionStack.length-2];
  8493. },
  8494. pushState:function begin(condition) {
  8495. this.begin(condition);
  8496. }});
  8497. lexer.options = {};
  8498. lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {
  8499. var YYSTATE=YY_START
  8500. switch($avoiding_name_collisions) {
  8501. case 0:
  8502. if(yy_.yytext.slice(-1) !== "\\") this.begin("mu");
  8503. if(yy_.yytext.slice(-1) === "\\") yy_.yytext = yy_.yytext.substr(0,yy_.yyleng-1), this.begin("emu");
  8504. if(yy_.yytext) return 14;
  8505. break;
  8506. case 1: return 14;
  8507. break;
  8508. case 2:
  8509. if(yy_.yytext.slice(-1) !== "\\") this.popState();
  8510. if(yy_.yytext.slice(-1) === "\\") yy_.yytext = yy_.yytext.substr(0,yy_.yyleng-1);
  8511. return 14;
  8512. break;
  8513. case 3: return 24;
  8514. break;
  8515. case 4: return 16;
  8516. break;
  8517. case 5: return 20;
  8518. break;
  8519. case 6: return 19;
  8520. break;
  8521. case 7: return 19;
  8522. break;
  8523. case 8: return 23;
  8524. break;
  8525. case 9: return 23;
  8526. break;
  8527. case 10: yy_.yytext = yy_.yytext.substr(3,yy_.yyleng-5); this.popState(); return 15;
  8528. break;
  8529. case 11: return 22;
  8530. break;
  8531. case 12: return 35;
  8532. break;
  8533. case 13: return 34;
  8534. break;
  8535. case 14: return 34;
  8536. break;
  8537. case 15: return 37;
  8538. break;
  8539. case 16: /*ignore whitespace*/
  8540. break;
  8541. case 17: this.popState(); return 18;
  8542. break;
  8543. case 18: this.popState(); return 18;
  8544. break;
  8545. case 19: yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2).replace(/\\"/g,'"'); return 29;
  8546. break;
  8547. case 20: yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2).replace(/\\"/g,'"'); return 29;
  8548. break;
  8549. case 21: yy_.yytext = yy_.yytext.substr(1); return 27;
  8550. break;
  8551. case 22: return 31;
  8552. break;
  8553. case 23: return 31;
  8554. break;
  8555. case 24: return 30;
  8556. break;
  8557. case 25: return 34;
  8558. break;
  8559. case 26: yy_.yytext = yy_.yytext.substr(1, yy_.yyleng-2); return 34;
  8560. break;
  8561. case 27: return 'INVALID';
  8562. break;
  8563. case 28: return 5;
  8564. break;
  8565. }
  8566. };
  8567. lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|$)))/,/^(?:\{\{>)/,/^(?:\{\{#)/,/^(?:\{\{\/)/,/^(?:\{\{\^)/,/^(?:\{\{\s*else\b)/,/^(?:\{\{\{)/,/^(?:\{\{&)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{)/,/^(?:=)/,/^(?:\.(?=[} ]))/,/^(?:\.\.)/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}\}\})/,/^(?:\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@[a-zA-Z]+)/,/^(?:true(?=[}\s]))/,/^(?:false(?=[}\s]))/,/^(?:[0-9]+(?=[}\s]))/,/^(?:[a-zA-Z0-9_$-]+(?=[=}\s\/.]))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/];
  8568. lexer.conditions = {"mu":{"rules":[3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28],"inclusive":false},"emu":{"rules":[2],"inclusive":false},"INITIAL":{"rules":[0,1,28],"inclusive":true}};
  8569. return lexer;})()
  8570. parser.lexer = lexer;
  8571. function Parser () { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser;
  8572. return new Parser;
  8573. })();
  8574. if (typeof require !== 'undefined' && typeof exports !== 'undefined') {
  8575. exports.parser = handlebars;
  8576. exports.Parser = handlebars.Parser;
  8577. exports.parse = function () { return handlebars.parse.apply(handlebars, arguments); }
  8578. exports.main = function commonjsMain(args) {
  8579. if (!args[1])
  8580. throw new Error('Usage: '+args[0]+' FILE');
  8581. var source, cwd;
  8582. if (typeof process !== 'undefined') {
  8583. source = require('fs').readFileSync(require('path').resolve(args[1]), "utf8");
  8584. } else {
  8585. source = require("file").path(require("file").cwd()).join(args[1]).read({charset: "utf-8"});
  8586. }
  8587. return exports.parser.parse(source);
  8588. }
  8589. if (typeof module !== 'undefined' && require.main === module) {
  8590. exports.main(typeof process !== 'undefined' ? process.argv.slice(1) : require("system").args);
  8591. }
  8592. };
  8593. ;
  8594. // lib/handlebars/compiler/base.js
  8595. Handlebars.Parser = handlebars;
  8596. Handlebars.parse = function(string) {
  8597. Handlebars.Parser.yy = Handlebars.AST;
  8598. return Handlebars.Parser.parse(string);
  8599. };
  8600. Handlebars.print = function(ast) {
  8601. return new Handlebars.PrintVisitor().accept(ast);
  8602. };
  8603. Handlebars.logger = {
  8604. DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, level: 3,
  8605. // override in the host environment
  8606. log: function(level, str) {}
  8607. };
  8608. Handlebars.log = function(level, str) { Handlebars.logger.log(level, str); };
  8609. ;
  8610. // lib/handlebars/compiler/ast.js
  8611. (function() {
  8612. Handlebars.AST = {};
  8613. Handlebars.AST.ProgramNode = function(statements, inverse) {
  8614. this.type = "program";
  8615. this.statements = statements;
  8616. if(inverse) { this.inverse = new Handlebars.AST.ProgramNode(inverse); }
  8617. };
  8618. Handlebars.AST.MustacheNode = function(rawParams, hash, unescaped) {
  8619. this.type = "mustache";
  8620. this.escaped = !unescaped;
  8621. this.hash = hash;
  8622. var id = this.id = rawParams[0];
  8623. var params = this.params = rawParams.slice(1);
  8624. // a mustache is an eligible helper if:
  8625. // * its id is simple (a single part, not `this` or `..`)
  8626. var eligibleHelper = this.eligibleHelper = id.isSimple;
  8627. // a mustache is definitely a helper if:
  8628. // * it is an eligible helper, and
  8629. // * it has at least one parameter or hash segment
  8630. this.isHelper = eligibleHelper && (params.length || hash);
  8631. // if a mustache is an eligible helper but not a definite
  8632. // helper, it is ambiguous, and will be resolved in a later
  8633. // pass or at runtime.
  8634. };
  8635. Handlebars.AST.PartialNode = function(id, context) {
  8636. this.type = "partial";
  8637. // TODO: disallow complex IDs
  8638. this.id = id;
  8639. this.context = context;
  8640. };
  8641. var verifyMatch = function(open, close) {
  8642. if(open.original !== close.original) {
  8643. throw new Handlebars.Exception(open.original + " doesn't match " + close.original);
  8644. }
  8645. };
  8646. Handlebars.AST.BlockNode = function(mustache, program, inverse, close) {
  8647. verifyMatch(mustache.id, close);
  8648. this.type = "block";
  8649. this.mustache = mustache;
  8650. this.program = program;
  8651. this.inverse = inverse;
  8652. if (this.inverse && !this.program) {
  8653. this.isInverse = true;
  8654. }
  8655. };
  8656. Handlebars.AST.ContentNode = function(string) {
  8657. this.type = "content";
  8658. this.string = string;
  8659. };
  8660. Handlebars.AST.HashNode = function(pairs) {
  8661. this.type = "hash";
  8662. this.pairs = pairs;
  8663. };
  8664. Handlebars.AST.IdNode = function(parts) {
  8665. this.type = "ID";
  8666. this.original = parts.join(".");
  8667. var dig = [], depth = 0;
  8668. for(var i=0,l=parts.length; i<l; i++) {
  8669. var part = parts[i];
  8670. if(part === "..") { depth++; }
  8671. else if(part === "." || part === "this") { this.isScoped = true; }
  8672. else { dig.push(part); }
  8673. }
  8674. this.parts = dig;
  8675. this.string = dig.join('.');
  8676. this.depth = depth;
  8677. // an ID is simple if it only has one part, and that part is not
  8678. // `..` or `this`.
  8679. this.isSimple = parts.length === 1 && !this.isScoped && depth === 0;
  8680. };
  8681. Handlebars.AST.DataNode = function(id) {
  8682. this.type = "DATA";
  8683. this.id = id;
  8684. };
  8685. Handlebars.AST.StringNode = function(string) {
  8686. this.type = "STRING";
  8687. this.string = string;
  8688. };
  8689. Handlebars.AST.IntegerNode = function(integer) {
  8690. this.type = "INTEGER";
  8691. this.integer = integer;
  8692. };
  8693. Handlebars.AST.BooleanNode = function(bool) {
  8694. this.type = "BOOLEAN";
  8695. this.bool = bool;
  8696. };
  8697. Handlebars.AST.CommentNode = function(comment) {
  8698. this.type = "comment";
  8699. this.comment = comment;
  8700. };
  8701. })();;
  8702. // lib/handlebars/utils.js
  8703. Handlebars.Exception = function(message) {
  8704. var tmp = Error.prototype.constructor.apply(this, arguments);
  8705. for (var p in tmp) {
  8706. if (tmp.hasOwnProperty(p)) { this[p] = tmp[p]; }
  8707. }
  8708. this.message = tmp.message;
  8709. };
  8710. Handlebars.Exception.prototype = new Error();
  8711. // Build out our basic SafeString type
  8712. Handlebars.SafeString = function(string) {
  8713. this.string = string;
  8714. };
  8715. Handlebars.SafeString.prototype.toString = function() {
  8716. return this.string.toString();
  8717. };
  8718. (function() {
  8719. var escape = {
  8720. "&": "&amp;",
  8721. "<": "&lt;",
  8722. ">": "&gt;",
  8723. '"': "&quot;",
  8724. "'": "&#x27;",
  8725. "`": "&#x60;"
  8726. };
  8727. var badChars = /[&<>"'`]/g;
  8728. var possible = /[&<>"'`]/;
  8729. var escapeChar = function(chr) {
  8730. return escape[chr] || "&amp;";
  8731. };
  8732. Handlebars.Utils = {
  8733. escapeExpression: function(string) {
  8734. // don't escape SafeStrings, since they're already safe
  8735. if (string instanceof Handlebars.SafeString) {
  8736. return string.toString();
  8737. } else if (string == null || string === false) {
  8738. return "";
  8739. }
  8740. if(!possible.test(string)) { return string; }
  8741. return string.replace(badChars, escapeChar);
  8742. },
  8743. isEmpty: function(value) {
  8744. if (typeof value === "undefined") {
  8745. return true;
  8746. } else if (value === null) {
  8747. return true;
  8748. } else if (value === false) {
  8749. return true;
  8750. } else if(Object.prototype.toString.call(value) === "[object Array]" && value.length === 0) {
  8751. return true;
  8752. } else {
  8753. return false;
  8754. }
  8755. }
  8756. };
  8757. })();;
  8758. // lib/handlebars/compiler/compiler.js
  8759. /*jshint eqnull:true*/
  8760. Handlebars.Compiler = function() {};
  8761. Handlebars.JavaScriptCompiler = function() {};
  8762. (function(Compiler, JavaScriptCompiler) {
  8763. // the foundHelper register will disambiguate helper lookup from finding a
  8764. // function in a context. This is necessary for mustache compatibility, which
  8765. // requires that context functions in blocks are evaluated by blockHelperMissing,
  8766. // and then proceed as if the resulting value was provided to blockHelperMissing.
  8767. Compiler.prototype = {
  8768. compiler: Compiler,
  8769. disassemble: function() {
  8770. var opcodes = this.opcodes, opcode, out = [], params, param;
  8771. for (var i=0, l=opcodes.length; i<l; i++) {
  8772. opcode = opcodes[i];
  8773. if (opcode.opcode === 'DECLARE') {
  8774. out.push("DECLARE " + opcode.name + "=" + opcode.value);
  8775. } else {
  8776. params = [];
  8777. for (var j=0; j<opcode.args.length; j++) {
  8778. param = opcode.args[j];
  8779. if (typeof param === "string") {
  8780. param = "\"" + param.replace("\n", "\\n") + "\"";
  8781. }
  8782. params.push(param);
  8783. }
  8784. out.push(opcode.opcode + " " + params.join(" "));
  8785. }
  8786. }
  8787. return out.join("\n");
  8788. },
  8789. guid: 0,
  8790. compile: function(program, options) {
  8791. this.children = [];
  8792. this.depths = {list: []};
  8793. this.options = options;
  8794. // These changes will propagate to the other compiler components
  8795. var knownHelpers = this.options.knownHelpers;
  8796. this.options.knownHelpers = {
  8797. 'helperMissing': true,
  8798. 'blockHelperMissing': true,
  8799. 'each': true,
  8800. 'if': true,
  8801. 'unless': true,
  8802. 'with': true,
  8803. 'log': true
  8804. };
  8805. if (knownHelpers) {
  8806. for (var name in knownHelpers) {
  8807. this.options.knownHelpers[name] = knownHelpers[name];
  8808. }
  8809. }
  8810. return this.program(program);
  8811. },
  8812. accept: function(node) {
  8813. return this[node.type](node);
  8814. },
  8815. program: function(program) {
  8816. var statements = program.statements, statement;
  8817. this.opcodes = [];
  8818. for(var i=0, l=statements.length; i<l; i++) {
  8819. statement = statements[i];
  8820. this[statement.type](statement);
  8821. }
  8822. this.isSimple = l === 1;
  8823. this.depths.list = this.depths.list.sort(function(a, b) {
  8824. return a - b;
  8825. });
  8826. return this;
  8827. },
  8828. compileProgram: function(program) {
  8829. var result = new this.compiler().compile(program, this.options);
  8830. var guid = this.guid++, depth;
  8831. this.usePartial = this.usePartial || result.usePartial;
  8832. this.children[guid] = result;
  8833. for(var i=0, l=result.depths.list.length; i<l; i++) {
  8834. depth = result.depths.list[i];
  8835. if(depth < 2) { continue; }
  8836. else { this.addDepth(depth - 1); }
  8837. }
  8838. return guid;
  8839. },
  8840. block: function(block) {
  8841. var mustache = block.mustache,
  8842. program = block.program,
  8843. inverse = block.inverse;
  8844. if (program) {
  8845. program = this.compileProgram(program);
  8846. }
  8847. if (inverse) {
  8848. inverse = this.compileProgram(inverse);
  8849. }
  8850. var type = this.classifyMustache(mustache);
  8851. if (type === "helper") {
  8852. this.helperMustache(mustache, program, inverse);
  8853. } else if (type === "simple") {
  8854. this.simpleMustache(mustache);
  8855. // now that the simple mustache is resolved, we need to
  8856. // evaluate it by executing `blockHelperMissing`
  8857. this.opcode('pushProgram', program);
  8858. this.opcode('pushProgram', inverse);
  8859. this.opcode('pushLiteral', '{}');
  8860. this.opcode('blockValue');
  8861. } else {
  8862. this.ambiguousMustache(mustache, program, inverse);
  8863. // now that the simple mustache is resolved, we need to
  8864. // evaluate it by executing `blockHelperMissing`
  8865. this.opcode('pushProgram', program);
  8866. this.opcode('pushProgram', inverse);
  8867. this.opcode('pushLiteral', '{}');
  8868. this.opcode('ambiguousBlockValue');
  8869. }
  8870. this.opcode('append');
  8871. },
  8872. hash: function(hash) {
  8873. var pairs = hash.pairs, pair, val;
  8874. this.opcode('push', '{}');
  8875. for(var i=0, l=pairs.length; i<l; i++) {
  8876. pair = pairs[i];
  8877. val = pair[1];
  8878. this.accept(val);
  8879. this.opcode('assignToHash', pair[0]);
  8880. }
  8881. },
  8882. partial: function(partial) {
  8883. var id = partial.id;
  8884. this.usePartial = true;
  8885. if(partial.context) {
  8886. this.ID(partial.context);
  8887. } else {
  8888. this.opcode('push', 'depth0');
  8889. }
  8890. this.opcode('invokePartial', id.original);
  8891. this.opcode('append');
  8892. },
  8893. content: function(content) {
  8894. this.opcode('appendContent', content.string);
  8895. },
  8896. mustache: function(mustache) {
  8897. var options = this.options;
  8898. var type = this.classifyMustache(mustache);
  8899. if (type === "simple") {
  8900. this.simpleMustache(mustache);
  8901. } else if (type === "helper") {
  8902. this.helperMustache(mustache);
  8903. } else {
  8904. this.ambiguousMustache(mustache);
  8905. }
  8906. if(mustache.escaped && !options.noEscape) {
  8907. this.opcode('appendEscaped');
  8908. } else {
  8909. this.opcode('append');
  8910. }
  8911. },
  8912. ambiguousMustache: function(mustache, program, inverse) {
  8913. var id = mustache.id, name = id.parts[0];
  8914. this.opcode('getContext', id.depth);
  8915. this.opcode('pushProgram', program);
  8916. this.opcode('pushProgram', inverse);
  8917. this.opcode('invokeAmbiguous', name);
  8918. },
  8919. simpleMustache: function(mustache, program, inverse) {
  8920. var id = mustache.id;
  8921. if (id.type === 'DATA') {
  8922. this.DATA(id);
  8923. } else if (id.parts.length) {
  8924. this.ID(id);
  8925. } else {
  8926. // Simplified ID for `this`
  8927. this.addDepth(id.depth);
  8928. this.opcode('getContext', id.depth);
  8929. this.opcode('pushContext');
  8930. }
  8931. this.opcode('resolvePossibleLambda');
  8932. },
  8933. helperMustache: function(mustache, program, inverse) {
  8934. var params = this.setupFullMustacheParams(mustache, program, inverse),
  8935. name = mustache.id.parts[0];
  8936. if (this.options.knownHelpers[name]) {
  8937. this.opcode('invokeKnownHelper', params.length, name);
  8938. } else if (this.knownHelpersOnly) {
  8939. throw new Error("You specified knownHelpersOnly, but used the unknown helper " + name);
  8940. } else {
  8941. this.opcode('invokeHelper', params.length, name);
  8942. }
  8943. },
  8944. ID: function(id) {
  8945. this.addDepth(id.depth);
  8946. this.opcode('getContext', id.depth);
  8947. var name = id.parts[0];
  8948. if (!name) {
  8949. this.opcode('pushContext');
  8950. } else {
  8951. this.opcode('lookupOnContext', id.parts[0]);
  8952. }
  8953. for(var i=1, l=id.parts.length; i<l; i++) {
  8954. this.opcode('lookup', id.parts[i]);
  8955. }
  8956. },
  8957. DATA: function(data) {
  8958. this.options.data = true;
  8959. this.opcode('lookupData', data.id);
  8960. },
  8961. STRING: function(string) {
  8962. this.opcode('pushString', string.string);
  8963. },
  8964. INTEGER: function(integer) {
  8965. this.opcode('pushLiteral', integer.integer);
  8966. },
  8967. BOOLEAN: function(bool) {
  8968. this.opcode('pushLiteral', bool.bool);
  8969. },
  8970. comment: function() {},
  8971. // HELPERS
  8972. opcode: function(name) {
  8973. this.opcodes.push({ opcode: name, args: [].slice.call(arguments, 1) });
  8974. },
  8975. declare: function(name, value) {
  8976. this.opcodes.push({ opcode: 'DECLARE', name: name, value: value });
  8977. },
  8978. addDepth: function(depth) {
  8979. if(isNaN(depth)) { throw new Error("EWOT"); }
  8980. if(depth === 0) { return; }
  8981. if(!this.depths[depth]) {
  8982. this.depths[depth] = true;
  8983. this.depths.list.push(depth);
  8984. }
  8985. },
  8986. classifyMustache: function(mustache) {
  8987. var isHelper = mustache.isHelper;
  8988. var isEligible = mustache.eligibleHelper;
  8989. var options = this.options;
  8990. // if ambiguous, we can possibly resolve the ambiguity now
  8991. if (isEligible && !isHelper) {
  8992. var name = mustache.id.parts[0];
  8993. if (options.knownHelpers[name]) {
  8994. isHelper = true;
  8995. } else if (options.knownHelpersOnly) {
  8996. isEligible = false;
  8997. }
  8998. }
  8999. if (isHelper) { return "helper"; }
  9000. else if (isEligible) { return "ambiguous"; }
  9001. else { return "simple"; }
  9002. },
  9003. pushParams: function(params) {
  9004. var i = params.length, param;
  9005. while(i--) {
  9006. param = params[i];
  9007. if(this.options.stringParams) {
  9008. if(param.depth) {
  9009. this.addDepth(param.depth);
  9010. }
  9011. this.opcode('getContext', param.depth || 0);
  9012. this.opcode('pushStringParam', param.string);
  9013. } else {
  9014. this[param.type](param);
  9015. }
  9016. }
  9017. },
  9018. setupMustacheParams: function(mustache) {
  9019. var params = mustache.params;
  9020. this.pushParams(params);
  9021. if(mustache.hash) {
  9022. this.hash(mustache.hash);
  9023. } else {
  9024. this.opcode('pushLiteral', '{}');
  9025. }
  9026. return params;
  9027. },
  9028. // this will replace setupMustacheParams when we're done
  9029. setupFullMustacheParams: function(mustache, program, inverse) {
  9030. var params = mustache.params;
  9031. this.pushParams(params);
  9032. this.opcode('pushProgram', program);
  9033. this.opcode('pushProgram', inverse);
  9034. if(mustache.hash) {
  9035. this.hash(mustache.hash);
  9036. } else {
  9037. this.opcode('pushLiteral', '{}');
  9038. }
  9039. return params;
  9040. }
  9041. };
  9042. var Literal = function(value) {
  9043. this.value = value;
  9044. };
  9045. JavaScriptCompiler.prototype = {
  9046. // PUBLIC API: You can override these methods in a subclass to provide
  9047. // alternative compiled forms for name lookup and buffering semantics
  9048. nameLookup: function(parent, name, type) {
  9049. if (/^[0-9]+$/.test(name)) {
  9050. return parent + "[" + name + "]";
  9051. } else if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
  9052. return parent + "." + name;
  9053. }
  9054. else {
  9055. return parent + "['" + name + "']";
  9056. }
  9057. },
  9058. appendToBuffer: function(string) {
  9059. if (this.environment.isSimple) {
  9060. return "return " + string + ";";
  9061. } else {
  9062. return "buffer += " + string + ";";
  9063. }
  9064. },
  9065. initializeBuffer: function() {
  9066. return this.quotedString("");
  9067. },
  9068. namespace: "Handlebars",
  9069. // END PUBLIC API
  9070. compile: function(environment, options, context, asObject) {
  9071. this.environment = environment;
  9072. this.options = options || {};
  9073. Handlebars.log(Handlebars.logger.DEBUG, this.environment.disassemble() + "\n\n");
  9074. this.name = this.environment.name;
  9075. this.isChild = !!context;
  9076. this.context = context || {
  9077. programs: [],
  9078. aliases: { }
  9079. };
  9080. this.preamble();
  9081. this.stackSlot = 0;
  9082. this.stackVars = [];
  9083. this.registers = { list: [] };
  9084. this.compileStack = [];
  9085. this.compileChildren(environment, options);
  9086. var opcodes = environment.opcodes, opcode;
  9087. this.i = 0;
  9088. for(l=opcodes.length; this.i<l; this.i++) {
  9089. opcode = opcodes[this.i];
  9090. if(opcode.opcode === 'DECLARE') {
  9091. this[opcode.name] = opcode.value;
  9092. } else {
  9093. this[opcode.opcode].apply(this, opcode.args);
  9094. }
  9095. }
  9096. return this.createFunctionContext(asObject);
  9097. },
  9098. nextOpcode: function() {
  9099. var opcodes = this.environment.opcodes, opcode = opcodes[this.i + 1];
  9100. return opcodes[this.i + 1];
  9101. },
  9102. eat: function(opcode) {
  9103. this.i = this.i + 1;
  9104. },
  9105. preamble: function() {
  9106. var out = [];
  9107. if (!this.isChild) {
  9108. var namespace = this.namespace;
  9109. var copies = "helpers = helpers || " + namespace + ".helpers;";
  9110. if (this.environment.usePartial) { copies = copies + " partials = partials || " + namespace + ".partials;"; }
  9111. if (this.options.data) { copies = copies + " data = data || {};"; }
  9112. out.push(copies);
  9113. } else {
  9114. out.push('');
  9115. }
  9116. if (!this.environment.isSimple) {
  9117. out.push(", buffer = " + this.initializeBuffer());
  9118. } else {
  9119. out.push("");
  9120. }
  9121. // track the last context pushed into place to allow skipping the
  9122. // getContext opcode when it would be a noop
  9123. this.lastContext = 0;
  9124. this.source = out;
  9125. },
  9126. createFunctionContext: function(asObject) {
  9127. var locals = this.stackVars.concat(this.registers.list);
  9128. if(locals.length > 0) {
  9129. this.source[1] = this.source[1] + ", " + locals.join(", ");
  9130. }
  9131. // Generate minimizer alias mappings
  9132. if (!this.isChild) {
  9133. var aliases = [];
  9134. for (var alias in this.context.aliases) {
  9135. this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias];
  9136. }
  9137. }
  9138. if (this.source[1]) {
  9139. this.source[1] = "var " + this.source[1].substring(2) + ";";
  9140. }
  9141. // Merge children
  9142. if (!this.isChild) {
  9143. this.source[1] += '\n' + this.context.programs.join('\n') + '\n';
  9144. }
  9145. if (!this.environment.isSimple) {
  9146. this.source.push("return buffer;");
  9147. }
  9148. var params = this.isChild ? ["depth0", "data"] : ["Handlebars", "depth0", "helpers", "partials", "data"];
  9149. for(var i=0, l=this.environment.depths.list.length; i<l; i++) {
  9150. params.push("depth" + this.environment.depths.list[i]);
  9151. }
  9152. if (asObject) {
  9153. params.push(this.source.join("\n "));
  9154. return Function.apply(this, params);
  9155. } else {
  9156. var functionSource = 'function ' + (this.name || '') + '(' + params.join(',') + ') {\n ' + this.source.join("\n ") + '}';
  9157. Handlebars.log(Handlebars.logger.DEBUG, functionSource + "\n\n");
  9158. return functionSource;
  9159. }
  9160. },
  9161. // [blockValue]
  9162. //
  9163. // On stack, before: hash, inverse, program, value
  9164. // On stack, after: return value of blockHelperMissing
  9165. //
  9166. // The purpose of this opcode is to take a block of the form
  9167. // `{{#foo}}...{{/foo}}`, resolve the value of `foo`, and
  9168. // replace it on the stack with the result of properly
  9169. // invoking blockHelperMissing.
  9170. blockValue: function() {
  9171. this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing';
  9172. var params = ["depth0"];
  9173. this.setupParams(0, params);
  9174. this.replaceStack(function(current) {
  9175. params.splice(1, 0, current);
  9176. return current + " = blockHelperMissing.call(" + params.join(", ") + ")";
  9177. });
  9178. },
  9179. // [ambiguousBlockValue]
  9180. //
  9181. // On stack, before: hash, inverse, program, value
  9182. // Compiler value, before: lastHelper=value of last found helper, if any
  9183. // On stack, after, if no lastHelper: same as [blockValue]
  9184. // On stack, after, if lastHelper: value
  9185. ambiguousBlockValue: function() {
  9186. this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing';
  9187. var params = ["depth0"];
  9188. this.setupParams(0, params);
  9189. var current = this.topStack();
  9190. params.splice(1, 0, current);
  9191. this.source.push("if (!" + this.lastHelper + ") { " + current + " = blockHelperMissing.call(" + params.join(", ") + "); }");
  9192. },
  9193. // [appendContent]
  9194. //
  9195. // On stack, before: ...
  9196. // On stack, after: ...
  9197. //
  9198. // Appends the string value of `content` to the current buffer
  9199. appendContent: function(content) {
  9200. this.source.push(this.appendToBuffer(this.quotedString(content)));
  9201. },
  9202. // [append]
  9203. //
  9204. // On stack, before: value, ...
  9205. // On stack, after: ...
  9206. //
  9207. // Coerces `value` to a String and appends it to the current buffer.
  9208. //
  9209. // If `value` is truthy, or 0, it is coerced into a string and appended
  9210. // Otherwise, the empty string is appended
  9211. append: function() {
  9212. var local = this.popStack();
  9213. this.source.push("if(" + local + " || " + local + " === 0) { " + this.appendToBuffer(local) + " }");
  9214. if (this.environment.isSimple) {
  9215. this.source.push("else { " + this.appendToBuffer("''") + " }");
  9216. }
  9217. },
  9218. // [appendEscaped]
  9219. //
  9220. // On stack, before: value, ...
  9221. // On stack, after: ...
  9222. //
  9223. // Escape `value` and append it to the buffer
  9224. appendEscaped: function() {
  9225. var opcode = this.nextOpcode(), extra = "";
  9226. this.context.aliases.escapeExpression = 'this.escapeExpression';
  9227. if(opcode && opcode.opcode === 'appendContent') {
  9228. extra = " + " + this.quotedString(opcode.args[0]);
  9229. this.eat(opcode);
  9230. }
  9231. this.source.push(this.appendToBuffer("escapeExpression(" + this.popStack() + ")" + extra));
  9232. },
  9233. // [getContext]
  9234. //
  9235. // On stack, before: ...
  9236. // On stack, after: ...
  9237. // Compiler value, after: lastContext=depth
  9238. //
  9239. // Set the value of the `lastContext` compiler value to the depth
  9240. getContext: function(depth) {
  9241. if(this.lastContext !== depth) {
  9242. this.lastContext = depth;
  9243. }
  9244. },
  9245. // [lookupOnContext]
  9246. //
  9247. // On stack, before: ...
  9248. // On stack, after: currentContext[name], ...
  9249. //
  9250. // Looks up the value of `name` on the current context and pushes
  9251. // it onto the stack.
  9252. lookupOnContext: function(name) {
  9253. this.pushStack(this.nameLookup('depth' + this.lastContext, name, 'context'));
  9254. },
  9255. // [pushContext]
  9256. //
  9257. // On stack, before: ...
  9258. // On stack, after: currentContext, ...
  9259. //
  9260. // Pushes the value of the current context onto the stack.
  9261. pushContext: function() {
  9262. this.pushStackLiteral('depth' + this.lastContext);
  9263. },
  9264. // [resolvePossibleLambda]
  9265. //
  9266. // On stack, before: value, ...
  9267. // On stack, after: resolved value, ...
  9268. //
  9269. // If the `value` is a lambda, replace it on the stack by
  9270. // the return value of the lambda
  9271. resolvePossibleLambda: function() {
  9272. this.context.aliases.functionType = '"function"';
  9273. this.replaceStack(function(current) {
  9274. return "typeof " + current + " === functionType ? " + current + "() : " + current;
  9275. });
  9276. },
  9277. // [lookup]
  9278. //
  9279. // On stack, before: value, ...
  9280. // On stack, after: value[name], ...
  9281. //
  9282. // Replace the value on the stack with the result of looking
  9283. // up `name` on `value`
  9284. lookup: function(name) {
  9285. this.replaceStack(function(current) {
  9286. return current + " == null || " + current + " === false ? " + current + " : " + this.nameLookup(current, name, 'context');
  9287. });
  9288. },
  9289. // [lookupData]
  9290. //
  9291. // On stack, before: ...
  9292. // On stack, after: data[id], ...
  9293. //
  9294. // Push the result of looking up `id` on the current data
  9295. lookupData: function(id) {
  9296. this.pushStack(this.nameLookup('data', id, 'data'));
  9297. },
  9298. // [pushStringParam]
  9299. //
  9300. // On stack, before: ...
  9301. // On stack, after: string, currentContext, ...
  9302. //
  9303. // This opcode is designed for use in string mode, which
  9304. // provides the string value of a parameter along with its
  9305. // depth rather than resolving it immediately.
  9306. pushStringParam: function(string) {
  9307. this.pushStackLiteral('depth' + this.lastContext);
  9308. this.pushString(string);
  9309. },
  9310. // [pushString]
  9311. //
  9312. // On stack, before: ...
  9313. // On stack, after: quotedString(string), ...
  9314. //
  9315. // Push a quoted version of `string` onto the stack
  9316. pushString: function(string) {
  9317. this.pushStackLiteral(this.quotedString(string));
  9318. },
  9319. // [push]
  9320. //
  9321. // On stack, before: ...
  9322. // On stack, after: expr, ...
  9323. //
  9324. // Push an expression onto the stack
  9325. push: function(expr) {
  9326. this.pushStack(expr);
  9327. },
  9328. // [pushLiteral]
  9329. //
  9330. // On stack, before: ...
  9331. // On stack, after: value, ...
  9332. //
  9333. // Pushes a value onto the stack. This operation prevents
  9334. // the compiler from creating a temporary variable to hold
  9335. // it.
  9336. pushLiteral: function(value) {
  9337. this.pushStackLiteral(value);
  9338. },
  9339. // [pushProgram]
  9340. //
  9341. // On stack, before: ...
  9342. // On stack, after: program(guid), ...
  9343. //
  9344. // Push a program expression onto the stack. This takes
  9345. // a compile-time guid and converts it into a runtime-accessible
  9346. // expression.
  9347. pushProgram: function(guid) {
  9348. if (guid != null) {
  9349. this.pushStackLiteral(this.programExpression(guid));
  9350. } else {
  9351. this.pushStackLiteral(null);
  9352. }
  9353. },
  9354. // [invokeHelper]
  9355. //
  9356. // On stack, before: hash, inverse, program, params..., ...
  9357. // On stack, after: result of helper invocation
  9358. //
  9359. // Pops off the helper's parameters, invokes the helper,
  9360. // and pushes the helper's return value onto the stack.
  9361. //
  9362. // If the helper is not found, `helperMissing` is called.
  9363. invokeHelper: function(paramSize, name) {
  9364. this.context.aliases.helperMissing = 'helpers.helperMissing';
  9365. var helper = this.lastHelper = this.setupHelper(paramSize, name);
  9366. this.register('foundHelper', helper.name);
  9367. this.pushStack("foundHelper ? foundHelper.call(" +
  9368. helper.callParams + ") " + ": helperMissing.call(" +
  9369. helper.helperMissingParams + ")");
  9370. },
  9371. // [invokeKnownHelper]
  9372. //
  9373. // On stack, before: hash, inverse, program, params..., ...
  9374. // On stack, after: result of helper invocation
  9375. //
  9376. // This operation is used when the helper is known to exist,
  9377. // so a `helperMissing` fallback is not required.
  9378. invokeKnownHelper: function(paramSize, name) {
  9379. var helper = this.setupHelper(paramSize, name);
  9380. this.pushStack(helper.name + ".call(" + helper.callParams + ")");
  9381. },
  9382. // [invokeAmbiguous]
  9383. //
  9384. // On stack, before: hash, inverse, program, params..., ...
  9385. // On stack, after: result of disambiguation
  9386. //
  9387. // This operation is used when an expression like `{{foo}}`
  9388. // is provided, but we don't know at compile-time whether it
  9389. // is a helper or a path.
  9390. //
  9391. // This operation emits more code than the other options,
  9392. // and can be avoided by passing the `knownHelpers` and
  9393. // `knownHelpersOnly` flags at compile-time.
  9394. invokeAmbiguous: function(name) {
  9395. this.context.aliases.functionType = '"function"';
  9396. this.pushStackLiteral('{}');
  9397. var helper = this.setupHelper(0, name);
  9398. var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
  9399. this.register('foundHelper', helperName);
  9400. var nonHelper = this.nameLookup('depth' + this.lastContext, name, 'context');
  9401. var nextStack = this.nextStack();
  9402. this.source.push('if (foundHelper) { ' + nextStack + ' = foundHelper.call(' + helper.callParams + '); }');
  9403. this.source.push('else { ' + nextStack + ' = ' + nonHelper + '; ' + nextStack + ' = typeof ' + nextStack + ' === functionType ? ' + nextStack + '() : ' + nextStack + '; }');
  9404. },
  9405. // [invokePartial]
  9406. //
  9407. // On stack, before: context, ...
  9408. // On stack after: result of partial invocation
  9409. //
  9410. // This operation pops off a context, invokes a partial with that context,
  9411. // and pushes the result of the invocation back.
  9412. invokePartial: function(name) {
  9413. var params = [this.nameLookup('partials', name, 'partial'), "'" + name + "'", this.popStack(), "helpers", "partials"];
  9414. if (this.options.data) {
  9415. params.push("data");
  9416. }
  9417. this.context.aliases.self = "this";
  9418. this.pushStack("self.invokePartial(" + params.join(", ") + ");");
  9419. },
  9420. // [assignToHash]
  9421. //
  9422. // On stack, before: value, hash, ...
  9423. // On stack, after: hash, ...
  9424. //
  9425. // Pops a value and hash off the stack, assigns `hash[key] = value`
  9426. // and pushes the hash back onto the stack.
  9427. assignToHash: function(key) {
  9428. var value = this.popStack();
  9429. var hash = this.topStack();
  9430. this.source.push(hash + "['" + key + "'] = " + value + ";");
  9431. },
  9432. // HELPERS
  9433. compiler: JavaScriptCompiler,
  9434. compileChildren: function(environment, options) {
  9435. var children = environment.children, child, compiler;
  9436. for(var i=0, l=children.length; i<l; i++) {
  9437. child = children[i];
  9438. compiler = new this.compiler();
  9439. this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
  9440. var index = this.context.programs.length;
  9441. child.index = index;
  9442. child.name = 'program' + index;
  9443. this.context.programs[index] = compiler.compile(child, options, this.context);
  9444. }
  9445. },
  9446. programExpression: function(guid) {
  9447. this.context.aliases.self = "this";
  9448. if(guid == null) {
  9449. return "self.noop";
  9450. }
  9451. var child = this.environment.children[guid],
  9452. depths = child.depths.list, depth;
  9453. var programParams = [child.index, child.name, "data"];
  9454. for(var i=0, l = depths.length; i<l; i++) {
  9455. depth = depths[i];
  9456. if(depth === 1) { programParams.push("depth0"); }
  9457. else { programParams.push("depth" + (depth - 1)); }
  9458. }
  9459. if(depths.length === 0) {
  9460. return "self.program(" + programParams.join(", ") + ")";
  9461. } else {
  9462. programParams.shift();
  9463. return "self.programWithDepth(" + programParams.join(", ") + ")";
  9464. }
  9465. },
  9466. register: function(name, val) {
  9467. this.useRegister(name);
  9468. this.source.push(name + " = " + val + ";");
  9469. },
  9470. useRegister: function(name) {
  9471. if(!this.registers[name]) {
  9472. this.registers[name] = true;
  9473. this.registers.list.push(name);
  9474. }
  9475. },
  9476. pushStackLiteral: function(item) {
  9477. this.compileStack.push(new Literal(item));
  9478. return item;
  9479. },
  9480. pushStack: function(item) {
  9481. this.source.push(this.incrStack() + " = " + item + ";");
  9482. this.compileStack.push("stack" + this.stackSlot);
  9483. return "stack" + this.stackSlot;
  9484. },
  9485. replaceStack: function(callback) {
  9486. var item = callback.call(this, this.topStack());
  9487. this.source.push(this.topStack() + " = " + item + ";");
  9488. return "stack" + this.stackSlot;
  9489. },
  9490. nextStack: function(skipCompileStack) {
  9491. var name = this.incrStack();
  9492. this.compileStack.push("stack" + this.stackSlot);
  9493. return name;
  9494. },
  9495. incrStack: function() {
  9496. this.stackSlot++;
  9497. if(this.stackSlot > this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); }
  9498. return "stack" + this.stackSlot;
  9499. },
  9500. popStack: function() {
  9501. var item = this.compileStack.pop();
  9502. if (item instanceof Literal) {
  9503. return item.value;
  9504. } else {
  9505. this.stackSlot--;
  9506. return item;
  9507. }
  9508. },
  9509. topStack: function() {
  9510. var item = this.compileStack[this.compileStack.length - 1];
  9511. if (item instanceof Literal) {
  9512. return item.value;
  9513. } else {
  9514. return item;
  9515. }
  9516. },
  9517. quotedString: function(str) {
  9518. return '"' + str
  9519. .replace(/\\/g, '\\\\')
  9520. .replace(/"/g, '\\"')
  9521. .replace(/\n/g, '\\n')
  9522. .replace(/\r/g, '\\r') + '"';
  9523. },
  9524. setupHelper: function(paramSize, name) {
  9525. var params = [];
  9526. this.setupParams(paramSize, params);
  9527. var foundHelper = this.nameLookup('helpers', name, 'helper');
  9528. return {
  9529. params: params,
  9530. name: foundHelper,
  9531. callParams: ["depth0"].concat(params).join(", "),
  9532. helperMissingParams: ["depth0", this.quotedString(name)].concat(params).join(", ")
  9533. };
  9534. },
  9535. // the params and contexts arguments are passed in arrays
  9536. // to fill in
  9537. setupParams: function(paramSize, params) {
  9538. var options = [], contexts = [], param, inverse, program;
  9539. options.push("hash:" + this.popStack());
  9540. inverse = this.popStack();
  9541. program = this.popStack();
  9542. // Avoid setting fn and inverse if neither are set. This allows
  9543. // helpers to do a check for `if (options.fn)`
  9544. if (program || inverse) {
  9545. if (!program) {
  9546. this.context.aliases.self = "this";
  9547. program = "self.noop";
  9548. }
  9549. if (!inverse) {
  9550. this.context.aliases.self = "this";
  9551. inverse = "self.noop";
  9552. }
  9553. options.push("inverse:" + inverse);
  9554. options.push("fn:" + program);
  9555. }
  9556. for(var i=0; i<paramSize; i++) {
  9557. param = this.popStack();
  9558. params.push(param);
  9559. if(this.options.stringParams) {
  9560. contexts.push(this.popStack());
  9561. }
  9562. }
  9563. if (this.options.stringParams) {
  9564. options.push("contexts:[" + contexts.join(",") + "]");
  9565. }
  9566. if(this.options.data) {
  9567. options.push("data:data");
  9568. }
  9569. params.push("{" + options.join(",") + "}");
  9570. return params.join(", ");
  9571. }
  9572. };
  9573. var reservedWords = (
  9574. "break else new var" +
  9575. " case finally return void" +
  9576. " catch for switch while" +
  9577. " continue function this with" +
  9578. " default if throw" +
  9579. " delete in try" +
  9580. " do instanceof typeof" +
  9581. " abstract enum int short" +
  9582. " boolean export interface static" +
  9583. " byte extends long super" +
  9584. " char final native synchronized" +
  9585. " class float package throws" +
  9586. " const goto private transient" +
  9587. " debugger implements protected volatile" +
  9588. " double import public let yield"
  9589. ).split(" ");
  9590. var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
  9591. for(var i=0, l=reservedWords.length; i<l; i++) {
  9592. compilerWords[reservedWords[i]] = true;
  9593. }
  9594. JavaScriptCompiler.isValidJavaScriptVariableName = function(name) {
  9595. if(!JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]+$/.test(name)) {
  9596. return true;
  9597. }
  9598. return false;
  9599. };
  9600. })(Handlebars.Compiler, Handlebars.JavaScriptCompiler);
  9601. Handlebars.precompile = function(string, options) {
  9602. options = options || {};
  9603. if (!('data' in options)) {
  9604. options.data = true;
  9605. }
  9606. var ast = Handlebars.parse(string);
  9607. var environment = new Handlebars.Compiler().compile(ast, options);
  9608. return new Handlebars.JavaScriptCompiler().compile(environment, options);
  9609. };
  9610. Handlebars.compile = function(string, options) {
  9611. options = options || {};
  9612. if (!('data' in options)) {
  9613. options.data = true;
  9614. }
  9615. var compiled;
  9616. function compile() {
  9617. var ast = Handlebars.parse(string);
  9618. var environment = new Handlebars.Compiler().compile(ast, options);
  9619. var templateSpec = new Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true);
  9620. return Handlebars.template(templateSpec);
  9621. }
  9622. // Template is only compiled on first use and cached after that point.
  9623. return function(context, options) {
  9624. if (!compiled) {
  9625. compiled = compile();
  9626. }
  9627. return compiled.call(this, context, options);
  9628. };
  9629. };
  9630. ;
  9631. // lib/handlebars/runtime.js
  9632. Handlebars.VM = {
  9633. template: function(templateSpec) {
  9634. // Just add water
  9635. var container = {
  9636. escapeExpression: Handlebars.Utils.escapeExpression,
  9637. invokePartial: Handlebars.VM.invokePartial,
  9638. programs: [],
  9639. program: function(i, fn, data) {
  9640. var programWrapper = this.programs[i];
  9641. if(data) {
  9642. programWrapper = Handlebars.VM.program(fn, data);
  9643. programWrapper.program = i;
  9644. } else if (!programWrapper) {
  9645. programWrapper = this.programs[i] = Handlebars.VM.program(fn);
  9646. programWrapper.program = i;
  9647. }
  9648. return programWrapper;
  9649. },
  9650. programWithDepth: Handlebars.VM.programWithDepth,
  9651. noop: Handlebars.VM.noop
  9652. };
  9653. return function(context, options) {
  9654. options = options || {};
  9655. return templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data);
  9656. };
  9657. },
  9658. programWithDepth: function(fn, data, $depth) {
  9659. var args = Array.prototype.slice.call(arguments, 2);
  9660. return function(context, options) {
  9661. options = options || {};
  9662. return fn.apply(this, [context, options.data || data].concat(args));
  9663. };
  9664. },
  9665. program: function(fn, data) {
  9666. return function(context, options) {
  9667. options = options || {};
  9668. return fn(context, options.data || data);
  9669. };
  9670. },
  9671. noop: function() { return ""; },
  9672. invokePartial: function(partial, name, context, helpers, partials, data) {
  9673. var options = { helpers: helpers, partials: partials, data: data };
  9674. if(partial === undefined) {
  9675. throw new Handlebars.Exception("The partial " + name + " could not be found");
  9676. } else if(partial instanceof Function) {
  9677. return partial(context, options);
  9678. } else if (!Handlebars.compile) {
  9679. throw new Handlebars.Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
  9680. } else {
  9681. partials[name] = Handlebars.compile(partial, {data: data !== undefined});
  9682. return partials[name](context, options);
  9683. }
  9684. }
  9685. };
  9686. Handlebars.template = Handlebars.VM.template;
  9687. ;
  9688. // Underscore.js 1.4.2
  9689. // http://underscorejs.org
  9690. // (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
  9691. // Underscore may be freely distributed under the MIT license.
  9692. (function() {
  9693. // Baseline setup
  9694. // --------------
  9695. // Establish the root object, `window` in the browser, or `global` on the server.
  9696. var root = this;
  9697. // Save the previous value of the `_` variable.
  9698. var previousUnderscore = root._;
  9699. // Establish the object that gets returned to break out of a loop iteration.
  9700. var breaker = {};
  9701. // Save bytes in the minified (but not gzipped) version:
  9702. var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
  9703. // Create quick reference variables for speed access to core prototypes.
  9704. var push = ArrayProto.push,
  9705. slice = ArrayProto.slice,
  9706. concat = ArrayProto.concat,
  9707. unshift = ArrayProto.unshift,
  9708. toString = ObjProto.toString,
  9709. hasOwnProperty = ObjProto.hasOwnProperty;
  9710. // All **ECMAScript 5** native function implementations that we hope to use
  9711. // are declared here.
  9712. var
  9713. nativeForEach = ArrayProto.forEach,
  9714. nativeMap = ArrayProto.map,
  9715. nativeReduce = ArrayProto.reduce,
  9716. nativeReduceRight = ArrayProto.reduceRight,
  9717. nativeFilter = ArrayProto.filter,
  9718. nativeEvery = ArrayProto.every,
  9719. nativeSome = ArrayProto.some,
  9720. nativeIndexOf = ArrayProto.indexOf,
  9721. nativeLastIndexOf = ArrayProto.lastIndexOf,
  9722. nativeIsArray = Array.isArray,
  9723. nativeKeys = Object.keys,
  9724. nativeBind = FuncProto.bind;
  9725. // Create a safe reference to the Underscore object for use below.
  9726. var _ = function(obj) {
  9727. if (obj instanceof _) return obj;
  9728. if (!(this instanceof _)) return new _(obj);
  9729. this._wrapped = obj;
  9730. };
  9731. // Export the Underscore object for **Node.js**, with
  9732. // backwards-compatibility for the old `require()` API. If we're in
  9733. // the browser, add `_` as a global object via a string identifier,
  9734. // for Closure Compiler "advanced" mode.
  9735. if (typeof exports !== 'undefined') {
  9736. if (typeof module !== 'undefined' && module.exports) {
  9737. exports = module.exports = _;
  9738. }
  9739. exports._ = _;
  9740. } else {
  9741. root['_'] = _;
  9742. }
  9743. // Current version.
  9744. _.VERSION = '1.4.2';
  9745. // Collection Functions
  9746. // --------------------
  9747. // The cornerstone, an `each` implementation, aka `forEach`.
  9748. // Handles objects with the built-in `forEach`, arrays, and raw objects.
  9749. // Delegates to **ECMAScript 5**'s native `forEach` if available.
  9750. var each = _.each = _.forEach = function(obj, iterator, context) {
  9751. if (obj == null) return;
  9752. if (nativeForEach && obj.forEach === nativeForEach) {
  9753. obj.forEach(iterator, context);
  9754. } else if (obj.length === +obj.length) {
  9755. for (var i = 0, l = obj.length; i < l; i++) {
  9756. if (iterator.call(context, obj[i], i, obj) === breaker) return;
  9757. }
  9758. } else {
  9759. for (var key in obj) {
  9760. if (_.has(obj, key)) {
  9761. if (iterator.call(context, obj[key], key, obj) === breaker) return;
  9762. }
  9763. }
  9764. }
  9765. };
  9766. // Return the results of applying the iterator to each element.
  9767. // Delegates to **ECMAScript 5**'s native `map` if available.
  9768. _.map = _.collect = function(obj, iterator, context) {
  9769. var results = [];
  9770. if (obj == null) return results;
  9771. if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
  9772. each(obj, function(value, index, list) {
  9773. results[results.length] = iterator.call(context, value, index, list);
  9774. });
  9775. return results;
  9776. };
  9777. // **Reduce** builds up a single result from a list of values, aka `inject`,
  9778. // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  9779. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
  9780. var initial = arguments.length > 2;
  9781. if (obj == null) obj = [];
  9782. if (nativeReduce && obj.reduce === nativeReduce) {
  9783. if (context) iterator = _.bind(iterator, context);
  9784. return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
  9785. }
  9786. each(obj, function(value, index, list) {
  9787. if (!initial) {
  9788. memo = value;
  9789. initial = true;
  9790. } else {
  9791. memo = iterator.call(context, memo, value, index, list);
  9792. }
  9793. });
  9794. if (!initial) throw new TypeError('Reduce of empty array with no initial value');
  9795. return memo;
  9796. };
  9797. // The right-associative version of reduce, also known as `foldr`.
  9798. // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  9799. _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
  9800. var initial = arguments.length > 2;
  9801. if (obj == null) obj = [];
  9802. if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
  9803. if (context) iterator = _.bind(iterator, context);
  9804. return arguments.length > 2 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
  9805. }
  9806. var length = obj.length;
  9807. if (length !== +length) {
  9808. var keys = _.keys(obj);
  9809. length = keys.length;
  9810. }
  9811. each(obj, function(value, index, list) {
  9812. index = keys ? keys[--length] : --length;
  9813. if (!initial) {
  9814. memo = obj[index];
  9815. initial = true;
  9816. } else {
  9817. memo = iterator.call(context, memo, obj[index], index, list);
  9818. }
  9819. });
  9820. if (!initial) throw new TypeError('Reduce of empty array with no initial value');
  9821. return memo;
  9822. };
  9823. // Return the first value which passes a truth test. Aliased as `detect`.
  9824. _.find = _.detect = function(obj, iterator, context) {
  9825. var result;
  9826. any(obj, function(value, index, list) {
  9827. if (iterator.call(context, value, index, list)) {
  9828. result = value;
  9829. return true;
  9830. }
  9831. });
  9832. return result;
  9833. };
  9834. // Return all the elements that pass a truth test.
  9835. // Delegates to **ECMAScript 5**'s native `filter` if available.
  9836. // Aliased as `select`.
  9837. _.filter = _.select = function(obj, iterator, context) {
  9838. var results = [];
  9839. if (obj == null) return results;
  9840. if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
  9841. each(obj, function(value, index, list) {
  9842. if (iterator.call(context, value, index, list)) results[results.length] = value;
  9843. });
  9844. return results;
  9845. };
  9846. // Return all the elements for which a truth test fails.
  9847. _.reject = function(obj, iterator, context) {
  9848. var results = [];
  9849. if (obj == null) return results;
  9850. each(obj, function(value, index, list) {
  9851. if (!iterator.call(context, value, index, list)) results[results.length] = value;
  9852. });
  9853. return results;
  9854. };
  9855. // Determine whether all of the elements match a truth test.
  9856. // Delegates to **ECMAScript 5**'s native `every` if available.
  9857. // Aliased as `all`.
  9858. _.every = _.all = function(obj, iterator, context) {
  9859. iterator || (iterator = _.identity);
  9860. var result = true;
  9861. if (obj == null) return result;
  9862. if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
  9863. each(obj, function(value, index, list) {
  9864. if (!(result = result && iterator.call(context, value, index, list))) return breaker;
  9865. });
  9866. return !!result;
  9867. };
  9868. // Determine if at least one element in the object matches a truth test.
  9869. // Delegates to **ECMAScript 5**'s native `some` if available.
  9870. // Aliased as `any`.
  9871. var any = _.some = _.any = function(obj, iterator, context) {
  9872. iterator || (iterator = _.identity);
  9873. var result = false;
  9874. if (obj == null) return result;
  9875. if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
  9876. each(obj, function(value, index, list) {
  9877. if (result || (result = iterator.call(context, value, index, list))) return breaker;
  9878. });
  9879. return !!result;
  9880. };
  9881. // Determine if the array or object contains a given value (using `===`).
  9882. // Aliased as `include`.
  9883. _.contains = _.include = function(obj, target) {
  9884. var found = false;
  9885. if (obj == null) return found;
  9886. if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
  9887. found = any(obj, function(value) {
  9888. return value === target;
  9889. });
  9890. return found;
  9891. };
  9892. // Invoke a method (with arguments) on every item in a collection.
  9893. _.invoke = function(obj, method) {
  9894. var args = slice.call(arguments, 2);
  9895. return _.map(obj, function(value) {
  9896. return (_.isFunction(method) ? method : value[method]).apply(value, args);
  9897. });
  9898. };
  9899. // Convenience version of a common use case of `map`: fetching a property.
  9900. _.pluck = function(obj, key) {
  9901. return _.map(obj, function(value){ return value[key]; });
  9902. };
  9903. // Convenience version of a common use case of `filter`: selecting only objects
  9904. // with specific `key:value` pairs.
  9905. _.where = function(obj, attrs) {
  9906. if (_.isEmpty(attrs)) return [];
  9907. return _.filter(obj, function(value) {
  9908. for (var key in attrs) {
  9909. if (attrs[key] !== value[key]) return false;
  9910. }
  9911. return true;
  9912. });
  9913. };
  9914. // Return the maximum element or (element-based computation).
  9915. // Can't optimize arrays of integers longer than 65,535 elements.
  9916. // See: https://bugs.webkit.org/show_bug.cgi?id=80797
  9917. _.max = function(obj, iterator, context) {
  9918. if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
  9919. return Math.max.apply(Math, obj);
  9920. }
  9921. if (!iterator && _.isEmpty(obj)) return -Infinity;
  9922. var result = {computed : -Infinity};
  9923. each(obj, function(value, index, list) {
  9924. var computed = iterator ? iterator.call(context, value, index, list) : value;
  9925. computed >= result.computed && (result = {value : value, computed : computed});
  9926. });
  9927. return result.value;
  9928. };
  9929. // Return the minimum element (or element-based computation).
  9930. _.min = function(obj, iterator, context) {
  9931. if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
  9932. return Math.min.apply(Math, obj);
  9933. }
  9934. if (!iterator && _.isEmpty(obj)) return Infinity;
  9935. var result = {computed : Infinity};
  9936. each(obj, function(value, index, list) {
  9937. var computed = iterator ? iterator.call(context, value, index, list) : value;
  9938. computed < result.computed && (result = {value : value, computed : computed});
  9939. });
  9940. return result.value;
  9941. };
  9942. // Shuffle an array.
  9943. _.shuffle = function(obj) {
  9944. var rand;
  9945. var index = 0;
  9946. var shuffled = [];
  9947. each(obj, function(value) {
  9948. rand = _.random(index++);
  9949. shuffled[index - 1] = shuffled[rand];
  9950. shuffled[rand] = value;
  9951. });
  9952. return shuffled;
  9953. };
  9954. // An internal function to generate lookup iterators.
  9955. var lookupIterator = function(value) {
  9956. return _.isFunction(value) ? value : function(obj){ return obj[value]; };
  9957. };
  9958. // Sort the object's values by a criterion produced by an iterator.
  9959. _.sortBy = function(obj, value, context) {
  9960. var iterator = lookupIterator(value);
  9961. return _.pluck(_.map(obj, function(value, index, list) {
  9962. return {
  9963. value : value,
  9964. index : index,
  9965. criteria : iterator.call(context, value, index, list)
  9966. };
  9967. }).sort(function(left, right) {
  9968. var a = left.criteria;
  9969. var b = right.criteria;
  9970. if (a !== b) {
  9971. if (a > b || a === void 0) return 1;
  9972. if (a < b || b === void 0) return -1;
  9973. }
  9974. return left.index < right.index ? -1 : 1;
  9975. }), 'value');
  9976. };
  9977. // An internal function used for aggregate "group by" operations.
  9978. var group = function(obj, value, context, behavior) {
  9979. var result = {};
  9980. var iterator = lookupIterator(value);
  9981. each(obj, function(value, index) {
  9982. var key = iterator.call(context, value, index, obj);
  9983. behavior(result, key, value);
  9984. });
  9985. return result;
  9986. };
  9987. // Groups the object's values by a criterion. Pass either a string attribute
  9988. // to group by, or a function that returns the criterion.
  9989. _.groupBy = function(obj, value, context) {
  9990. return group(obj, value, context, function(result, key, value) {
  9991. (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
  9992. });
  9993. };
  9994. // Counts instances of an object that group by a certain criterion. Pass
  9995. // either a string attribute to count by, or a function that returns the
  9996. // criterion.
  9997. _.countBy = function(obj, value, context) {
  9998. return group(obj, value, context, function(result, key, value) {
  9999. if (!_.has(result, key)) result[key] = 0;
  10000. result[key]++;
  10001. });
  10002. };
  10003. // Use a comparator function to figure out the smallest index at which
  10004. // an object should be inserted so as to maintain order. Uses binary search.
  10005. _.sortedIndex = function(array, obj, iterator, context) {
  10006. iterator = iterator == null ? _.identity : lookupIterator(iterator);
  10007. var value = iterator.call(context, obj);
  10008. var low = 0, high = array.length;
  10009. while (low < high) {
  10010. var mid = (low + high) >>> 1;
  10011. iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
  10012. }
  10013. return low;
  10014. };
  10015. // Safely convert anything iterable into a real, live array.
  10016. _.toArray = function(obj) {
  10017. if (!obj) return [];
  10018. if (obj.length === +obj.length) return slice.call(obj);
  10019. return _.values(obj);
  10020. };
  10021. // Return the number of elements in an object.
  10022. _.size = function(obj) {
  10023. return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
  10024. };
  10025. // Array Functions
  10026. // ---------------
  10027. // Get the first element of an array. Passing **n** will return the first N
  10028. // values in the array. Aliased as `head` and `take`. The **guard** check
  10029. // allows it to work with `_.map`.
  10030. _.first = _.head = _.take = function(array, n, guard) {
  10031. return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  10032. };
  10033. // Returns everything but the last entry of the array. Especially useful on
  10034. // the arguments object. Passing **n** will return all the values in
  10035. // the array, excluding the last N. The **guard** check allows it to work with
  10036. // `_.map`.
  10037. _.initial = function(array, n, guard) {
  10038. return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
  10039. };
  10040. // Get the last element of an array. Passing **n** will return the last N
  10041. // values in the array. The **guard** check allows it to work with `_.map`.
  10042. _.last = function(array, n, guard) {
  10043. if ((n != null) && !guard) {
  10044. return slice.call(array, Math.max(array.length - n, 0));
  10045. } else {
  10046. return array[array.length - 1];
  10047. }
  10048. };
  10049. // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
  10050. // Especially useful on the arguments object. Passing an **n** will return
  10051. // the rest N values in the array. The **guard**
  10052. // check allows it to work with `_.map`.
  10053. _.rest = _.tail = _.drop = function(array, n, guard) {
  10054. return slice.call(array, (n == null) || guard ? 1 : n);
  10055. };
  10056. // Trim out all falsy values from an array.
  10057. _.compact = function(array) {
  10058. return _.filter(array, function(value){ return !!value; });
  10059. };
  10060. // Internal implementation of a recursive `flatten` function.
  10061. var flatten = function(input, shallow, output) {
  10062. each(input, function(value) {
  10063. if (_.isArray(value)) {
  10064. shallow ? push.apply(output, value) : flatten(value, shallow, output);
  10065. } else {
  10066. output.push(value);
  10067. }
  10068. });
  10069. return output;
  10070. };
  10071. // Return a completely flattened version of an array.
  10072. _.flatten = function(array, shallow) {
  10073. return flatten(array, shallow, []);
  10074. };
  10075. // Return a version of the array that does not contain the specified value(s).
  10076. _.without = function(array) {
  10077. return _.difference(array, slice.call(arguments, 1));
  10078. };
  10079. // Produce a duplicate-free version of the array. If the array has already
  10080. // been sorted, you have the option of using a faster algorithm.
  10081. // Aliased as `unique`.
  10082. _.uniq = _.unique = function(array, isSorted, iterator, context) {
  10083. var initial = iterator ? _.map(array, iterator, context) : array;
  10084. var results = [];
  10085. var seen = [];
  10086. each(initial, function(value, index) {
  10087. if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
  10088. seen.push(value);
  10089. results.push(array[index]);
  10090. }
  10091. });
  10092. return results;
  10093. };
  10094. // Produce an array that contains the union: each distinct element from all of
  10095. // the passed-in arrays.
  10096. _.union = function() {
  10097. return _.uniq(concat.apply(ArrayProto, arguments));
  10098. };
  10099. // Produce an array that contains every item shared between all the
  10100. // passed-in arrays.
  10101. _.intersection = function(array) {
  10102. var rest = slice.call(arguments, 1);
  10103. return _.filter(_.uniq(array), function(item) {
  10104. return _.every(rest, function(other) {
  10105. return _.indexOf(other, item) >= 0;
  10106. });
  10107. });
  10108. };
  10109. // Take the difference between one array and a number of other arrays.
  10110. // Only the elements present in just the first array will remain.
  10111. _.difference = function(array) {
  10112. var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
  10113. return _.filter(array, function(value){ return !_.contains(rest, value); });
  10114. };
  10115. // Zip together multiple lists into a single array -- elements that share
  10116. // an index go together.
  10117. _.zip = function() {
  10118. var args = slice.call(arguments);
  10119. var length = _.max(_.pluck(args, 'length'));
  10120. var results = new Array(length);
  10121. for (var i = 0; i < length; i++) {
  10122. results[i] = _.pluck(args, "" + i);
  10123. }
  10124. return results;
  10125. };
  10126. // Converts lists into objects. Pass either a single array of `[key, value]`
  10127. // pairs, or two parallel arrays of the same length -- one of keys, and one of
  10128. // the corresponding values.
  10129. _.object = function(list, values) {
  10130. var result = {};
  10131. for (var i = 0, l = list.length; i < l; i++) {
  10132. if (values) {
  10133. result[list[i]] = values[i];
  10134. } else {
  10135. result[list[i][0]] = list[i][1];
  10136. }
  10137. }
  10138. return result;
  10139. };
  10140. // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  10141. // we need this function. Return the position of the first occurrence of an
  10142. // item in an array, or -1 if the item is not included in the array.
  10143. // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  10144. // If the array is large and already in sort order, pass `true`
  10145. // for **isSorted** to use binary search.
  10146. _.indexOf = function(array, item, isSorted) {
  10147. if (array == null) return -1;
  10148. var i = 0, l = array.length;
  10149. if (isSorted) {
  10150. if (typeof isSorted == 'number') {
  10151. i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
  10152. } else {
  10153. i = _.sortedIndex(array, item);
  10154. return array[i] === item ? i : -1;
  10155. }
  10156. }
  10157. if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
  10158. for (; i < l; i++) if (array[i] === item) return i;
  10159. return -1;
  10160. };
  10161. // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  10162. _.lastIndexOf = function(array, item, from) {
  10163. if (array == null) return -1;
  10164. var hasIndex = from != null;
  10165. if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
  10166. return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
  10167. }
  10168. var i = (hasIndex ? from : array.length);
  10169. while (i--) if (array[i] === item) return i;
  10170. return -1;
  10171. };
  10172. // Generate an integer Array containing an arithmetic progression. A port of
  10173. // the native Python `range()` function. See
  10174. // [the Python documentation](http://docs.python.org/library/functions.html#range).
  10175. _.range = function(start, stop, step) {
  10176. if (arguments.length <= 1) {
  10177. stop = start || 0;
  10178. start = 0;
  10179. }
  10180. step = arguments[2] || 1;
  10181. var len = Math.max(Math.ceil((stop - start) / step), 0);
  10182. var idx = 0;
  10183. var range = new Array(len);
  10184. while(idx < len) {
  10185. range[idx++] = start;
  10186. start += step;
  10187. }
  10188. return range;
  10189. };
  10190. // Function (ahem) Functions
  10191. // ------------------
  10192. // Reusable constructor function for prototype setting.
  10193. var ctor = function(){};
  10194. // Create a function bound to a given object (assigning `this`, and arguments,
  10195. // optionally). Binding with arguments is also known as `curry`.
  10196. // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
  10197. // We check for `func.bind` first, to fail fast when `func` is undefined.
  10198. _.bind = function bind(func, context) {
  10199. var bound, args;
  10200. if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
  10201. if (!_.isFunction(func)) throw new TypeError;
  10202. args = slice.call(arguments, 2);
  10203. return bound = function() {
  10204. if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
  10205. ctor.prototype = func.prototype;
  10206. var self = new ctor;
  10207. var result = func.apply(self, args.concat(slice.call(arguments)));
  10208. if (Object(result) === result) return result;
  10209. return self;
  10210. };
  10211. };
  10212. // Bind all of an object's methods to that object. Useful for ensuring that
  10213. // all callbacks defined on an object belong to it.
  10214. _.bindAll = function(obj) {
  10215. var funcs = slice.call(arguments, 1);
  10216. if (funcs.length == 0) funcs = _.functions(obj);
  10217. each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
  10218. return obj;
  10219. };
  10220. // Memoize an expensive function by storing its results.
  10221. _.memoize = function(func, hasher) {
  10222. var memo = {};
  10223. hasher || (hasher = _.identity);
  10224. return function() {
  10225. var key = hasher.apply(this, arguments);
  10226. return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
  10227. };
  10228. };
  10229. // Delays a function for the given number of milliseconds, and then calls
  10230. // it with the arguments supplied.
  10231. _.delay = function(func, wait) {
  10232. var args = slice.call(arguments, 2);
  10233. return setTimeout(function(){ return func.apply(null, args); }, wait);
  10234. };
  10235. // Defers a function, scheduling it to run after the current call stack has
  10236. // cleared.
  10237. _.defer = function(func) {
  10238. return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  10239. };
  10240. // Returns a function, that, when invoked, will only be triggered at most once
  10241. // during a given window of time.
  10242. _.throttle = function(func, wait) {
  10243. var context, args, timeout, throttling, more, result;
  10244. var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
  10245. return function() {
  10246. context = this; args = arguments;
  10247. var later = function() {
  10248. timeout = null;
  10249. if (more) {
  10250. result = func.apply(context, args);
  10251. }
  10252. whenDone();
  10253. };
  10254. if (!timeout) timeout = setTimeout(later, wait);
  10255. if (throttling) {
  10256. more = true;
  10257. } else {
  10258. throttling = true;
  10259. result = func.apply(context, args);
  10260. }
  10261. whenDone();
  10262. return result;
  10263. };
  10264. };
  10265. // Returns a function, that, as long as it continues to be invoked, will not
  10266. // be triggered. The function will be called after it stops being called for
  10267. // N milliseconds. If `immediate` is passed, trigger the function on the
  10268. // leading edge, instead of the trailing.
  10269. _.debounce = function(func, wait, immediate) {
  10270. var timeout, result;
  10271. return function() {
  10272. var context = this, args = arguments;
  10273. var later = function() {
  10274. timeout = null;
  10275. if (!immediate) result = func.apply(context, args);
  10276. };
  10277. var callNow = immediate && !timeout;
  10278. clearTimeout(timeout);
  10279. timeout = setTimeout(later, wait);
  10280. if (callNow) result = func.apply(context, args);
  10281. return result;
  10282. };
  10283. };
  10284. // Returns a function that will be executed at most one time, no matter how
  10285. // often you call it. Useful for lazy initialization.
  10286. _.once = function(func) {
  10287. var ran = false, memo;
  10288. return function() {
  10289. if (ran) return memo;
  10290. ran = true;
  10291. memo = func.apply(this, arguments);
  10292. func = null;
  10293. return memo;
  10294. };
  10295. };
  10296. // Returns the first function passed as an argument to the second,
  10297. // allowing you to adjust arguments, run code before and after, and
  10298. // conditionally execute the original function.
  10299. _.wrap = function(func, wrapper) {
  10300. return function() {
  10301. var args = [func];
  10302. push.apply(args, arguments);
  10303. return wrapper.apply(this, args);
  10304. };
  10305. };
  10306. // Returns a function that is the composition of a list of functions, each
  10307. // consuming the return value of the function that follows.
  10308. _.compose = function() {
  10309. var funcs = arguments;
  10310. return function() {
  10311. var args = arguments;
  10312. for (var i = funcs.length - 1; i >= 0; i--) {
  10313. args = [funcs[i].apply(this, args)];
  10314. }
  10315. return args[0];
  10316. };
  10317. };
  10318. // Returns a function that will only be executed after being called N times.
  10319. _.after = function(times, func) {
  10320. if (times <= 0) return func();
  10321. return function() {
  10322. if (--times < 1) {
  10323. return func.apply(this, arguments);
  10324. }
  10325. };
  10326. };
  10327. // Object Functions
  10328. // ----------------
  10329. // Retrieve the names of an object's properties.
  10330. // Delegates to **ECMAScript 5**'s native `Object.keys`
  10331. _.keys = nativeKeys || function(obj) {
  10332. if (obj !== Object(obj)) throw new TypeError('Invalid object');
  10333. var keys = [];
  10334. for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
  10335. return keys;
  10336. };
  10337. // Retrieve the values of an object's properties.
  10338. _.values = function(obj) {
  10339. var values = [];
  10340. for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
  10341. return values;
  10342. };
  10343. // Convert an object into a list of `[key, value]` pairs.
  10344. _.pairs = function(obj) {
  10345. var pairs = [];
  10346. for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
  10347. return pairs;
  10348. };
  10349. // Invert the keys and values of an object. The values must be serializable.
  10350. _.invert = function(obj) {
  10351. var result = {};
  10352. for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
  10353. return result;
  10354. };
  10355. // Return a sorted list of the function names available on the object.
  10356. // Aliased as `methods`
  10357. _.functions = _.methods = function(obj) {
  10358. var names = [];
  10359. for (var key in obj) {
  10360. if (_.isFunction(obj[key])) names.push(key);
  10361. }
  10362. return names.sort();
  10363. };
  10364. // Extend a given object with all the properties in passed-in object(s).
  10365. _.extend = function(obj) {
  10366. each(slice.call(arguments, 1), function(source) {
  10367. for (var prop in source) {
  10368. obj[prop] = source[prop];
  10369. }
  10370. });
  10371. return obj;
  10372. };
  10373. // Return a copy of the object only containing the whitelisted properties.
  10374. _.pick = function(obj) {
  10375. var copy = {};
  10376. var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
  10377. each(keys, function(key) {
  10378. if (key in obj) copy[key] = obj[key];
  10379. });
  10380. return copy;
  10381. };
  10382. // Return a copy of the object without the blacklisted properties.
  10383. _.omit = function(obj) {
  10384. var copy = {};
  10385. var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
  10386. for (var key in obj) {
  10387. if (!_.contains(keys, key)) copy[key] = obj[key];
  10388. }
  10389. return copy;
  10390. };
  10391. // Fill in a given object with default properties.
  10392. _.defaults = function(obj) {
  10393. each(slice.call(arguments, 1), function(source) {
  10394. for (var prop in source) {
  10395. if (obj[prop] == null) obj[prop] = source[prop];
  10396. }
  10397. });
  10398. return obj;
  10399. };
  10400. // Create a (shallow-cloned) duplicate of an object.
  10401. _.clone = function(obj) {
  10402. if (!_.isObject(obj)) return obj;
  10403. return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  10404. };
  10405. // Invokes interceptor with the obj, and then returns obj.
  10406. // The primary purpose of this method is to "tap into" a method chain, in
  10407. // order to perform operations on intermediate results within the chain.
  10408. _.tap = function(obj, interceptor) {
  10409. interceptor(obj);
  10410. return obj;
  10411. };
  10412. // Internal recursive comparison function for `isEqual`.
  10413. var eq = function(a, b, aStack, bStack) {
  10414. // Identical objects are equal. `0 === -0`, but they aren't identical.
  10415. // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
  10416. if (a === b) return a !== 0 || 1 / a == 1 / b;
  10417. // A strict comparison is necessary because `null == undefined`.
  10418. if (a == null || b == null) return a === b;
  10419. // Unwrap any wrapped objects.
  10420. if (a instanceof _) a = a._wrapped;
  10421. if (b instanceof _) b = b._wrapped;
  10422. // Compare `[[Class]]` names.
  10423. var className = toString.call(a);
  10424. if (className != toString.call(b)) return false;
  10425. switch (className) {
  10426. // Strings, numbers, dates, and booleans are compared by value.
  10427. case '[object String]':
  10428. // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
  10429. // equivalent to `new String("5")`.
  10430. return a == String(b);
  10431. case '[object Number]':
  10432. // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
  10433. // other numeric values.
  10434. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
  10435. case '[object Date]':
  10436. case '[object Boolean]':
  10437. // Coerce dates and booleans to numeric primitive values. Dates are compared by their
  10438. // millisecond representations. Note that invalid dates with millisecond representations
  10439. // of `NaN` are not equivalent.
  10440. return +a == +b;
  10441. // RegExps are compared by their source patterns and flags.
  10442. case '[object RegExp]':
  10443. return a.source == b.source &&
  10444. a.global == b.global &&
  10445. a.multiline == b.multiline &&
  10446. a.ignoreCase == b.ignoreCase;
  10447. }
  10448. if (typeof a != 'object' || typeof b != 'object') return false;
  10449. // Assume equality for cyclic structures. The algorithm for detecting cyclic
  10450. // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
  10451. var length = aStack.length;
  10452. while (length--) {
  10453. // Linear search. Performance is inversely proportional to the number of
  10454. // unique nested structures.
  10455. if (aStack[length] == a) return bStack[length] == b;
  10456. }
  10457. // Add the first object to the stack of traversed objects.
  10458. aStack.push(a);
  10459. bStack.push(b);
  10460. var size = 0, result = true;
  10461. // Recursively compare objects and arrays.
  10462. if (className == '[object Array]') {
  10463. // Compare array lengths to determine if a deep comparison is necessary.
  10464. size = a.length;
  10465. result = size == b.length;
  10466. if (result) {
  10467. // Deep compare the contents, ignoring non-numeric properties.
  10468. while (size--) {
  10469. if (!(result = eq(a[size], b[size], aStack, bStack))) break;
  10470. }
  10471. }
  10472. } else {
  10473. // Objects with different constructors are not equivalent, but `Object`s
  10474. // from different frames are.
  10475. var aCtor = a.constructor, bCtor = b.constructor;
  10476. if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
  10477. _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
  10478. return false;
  10479. }
  10480. // Deep compare objects.
  10481. for (var key in a) {
  10482. if (_.has(a, key)) {
  10483. // Count the expected number of properties.
  10484. size++;
  10485. // Deep compare each member.
  10486. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
  10487. }
  10488. }
  10489. // Ensure that both objects contain the same number of properties.
  10490. if (result) {
  10491. for (key in b) {
  10492. if (_.has(b, key) && !(size--)) break;
  10493. }
  10494. result = !size;
  10495. }
  10496. }
  10497. // Remove the first object from the stack of traversed objects.
  10498. aStack.pop();
  10499. bStack.pop();
  10500. return result;
  10501. };
  10502. // Perform a deep comparison to check if two objects are equal.
  10503. _.isEqual = function(a, b) {
  10504. return eq(a, b, [], []);
  10505. };
  10506. // Is a given array, string, or object empty?
  10507. // An "empty" object has no enumerable own-properties.
  10508. _.isEmpty = function(obj) {
  10509. if (obj == null) return true;
  10510. if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
  10511. for (var key in obj) if (_.has(obj, key)) return false;
  10512. return true;
  10513. };
  10514. // Is a given value a DOM element?
  10515. _.isElement = function(obj) {
  10516. return !!(obj && obj.nodeType === 1);
  10517. };
  10518. // Is a given value an array?
  10519. // Delegates to ECMA5's native Array.isArray
  10520. _.isArray = nativeIsArray || function(obj) {
  10521. return toString.call(obj) == '[object Array]';
  10522. };
  10523. // Is a given variable an object?
  10524. _.isObject = function(obj) {
  10525. return obj === Object(obj);
  10526. };
  10527. // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
  10528. each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
  10529. _['is' + name] = function(obj) {
  10530. return toString.call(obj) == '[object ' + name + ']';
  10531. };
  10532. });
  10533. // Define a fallback version of the method in browsers (ahem, IE), where
  10534. // there isn't any inspectable "Arguments" type.
  10535. if (!_.isArguments(arguments)) {
  10536. _.isArguments = function(obj) {
  10537. return !!(obj && _.has(obj, 'callee'));
  10538. };
  10539. }
  10540. // Optimize `isFunction` if appropriate.
  10541. if (typeof (/./) !== 'function') {
  10542. _.isFunction = function(obj) {
  10543. return typeof obj === 'function';
  10544. };
  10545. }
  10546. // Is a given object a finite number?
  10547. _.isFinite = function(obj) {
  10548. return _.isNumber(obj) && isFinite(obj);
  10549. };
  10550. // Is the given value `NaN`? (NaN is the only number which does not equal itself).
  10551. _.isNaN = function(obj) {
  10552. return _.isNumber(obj) && obj != +obj;
  10553. };
  10554. // Is a given value a boolean?
  10555. _.isBoolean = function(obj) {
  10556. return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
  10557. };
  10558. // Is a given value equal to null?
  10559. _.isNull = function(obj) {
  10560. return obj === null;
  10561. };
  10562. // Is a given variable undefined?
  10563. _.isUndefined = function(obj) {
  10564. return obj === void 0;
  10565. };
  10566. // Shortcut function for checking if an object has a given property directly
  10567. // on itself (in other words, not on a prototype).
  10568. _.has = function(obj, key) {
  10569. return hasOwnProperty.call(obj, key);
  10570. };
  10571. // Utility Functions
  10572. // -----------------
  10573. // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  10574. // previous owner. Returns a reference to the Underscore object.
  10575. _.noConflict = function() {
  10576. root._ = previousUnderscore;
  10577. return this;
  10578. };
  10579. // Keep the identity function around for default iterators.
  10580. _.identity = function(value) {
  10581. return value;
  10582. };
  10583. // Run a function **n** times.
  10584. _.times = function(n, iterator, context) {
  10585. for (var i = 0; i < n; i++) iterator.call(context, i);
  10586. };
  10587. // Return a random integer between min and max (inclusive).
  10588. _.random = function(min, max) {
  10589. if (max == null) {
  10590. max = min;
  10591. min = 0;
  10592. }
  10593. return min + (0 | Math.random() * (max - min + 1));
  10594. };
  10595. // List of HTML entities for escaping.
  10596. var entityMap = {
  10597. escape: {
  10598. '&': '&amp;',
  10599. '<': '&lt;',
  10600. '>': '&gt;',
  10601. '"': '&quot;',
  10602. "'": '&#x27;',
  10603. '/': '&#x2F;'
  10604. }
  10605. };
  10606. entityMap.unescape = _.invert(entityMap.escape);
  10607. // Regexes containing the keys and values listed immediately above.
  10608. var entityRegexes = {
  10609. escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
  10610. unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
  10611. };
  10612. // Functions for escaping and unescaping strings to/from HTML interpolation.
  10613. _.each(['escape', 'unescape'], function(method) {
  10614. _[method] = function(string) {
  10615. if (string == null) return '';
  10616. return ('' + string).replace(entityRegexes[method], function(match) {
  10617. return entityMap[method][match];
  10618. });
  10619. };
  10620. });
  10621. // If the value of the named property is a function then invoke it;
  10622. // otherwise, return it.
  10623. _.result = function(object, property) {
  10624. if (object == null) return null;
  10625. var value = object[property];
  10626. return _.isFunction(value) ? value.call(object) : value;
  10627. };
  10628. // Add your own custom functions to the Underscore object.
  10629. _.mixin = function(obj) {
  10630. each(_.functions(obj), function(name){
  10631. var func = _[name] = obj[name];
  10632. _.prototype[name] = function() {
  10633. var args = [this._wrapped];
  10634. push.apply(args, arguments);
  10635. return result.call(this, func.apply(_, args));
  10636. };
  10637. });
  10638. };
  10639. // Generate a unique integer id (unique within the entire client session).
  10640. // Useful for temporary DOM ids.
  10641. var idCounter = 0;
  10642. _.uniqueId = function(prefix) {
  10643. var id = idCounter++;
  10644. return prefix ? prefix + id : id;
  10645. };
  10646. // By default, Underscore uses ERB-style template delimiters, change the
  10647. // following template settings to use alternative delimiters.
  10648. _.templateSettings = {
  10649. evaluate : /<%([\s\S]+?)%>/g,
  10650. interpolate : /<%=([\s\S]+?)%>/g,
  10651. escape : /<%-([\s\S]+?)%>/g
  10652. };
  10653. // When customizing `templateSettings`, if you don't want to define an
  10654. // interpolation, evaluation or escaping regex, we need one that is
  10655. // guaranteed not to match.
  10656. var noMatch = /(.)^/;
  10657. // Certain characters need to be escaped so that they can be put into a
  10658. // string literal.
  10659. var escapes = {
  10660. "'": "'",
  10661. '\\': '\\',
  10662. '\r': 'r',
  10663. '\n': 'n',
  10664. '\t': 't',
  10665. '\u2028': 'u2028',
  10666. '\u2029': 'u2029'
  10667. };
  10668. var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
  10669. // JavaScript micro-templating, similar to John Resig's implementation.
  10670. // Underscore templating handles arbitrary delimiters, preserves whitespace,
  10671. // and correctly escapes quotes within interpolated code.
  10672. _.template = function(text, data, settings) {
  10673. settings = _.defaults({}, settings, _.templateSettings);
  10674. // Combine delimiters into one regular expression via alternation.
  10675. var matcher = new RegExp([
  10676. (settings.escape || noMatch).source,
  10677. (settings.interpolate || noMatch).source,
  10678. (settings.evaluate || noMatch).source
  10679. ].join('|') + '|$', 'g');
  10680. // Compile the template source, escaping string literals appropriately.
  10681. var index = 0;
  10682. var source = "__p+='";
  10683. text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
  10684. source += text.slice(index, offset)
  10685. .replace(escaper, function(match) { return '\\' + escapes[match]; });
  10686. source +=
  10687. escape ? "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'" :
  10688. interpolate ? "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'" :
  10689. evaluate ? "';\n" + evaluate + "\n__p+='" : '';
  10690. index = offset + match.length;
  10691. });
  10692. source += "';\n";
  10693. // If a variable is not specified, place data values in local scope.
  10694. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
  10695. source = "var __t,__p='',__j=Array.prototype.join," +
  10696. "print=function(){__p+=__j.call(arguments,'');};\n" +
  10697. source + "return __p;\n";
  10698. try {
  10699. var render = new Function(settings.variable || 'obj', '_', source);
  10700. } catch (e) {
  10701. e.source = source;
  10702. throw e;
  10703. }
  10704. if (data) return render(data, _);
  10705. var template = function(data) {
  10706. return render.call(this, data, _);
  10707. };
  10708. // Provide the compiled function source as a convenience for precompilation.
  10709. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
  10710. return template;
  10711. };
  10712. // Add a "chain" function, which will delegate to the wrapper.
  10713. _.chain = function(obj) {
  10714. return _(obj).chain();
  10715. };
  10716. // OOP
  10717. // ---------------
  10718. // If Underscore is called as a function, it returns a wrapped object that
  10719. // can be used OO-style. This wrapper holds altered versions of all the
  10720. // underscore functions. Wrapped objects may be chained.
  10721. // Helper function to continue chaining intermediate results.
  10722. var result = function(obj) {
  10723. return this._chain ? _(obj).chain() : obj;
  10724. };
  10725. // Add all of the Underscore functions to the wrapper object.
  10726. _.mixin(_);
  10727. // Add all mutator Array functions to the wrapper.
  10728. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  10729. var method = ArrayProto[name];
  10730. _.prototype[name] = function() {
  10731. var obj = this._wrapped;
  10732. method.apply(obj, arguments);
  10733. if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
  10734. return result.call(this, obj);
  10735. };
  10736. });
  10737. // Add all accessor Array functions to the wrapper.
  10738. each(['concat', 'join', 'slice'], function(name) {
  10739. var method = ArrayProto[name];
  10740. _.prototype[name] = function() {
  10741. return result.call(this, method.apply(this._wrapped, arguments));
  10742. };
  10743. });
  10744. _.extend(_.prototype, {
  10745. // Start chaining a wrapped Underscore object.
  10746. chain: function() {
  10747. this._chain = true;
  10748. return this;
  10749. },
  10750. // Extracts the result from a wrapped and chained object.
  10751. value: function() {
  10752. return this._wrapped;
  10753. }
  10754. });
  10755. }).call(this);
  10756. // Backbone.js 0.9.9
  10757. // (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc.
  10758. // Backbone may be freely distributed under the MIT license.
  10759. // For all details and documentation:
  10760. // http://backbonejs.org
  10761. (function(){
  10762. // Initial Setup
  10763. // -------------
  10764. // Save a reference to the global object (`window` in the browser, `exports`
  10765. // on the server).
  10766. var root = this;
  10767. // Save the previous value of the `Backbone` variable, so that it can be
  10768. // restored later on, if `noConflict` is used.
  10769. var previousBackbone = root.Backbone;
  10770. // Create a local reference to array methods.
  10771. var array = [];
  10772. var push = array.push;
  10773. var slice = array.slice;
  10774. var splice = array.splice;
  10775. // The top-level namespace. All public Backbone classes and modules will
  10776. // be attached to this. Exported for both CommonJS and the browser.
  10777. var Backbone;
  10778. if (typeof exports !== 'undefined') {
  10779. Backbone = exports;
  10780. } else {
  10781. Backbone = root.Backbone = {};
  10782. }
  10783. // Current version of the library. Keep in sync with `package.json`.
  10784. Backbone.VERSION = '0.9.9';
  10785. // Require Underscore, if we're on the server, and it's not already present.
  10786. var _ = root._;
  10787. if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
  10788. // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable.
  10789. Backbone.$ = root.jQuery || root.Zepto || root.ender;
  10790. // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
  10791. // to its previous owner. Returns a reference to this Backbone object.
  10792. Backbone.noConflict = function() {
  10793. root.Backbone = previousBackbone;
  10794. return this;
  10795. };
  10796. // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
  10797. // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
  10798. // set a `X-Http-Method-Override` header.
  10799. Backbone.emulateHTTP = false;
  10800. // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  10801. // `application/json` requests ... will encode the body as
  10802. // `application/x-www-form-urlencoded` instead and will send the model in a
  10803. // form param named `model`.
  10804. Backbone.emulateJSON = false;
  10805. // Backbone.Events
  10806. // ---------------
  10807. // Regular expression used to split event strings.
  10808. var eventSplitter = /\s+/;
  10809. // Implement fancy features of the Events API such as multiple event
  10810. // names `"change blur"` and jQuery-style event maps `{change: action}`
  10811. // in terms of the existing API.
  10812. var eventsApi = function(obj, action, name, rest) {
  10813. if (!name) return true;
  10814. if (typeof name === 'object') {
  10815. for (var key in name) {
  10816. obj[action].apply(obj, [key, name[key]].concat(rest));
  10817. }
  10818. } else if (eventSplitter.test(name)) {
  10819. var names = name.split(eventSplitter);
  10820. for (var i = 0, l = names.length; i < l; i++) {
  10821. obj[action].apply(obj, [names[i]].concat(rest));
  10822. }
  10823. } else {
  10824. return true;
  10825. }
  10826. };
  10827. // Optimized internal dispatch function for triggering events. Tries to
  10828. // keep the usual cases speedy (most Backbone events have 3 arguments).
  10829. var triggerEvents = function(obj, events, args) {
  10830. var ev, i = -1, l = events.length;
  10831. switch (args.length) {
  10832. case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx);
  10833. return;
  10834. case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0]);
  10835. return;
  10836. case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1]);
  10837. return;
  10838. case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1], args[2]);
  10839. return;
  10840. default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
  10841. }
  10842. };
  10843. // A module that can be mixed in to *any object* in order to provide it with
  10844. // custom events. You may bind with `on` or remove with `off` callback
  10845. // functions to an event; `trigger`-ing an event fires all callbacks in
  10846. // succession.
  10847. //
  10848. // var object = {};
  10849. // _.extend(object, Backbone.Events);
  10850. // object.on('expand', function(){ alert('expanded'); });
  10851. // object.trigger('expand');
  10852. //
  10853. var Events = Backbone.Events = {
  10854. // Bind one or more space separated events, or an events map,
  10855. // to a `callback` function. Passing `"all"` will bind the callback to
  10856. // all events fired.
  10857. on: function(name, callback, context) {
  10858. if (!(eventsApi(this, 'on', name, [callback, context]) && callback)) return this;
  10859. this._events || (this._events = {});
  10860. var list = this._events[name] || (this._events[name] = []);
  10861. list.push({callback: callback, context: context, ctx: context || this});
  10862. return this;
  10863. },
  10864. // Bind events to only be triggered a single time. After the first time
  10865. // the callback is invoked, it will be removed.
  10866. once: function(name, callback, context) {
  10867. if (!(eventsApi(this, 'once', name, [callback, context]) && callback)) return this;
  10868. var self = this;
  10869. var once = _.once(function() {
  10870. self.off(name, once);
  10871. callback.apply(this, arguments);
  10872. });
  10873. once._callback = callback;
  10874. this.on(name, once, context);
  10875. return this;
  10876. },
  10877. // Remove one or many callbacks. If `context` is null, removes all
  10878. // callbacks with that function. If `callback` is null, removes all
  10879. // callbacks for the event. If `events` is null, removes all bound
  10880. // callbacks for all events.
  10881. off: function(name, callback, context) {
  10882. var list, ev, events, names, i, l, j, k;
  10883. if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
  10884. if (!name && !callback && !context) {
  10885. this._events = {};
  10886. return this;
  10887. }
  10888. names = name ? [name] : _.keys(this._events);
  10889. for (i = 0, l = names.length; i < l; i++) {
  10890. name = names[i];
  10891. if (list = this._events[name]) {
  10892. events = [];
  10893. if (callback || context) {
  10894. for (j = 0, k = list.length; j < k; j++) {
  10895. ev = list[j];
  10896. if ((callback && callback !== (ev.callback._callback || ev.callback)) ||
  10897. (context && context !== ev.context)) {
  10898. events.push(ev);
  10899. }
  10900. }
  10901. }
  10902. this._events[name] = events;
  10903. }
  10904. }
  10905. return this;
  10906. },
  10907. // Trigger one or many events, firing all bound callbacks. Callbacks are
  10908. // passed the same arguments as `trigger` is, apart from the event name
  10909. // (unless you're listening on `"all"`, which will cause your callback to
  10910. // receive the true name of the event as the first argument).
  10911. trigger: function(name) {
  10912. if (!this._events) return this;
  10913. var args = slice.call(arguments, 1);
  10914. if (!eventsApi(this, 'trigger', name, args)) return this;
  10915. var events = this._events[name];
  10916. var allEvents = this._events.all;
  10917. if (events) triggerEvents(this, events, args);
  10918. if (allEvents) triggerEvents(this, allEvents, arguments);
  10919. return this;
  10920. },
  10921. // An inversion-of-control version of `on`. Tell *this* object to listen to
  10922. // an event in another object ... keeping track of what it's listening to.
  10923. listenTo: function(object, events, callback) {
  10924. var listeners = this._listeners || (this._listeners = {});
  10925. var id = object._listenerId || (object._listenerId = _.uniqueId('l'));
  10926. listeners[id] = object;
  10927. object.on(events, callback || this, this);
  10928. return this;
  10929. },
  10930. // Tell this object to stop listening to either specific events ... or
  10931. // to every object it's currently listening to.
  10932. stopListening: function(object, events, callback) {
  10933. var listeners = this._listeners;
  10934. if (!listeners) return;
  10935. if (object) {
  10936. object.off(events, callback, this);
  10937. if (!events && !callback) delete listeners[object._listenerId];
  10938. } else {
  10939. for (var id in listeners) {
  10940. listeners[id].off(null, null, this);
  10941. }
  10942. this._listeners = {};
  10943. }
  10944. return this;
  10945. }
  10946. };
  10947. // Aliases for backwards compatibility.
  10948. Events.bind = Events.on;
  10949. Events.unbind = Events.off;
  10950. // Allow the `Backbone` object to serve as a global event bus, for folks who
  10951. // want global "pubsub" in a convenient place.
  10952. _.extend(Backbone, Events);
  10953. // Backbone.Model
  10954. // --------------
  10955. // Create a new model, with defined attributes. A client id (`cid`)
  10956. // is automatically generated and assigned for you.
  10957. var Model = Backbone.Model = function(attributes, options) {
  10958. var defaults;
  10959. var attrs = attributes || {};
  10960. this.cid = _.uniqueId('c');
  10961. this.changed = {};
  10962. this.attributes = {};
  10963. this._changes = [];
  10964. if (options && options.collection) this.collection = options.collection;
  10965. if (options && options.parse) attrs = this.parse(attrs);
  10966. if (defaults = _.result(this, 'defaults')) _.defaults(attrs, defaults);
  10967. this.set(attrs, {silent: true});
  10968. this._currentAttributes = _.clone(this.attributes);
  10969. this._previousAttributes = _.clone(this.attributes);
  10970. this.initialize.apply(this, arguments);
  10971. };
  10972. // Attach all inheritable methods to the Model prototype.
  10973. _.extend(Model.prototype, Events, {
  10974. // A hash of attributes whose current and previous value differ.
  10975. changed: null,
  10976. // The default name for the JSON `id` attribute is `"id"`. MongoDB and
  10977. // CouchDB users may want to set this to `"_id"`.
  10978. idAttribute: 'id',
  10979. // Initialize is an empty function by default. Override it with your own
  10980. // initialization logic.
  10981. initialize: function(){},
  10982. // Return a copy of the model's `attributes` object.
  10983. toJSON: function(options) {
  10984. return _.clone(this.attributes);
  10985. },
  10986. // Proxy `Backbone.sync` by default.
  10987. sync: function() {
  10988. return Backbone.sync.apply(this, arguments);
  10989. },
  10990. // Get the value of an attribute.
  10991. get: function(attr) {
  10992. return this.attributes[attr];
  10993. },
  10994. // Get the HTML-escaped value of an attribute.
  10995. escape: function(attr) {
  10996. return _.escape(this.get(attr));
  10997. },
  10998. // Returns `true` if the attribute contains a value that is not null
  10999. // or undefined.
  11000. has: function(attr) {
  11001. return this.get(attr) != null;
  11002. },
  11003. // Set a hash of model attributes on the object, firing `"change"` unless
  11004. // you choose to silence it.
  11005. set: function(key, val, options) {
  11006. var attr, attrs;
  11007. if (key == null) return this;
  11008. // Handle both `"key", value` and `{key: value}` -style arguments.
  11009. if (_.isObject(key)) {
  11010. attrs = key;
  11011. options = val;
  11012. } else {
  11013. (attrs = {})[key] = val;
  11014. }
  11015. // Extract attributes and options.
  11016. var silent = options && options.silent;
  11017. var unset = options && options.unset;
  11018. // Run validation.
  11019. if (!this._validate(attrs, options)) return false;
  11020. // Check for changes of `id`.
  11021. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
  11022. var now = this.attributes;
  11023. // For each `set` attribute...
  11024. for (attr in attrs) {
  11025. val = attrs[attr];
  11026. // Update or delete the current value, and track the change.
  11027. unset ? delete now[attr] : now[attr] = val;
  11028. this._changes.push(attr, val);
  11029. }
  11030. // Signal that the model's state has potentially changed, and we need
  11031. // to recompute the actual changes.
  11032. this._hasComputed = false;
  11033. // Fire the `"change"` events.
  11034. if (!silent) this.change(options);
  11035. return this;
  11036. },
  11037. // Remove an attribute from the model, firing `"change"` unless you choose
  11038. // to silence it. `unset` is a noop if the attribute doesn't exist.
  11039. unset: function(attr, options) {
  11040. return this.set(attr, void 0, _.extend({}, options, {unset: true}));
  11041. },
  11042. // Clear all attributes on the model, firing `"change"` unless you choose
  11043. // to silence it.
  11044. clear: function(options) {
  11045. var attrs = {};
  11046. for (var key in this.attributes) attrs[key] = void 0;
  11047. return this.set(attrs, _.extend({}, options, {unset: true}));
  11048. },
  11049. // Fetch the model from the server. If the server's representation of the
  11050. // model differs from its current attributes, they will be overriden,
  11051. // triggering a `"change"` event.
  11052. fetch: function(options) {
  11053. options = options ? _.clone(options) : {};
  11054. if (options.parse === void 0) options.parse = true;
  11055. var model = this;
  11056. var success = options.success;
  11057. options.success = function(resp, status, xhr) {
  11058. if (!model.set(model.parse(resp), options)) return false;
  11059. if (success) success(model, resp, options);
  11060. };
  11061. return this.sync('read', this, options);
  11062. },
  11063. // Set a hash of model attributes, and sync the model to the server.
  11064. // If the server returns an attributes hash that differs, the model's
  11065. // state will be `set` again.
  11066. save: function(key, val, options) {
  11067. var attrs, current, done;
  11068. // Handle both `"key", value` and `{key: value}` -style arguments.
  11069. if (key == null || _.isObject(key)) {
  11070. attrs = key;
  11071. options = val;
  11072. } else if (key != null) {
  11073. (attrs = {})[key] = val;
  11074. }
  11075. options = options ? _.clone(options) : {};
  11076. // If we're "wait"-ing to set changed attributes, validate early.
  11077. if (options.wait) {
  11078. if (attrs && !this._validate(attrs, options)) return false;
  11079. current = _.clone(this.attributes);
  11080. }
  11081. // Regular saves `set` attributes before persisting to the server.
  11082. var silentOptions = _.extend({}, options, {silent: true});
  11083. if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) {
  11084. return false;
  11085. }
  11086. // Do not persist invalid models.
  11087. if (!attrs && !this._validate(null, options)) return false;
  11088. // After a successful server-side save, the client is (optionally)
  11089. // updated with the server-side state.
  11090. var model = this;
  11091. var success = options.success;
  11092. options.success = function(resp, status, xhr) {
  11093. done = true;
  11094. var serverAttrs = model.parse(resp);
  11095. if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
  11096. if (!model.set(serverAttrs, options)) return false;
  11097. if (success) success(model, resp, options);
  11098. };
  11099. // Finish configuring and sending the Ajax request.
  11100. var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
  11101. if (method == 'patch') options.attrs = attrs;
  11102. var xhr = this.sync(method, this, options);
  11103. // When using `wait`, reset attributes to original values unless
  11104. // `success` has been called already.
  11105. if (!done && options.wait) {
  11106. this.clear(silentOptions);
  11107. this.set(current, silentOptions);
  11108. }
  11109. return xhr;
  11110. },
  11111. // Destroy this model on the server if it was already persisted.
  11112. // Optimistically removes the model from its collection, if it has one.
  11113. // If `wait: true` is passed, waits for the server to respond before removal.
  11114. destroy: function(options) {
  11115. options = options ? _.clone(options) : {};
  11116. var model = this;
  11117. var success = options.success;
  11118. var destroy = function() {
  11119. model.trigger('destroy', model, model.collection, options);
  11120. };
  11121. options.success = function(resp) {
  11122. if (options.wait || model.isNew()) destroy();
  11123. if (success) success(model, resp, options);
  11124. };
  11125. if (this.isNew()) {
  11126. options.success();
  11127. return false;
  11128. }
  11129. var xhr = this.sync('delete', this, options);
  11130. if (!options.wait) destroy();
  11131. return xhr;
  11132. },
  11133. // Default URL for the model's representation on the server -- if you're
  11134. // using Backbone's restful methods, override this to change the endpoint
  11135. // that will be called.
  11136. url: function() {
  11137. var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
  11138. if (this.isNew()) return base;
  11139. return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
  11140. },
  11141. // **parse** converts a response into the hash of attributes to be `set` on
  11142. // the model. The default implementation is just to pass the response along.
  11143. parse: function(resp) {
  11144. return resp;
  11145. },
  11146. // Create a new model with identical attributes to this one.
  11147. clone: function() {
  11148. return new this.constructor(this.attributes);
  11149. },
  11150. // A model is new if it has never been saved to the server, and lacks an id.
  11151. isNew: function() {
  11152. return this.id == null;
  11153. },
  11154. // Call this method to manually fire a `"change"` event for this model and
  11155. // a `"change:attribute"` event for each changed attribute.
  11156. // Calling this will cause all objects observing the model to update.
  11157. change: function(options) {
  11158. var changing = this._changing;
  11159. this._changing = true;
  11160. // Generate the changes to be triggered on the model.
  11161. var triggers = this._computeChanges(true);
  11162. this._pending = !!triggers.length;
  11163. for (var i = triggers.length - 2; i >= 0; i -= 2) {
  11164. this.trigger('change:' + triggers[i], this, triggers[i + 1], options);
  11165. }
  11166. if (changing) return this;
  11167. // Trigger a `change` while there have been changes.
  11168. while (this._pending) {
  11169. this._pending = false;
  11170. this.trigger('change', this, options);
  11171. this._previousAttributes = _.clone(this.attributes);
  11172. }
  11173. this._changing = false;
  11174. return this;
  11175. },
  11176. // Determine if the model has changed since the last `"change"` event.
  11177. // If you specify an attribute name, determine if that attribute has changed.
  11178. hasChanged: function(attr) {
  11179. if (!this._hasComputed) this._computeChanges();
  11180. if (attr == null) return !_.isEmpty(this.changed);
  11181. return _.has(this.changed, attr);
  11182. },
  11183. // Return an object containing all the attributes that have changed, or
  11184. // false if there are no changed attributes. Useful for determining what
  11185. // parts of a view need to be updated and/or what attributes need to be
  11186. // persisted to the server. Unset attributes will be set to undefined.
  11187. // You can also pass an attributes object to diff against the model,
  11188. // determining if there *would be* a change.
  11189. changedAttributes: function(diff) {
  11190. if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
  11191. var val, changed = false, old = this._previousAttributes;
  11192. for (var attr in diff) {
  11193. if (_.isEqual(old[attr], (val = diff[attr]))) continue;
  11194. (changed || (changed = {}))[attr] = val;
  11195. }
  11196. return changed;
  11197. },
  11198. // Looking at the built up list of `set` attribute changes, compute how
  11199. // many of the attributes have actually changed. If `loud`, return a
  11200. // boiled-down list of only the real changes.
  11201. _computeChanges: function(loud) {
  11202. this.changed = {};
  11203. var already = {};
  11204. var triggers = [];
  11205. // WARN: monkey patch for 0.9.9, will go away when upgrading
  11206. // to future version of backbone
  11207. var current = this._currentAttributes || {};
  11208. var changes = this._changes;
  11209. // Loop through the current queue of potential model changes.
  11210. for (var i = changes.length - 2; i >= 0; i -= 2) {
  11211. var key = changes[i], val = changes[i + 1];
  11212. if (already[key]) continue;
  11213. already[key] = true;
  11214. // Check if the attribute has been modified since the last change,
  11215. // and update `this.changed` accordingly. If we're inside of a `change`
  11216. // call, also add a trigger to the list.
  11217. if (current[key] !== val) {
  11218. this.changed[key] = val;
  11219. if (!loud) continue;
  11220. triggers.push(key, val);
  11221. current[key] = val;
  11222. }
  11223. }
  11224. if (loud) this._changes = [];
  11225. // Signals `this.changed` is current to prevent duplicate calls from `this.hasChanged`.
  11226. this._hasComputed = true;
  11227. return triggers;
  11228. },
  11229. // Get the previous value of an attribute, recorded at the time the last
  11230. // `"change"` event was fired.
  11231. previous: function(attr) {
  11232. if (attr == null || !this._previousAttributes) return null;
  11233. return this._previousAttributes[attr];
  11234. },
  11235. // Get all of the attributes of the model at the time of the previous
  11236. // `"change"` event.
  11237. previousAttributes: function() {
  11238. return _.clone(this._previousAttributes);
  11239. },
  11240. // Run validation against the next complete set of model attributes,
  11241. // returning `true` if all is well. If a specific `error` callback has
  11242. // been passed, call that instead of firing the general `"error"` event.
  11243. _validate: function(attrs, options) {
  11244. if (!this.validate) return true;
  11245. attrs = _.extend({}, this.attributes, attrs);
  11246. var error = this.validate(attrs, options);
  11247. if (!error) return true;
  11248. if (options && options.error) options.error(this, error, options);
  11249. this.trigger('error', this, error, options);
  11250. return false;
  11251. }
  11252. });
  11253. // Backbone.Collection
  11254. // -------------------
  11255. // Provides a standard collection class for our sets of models, ordered
  11256. // or unordered. If a `comparator` is specified, the Collection will maintain
  11257. // its models in sort order, as they're added and removed.
  11258. var Collection = Backbone.Collection = function(models, options) {
  11259. options || (options = {});
  11260. if (options.model) this.model = options.model;
  11261. if (options.comparator !== void 0) this.comparator = options.comparator;
  11262. this._reset();
  11263. this.initialize.apply(this, arguments);
  11264. if (models) this.reset(models, _.extend({silent: true}, options));
  11265. };
  11266. // Define the Collection's inheritable methods.
  11267. _.extend(Collection.prototype, Events, {
  11268. // The default model for a collection is just a **Backbone.Model**.
  11269. // This should be overridden in most cases.
  11270. model: Model,
  11271. // Initialize is an empty function by default. Override it with your own
  11272. // initialization logic.
  11273. initialize: function(){},
  11274. // The JSON representation of a Collection is an array of the
  11275. // models' attributes.
  11276. toJSON: function(options) {
  11277. return this.map(function(model){ return model.toJSON(options); });
  11278. },
  11279. // Proxy `Backbone.sync` by default.
  11280. sync: function() {
  11281. return Backbone.sync.apply(this, arguments);
  11282. },
  11283. // Add a model, or list of models to the set. Pass **silent** to avoid
  11284. // firing the `add` event for every new model.
  11285. add: function(models, options) {
  11286. var i, args, length, model, existing, needsSort;
  11287. var at = options && options.at;
  11288. var sort = ((options && options.sort) == null ? true : options.sort);
  11289. models = _.isArray(models) ? models.slice() : [models];
  11290. // Turn bare objects into model references, and prevent invalid models
  11291. // from being added.
  11292. for (i = models.length - 1; i >= 0; i--) {
  11293. if(!(model = this._prepareModel(models[i], options))) {
  11294. this.trigger("error", this, models[i], options);
  11295. models.splice(i, 1);
  11296. continue;
  11297. }
  11298. models[i] = model;
  11299. existing = model.id != null && this._byId[model.id];
  11300. // If a duplicate is found, prevent it from being added and
  11301. // optionally merge it into the existing model.
  11302. if (existing || this._byCid[model.cid]) {
  11303. if (options && options.merge && existing) {
  11304. existing.set(model.attributes, options);
  11305. needsSort = sort;
  11306. }
  11307. models.splice(i, 1);
  11308. continue;
  11309. }
  11310. // Listen to added models' events, and index models for lookup by
  11311. // `id` and by `cid`.
  11312. model.on('all', this._onModelEvent, this);
  11313. this._byCid[model.cid] = model;
  11314. if (model.id != null) this._byId[model.id] = model;
  11315. }
  11316. // See if sorting is needed, update `length` and splice in new models.
  11317. if (models.length) needsSort = sort;
  11318. this.length += models.length;
  11319. args = [at != null ? at : this.models.length, 0];
  11320. push.apply(args, models);
  11321. splice.apply(this.models, args);
  11322. // Sort the collection if appropriate.
  11323. if (needsSort && this.comparator && at == null) this.sort({silent: true});
  11324. if (options && options.silent) return this;
  11325. // Trigger `add` events.
  11326. while (model = models.shift()) {
  11327. model.trigger('add', model, this, options);
  11328. }
  11329. return this;
  11330. },
  11331. // Remove a model, or a list of models from the set. Pass silent to avoid
  11332. // firing the `remove` event for every model removed.
  11333. remove: function(models, options) {
  11334. var i, l, index, model;
  11335. options || (options = {});
  11336. models = _.isArray(models) ? models.slice() : [models];
  11337. for (i = 0, l = models.length; i < l; i++) {
  11338. model = this.get(models[i]);
  11339. if (!model) continue;
  11340. delete this._byId[model.id];
  11341. delete this._byCid[model.cid];
  11342. index = this.indexOf(model);
  11343. this.models.splice(index, 1);
  11344. this.length--;
  11345. if (!options.silent) {
  11346. options.index = index;
  11347. model.trigger('remove', model, this, options);
  11348. }
  11349. this._removeReference(model);
  11350. }
  11351. return this;
  11352. },
  11353. // Add a model to the end of the collection.
  11354. push: function(model, options) {
  11355. model = this._prepareModel(model, options);
  11356. this.add(model, _.extend({at: this.length}, options));
  11357. return model;
  11358. },
  11359. // Remove a model from the end of the collection.
  11360. pop: function(options) {
  11361. var model = this.at(this.length - 1);
  11362. this.remove(model, options);
  11363. return model;
  11364. },
  11365. // Add a model to the beginning of the collection.
  11366. unshift: function(model, options) {
  11367. model = this._prepareModel(model, options);
  11368. this.add(model, _.extend({at: 0}, options));
  11369. return model;
  11370. },
  11371. // Remove a model from the beginning of the collection.
  11372. shift: function(options) {
  11373. var model = this.at(0);
  11374. this.remove(model, options);
  11375. return model;
  11376. },
  11377. // Slice out a sub-array of models from the collection.
  11378. slice: function(begin, end) {
  11379. return this.models.slice(begin, end);
  11380. },
  11381. // Get a model from the set by id.
  11382. get: function(obj) {
  11383. if (obj == null) return void 0;
  11384. return this._byId[obj.id != null ? obj.id : obj] || this._byCid[obj.cid || obj];
  11385. },
  11386. // Get the model at the given index.
  11387. at: function(index) {
  11388. return this.models[index];
  11389. },
  11390. // Return models with matching attributes. Useful for simple cases of `filter`.
  11391. where: function(attrs) {
  11392. if (_.isEmpty(attrs)) return [];
  11393. return this.filter(function(model) {
  11394. for (var key in attrs) {
  11395. if (attrs[key] !== model.get(key)) return false;
  11396. }
  11397. return true;
  11398. });
  11399. },
  11400. // Force the collection to re-sort itself. You don't need to call this under
  11401. // normal circumstances, as the set will maintain sort order as each item
  11402. // is added.
  11403. sort: function(options) {
  11404. if (!this.comparator) {
  11405. throw new Error('Cannot sort a set without a comparator');
  11406. }
  11407. if (_.isString(this.comparator) || this.comparator.length === 1) {
  11408. this.models = this.sortBy(this.comparator, this);
  11409. } else {
  11410. this.models.sort(_.bind(this.comparator, this));
  11411. }
  11412. if (!options || !options.silent) this.trigger('sort', this, options);
  11413. return this;
  11414. },
  11415. // Pluck an attribute from each model in the collection.
  11416. pluck: function(attr) {
  11417. return _.invoke(this.models, 'get', attr);
  11418. },
  11419. // Smartly update a collection with a change set of models, adding,
  11420. // removing, and merging as necessary.
  11421. update: function(models, options) {
  11422. var model, i, l, existing;
  11423. var add = [], remove = [], modelMap = {};
  11424. var idAttr = this.model.prototype.idAttribute;
  11425. options = _.extend({add: true, merge: true, remove: true}, options);
  11426. if (options.parse) models = this.parse(models);
  11427. // Allow a single model (or no argument) to be passed.
  11428. if (!_.isArray(models)) models = models ? [models] : [];
  11429. // Proxy to `add` for this case, no need to iterate...
  11430. if (options.add && !options.remove) return this.add(models, options);
  11431. // Determine which models to add and merge, and which to remove.
  11432. for (i = 0, l = models.length; i < l; i++) {
  11433. model = models[i];
  11434. existing = this.get(model.id || model.cid || model[idAttr]);
  11435. if (options.remove && existing) modelMap[existing.cid] = true;
  11436. if ((options.add && !existing) || (options.merge && existing)) {
  11437. add.push(model);
  11438. }
  11439. }
  11440. if (options.remove) {
  11441. for (i = 0, l = this.models.length; i < l; i++) {
  11442. model = this.models[i];
  11443. if (!modelMap[model.cid]) remove.push(model);
  11444. }
  11445. }
  11446. // Remove models (if applicable) before we add and merge the rest.
  11447. if (remove.length) this.remove(remove, options);
  11448. if (add.length) this.add(add, options);
  11449. return this;
  11450. },
  11451. // When you have more items than you want to add or remove individually,
  11452. // you can reset the entire set with a new list of models, without firing
  11453. // any `add` or `remove` events. Fires `reset` when finished.
  11454. reset: function(models, options) {
  11455. options || (options = {});
  11456. if (options.parse) models = this.parse(models);
  11457. for (var i = 0, l = this.models.length; i < l; i++) {
  11458. this._removeReference(this.models[i]);
  11459. }
  11460. options.previousModels = this.models;
  11461. this._reset();
  11462. if (models) this.add(models, _.extend({silent: true}, options));
  11463. if (!options.silent) this.trigger('reset', this, options);
  11464. return this;
  11465. },
  11466. // Fetch the default set of models for this collection, resetting the
  11467. // collection when they arrive. If `add: true` is passed, appends the
  11468. // models to the collection instead of resetting.
  11469. fetch: function(options) {
  11470. options = options ? _.clone(options) : {};
  11471. if (options.parse === void 0) options.parse = true;
  11472. var collection = this;
  11473. var success = options.success;
  11474. options.success = function(resp, status, xhr) {
  11475. var method = options.update ? 'update' : 'reset';
  11476. collection[method](resp, options);
  11477. if (success) success(collection, resp, options);
  11478. };
  11479. return this.sync('read', this, options);
  11480. },
  11481. // Create a new instance of a model in this collection. Add the model to the
  11482. // collection immediately, unless `wait: true` is passed, in which case we
  11483. // wait for the server to agree.
  11484. create: function(model, options) {
  11485. var collection = this;
  11486. options = options ? _.clone(options) : {};
  11487. model = this._prepareModel(model, options);
  11488. if (!model) return false;
  11489. if (!options.wait) collection.add(model, options);
  11490. var success = options.success;
  11491. options.success = function(model, resp, options) {
  11492. if (options.wait) collection.add(model, options);
  11493. if (success) success(model, resp, options);
  11494. };
  11495. model.save(null, options);
  11496. return model;
  11497. },
  11498. // **parse** converts a response into a list of models to be added to the
  11499. // collection. The default implementation is just to pass it through.
  11500. parse: function(resp) {
  11501. return resp;
  11502. },
  11503. // Create a new collection with an identical list of models as this one.
  11504. clone: function() {
  11505. return new this.constructor(this.models);
  11506. },
  11507. // Proxy to _'s chain. Can't be proxied the same way the rest of the
  11508. // underscore methods are proxied because it relies on the underscore
  11509. // constructor.
  11510. chain: function() {
  11511. return _(this.models).chain();
  11512. },
  11513. // Reset all internal state. Called when the collection is reset.
  11514. _reset: function() {
  11515. this.length = 0;
  11516. this.models = [];
  11517. this._byId = {};
  11518. this._byCid = {};
  11519. },
  11520. // Prepare a model or hash of attributes to be added to this collection.
  11521. _prepareModel: function(attrs, options) {
  11522. if (attrs instanceof Model) {
  11523. if (!attrs.collection) attrs.collection = this;
  11524. return attrs;
  11525. }
  11526. options || (options = {});
  11527. options.collection = this;
  11528. var model = new this.model(attrs, options);
  11529. if (!model._validate(attrs, options)) return false;
  11530. return model;
  11531. },
  11532. // Internal method to remove a model's ties to a collection.
  11533. _removeReference: function(model) {
  11534. if (this === model.collection) delete model.collection;
  11535. model.off('all', this._onModelEvent, this);
  11536. },
  11537. // Internal method called every time a model in the set fires an event.
  11538. // Sets need to update their indexes when models change ids. All other
  11539. // events simply proxy through. "add" and "remove" events that originate
  11540. // in other collections are ignored.
  11541. _onModelEvent: function(event, model, collection, options) {
  11542. if ((event === 'add' || event === 'remove') && collection !== this) return;
  11543. if (event === 'destroy') this.remove(model, options);
  11544. if (model && event === 'change:' + model.idAttribute) {
  11545. delete this._byId[model.previous(model.idAttribute)];
  11546. if (model.id != null) this._byId[model.id] = model;
  11547. }
  11548. this.trigger.apply(this, arguments);
  11549. }
  11550. });
  11551. // Underscore methods that we want to implement on the Collection.
  11552. var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
  11553. 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
  11554. 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
  11555. 'max', 'min', 'sortedIndex', 'toArray', 'size', 'first', 'head', 'take',
  11556. 'initial', 'rest', 'tail', 'last', 'without', 'indexOf', 'shuffle',
  11557. 'lastIndexOf', 'isEmpty'];
  11558. // Mix in each Underscore method as a proxy to `Collection#models`.
  11559. _.each(methods, function(method) {
  11560. Collection.prototype[method] = function() {
  11561. var args = slice.call(arguments);
  11562. args.unshift(this.models);
  11563. return _[method].apply(_, args);
  11564. };
  11565. });
  11566. // Underscore methods that take a property name as an argument.
  11567. var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
  11568. // Use attributes instead of properties.
  11569. _.each(attributeMethods, function(method) {
  11570. Collection.prototype[method] = function(value, context) {
  11571. var iterator = _.isFunction(value) ? value : function(model) {
  11572. return model.get(value);
  11573. };
  11574. return _[method](this.models, iterator, context);
  11575. };
  11576. });
  11577. // Backbone.Router
  11578. // ---------------
  11579. // Routers map faux-URLs to actions, and fire events when routes are
  11580. // matched. Creating a new one sets its `routes` hash, if not set statically.
  11581. var Router = Backbone.Router = function(options) {
  11582. options || (options = {});
  11583. if (options.routes) this.routes = options.routes;
  11584. this._bindRoutes();
  11585. this.initialize.apply(this, arguments);
  11586. };
  11587. // Cached regular expressions for matching named param parts and splatted
  11588. // parts of route strings.
  11589. var optionalParam = /\((.*?)\)/g;
  11590. var namedParam = /:\w+/g;
  11591. var splatParam = /\*\w+/g;
  11592. var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
  11593. // Set up all inheritable **Backbone.Router** properties and methods.
  11594. _.extend(Router.prototype, Events, {
  11595. // Initialize is an empty function by default. Override it with your own
  11596. // initialization logic.
  11597. initialize: function(){},
  11598. // Manually bind a single named route to a callback. For example:
  11599. //
  11600. // this.route('search/:query/p:num', 'search', function(query, num) {
  11601. // ...
  11602. // });
  11603. //
  11604. route: function(route, name, callback) {
  11605. if (!_.isRegExp(route)) route = this._routeToRegExp(route);
  11606. if (!callback) callback = this[name];
  11607. Backbone.history.route(route, _.bind(function(fragment) {
  11608. var args = this._extractParameters(route, fragment);
  11609. callback && callback.apply(this, args);
  11610. this.trigger.apply(this, ['route:' + name].concat(args));
  11611. Backbone.history.trigger('route', this, name, args);
  11612. }, this));
  11613. return this;
  11614. },
  11615. // Simple proxy to `Backbone.history` to save a fragment into the history.
  11616. navigate: function(fragment, options) {
  11617. Backbone.history.navigate(fragment, options);
  11618. return this;
  11619. },
  11620. // Bind all defined routes to `Backbone.history`. We have to reverse the
  11621. // order of the routes here to support behavior where the most general
  11622. // routes can be defined at the bottom of the route map.
  11623. _bindRoutes: function() {
  11624. if (!this.routes) return;
  11625. var route, routes = _.keys(this.routes);
  11626. while ((route = routes.pop()) != null) {
  11627. this.route(route, this.routes[route]);
  11628. }
  11629. },
  11630. // Convert a route string into a regular expression, suitable for matching
  11631. // against the current location hash.
  11632. _routeToRegExp: function(route) {
  11633. route = route.replace(escapeRegExp, '\\$&')
  11634. .replace(optionalParam, '(?:$1)?')
  11635. .replace(namedParam, '([^\/]+)')
  11636. .replace(splatParam, '(.*?)');
  11637. return new RegExp('^' + route + '$');
  11638. },
  11639. // Given a route, and a URL fragment that it matches, return the array of
  11640. // extracted parameters.
  11641. _extractParameters: function(route, fragment) {
  11642. return route.exec(fragment).slice(1);
  11643. }
  11644. });
  11645. // Backbone.History
  11646. // ----------------
  11647. // Handles cross-browser history management, based on URL fragments. If the
  11648. // browser does not support `onhashchange`, falls back to polling.
  11649. var History = Backbone.History = function() {
  11650. this.handlers = [];
  11651. _.bindAll(this, 'checkUrl');
  11652. // Ensure that `History` can be used outside of the browser.
  11653. if (typeof window !== 'undefined') {
  11654. this.location = window.location;
  11655. this.history = window.history;
  11656. }
  11657. };
  11658. // Cached regex for stripping a leading hash/slash and trailing space.
  11659. var routeStripper = /^[#\/]|\s+$/g;
  11660. // Cached regex for stripping leading and trailing slashes.
  11661. var rootStripper = /^\/+|\/+$/g;
  11662. // Cached regex for detecting MSIE.
  11663. var isExplorer = /msie [\w.]+/;
  11664. // Cached regex for removing a trailing slash.
  11665. var trailingSlash = /\/$/;
  11666. // Has the history handling already been started?
  11667. History.started = false;
  11668. // Set up all inheritable **Backbone.History** properties and methods.
  11669. _.extend(History.prototype, Events, {
  11670. // The default interval to poll for hash changes, if necessary, is
  11671. // twenty times a second.
  11672. interval: 50,
  11673. // Gets the true hash value. Cannot use location.hash directly due to bug
  11674. // in Firefox where location.hash will always be decoded.
  11675. getHash: function(window) {
  11676. var match = (window || this).location.href.match(/#(.*)$/);
  11677. return match ? match[1] : '';
  11678. },
  11679. // Get the cross-browser normalized URL fragment, either from the URL,
  11680. // the hash, or the override.
  11681. getFragment: function(fragment, forcePushState) {
  11682. if (fragment == null) {
  11683. if (this._hasPushState || !this._wantsHashChange || forcePushState) {
  11684. fragment = this.location.pathname;
  11685. var root = this.root.replace(trailingSlash, '');
  11686. if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
  11687. } else {
  11688. fragment = this.getHash();
  11689. }
  11690. }
  11691. return fragment.replace(routeStripper, '');
  11692. },
  11693. // Start the hash change handling, returning `true` if the current URL matches
  11694. // an existing route, and `false` otherwise.
  11695. start: function(options) {
  11696. if (History.started) throw new Error("Backbone.history has already been started");
  11697. History.started = true;
  11698. // Figure out the initial configuration. Do we need an iframe?
  11699. // Is pushState desired ... is it available?
  11700. this.options = _.extend({}, {root: '/'}, this.options, options);
  11701. this.root = this.options.root;
  11702. this._wantsHashChange = this.options.hashChange !== false;
  11703. this._wantsPushState = !!this.options.pushState;
  11704. this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
  11705. var fragment = this.getFragment();
  11706. var docMode = document.documentMode;
  11707. var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
  11708. // Normalize root to always include a leading and trailing slash.
  11709. this.root = ('/' + this.root + '/').replace(rootStripper, '/');
  11710. if (oldIE && this._wantsHashChange) {
  11711. this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
  11712. this.navigate(fragment);
  11713. }
  11714. // Depending on whether we're using pushState or hashes, and whether
  11715. // 'onhashchange' is supported, determine how we check the URL state.
  11716. if (this._hasPushState) {
  11717. Backbone.$(window).bind('popstate', this.checkUrl);
  11718. } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
  11719. Backbone.$(window).bind('hashchange', this.checkUrl);
  11720. } else if (this._wantsHashChange) {
  11721. this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
  11722. }
  11723. // Determine if we need to change the base url, for a pushState link
  11724. // opened by a non-pushState browser.
  11725. this.fragment = fragment;
  11726. var loc = this.location;
  11727. var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
  11728. // If we've started off with a route from a `pushState`-enabled browser,
  11729. // but we're currently in a browser that doesn't support it...
  11730. if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
  11731. this.fragment = this.getFragment(null, true);
  11732. this.location.replace(this.root + this.location.search + '#' + this.fragment);
  11733. // Return immediately as browser will do redirect to new url
  11734. return true;
  11735. // Or if we've started out with a hash-based route, but we're currently
  11736. // in a browser where it could be `pushState`-based instead...
  11737. } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
  11738. this.fragment = this.getHash().replace(routeStripper, '');
  11739. this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
  11740. }
  11741. if (!this.options.silent) return this.loadUrl();
  11742. },
  11743. // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
  11744. // but possibly useful for unit testing Routers.
  11745. stop: function() {
  11746. Backbone.$(window).unbind('popstate', this.checkUrl).unbind('hashchange', this.checkUrl);
  11747. clearInterval(this._checkUrlInterval);
  11748. History.started = false;
  11749. },
  11750. // Add a route to be tested when the fragment changes. Routes added later
  11751. // may override previous routes.
  11752. route: function(route, callback) {
  11753. this.handlers.unshift({route: route, callback: callback});
  11754. },
  11755. // Checks the current URL to see if it has changed, and if it has,
  11756. // calls `loadUrl`, normalizing across the hidden iframe.
  11757. checkUrl: function(e) {
  11758. var current = this.getFragment();
  11759. if (current === this.fragment && this.iframe) {
  11760. current = this.getFragment(this.getHash(this.iframe));
  11761. }
  11762. if (current === this.fragment) return false;
  11763. if (this.iframe) this.navigate(current);
  11764. this.loadUrl() || this.loadUrl(this.getHash());
  11765. },
  11766. // Attempt to load the current URL fragment. If a route succeeds with a
  11767. // match, returns `true`. If no defined routes matches the fragment,
  11768. // returns `false`.
  11769. loadUrl: function(fragmentOverride) {
  11770. var fragment = this.fragment = this.getFragment(fragmentOverride);
  11771. var matched = _.any(this.handlers, function(handler) {
  11772. if (handler.route.test(fragment)) {
  11773. handler.callback(fragment);
  11774. return true;
  11775. }
  11776. });
  11777. return matched;
  11778. },
  11779. // Save a fragment into the hash history, or replace the URL state if the
  11780. // 'replace' option is passed. You are responsible for properly URL-encoding
  11781. // the fragment in advance.
  11782. //
  11783. // The options object can contain `trigger: true` if you wish to have the
  11784. // route callback be fired (not usually desirable), or `replace: true`, if
  11785. // you wish to modify the current URL without adding an entry to the history.
  11786. navigate: function(fragment, options) {
  11787. if (!History.started) return false;
  11788. if (!options || options === true) options = {trigger: options};
  11789. fragment = this.getFragment(fragment || '');
  11790. if (this.fragment === fragment) return;
  11791. this.fragment = fragment;
  11792. var url = this.root + fragment;
  11793. // If pushState is available, we use it to set the fragment as a real URL.
  11794. if (this._hasPushState) {
  11795. this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
  11796. // If hash changes haven't been explicitly disabled, update the hash
  11797. // fragment to store history.
  11798. } else if (this._wantsHashChange) {
  11799. this._updateHash(this.location, fragment, options.replace);
  11800. if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
  11801. // Opening and closing the iframe tricks IE7 and earlier to push a
  11802. // history entry on hash-tag change. When replace is true, we don't
  11803. // want this.
  11804. if(!options.replace) this.iframe.document.open().close();
  11805. this._updateHash(this.iframe.location, fragment, options.replace);
  11806. }
  11807. // If you've told us that you explicitly don't want fallback hashchange-
  11808. // based history, then `navigate` becomes a page refresh.
  11809. } else {
  11810. return this.location.assign(url);
  11811. }
  11812. if (options.trigger) this.loadUrl(fragment);
  11813. },
  11814. // Update the hash location, either replacing the current entry, or adding
  11815. // a new one to the browser history.
  11816. _updateHash: function(location, fragment, replace) {
  11817. if (replace) {
  11818. var href = location.href.replace(/(javascript:|#).*$/, '');
  11819. location.replace(href + '#' + fragment);
  11820. } else {
  11821. // Some browsers require that `hash` contains a leading #.
  11822. location.hash = '#' + fragment;
  11823. }
  11824. }
  11825. });
  11826. // Create the default Backbone.history.
  11827. Backbone.history = new History;
  11828. // Backbone.View
  11829. // -------------
  11830. // Creating a Backbone.View creates its initial element outside of the DOM,
  11831. // if an existing element is not provided...
  11832. var View = Backbone.View = function(options) {
  11833. this.cid = _.uniqueId('view');
  11834. this._configure(options || {});
  11835. this._ensureElement();
  11836. this.initialize.apply(this, arguments);
  11837. this.delegateEvents();
  11838. };
  11839. // Cached regex to split keys for `delegate`.
  11840. var delegateEventSplitter = /^(\S+)\s*(.*)$/;
  11841. // List of view options to be merged as properties.
  11842. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
  11843. // Set up all inheritable **Backbone.View** properties and methods.
  11844. _.extend(View.prototype, Events, {
  11845. // The default `tagName` of a View's element is `"div"`.
  11846. tagName: 'div',
  11847. // jQuery delegate for element lookup, scoped to DOM elements within the
  11848. // current view. This should be prefered to global lookups where possible.
  11849. $: function(selector) {
  11850. return this.$el.find(selector);
  11851. },
  11852. // Initialize is an empty function by default. Override it with your own
  11853. // initialization logic.
  11854. initialize: function(){},
  11855. // **render** is the core function that your view should override, in order
  11856. // to populate its element (`this.el`), with the appropriate HTML. The
  11857. // convention is for **render** to always return `this`.
  11858. render: function() {
  11859. return this;
  11860. },
  11861. // Remove this view by taking the element out of the DOM, and removing any
  11862. // applicable Backbone.Events listeners.
  11863. remove: function() {
  11864. this.$el.remove();
  11865. this.stopListening();
  11866. return this;
  11867. },
  11868. // For small amounts of DOM Elements, where a full-blown template isn't
  11869. // needed, use **make** to manufacture elements, one at a time.
  11870. //
  11871. // var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
  11872. //
  11873. make: function(tagName, attributes, content) {
  11874. var el = document.createElement(tagName);
  11875. if (attributes) Backbone.$(el).attr(attributes);
  11876. if (content != null) Backbone.$(el).html(content);
  11877. return el;
  11878. },
  11879. // Change the view's element (`this.el` property), including event
  11880. // re-delegation.
  11881. setElement: function(element, delegate) {
  11882. if (this.$el) this.undelegateEvents();
  11883. this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
  11884. this.el = this.$el[0];
  11885. if (delegate !== false) this.delegateEvents();
  11886. return this;
  11887. },
  11888. // Set callbacks, where `this.events` is a hash of
  11889. //
  11890. // *{"event selector": "callback"}*
  11891. //
  11892. // {
  11893. // 'mousedown .title': 'edit',
  11894. // 'click .button': 'save'
  11895. // 'click .open': function(e) { ... }
  11896. // }
  11897. //
  11898. // pairs. Callbacks will be bound to the view, with `this` set properly.
  11899. // Uses event delegation for efficiency.
  11900. // Omitting the selector binds the event to `this.el`.
  11901. // This only works for delegate-able events: not `focus`, `blur`, and
  11902. // not `change`, `submit`, and `reset` in Internet Explorer.
  11903. delegateEvents: function(events) {
  11904. if (!(events || (events = _.result(this, 'events')))) return;
  11905. this.undelegateEvents();
  11906. for (var key in events) {
  11907. var method = events[key];
  11908. if (!_.isFunction(method)) method = this[events[key]];
  11909. if (!method) throw new Error('Method "' + events[key] + '" does not exist');
  11910. var match = key.match(delegateEventSplitter);
  11911. var eventName = match[1], selector = match[2];
  11912. method = _.bind(method, this);
  11913. eventName += '.delegateEvents' + this.cid;
  11914. if (selector === '') {
  11915. this.$el.bind(eventName, method);
  11916. } else {
  11917. this.$el.delegate(selector, eventName, method);
  11918. }
  11919. }
  11920. },
  11921. // Clears all callbacks previously bound to the view with `delegateEvents`.
  11922. // You usually don't need to use this, but may wish to if you have multiple
  11923. // Backbone views attached to the same DOM element.
  11924. undelegateEvents: function() {
  11925. this.$el.unbind('.delegateEvents' + this.cid);
  11926. },
  11927. // Performs the initial configuration of a View with a set of options.
  11928. // Keys with special meaning *(model, collection, id, className)*, are
  11929. // attached directly to the view.
  11930. _configure: function(options) {
  11931. if (this.options) options = _.extend({}, _.result(this, 'options'), options);
  11932. _.extend(this, _.pick(options, viewOptions));
  11933. this.options = options;
  11934. },
  11935. // Ensure that the View has a DOM element to render into.
  11936. // If `this.el` is a string, pass it through `$()`, take the first
  11937. // matching element, and re-assign it to `el`. Otherwise, create
  11938. // an element from the `id`, `className` and `tagName` properties.
  11939. _ensureElement: function() {
  11940. if (!this.el) {
  11941. var attrs = _.extend({}, _.result(this, 'attributes'));
  11942. if (this.id) attrs.id = _.result(this, 'id');
  11943. if (this.className) attrs['class'] = _.result(this, 'className');
  11944. this.setElement(this.make(_.result(this, 'tagName'), attrs), false);
  11945. } else {
  11946. this.setElement(_.result(this, 'el'), false);
  11947. }
  11948. }
  11949. });
  11950. // Backbone.sync
  11951. // -------------
  11952. // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  11953. var methodMap = {
  11954. 'create': 'POST',
  11955. 'update': 'PUT',
  11956. 'patch': 'PATCH',
  11957. 'delete': 'DELETE',
  11958. 'read': 'GET'
  11959. };
  11960. // Override this function to change the manner in which Backbone persists
  11961. // models to the server. You will be passed the type of request, and the
  11962. // model in question. By default, makes a RESTful Ajax request
  11963. // to the model's `url()`. Some possible customizations could be:
  11964. //
  11965. // * Use `setTimeout` to batch rapid-fire updates into a single request.
  11966. // * Send up the models as XML instead of JSON.
  11967. // * Persist models via WebSockets instead of Ajax.
  11968. //
  11969. // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  11970. // as `POST`, with a `_method` parameter containing the true HTTP method,
  11971. // as well as all requests with the body as `application/x-www-form-urlencoded`
  11972. // instead of `application/json` with the model in a param named `model`.
  11973. // Useful when interfacing with server-side languages like **PHP** that make
  11974. // it difficult to read the body of `PUT` requests.
  11975. Backbone.sync = function(method, model, options) {
  11976. var type = methodMap[method];
  11977. // Default options, unless specified.
  11978. _.defaults(options || (options = {}), {
  11979. emulateHTTP: Backbone.emulateHTTP,
  11980. emulateJSON: Backbone.emulateJSON
  11981. });
  11982. // Default JSON-request options.
  11983. var params = {type: type, dataType: 'json'};
  11984. // Ensure that we have a URL.
  11985. if (!options.url) {
  11986. params.url = _.result(model, 'url') || urlError();
  11987. }
  11988. // Ensure that we have the appropriate request data.
  11989. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
  11990. params.contentType = 'application/json';
  11991. params.data = JSON.stringify(options.attrs || model.toJSON(options));
  11992. }
  11993. // For older servers, emulate JSON by encoding the request into an HTML-form.
  11994. if (options.emulateJSON) {
  11995. params.contentType = 'application/x-www-form-urlencoded';
  11996. params.data = params.data ? {model: params.data} : {};
  11997. }
  11998. // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
  11999. // And an `X-HTTP-Method-Override` header.
  12000. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
  12001. params.type = 'POST';
  12002. if (options.emulateJSON) params.data._method = type;
  12003. var beforeSend = options.beforeSend;
  12004. options.beforeSend = function(xhr) {
  12005. xhr.setRequestHeader('X-HTTP-Method-Override', type);
  12006. if (beforeSend) return beforeSend.apply(this, arguments);
  12007. };
  12008. }
  12009. // Don't process data on a non-GET request.
  12010. if (params.type !== 'GET' && !options.emulateJSON) {
  12011. params.processData = false;
  12012. }
  12013. var success = options.success;
  12014. options.success = function(resp, status, xhr) {
  12015. if (success) success(resp, status, xhr);
  12016. model.trigger('sync', model, resp, options);
  12017. };
  12018. var error = options.error;
  12019. options.error = function(xhr, status, thrown) {
  12020. if (error) error(model, xhr, options);
  12021. model.trigger('error', model, xhr, options);
  12022. };
  12023. // Make the request, allowing the user to override any Ajax options.
  12024. var xhr = Backbone.ajax(_.extend(params, options));
  12025. model.trigger('request', model, xhr, options);
  12026. return xhr;
  12027. };
  12028. // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
  12029. Backbone.ajax = function() {
  12030. return Backbone.$.ajax.apply(Backbone.$, arguments);
  12031. };
  12032. // Helpers
  12033. // -------
  12034. // Helper function to correctly set up the prototype chain, for subclasses.
  12035. // Similar to `goog.inherits`, but uses a hash of prototype properties and
  12036. // class properties to be extended.
  12037. var extend = function(protoProps, staticProps) {
  12038. var parent = this;
  12039. var child;
  12040. // The constructor function for the new subclass is either defined by you
  12041. // (the "constructor" property in your `extend` definition), or defaulted
  12042. // by us to simply call the parent's constructor.
  12043. if (protoProps && _.has(protoProps, 'constructor')) {
  12044. child = protoProps.constructor;
  12045. } else {
  12046. child = function(){ parent.apply(this, arguments); };
  12047. }
  12048. // Add static properties to the constructor function, if supplied.
  12049. _.extend(child, parent, staticProps);
  12050. // Set the prototype chain to inherit from `parent`, without calling
  12051. // `parent`'s constructor function.
  12052. var Surrogate = function(){ this.constructor = child; };
  12053. Surrogate.prototype = parent.prototype;
  12054. child.prototype = new Surrogate;
  12055. // Add prototype properties (instance properties) to the subclass,
  12056. // if supplied.
  12057. if (protoProps) _.extend(child.prototype, protoProps);
  12058. // Set a convenience property in case the parent's prototype is needed
  12059. // later.
  12060. child.__super__ = parent.prototype;
  12061. return child;
  12062. };
  12063. // Set up inheritance for the model, collection, router, view and history.
  12064. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
  12065. // Throw an error when a URL is needed, and none is supplied.
  12066. var urlError = function() {
  12067. throw new Error('A "url" property or function must be specified');
  12068. };
  12069. }).call(this);
  12070. /*
  12071. Copyright (c) 2011-2013 @WalmartLabs
  12072. Permission is hereby granted, free of charge, to any person obtaining a copy
  12073. of this software and associated documentation files (the "Software"), to
  12074. deal in the Software without restriction, including without limitation the
  12075. rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  12076. sell copies of the Software, and to permit persons to whom the Software is
  12077. furnished to do so, subject to the following conditions:
  12078. The above copyright notice and this permission notice shall be included in
  12079. all copies or substantial portions of the Software.
  12080. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12081. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12082. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  12083. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  12084. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  12085. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  12086. DEALINGS IN THE SOFTWARE.
  12087. */
  12088. ;;
  12089. (function() {
  12090. /*global cloneInheritVars, createInheritVars, createRegistryWrapper, getValue, inheritVars */
  12091. //support zepto.forEach on jQuery
  12092. if (!$.fn.forEach) {
  12093. $.fn.forEach = function(iterator, context) {
  12094. $.fn.each.call(this, function(index) {
  12095. iterator.call(context || this, this, index);
  12096. });
  12097. };
  12098. }
  12099. var viewNameAttributeName = 'data-view-name',
  12100. viewCidAttributeName = 'data-view-cid',
  12101. viewHelperAttributeName = 'data-view-helper';
  12102. //view instances
  12103. var viewsIndexedByCid = {};
  12104. var Thorax = this.Thorax = {
  12105. VERSION: '2.0.0rc1',
  12106. templatePathPrefix: '',
  12107. templates: {},
  12108. //view classes
  12109. Views: {},
  12110. //certain error prone pieces of code (on Android only it seems)
  12111. //are wrapped in a try catch block, then trigger this handler in
  12112. //the catch, with the name of the function or event that was
  12113. //trying to be executed. Override this with a custom handler
  12114. //to debug / log / etc
  12115. onException: function(name, err) {
  12116. throw err;
  12117. }
  12118. };
  12119. Thorax.View = Backbone.View.extend({
  12120. constructor: function() {
  12121. var response = Backbone.View.apply(this, arguments);
  12122. _.each(inheritVars, function(obj) {
  12123. if (obj.ctor) {
  12124. obj.ctor.call(this, response);
  12125. }
  12126. }, this);
  12127. return response;
  12128. },
  12129. _configure: function(options) {
  12130. var self = this;
  12131. this._objectOptionsByCid = {};
  12132. this._boundDataObjectsByCid = {};
  12133. // Setup object event tracking
  12134. _.each(inheritVars, function(obj) {
  12135. self[obj.name] = [];
  12136. });
  12137. viewsIndexedByCid[this.cid] = this;
  12138. this.children = {};
  12139. this._renderCount = 0;
  12140. //this.options is removed in Thorax.View, we merge passed
  12141. //properties directly with the view and template context
  12142. _.extend(this, options || {});
  12143. // Setup helpers
  12144. bindHelpers.call(this);
  12145. _.each(inheritVars, function(obj) {
  12146. if (obj.configure) {
  12147. obj.configure.call(this);
  12148. }
  12149. }, this);
  12150. },
  12151. setElement : function() {
  12152. var response = Backbone.View.prototype.setElement.apply(this, arguments);
  12153. this.name && this.$el.attr(viewNameAttributeName, this.name);
  12154. this.$el.attr(viewCidAttributeName, this.cid);
  12155. return response;
  12156. },
  12157. _addChild: function(view) {
  12158. this.children[view.cid] = view;
  12159. if (!view.parent) {
  12160. view.parent = this;
  12161. }
  12162. this.trigger('child', view);
  12163. return view;
  12164. },
  12165. _removeChild: function(view) {
  12166. delete this.children[view.cid];
  12167. view.parent = null;
  12168. return view;
  12169. },
  12170. destroy: function(options) {
  12171. options = _.defaults(options || {}, {
  12172. children: true
  12173. });
  12174. _.each(this._boundDataObjectsByCid, this.unbindDataObject, this);
  12175. this.trigger('destroyed');
  12176. delete viewsIndexedByCid[this.cid];
  12177. _.each(this.children, function(child) {
  12178. this._removeChild(child);
  12179. if (options.children) {
  12180. child.destroy();
  12181. }
  12182. }, this);
  12183. if (this.parent) {
  12184. this.parent._removeChild(this);
  12185. }
  12186. this.remove(); // Will call stopListening()
  12187. },
  12188. render: function(output) {
  12189. this._previousHelpers = _.filter(this.children, function(child) { return child._helperOptions; });
  12190. var children = {};
  12191. _.each(this.children, function(child, key) {
  12192. if (!child._helperOptions) {
  12193. children[key] = child;
  12194. }
  12195. });
  12196. this.children = children;
  12197. if (_.isUndefined(output) || (!_.isElement(output) && !Thorax.Util.is$(output) && !(output && output.el) && !_.isString(output) && !_.isFunction(output))) {
  12198. // try one more time to assign the template, if we don't
  12199. // yet have one we must raise
  12200. assignTemplate.call(this, 'template', {
  12201. required: true
  12202. });
  12203. output = this.renderTemplate(this.template);
  12204. } else if (_.isFunction(output)) {
  12205. output = this.renderTemplate(output);
  12206. }
  12207. // Destroy any helpers that may be lingering
  12208. _.each(this._previousHelpers, function(child) {
  12209. child.destroy();
  12210. child.parent = undefined;
  12211. });
  12212. this._previousHelpers = undefined;
  12213. //accept a view, string, Handlebars.SafeString or DOM element
  12214. this.html((output && output.el) || (output && output.string) || output);
  12215. ++this._renderCount;
  12216. this.trigger('rendered');
  12217. return output;
  12218. },
  12219. context: function() {
  12220. return _.extend({}, (this.model && this.model.attributes) || {});
  12221. },
  12222. _getContext: function() {
  12223. return _.extend({}, this, getValue(this, 'context') || {});
  12224. },
  12225. // Private variables in handlebars / options.data in template helpers
  12226. _getData: function(data) {
  12227. return {
  12228. view: this,
  12229. cid: _.uniqueId('t'),
  12230. yield: function() {
  12231. // fn is seeded by template helper passing context to data
  12232. return data.fn && data.fn(data);
  12233. }
  12234. };
  12235. },
  12236. _getHelpers: function() {
  12237. if (this.helpers) {
  12238. return _.extend({}, Handlebars.helpers, this.helpers);
  12239. } else {
  12240. return Handlebars.helpers;
  12241. }
  12242. },
  12243. renderTemplate: function(file, context, ignoreErrors) {
  12244. var template;
  12245. context = context || this._getContext();
  12246. if (_.isFunction(file)) {
  12247. template = file;
  12248. } else {
  12249. template = Thorax.Util.getTemplate(file, ignoreErrors);
  12250. }
  12251. if (!template) {
  12252. return '';
  12253. } else {
  12254. return template(context, {
  12255. helpers: this._getHelpers(),
  12256. data: this._getData(context)
  12257. });
  12258. }
  12259. },
  12260. ensureRendered: function() {
  12261. !this._renderCount && this.render();
  12262. },
  12263. appendTo: function(el) {
  12264. this.ensureRendered();
  12265. $(el).append(this.el);
  12266. this.trigger('ready', {target: this});
  12267. },
  12268. html: function(html) {
  12269. if (_.isUndefined(html)) {
  12270. return this.el.innerHTML;
  12271. } else {
  12272. // Event for IE element fixes
  12273. this.trigger('before:append');
  12274. var element = this._replaceHTML(html);
  12275. this.trigger('append');
  12276. return element;
  12277. }
  12278. },
  12279. _replaceHTML: function(html) {
  12280. this.el.innerHTML = "";
  12281. return this.$el.append(html);
  12282. },
  12283. _anchorClick: function(event) {
  12284. var target = $(event.currentTarget),
  12285. href = target.attr('href');
  12286. // Route anything that starts with # or / (excluding //domain urls)
  12287. if (href && (href[0] === '#' || (href[0] === '/' && href[1] !== '/'))) {
  12288. Backbone.history.navigate(href, {
  12289. trigger: true
  12290. });
  12291. return false;
  12292. }
  12293. return true;
  12294. }
  12295. });
  12296. Thorax.View.extend = function() {
  12297. createInheritVars(this);
  12298. var child = Backbone.View.extend.apply(this, arguments);
  12299. child.__parent__ = this;
  12300. resetInheritVars(child);
  12301. return child;
  12302. };
  12303. createRegistryWrapper(Thorax.View, Thorax.Views);
  12304. function bindHelpers() {
  12305. if (this.helpers) {
  12306. _.each(this.helpers, function(helper, name) {
  12307. var view = this;
  12308. this.helpers[name] = function() {
  12309. var args = _.toArray(arguments),
  12310. options = _.last(args);
  12311. options.context = this;
  12312. return helper.apply(view, args);
  12313. };
  12314. }, this);
  12315. }
  12316. }
  12317. //$(selector).view() helper
  12318. $.fn.view = function(options) {
  12319. options = _.defaults(options || {}, {
  12320. helper: true
  12321. });
  12322. var selector = '[' + viewCidAttributeName + ']';
  12323. if (!options.helper) {
  12324. selector += ':not([' + viewHelperAttributeName + '])';
  12325. }
  12326. var el = $(this).closest(selector);
  12327. return (el && viewsIndexedByCid[el.attr(viewCidAttributeName)]) || false;
  12328. };
  12329. ;;
  12330. /*global createRegistryWrapper:true, cloneEvents: true */
  12331. function createRegistryWrapper(klass, hash) {
  12332. var $super = klass.extend;
  12333. klass.extend = function() {
  12334. var child = $super.apply(this, arguments);
  12335. if (child.prototype.name) {
  12336. hash[child.prototype.name] = child;
  12337. }
  12338. return child;
  12339. };
  12340. }
  12341. function registryGet(object, type, name, ignoreErrors) {
  12342. var target = object[type],
  12343. value;
  12344. if (name.indexOf('.') >= 0) {
  12345. var bits = name.split(/\./);
  12346. name = bits.pop();
  12347. _.each(bits, function(key) {
  12348. target = target[key];
  12349. });
  12350. }
  12351. target && (value = target[name]);
  12352. if (!value && !ignoreErrors) {
  12353. throw new Error(type + ': ' + name + ' does not exist.');
  12354. } else {
  12355. return value;
  12356. }
  12357. }
  12358. function assignTemplate(attributeName, options) {
  12359. var template;
  12360. // if attribute is the name of template to fetch
  12361. if (_.isString(this[attributeName])) {
  12362. template = Thorax.Util.getTemplate(this[attributeName], true);
  12363. // else try and fetch the template based on the name
  12364. } else if (this.name && !_.isFunction(this[attributeName])) {
  12365. template = Thorax.Util.getTemplate(this.name + (options.extension || ''), true);
  12366. }
  12367. // CollectionView and LayoutView have a defaultTemplate that may be used if none
  12368. // was found, regular views must have a template if render() is called
  12369. if (!template && attributeName === 'template' && this._defaultTemplate) {
  12370. template = this._defaultTemplate;
  12371. }
  12372. // if we found something, assign it
  12373. if (template && !_.isFunction(this[attributeName])) {
  12374. this[attributeName] = template;
  12375. }
  12376. // if nothing was found and it's required, throw
  12377. if (options.required && !_.isFunction(this[attributeName])) {
  12378. throw new Error('View ' + (this.name || this.cid) + ' requires: ' + attributeName);
  12379. }
  12380. }
  12381. // getValue is used instead of _.result because we
  12382. // need an extra scope parameter, and will minify
  12383. // better than _.result
  12384. function getValue(object, prop, scope) {
  12385. if (!(object && object[prop])) {
  12386. return null;
  12387. }
  12388. return _.isFunction(object[prop])
  12389. ? object[prop].call(scope || object)
  12390. : object[prop];
  12391. }
  12392. var inheritVars = {};
  12393. function createInheritVars(self) {
  12394. // Ensure that we have our static event objects
  12395. _.each(inheritVars, function(obj) {
  12396. if (!self[obj.name]) {
  12397. self[obj.name] = [];
  12398. }
  12399. });
  12400. }
  12401. function resetInheritVars(self) {
  12402. // Ensure that we have our static event objects
  12403. _.each(inheritVars, function(obj) {
  12404. self[obj.name] = [];
  12405. });
  12406. }
  12407. function walkInheritTree(source, fieldName, isStatic, callback) {
  12408. var tree = [];
  12409. if (_.has(source, fieldName)) {
  12410. tree.push(source);
  12411. }
  12412. var iterate = source;
  12413. if (isStatic) {
  12414. while (iterate = iterate.__parent__) {
  12415. if (_.has(iterate, fieldName)) {
  12416. tree.push(iterate);
  12417. }
  12418. }
  12419. } else {
  12420. iterate = iterate.constructor;
  12421. while (iterate) {
  12422. if (iterate.prototype && _.has(iterate.prototype, fieldName)) {
  12423. tree.push(iterate.prototype);
  12424. }
  12425. iterate = iterate.__super__ && iterate.__super__.constructor;
  12426. }
  12427. }
  12428. var i = tree.length;
  12429. while (i--) {
  12430. _.each(getValue(tree[i], fieldName, source), callback);
  12431. }
  12432. }
  12433. function objectEvents(target, eventName, callback, context) {
  12434. if (_.isObject(callback)) {
  12435. var spec = inheritVars[eventName];
  12436. if (spec && spec.event) {
  12437. addEvents(target['_' + eventName + 'Events'], callback, context);
  12438. return true;
  12439. }
  12440. }
  12441. }
  12442. function addEvents(target, source, context) {
  12443. _.each(source, function(callback, eventName) {
  12444. if (_.isArray(callback)) {
  12445. _.each(callback, function(cb) {
  12446. target.push([eventName, cb, context]);
  12447. });
  12448. } else {
  12449. target.push([eventName, callback, context]);
  12450. }
  12451. });
  12452. }
  12453. function getOptionsData(options) {
  12454. if (!options || !options.data) {
  12455. throw new Error('Handlebars template compiled without data, use: Handlebars.compile(template, {data: true})');
  12456. }
  12457. return options.data;
  12458. }
  12459. // These whitelisted attributes will be the only ones passed
  12460. // from the options hash to Thorax.Util.tag
  12461. var htmlAttributesToCopy = ['id', 'className', 'tagName'];
  12462. // In helpers "tagName" or "tag" may be specified, as well
  12463. // as "class" or "className". Normalize to "tagName" and
  12464. // "className" to match the property names used by Backbone
  12465. // jQuery, etc. Special case for "className" in
  12466. // Thorax.Util.tag: will be rewritten as "class" in
  12467. // generated HTML.
  12468. function normalizeHTMLAttributeOptions(options) {
  12469. if (options.tag) {
  12470. options.tagName = options.tag;
  12471. delete options.tag;
  12472. }
  12473. if (options['class']) {
  12474. options.className = options['class'];
  12475. delete options['class'];
  12476. }
  12477. }
  12478. Thorax.Util = {
  12479. getViewInstance: function(name, attributes) {
  12480. attributes = attributes || {};
  12481. if (_.isString(name)) {
  12482. var Klass = registryGet(Thorax, 'Views', name, false);
  12483. return Klass.cid ? _.extend(Klass, attributes || {}) : new Klass(attributes);
  12484. } else if (_.isFunction(name)) {
  12485. return new name(attributes);
  12486. } else {
  12487. return name;
  12488. }
  12489. },
  12490. getTemplate: function(file, ignoreErrors) {
  12491. //append the template path prefix if it is missing
  12492. var pathPrefix = Thorax.templatePathPrefix,
  12493. template;
  12494. if (pathPrefix && file.substr(0, pathPrefix.length) !== pathPrefix) {
  12495. file = pathPrefix + file;
  12496. }
  12497. // Without extension
  12498. file = file.replace(/\.handlebars$/, '');
  12499. template = Thorax.templates[file];
  12500. if (!template) {
  12501. // With extension
  12502. file = file + '.handlebars';
  12503. template = Thorax.templates[file];
  12504. }
  12505. if (!template && !ignoreErrors) {
  12506. throw new Error('templates: ' + file + ' does not exist.');
  12507. }
  12508. return template;
  12509. },
  12510. //'selector' is not present in $('<p></p>')
  12511. //TODO: investigage a better detection method
  12512. is$: function(obj) {
  12513. return _.isObject(obj) && ('length' in obj);
  12514. },
  12515. expandToken: function(input, scope) {
  12516. if (input && input.indexOf && input.indexOf('{{') >= 0) {
  12517. var re = /(?:\{?[^{]+)|(?:\{\{([^}]+)\}\})/g,
  12518. match,
  12519. ret = [];
  12520. function deref(token, scope) {
  12521. if (token.match(/^("|')/) && token.match(/("|')$/)) {
  12522. return token.replace(/(^("|')|('|")$)/g, '');
  12523. }
  12524. var segments = token.split('.'),
  12525. len = segments.length;
  12526. for (var i = 0; scope && i < len; i++) {
  12527. if (segments[i] !== 'this') {
  12528. scope = scope[segments[i]];
  12529. }
  12530. }
  12531. return scope;
  12532. }
  12533. while (match = re.exec(input)) {
  12534. if (match[1]) {
  12535. var params = match[1].split(/\s+/);
  12536. if (params.length > 1) {
  12537. var helper = params.shift();
  12538. params = _.map(params, function(param) { return deref(param, scope); });
  12539. if (Handlebars.helpers[helper]) {
  12540. ret.push(Handlebars.helpers[helper].apply(scope, params));
  12541. } else {
  12542. // If the helper is not defined do nothing
  12543. ret.push(match[0]);
  12544. }
  12545. } else {
  12546. ret.push(deref(params[0], scope));
  12547. }
  12548. } else {
  12549. ret.push(match[0]);
  12550. }
  12551. }
  12552. input = ret.join('');
  12553. }
  12554. return input;
  12555. },
  12556. tag: function(attributes, content, scope) {
  12557. var htmlAttributes = _.omit(attributes, 'tagName'),
  12558. tag = attributes.tagName || 'div';
  12559. return '<' + tag + ' ' + _.map(htmlAttributes, function(value, key) {
  12560. if (_.isUndefined(value) || key === 'expand-tokens') {
  12561. return '';
  12562. }
  12563. var formattedValue = value;
  12564. if (scope) {
  12565. formattedValue = Thorax.Util.expandToken(value, scope);
  12566. }
  12567. return (key === 'className' ? 'class' : key) + '="' + Handlebars.Utils.escapeExpression(formattedValue) + '"';
  12568. }).join(' ') + '>' + (_.isUndefined(content) ? '' : content) + '</' + tag + '>';
  12569. }
  12570. };
  12571. ;;
  12572. /*global createInheritVars, inheritVars */
  12573. Thorax.Mixins = {};
  12574. inheritVars.mixins = {
  12575. name: 'mixins',
  12576. configure: function() {
  12577. _.each(this.constructor.mixins, this.mixin, this);
  12578. _.each(this.mixins, this.mixin, this);
  12579. }
  12580. };
  12581. _.extend(Thorax.View, {
  12582. mixin: function(mixin) {
  12583. createInheritVars(this);
  12584. this.mixins.push(mixin);
  12585. },
  12586. registerMixin: function(name, callback, methods) {
  12587. Thorax.Mixins[name] = [callback, methods];
  12588. }
  12589. });
  12590. Thorax.View.prototype.mixin = function(name) {
  12591. if (!this._appliedMixins) {
  12592. this._appliedMixins = [];
  12593. }
  12594. if (this._appliedMixins.indexOf(name) === -1) {
  12595. this._appliedMixins.push(name);
  12596. if (_.isFunction(name)) {
  12597. name.call(this);
  12598. } else {
  12599. var mixin = Thorax.Mixins[name];
  12600. _.extend(this, mixin[1]);
  12601. //mixin callback may be an array of [callback, arguments]
  12602. if (_.isArray(mixin[0])) {
  12603. mixin[0][0].apply(this, mixin[0][1]);
  12604. } else {
  12605. mixin[0].apply(this, _.toArray(arguments).slice(1));
  12606. }
  12607. }
  12608. }
  12609. };
  12610. ;;
  12611. /*global createInheritVars, inheritVars, objectEvents, walkInheritTree */
  12612. // Save a copy of the _on method to call as a $super method
  12613. var _on = Thorax.View.prototype.on;
  12614. inheritVars.event = {
  12615. name: '_events',
  12616. configure: function() {
  12617. var self = this;
  12618. walkInheritTree(this.constructor, '_events', true, function(event) {
  12619. self.on.apply(self, event);
  12620. });
  12621. walkInheritTree(this, 'events', false, function(handler, eventName) {
  12622. self.on(eventName, handler, self);
  12623. });
  12624. }
  12625. };
  12626. _.extend(Thorax.View, {
  12627. on: function(eventName, callback) {
  12628. createInheritVars(this);
  12629. if (objectEvents(this, eventName, callback)) {
  12630. return this;
  12631. }
  12632. //accept on({"rendered": handler})
  12633. if (_.isObject(eventName)) {
  12634. _.each(eventName, function(value, key) {
  12635. this.on(key, value);
  12636. }, this);
  12637. } else {
  12638. //accept on({"rendered": [handler, handler]})
  12639. if (_.isArray(callback)) {
  12640. _.each(callback, function(cb) {
  12641. this._events.push([eventName, cb]);
  12642. }, this);
  12643. //accept on("rendered", handler)
  12644. } else {
  12645. this._events.push([eventName, callback]);
  12646. }
  12647. }
  12648. return this;
  12649. }
  12650. });
  12651. _.extend(Thorax.View.prototype, {
  12652. on: function(eventName, callback, context) {
  12653. if (objectEvents(this, eventName, callback, context)) {
  12654. return this;
  12655. }
  12656. if (_.isObject(eventName) && arguments.length < 3) {
  12657. //accept on({"rendered": callback})
  12658. _.each(eventName, function(value, key) {
  12659. this.on(key, value, callback || this); // callback is context in this form of the call
  12660. }, this);
  12661. } else {
  12662. //accept on("rendered", callback, context)
  12663. //accept on("click a", callback, context)
  12664. _.each((_.isArray(callback) ? callback : [callback]), function(callback) {
  12665. var params = eventParamsFromEventItem.call(this, eventName, callback, context || this);
  12666. if (params.type === 'DOM') {
  12667. //will call _addEvent during delegateEvents()
  12668. if (!this._eventsToDelegate) {
  12669. this._eventsToDelegate = [];
  12670. }
  12671. this._eventsToDelegate.push(params);
  12672. } else {
  12673. this._addEvent(params);
  12674. }
  12675. }, this);
  12676. }
  12677. return this;
  12678. },
  12679. delegateEvents: function(events) {
  12680. this.undelegateEvents();
  12681. if (events) {
  12682. if (_.isFunction(events)) {
  12683. events = events.call(this);
  12684. }
  12685. this._eventsToDelegate = [];
  12686. this.on(events);
  12687. }
  12688. this._eventsToDelegate && _.each(this._eventsToDelegate, this._addEvent, this);
  12689. },
  12690. //params may contain:
  12691. //- name
  12692. //- originalName
  12693. //- selector
  12694. //- type "view" || "DOM"
  12695. //- handler
  12696. _addEvent: function(params) {
  12697. if (params.type === 'view') {
  12698. _.each(params.name.split(/\s+/), function(name) {
  12699. _on.call(this, name, bindEventHandler.call(this, 'view-event:', params));
  12700. }, this);
  12701. } else {
  12702. var boundHandler = bindEventHandler.call(this, 'dom-event:', params);
  12703. if (!params.nested) {
  12704. boundHandler = containHandlerToCurentView(boundHandler, this.cid);
  12705. }
  12706. if (params.selector) {
  12707. var name = params.name + '.delegateEvents' + this.cid;
  12708. this.$el.on(name, params.selector, boundHandler);
  12709. } else {
  12710. this.$el.on(params.name, boundHandler);
  12711. }
  12712. }
  12713. }
  12714. });
  12715. // When view is ready trigger ready event on all
  12716. // children that are present, then register an
  12717. // event that will trigger ready on new children
  12718. // when they are added
  12719. Thorax.View.on('ready', function(options) {
  12720. if (!this._isReady) {
  12721. this._isReady = true;
  12722. function triggerReadyOnChild(child) {
  12723. child.trigger('ready', options);
  12724. }
  12725. _.each(this.children, triggerReadyOnChild);
  12726. this.on('child', triggerReadyOnChild);
  12727. }
  12728. });
  12729. var eventSplitter = /^(nested\s+)?(\S+)(?:\s+(.+))?/;
  12730. var domEvents = [],
  12731. domEventRegexp;
  12732. function pushDomEvents(events) {
  12733. domEvents.push.apply(domEvents, events);
  12734. domEventRegexp = new RegExp('^(nested\\s+)?(' + domEvents.join('|') + ')(?:\\s|$)');
  12735. }
  12736. pushDomEvents([
  12737. 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout',
  12738. 'touchstart', 'touchend', 'touchmove',
  12739. 'click', 'dblclick',
  12740. 'keyup', 'keydown', 'keypress',
  12741. 'submit', 'change',
  12742. 'focus', 'blur'
  12743. ]);
  12744. function containHandlerToCurentView(handler, cid) {
  12745. return function(event) {
  12746. var view = $(event.target).view({helper: false});
  12747. if (view && view.cid === cid) {
  12748. event.originalContext = this;
  12749. handler(event);
  12750. }
  12751. };
  12752. }
  12753. function bindEventHandler(eventName, params) {
  12754. eventName += params.originalName;
  12755. var callback = params.handler,
  12756. method = _.isFunction(callback) ? callback : this[callback];
  12757. if (!method) {
  12758. throw new Error('Event "' + callback + '" does not exist ' + (this.name || this.cid) + ':' + eventName);
  12759. }
  12760. return _.bind(function() {
  12761. try {
  12762. method.apply(this, arguments);
  12763. } catch (e) {
  12764. Thorax.onException('thorax-exception: ' + (this.name || this.cid) + ':' + eventName, e);
  12765. }
  12766. }, params.context || this);
  12767. }
  12768. function eventParamsFromEventItem(name, handler, context) {
  12769. var params = {
  12770. originalName: name,
  12771. handler: _.isString(handler) ? this[handler] : handler
  12772. };
  12773. if (name.match(domEventRegexp)) {
  12774. var match = eventSplitter.exec(name);
  12775. params.nested = !!match[1];
  12776. params.name = match[2];
  12777. params.type = 'DOM';
  12778. params.selector = match[3];
  12779. } else {
  12780. params.name = name;
  12781. params.type = 'view';
  12782. }
  12783. params.context = context;
  12784. return params;
  12785. }
  12786. ;;
  12787. /*global getOptionsData, htmlAttributesToCopy, normalizeHTMLAttributeOptions, viewHelperAttributeName */
  12788. var viewPlaceholderAttributeName = 'data-view-tmp',
  12789. viewTemplateOverrides = {};
  12790. // Will be shared by HelperView and CollectionHelperView
  12791. var helperViewPrototype = {
  12792. _ensureElement: function() {
  12793. Thorax.View.prototype._ensureElement.apply(this, arguments);
  12794. this.$el.attr(viewHelperAttributeName, this._helperName);
  12795. },
  12796. _getContext: function() {
  12797. return this.parent._getContext.apply(this.parent, arguments);
  12798. }
  12799. };
  12800. Thorax.HelperView = Thorax.View.extend(helperViewPrototype);
  12801. // Ensure nested inline helpers will always have this.parent
  12802. // set to the view containing the template
  12803. function getParent(parent) {
  12804. // The `view` helper is a special case as it embeds
  12805. // a view instead of creating a new one
  12806. while (parent._helperName && parent._helperName !== 'view') {
  12807. parent = parent.parent;
  12808. }
  12809. return parent;
  12810. }
  12811. Handlebars.registerViewHelper = function(name, ViewClass, callback) {
  12812. if (arguments.length === 2) {
  12813. if (ViewClass.factory) {
  12814. callback = ViewClass.callback;
  12815. } else {
  12816. callback = ViewClass;
  12817. ViewClass = Thorax.HelperView;
  12818. }
  12819. }
  12820. Handlebars.registerHelper(name, function() {
  12821. var args = _.toArray(arguments),
  12822. options = args.pop(),
  12823. declaringView = getOptionsData(options).view;
  12824. var viewOptions = {
  12825. template: options.fn || Handlebars.VM.noop,
  12826. inverse: options.inverse,
  12827. options: options.hash,
  12828. declaringView: declaringView,
  12829. parent: getParent(declaringView),
  12830. _helperName: name,
  12831. _helperOptions: {
  12832. options: cloneHelperOptions(options),
  12833. args: _.clone(args)
  12834. }
  12835. };
  12836. normalizeHTMLAttributeOptions(options.hash);
  12837. _.extend(viewOptions, _.pick(options.hash, htmlAttributesToCopy));
  12838. // Check to see if we have an existing instance that we can reuse
  12839. var instance = _.find(declaringView._previousHelpers, function(child) {
  12840. return compareHelperOptions(viewOptions, child);
  12841. });
  12842. // Create the instance if we don't already have one
  12843. if (!instance) {
  12844. if (ViewClass.factory) {
  12845. instance = ViewClass.factory(args, viewOptions);
  12846. if (!instance) {
  12847. return '';
  12848. }
  12849. instance._helperName = viewOptions._helperName;
  12850. instance._helperOptions = viewOptions._helperOptions;
  12851. } else {
  12852. instance = new ViewClass(viewOptions);
  12853. }
  12854. args.push(instance);
  12855. declaringView._addChild(instance);
  12856. declaringView.trigger.apply(declaringView, ['helper', name].concat(args));
  12857. declaringView.trigger.apply(declaringView, ['helper:' + name].concat(args));
  12858. callback && callback.apply(this, args);
  12859. } else {
  12860. declaringView._previousHelpers = _.without(declaringView._previousHelpers, instance);
  12861. declaringView.children[instance.cid] = instance;
  12862. }
  12863. var htmlAttributes = _.pick(options.hash, htmlAttributesToCopy);
  12864. htmlAttributes[viewPlaceholderAttributeName] = instance.cid;
  12865. var expandTokens = options.hash['expand-tokens'];
  12866. return new Handlebars.SafeString(Thorax.Util.tag(htmlAttributes, '', expandTokens ? this : null));
  12867. });
  12868. var helper = Handlebars.helpers[name];
  12869. return helper;
  12870. };
  12871. Thorax.View.on('append', function(scope, callback) {
  12872. (scope || this.$el).find('[' + viewPlaceholderAttributeName + ']').forEach(function(el) {
  12873. var placeholderId = el.getAttribute(viewPlaceholderAttributeName),
  12874. view = this.children[placeholderId];
  12875. if (view) {
  12876. //see if the view helper declared an override for the view
  12877. //if not, ensure the view has been rendered at least once
  12878. if (viewTemplateOverrides[placeholderId]) {
  12879. view.render(viewTemplateOverrides[placeholderId]);
  12880. delete viewTemplateOverrides[placeholderId];
  12881. } else {
  12882. view.ensureRendered();
  12883. }
  12884. $(el).replaceWith(view.el);
  12885. callback && callback(view.el);
  12886. }
  12887. }, this);
  12888. });
  12889. /**
  12890. * Clones the helper options, dropping items that are known to change
  12891. * between rendering cycles as appropriate.
  12892. */
  12893. function cloneHelperOptions(options) {
  12894. var ret = _.pick(options, 'fn', 'inverse', 'hash', 'data');
  12895. ret.data = _.omit(options.data, 'cid', 'view', 'yield');
  12896. return ret;
  12897. }
  12898. /**
  12899. * Checks for basic equality between two sets of parameters for a helper view.
  12900. *
  12901. * Checked fields include:
  12902. * - _helperName
  12903. * - All args
  12904. * - Hash
  12905. * - Data
  12906. * - Function and Invert (id based if possible)
  12907. *
  12908. * This method allows us to determine if the inputs to a given view are the same. If they
  12909. * are then we make the assumption that the rendering will be the same (or the child view will
  12910. * otherwise rerendering it by monitoring it's parameters as necessary) and reuse the view on
  12911. * rerender of the parent view.
  12912. */
  12913. function compareHelperOptions(a, b) {
  12914. function compareValues(a, b) {
  12915. return _.every(a, function(value, key) {
  12916. return b[key] === value;
  12917. });
  12918. }
  12919. if (a._helperName !== b._helperName) {
  12920. return false;
  12921. }
  12922. a = a._helperOptions;
  12923. b = b._helperOptions;
  12924. // Implements a first level depth comparison
  12925. return a.args.length === b.args.length
  12926. && compareValues(a.args, b.args)
  12927. && _.isEqual(_.keys(a.options), _.keys(b.options))
  12928. && _.every(a.options, function(value, key) {
  12929. if (key === 'data' || key === 'hash') {
  12930. return compareValues(a.options[key], b.options[key]);
  12931. } else if (key === 'fn' || key === 'inverse') {
  12932. if (b.options[key] === value) {
  12933. return true;
  12934. }
  12935. var other = b.options[key] || {};
  12936. return value && _.has(value, 'program') && !value.depth && other.program === value.program;
  12937. }
  12938. return b.options[key] === value;
  12939. });
  12940. }
  12941. ;;
  12942. /*global getValue, inheritVars, walkInheritTree */
  12943. function dataObject(type, spec) {
  12944. spec = inheritVars[type] = _.defaults({
  12945. name: '_' + type + 'Events',
  12946. event: true
  12947. }, spec);
  12948. // Add a callback in the view constructor
  12949. spec.ctor = function() {
  12950. if (this[type]) {
  12951. // Need to null this.model/collection so setModel/Collection will
  12952. // not treat it as the old model/collection and immediately return
  12953. var object = this[type];
  12954. this[type] = null;
  12955. this[spec.set](object);
  12956. }
  12957. };
  12958. function setObject(dataObject, options) {
  12959. var old = this[type],
  12960. $el = getValue(this, spec.$el);
  12961. if (dataObject === old) {
  12962. return this;
  12963. }
  12964. if (old) {
  12965. this.unbindDataObject(old);
  12966. }
  12967. if (dataObject) {
  12968. this[type] = dataObject;
  12969. if (spec.loading) {
  12970. spec.loading.call(this);
  12971. }
  12972. this.bindDataObject(type, dataObject, _.extend({}, this.options, options));
  12973. $el && $el.attr(spec.cidAttrName, dataObject.cid);
  12974. dataObject.trigger('set', dataObject, old);
  12975. } else {
  12976. this[type] = false;
  12977. if (spec.change) {
  12978. spec.change.call(this, false);
  12979. }
  12980. $el && $el.removeAttr(spec.cidAttrName);
  12981. }
  12982. this.trigger('change:data-object', type, dataObject, old);
  12983. return this;
  12984. }
  12985. Thorax.View.prototype[spec.set] = setObject;
  12986. }
  12987. _.extend(Thorax.View.prototype, {
  12988. bindDataObject: function(type, dataObject, options) {
  12989. if (this._boundDataObjectsByCid[dataObject.cid]) {
  12990. return false;
  12991. }
  12992. this._boundDataObjectsByCid[dataObject.cid] = dataObject;
  12993. var options = this._modifyDataObjectOptions(dataObject, _.extend({}, inheritVars[type].defaultOptions, options));
  12994. this._objectOptionsByCid[dataObject.cid] = options;
  12995. bindEvents.call(this, type, dataObject, this.constructor);
  12996. bindEvents.call(this, type, dataObject, this);
  12997. var spec = inheritVars[type];
  12998. spec.bindCallback && spec.bindCallback.call(this, dataObject, options);
  12999. if (dataObject.shouldFetch && dataObject.shouldFetch(options)) {
  13000. loadObject(dataObject, options);
  13001. } else if (inheritVars[type].change) {
  13002. // want to trigger built in rendering without triggering event on model
  13003. inheritVars[type].change.call(this, dataObject, options);
  13004. }
  13005. return true;
  13006. },
  13007. unbindDataObject: function (dataObject) {
  13008. if (!this._boundDataObjectsByCid[dataObject.cid]) {
  13009. return false;
  13010. }
  13011. delete this._boundDataObjectsByCid[dataObject.cid];
  13012. this.stopListening(dataObject);
  13013. delete this._objectOptionsByCid[dataObject.cid];
  13014. return true;
  13015. },
  13016. _modifyDataObjectOptions: function(dataObject, options) {
  13017. return options;
  13018. }
  13019. });
  13020. function bindEvents(type, target, source) {
  13021. var context = this;
  13022. walkInheritTree(source, '_' + type + 'Events', true, function(event) {
  13023. // getEventCallback will resolve if it is a string or a method
  13024. // and return a method
  13025. context.listenTo(target, event[0], _.bind(getEventCallback(event[1], context), event[2] || context));
  13026. });
  13027. }
  13028. function loadObject(dataObject, options) {
  13029. if (dataObject.load) {
  13030. dataObject.load(function() {
  13031. options && options.success && options.success(dataObject);
  13032. }, options);
  13033. } else {
  13034. dataObject.fetch(options);
  13035. }
  13036. }
  13037. function getEventCallback(callback, context) {
  13038. if (_.isFunction(callback)) {
  13039. return callback;
  13040. } else {
  13041. return context[callback];
  13042. }
  13043. }
  13044. ;;
  13045. /*global createRegistryWrapper, dataObject, getValue */
  13046. var modelCidAttributeName = 'data-model-cid';
  13047. Thorax.Model = Backbone.Model.extend({
  13048. isEmpty: function() {
  13049. return !this.isPopulated();
  13050. },
  13051. isPopulated: function() {
  13052. // We are populated if we have attributes set
  13053. var attributes = _.clone(this.attributes),
  13054. defaults = getValue(this, 'defaults') || {};
  13055. for (var default_key in defaults) {
  13056. if (attributes[default_key] != defaults[default_key]) {
  13057. return true;
  13058. }
  13059. delete attributes[default_key];
  13060. }
  13061. var keys = _.keys(attributes);
  13062. return keys.length > 1 || (keys.length === 1 && keys[0] !== this.idAttribute);
  13063. },
  13064. shouldFetch: function(options) {
  13065. // url() will throw if model has no `urlRoot` and no `collection`
  13066. // or has `collection` and `collection` has no `url`
  13067. var url;
  13068. try {
  13069. url = getValue(this, 'url');
  13070. } catch(e) {
  13071. url = false;
  13072. }
  13073. return options.fetch && !!url && !this.isPopulated();
  13074. }
  13075. });
  13076. Thorax.Models = {};
  13077. createRegistryWrapper(Thorax.Model, Thorax.Models);
  13078. dataObject('model', {
  13079. set: 'setModel',
  13080. defaultOptions: {
  13081. render: true,
  13082. fetch: true,
  13083. success: false,
  13084. errors: true
  13085. },
  13086. change: onModelChange,
  13087. $el: '$el',
  13088. cidAttrName: modelCidAttributeName
  13089. });
  13090. function onModelChange(model) {
  13091. var modelOptions = model && this._objectOptionsByCid[model.cid];
  13092. // !modelOptions will be true when setModel(false) is called
  13093. if (!modelOptions || (modelOptions && modelOptions.render)) {
  13094. this.render();
  13095. }
  13096. }
  13097. Thorax.View.on({
  13098. model: {
  13099. error: function(model, errors) {
  13100. if (this._objectOptionsByCid[model.cid].errors) {
  13101. this.trigger('error', errors, model);
  13102. }
  13103. },
  13104. change: function(model) {
  13105. onModelChange.call(this, model);
  13106. }
  13107. }
  13108. });
  13109. $.fn.model = function(view) {
  13110. var $this = $(this),
  13111. modelElement = $this.closest('[' + modelCidAttributeName + ']'),
  13112. modelCid = modelElement && modelElement.attr(modelCidAttributeName);
  13113. if (modelCid) {
  13114. var view = view || $this.view();
  13115. if (view && view.model && view.model.cid === modelCid) {
  13116. return view.model || false;
  13117. }
  13118. var collection = $this.collection(view);
  13119. if (collection) {
  13120. return collection.get(modelCid);
  13121. }
  13122. }
  13123. return false;
  13124. };
  13125. ;;
  13126. /*global createRegistryWrapper, dataObject, getEventCallback, getValue, modelCidAttributeName, viewCidAttributeName */
  13127. var _fetch = Backbone.Collection.prototype.fetch,
  13128. _reset = Backbone.Collection.prototype.reset,
  13129. _replaceHTML = Thorax.View.prototype._replaceHTML,
  13130. collectionCidAttributeName = 'data-collection-cid',
  13131. collectionEmptyAttributeName = 'data-collection-empty',
  13132. collectionElementAttributeName = 'data-collection-element',
  13133. ELEMENT_NODE_TYPE = 1;
  13134. Thorax.Collection = Backbone.Collection.extend({
  13135. model: Thorax.Model || Backbone.Model,
  13136. initialize: function() {
  13137. this.cid = _.uniqueId('collection');
  13138. return Backbone.Collection.prototype.initialize.apply(this, arguments);
  13139. },
  13140. isEmpty: function() {
  13141. if (this.length > 0) {
  13142. return false;
  13143. } else {
  13144. return this.length === 0 && this.isPopulated();
  13145. }
  13146. },
  13147. isPopulated: function() {
  13148. return this._fetched || this.length > 0 || (!this.length && !getValue(this, 'url'));
  13149. },
  13150. shouldFetch: function(options) {
  13151. return options.fetch && !!getValue(this, 'url') && !this.isPopulated();
  13152. },
  13153. fetch: function(options) {
  13154. options = options || {};
  13155. var success = options.success;
  13156. options.success = function(collection, response) {
  13157. collection._fetched = true;
  13158. success && success(collection, response);
  13159. };
  13160. return _fetch.apply(this, arguments);
  13161. },
  13162. reset: function(models, options) {
  13163. this._fetched = !!models;
  13164. return _reset.call(this, models, options);
  13165. }
  13166. });
  13167. Thorax.Collections = {};
  13168. createRegistryWrapper(Thorax.Collection, Thorax.Collections);
  13169. dataObject('collection', {
  13170. set: 'setCollection',
  13171. bindCallback: onSetCollection,
  13172. defaultOptions: {
  13173. render: true,
  13174. fetch: true,
  13175. success: false,
  13176. errors: true
  13177. },
  13178. change: onCollectionReset,
  13179. $el: 'getCollectionElement',
  13180. cidAttrName: collectionCidAttributeName
  13181. });
  13182. Thorax.CollectionView = Thorax.View.extend({
  13183. _defaultTemplate: Handlebars.VM.noop,
  13184. _collectionSelector: '[' + collectionElementAttributeName + ']',
  13185. // preserve collection element if it was not created with {{collection}} helper
  13186. _replaceHTML: function(html) {
  13187. if (this.collection && this._objectOptionsByCid[this.collection.cid] && this._renderCount) {
  13188. var element;
  13189. var oldCollectionElement = this.getCollectionElement();
  13190. element = _replaceHTML.call(this, html);
  13191. if (!oldCollectionElement.attr('data-view-cid')) {
  13192. this.getCollectionElement().replaceWith(oldCollectionElement);
  13193. }
  13194. } else {
  13195. return _replaceHTML.call(this, html);
  13196. }
  13197. },
  13198. //appendItem(model [,index])
  13199. //appendItem(html_string, index)
  13200. //appendItem(view, index)
  13201. appendItem: function(model, index, options) {
  13202. //empty item
  13203. if (!model) {
  13204. return;
  13205. }
  13206. var itemView,
  13207. $el = this.getCollectionElement();
  13208. options = _.defaults(options || {}, {
  13209. filter: true
  13210. });
  13211. //if index argument is a view
  13212. index && index.el && (index = $el.children().indexOf(index.el) + 1);
  13213. //if argument is a view, or html string
  13214. if (model.el || _.isString(model)) {
  13215. itemView = model;
  13216. model = false;
  13217. } else {
  13218. index = index || this.collection.indexOf(model) || 0;
  13219. itemView = this.renderItem(model, index);
  13220. }
  13221. if (itemView) {
  13222. itemView.cid && this._addChild(itemView);
  13223. //if the renderer's output wasn't contained in a tag, wrap it in a div
  13224. //plain text, or a mixture of top level text nodes and element nodes
  13225. //will get wrapped
  13226. if (_.isString(itemView) && !itemView.match(/^\s*</m)) {
  13227. itemView = '<div>' + itemView + '</div>';
  13228. }
  13229. var itemElement = itemView.el ? [itemView.el] : _.filter($($.trim(itemView)), function(node) {
  13230. //filter out top level whitespace nodes
  13231. return node.nodeType === ELEMENT_NODE_TYPE;
  13232. });
  13233. model && $(itemElement).attr(modelCidAttributeName, model.cid);
  13234. var previousModel = index > 0 ? this.collection.at(index - 1) : false;
  13235. if (!previousModel) {
  13236. $el.prepend(itemElement);
  13237. } else {
  13238. //use last() as appendItem can accept multiple nodes from a template
  13239. var last = $el.children('[' + modelCidAttributeName + '="' + previousModel.cid + '"]').last();
  13240. last.after(itemElement);
  13241. }
  13242. this.trigger('append', null, function(el) {
  13243. el.setAttribute(modelCidAttributeName, model.cid);
  13244. });
  13245. !options.silent && this.trigger('rendered:item', this, this.collection, model, itemElement, index);
  13246. options.filter && applyItemVisiblityFilter.call(this, model);
  13247. }
  13248. return itemView;
  13249. },
  13250. // updateItem only useful if there is no item view, otherwise
  13251. // itemView.render() provides the same functionality
  13252. updateItem: function(model) {
  13253. this.removeItem(model);
  13254. this.appendItem(model);
  13255. },
  13256. removeItem: function(model) {
  13257. var $el = this.getCollectionElement(),
  13258. viewEl = $el.find('[' + modelCidAttributeName + '="' + model.cid + '"]');
  13259. if (!viewEl.length) {
  13260. return false;
  13261. }
  13262. viewEl.remove();
  13263. var viewCid = viewEl.attr(viewCidAttributeName),
  13264. child = this.children[viewCid];
  13265. if (child) {
  13266. this._removeChild(child);
  13267. child.destroy();
  13268. }
  13269. return true;
  13270. },
  13271. renderCollection: function() {
  13272. if (this.collection) {
  13273. if (this.collection.isEmpty()) {
  13274. handleChangeFromNotEmptyToEmpty.call(this);
  13275. } else {
  13276. handleChangeFromEmptyToNotEmpty.call(this);
  13277. this.collection.forEach(function(item, i) {
  13278. this.appendItem(item, i);
  13279. }, this);
  13280. }
  13281. this.trigger('rendered:collection', this, this.collection);
  13282. applyVisibilityFilter.call(this);
  13283. } else {
  13284. handleChangeFromNotEmptyToEmpty.call(this);
  13285. }
  13286. },
  13287. emptyClass: 'empty',
  13288. renderEmpty: function() {
  13289. if (!this.emptyTemplate && !this.emptyView) {
  13290. assignTemplate.call(this, 'emptyTemplate', {
  13291. extension: '-empty',
  13292. required: false
  13293. });
  13294. }
  13295. if (this.emptyView) {
  13296. var viewOptions = {};
  13297. if (this.emptyTemplate) {
  13298. viewOptions.template = this.emptyTemplate;
  13299. }
  13300. var view = Thorax.Util.getViewInstance(this.emptyView, viewOptions);
  13301. view.ensureRendered();
  13302. return view;
  13303. } else {
  13304. return this.emptyTemplate && this.renderTemplate(this.emptyTemplate);
  13305. }
  13306. },
  13307. renderItem: function(model, i) {
  13308. if (!this.itemTemplate && !this.itemView) {
  13309. assignTemplate.call(this, 'itemTemplate', {
  13310. extension: '-item',
  13311. // only require an itemTemplate if an itemView
  13312. // is not present
  13313. required: !this.itemView
  13314. });
  13315. }
  13316. if (this.itemView) {
  13317. var viewOptions = {
  13318. model: model
  13319. };
  13320. if (this.itemTemplate) {
  13321. viewOptions.template = this.itemTemplate;
  13322. }
  13323. var view = Thorax.Util.getViewInstance(this.itemView, viewOptions);
  13324. view.ensureRendered();
  13325. return view;
  13326. } else {
  13327. return this.renderTemplate(this.itemTemplate, this.itemContext(model, i));
  13328. }
  13329. },
  13330. itemContext: function(model /*, i */) {
  13331. return model.attributes;
  13332. },
  13333. appendEmpty: function() {
  13334. var $el = this.getCollectionElement();
  13335. $el.empty();
  13336. var emptyContent = this.renderEmpty();
  13337. emptyContent && this.appendItem(emptyContent, 0, {
  13338. silent: true,
  13339. filter: false
  13340. });
  13341. this.trigger('rendered:empty', this, this.collection);
  13342. },
  13343. getCollectionElement: function() {
  13344. var element = this.$(this._collectionSelector);
  13345. return element.length === 0 ? this.$el : element;
  13346. }
  13347. });
  13348. Thorax.CollectionView.on({
  13349. collection: {
  13350. reset: onCollectionReset,
  13351. sort: onCollectionReset,
  13352. filter: function() {
  13353. applyVisibilityFilter.call(this);
  13354. },
  13355. change: function(model) {
  13356. // If we rendered with item views, model changes will be observed
  13357. // by the generated item view but if we rendered with templates
  13358. // then model changes need to be bound as nothing is watching
  13359. !this.itemView && this.updateItem(model);
  13360. applyItemVisiblityFilter.call(this, model);
  13361. },
  13362. add: function(model) {
  13363. var $el = this.getCollectionElement();
  13364. this.collection.length === 1 && $el.length && handleChangeFromEmptyToNotEmpty.call(this);
  13365. if ($el.length) {
  13366. var index = this.collection.indexOf(model);
  13367. this.appendItem(model, index);
  13368. }
  13369. },
  13370. remove: function(model) {
  13371. var $el = this.getCollectionElement();
  13372. this.removeItem(model);
  13373. this.collection.length === 0 && $el.length && handleChangeFromNotEmptyToEmpty.call(this);
  13374. }
  13375. }
  13376. });
  13377. Thorax.View.on({
  13378. collection: {
  13379. error: function(collection, message) {
  13380. if (this._objectOptionsByCid[collection.cid].errors) {
  13381. this.trigger('error', message, collection);
  13382. }
  13383. }
  13384. }
  13385. });
  13386. function onCollectionReset(collection) {
  13387. var options = collection && this._objectOptionsByCid[collection.cid];
  13388. // we would want to still render in the case that the
  13389. // collection has transitioned to being falsy
  13390. if (!collection || (options && options.render)) {
  13391. this.renderCollection && this.renderCollection();
  13392. }
  13393. }
  13394. // Even if the view is not a CollectionView
  13395. // ensureRendered() to provide similar behavior
  13396. // to a model
  13397. function onSetCollection() {
  13398. this.ensureRendered();
  13399. }
  13400. function applyVisibilityFilter() {
  13401. if (this.itemFilter) {
  13402. this.collection.forEach(function(model) {
  13403. applyItemVisiblityFilter.call(this, model);
  13404. }, this);
  13405. }
  13406. }
  13407. function applyItemVisiblityFilter(model) {
  13408. var $el = this.getCollectionElement();
  13409. this.itemFilter && $el.find('[' + modelCidAttributeName + '="' + model.cid + '"]')[itemShouldBeVisible.call(this, model) ? 'show' : 'hide']();
  13410. }
  13411. function itemShouldBeVisible(model) {
  13412. return this.itemFilter(model, this.collection.indexOf(model));
  13413. }
  13414. function handleChangeFromEmptyToNotEmpty() {
  13415. var $el = this.getCollectionElement();
  13416. this.emptyClass && $el.removeClass(this.emptyClass);
  13417. $el.removeAttr(collectionEmptyAttributeName);
  13418. $el.empty();
  13419. }
  13420. function handleChangeFromNotEmptyToEmpty() {
  13421. var $el = this.getCollectionElement();
  13422. this.emptyClass && $el.addClass(this.emptyClass);
  13423. $el.attr(collectionEmptyAttributeName, true);
  13424. this.appendEmpty();
  13425. }
  13426. //$(selector).collection() helper
  13427. $.fn.collection = function(view) {
  13428. if (view && view.collection) {
  13429. return view.collection;
  13430. }
  13431. var $this = $(this),
  13432. collectionElement = $this.closest('[' + collectionCidAttributeName + ']'),
  13433. collectionCid = collectionElement && collectionElement.attr(collectionCidAttributeName);
  13434. if (collectionCid) {
  13435. view = $this.view();
  13436. if (view) {
  13437. return view.collection;
  13438. }
  13439. }
  13440. return false;
  13441. };
  13442. ;;
  13443. /*global inheritVars */
  13444. inheritVars.model.defaultOptions.populate = true;
  13445. var oldModelChange = inheritVars.model.change;
  13446. inheritVars.model.change = function() {
  13447. oldModelChange.apply(this, arguments);
  13448. // TODO : What can we do to remove this duplication?
  13449. var modelOptions = this.model && this._objectOptionsByCid[this.model.cid];
  13450. if (modelOptions && modelOptions.populate) {
  13451. this.populate(this.model.attributes, modelOptions.populate === true ? {} : modelOptions.populate);
  13452. }
  13453. };
  13454. inheritVars.model.defaultOptions.populate = true;
  13455. _.extend(Thorax.View.prototype, {
  13456. //serializes a form present in the view, returning the serialized data
  13457. //as an object
  13458. //pass {set:false} to not update this.model if present
  13459. //can pass options, callback or event in any order
  13460. serialize: function() {
  13461. var callback, options, event;
  13462. //ignore undefined arguments in case event was null
  13463. for (var i = 0; i < arguments.length; ++i) {
  13464. if (_.isFunction(arguments[i])) {
  13465. callback = arguments[i];
  13466. } else if (_.isObject(arguments[i])) {
  13467. if ('stopPropagation' in arguments[i] && 'preventDefault' in arguments[i]) {
  13468. event = arguments[i];
  13469. } else {
  13470. options = arguments[i];
  13471. }
  13472. }
  13473. }
  13474. if (event && !this._preventDuplicateSubmission(event)) {
  13475. return;
  13476. }
  13477. options = _.extend({
  13478. set: true,
  13479. validate: true,
  13480. children: true,
  13481. silent: true
  13482. }, options || {});
  13483. var attributes = options.attributes || {};
  13484. //callback has context of element
  13485. var view = this;
  13486. var errors = [];
  13487. eachNamedInput.call(this, options, function() {
  13488. var value = view._getInputValue(this, options, errors);
  13489. if (!_.isUndefined(value)) {
  13490. objectAndKeyFromAttributesAndName.call(this, attributes, this.name, {mode: 'serialize'}, function(object, key) {
  13491. if (!object[key]) {
  13492. object[key] = value;
  13493. } else if (_.isArray(object[key])) {
  13494. object[key].push(value);
  13495. } else {
  13496. object[key] = [object[key], value];
  13497. }
  13498. });
  13499. }
  13500. });
  13501. this.trigger('serialize', attributes, options);
  13502. if (options.validate) {
  13503. var validateInputErrors = this.validateInput(attributes);
  13504. if (validateInputErrors && validateInputErrors.length) {
  13505. errors = errors.concat(validateInputErrors);
  13506. }
  13507. this.trigger('validate', attributes, errors, options);
  13508. if (errors.length) {
  13509. this.trigger('error', errors);
  13510. return;
  13511. }
  13512. }
  13513. if (options.set && this.model) {
  13514. if (!this.model.set(attributes, {silent: options.silent})) {
  13515. return false;
  13516. }
  13517. }
  13518. callback && callback.call(this, attributes, _.bind(resetSubmitState, this));
  13519. return attributes;
  13520. },
  13521. _preventDuplicateSubmission: function(event, callback) {
  13522. event.preventDefault();
  13523. var form = $(event.target);
  13524. if ((event.target.tagName || '').toLowerCase() !== 'form') {
  13525. // Handle non-submit events by gating on the form
  13526. form = $(event.target).closest('form');
  13527. }
  13528. if (!form.attr('data-submit-wait')) {
  13529. form.attr('data-submit-wait', 'true');
  13530. if (callback) {
  13531. callback.call(this, event);
  13532. }
  13533. return true;
  13534. } else {
  13535. return false;
  13536. }
  13537. },
  13538. //populate a form from the passed attributes or this.model if present
  13539. populate: function(attributes, options) {
  13540. options = _.extend({
  13541. children: true
  13542. }, options || {});
  13543. var value,
  13544. attributes = attributes || this._getContext();
  13545. //callback has context of element
  13546. eachNamedInput.call(this, options, function() {
  13547. objectAndKeyFromAttributesAndName.call(this, attributes, this.name, {mode: 'populate'}, function(object, key) {
  13548. value = object && object[key];
  13549. if (!_.isUndefined(value)) {
  13550. //will only execute if we have a name that matches the structure in attributes
  13551. if (this.type === 'checkbox' && _.isBoolean(value)) {
  13552. this.checked = value;
  13553. } else if (this.type === 'checkbox' || this.type === 'radio') {
  13554. this.checked = value == this.value;
  13555. } else {
  13556. this.value = value;
  13557. }
  13558. }
  13559. });
  13560. });
  13561. this.trigger('populate', attributes);
  13562. },
  13563. //perform form validation, implemented by child class
  13564. validateInput: function(/* attributes, options, errors */) {},
  13565. _getInputValue: function(input /* , options, errors */) {
  13566. if (input.type === 'checkbox' || input.type === 'radio') {
  13567. if (input.checked) {
  13568. return input.value;
  13569. }
  13570. } else if (input.multiple === true) {
  13571. var values = [];
  13572. $('option', input).each(function() {
  13573. if (this.selected) {
  13574. values.push(this.value);
  13575. }
  13576. });
  13577. return values;
  13578. } else {
  13579. return input.value;
  13580. }
  13581. }
  13582. });
  13583. Thorax.View.on({
  13584. error: function() {
  13585. resetSubmitState.call(this);
  13586. // If we errored with a model we want to reset the content but leave the UI
  13587. // intact. If the user updates the data and serializes any overwritten data
  13588. // will be restored.
  13589. if (this.model && this.model.previousAttributes) {
  13590. this.model.set(this.model.previousAttributes(), {
  13591. silent: true
  13592. });
  13593. }
  13594. },
  13595. deactivated: function() {
  13596. resetSubmitState.call(this);
  13597. }
  13598. });
  13599. function eachNamedInput(options, iterator, context) {
  13600. var i = 0,
  13601. self = this;
  13602. this.$('select,input,textarea', options.root || this.el).each(function() {
  13603. if (!options.child