Fix some whitespace issues. Improve and correct an events test.
[jquery.git] / src / core.js
1 var jQuery = (function() {
2
3 // Define a local copy of jQuery
4 var jQuery = function( selector, context ) {
5                 // The jQuery object is actually just the init constructor 'enhanced'
6                 return new jQuery.fn.init( selector, context, rootjQuery );
7         },
8
9         // Map over jQuery in case of overwrite
10         _jQuery = window.jQuery,
11
12         // Map over the $ in case of overwrite
13         _$ = window.$,
14
15         // A central reference to the root jQuery(document)
16         rootjQuery,
17
18         // A simple way to check for HTML strings or ID strings
19         // (both of which we optimize for)
20         quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
21
22         // Check if a string has a non-whitespace character in it
23         rnotwhite = /\S/,
24
25         // Used for trimming whitespace
26         trimLeft = /^\s+/,
27         trimRight = /\s+$/,
28
29         // Check for digits
30         rdigit = /\d/,
31
32         // Match a standalone tag
33         rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
34
35         // JSON RegExp
36         rvalidchars = /^[\],:{}\s]*$/,
37         rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
38         rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
39         rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
40
41         // Useragent RegExp
42         rwebkit = /(webkit)[ \/]([\w.]+)/,
43         ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
44         rmsie = /(msie) ([\w.]+)/,
45         rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
46
47         // Keep a UserAgent string for use with jQuery.browser
48         userAgent = navigator.userAgent,
49
50         // For matching the engine and version of the browser
51         browserMatch,
52
53         // Has the ready events already been bound?
54         readyBound = false,
55
56         // The deferred used on DOM ready
57         readyList,
58
59         // Promise methods (with equivalent for invert)
60         promiseMethods = {
61                 then: 0, // will be overwritten for invert
62                 done: "fail",
63                 fail: "done",
64                 isResolved: "isRejected",
65                 isRejected: "isResolved",
66                 promise: "invert",
67                 invert: "promise"
68         },
69
70         // The ready event handler
71         DOMContentLoaded,
72
73         // Save a reference to some core methods
74         toString = Object.prototype.toString,
75         hasOwn = Object.prototype.hasOwnProperty,
76         push = Array.prototype.push,
77         slice = Array.prototype.slice,
78         trim = String.prototype.trim,
79         indexOf = Array.prototype.indexOf,
80
81         // [[Class]] -> type pairs
82         class2type = {};
83
84 jQuery.fn = jQuery.prototype = {
85         constructor: jQuery,
86         init: function( selector, context, rootjQuery ) {
87                 var match, elem, ret, doc;
88
89                 // Handle $(""), $(null), or $(undefined)
90                 if ( !selector ) {
91                         return this;
92                 }
93
94                 // Handle $(DOMElement)
95                 if ( selector.nodeType ) {
96                         this.context = this[0] = selector;
97                         this.length = 1;
98                         return this;
99                 }
100
101                 // The body element only exists once, optimize finding it
102                 if ( selector === "body" && !context && document.body ) {
103                         this.context = document;
104                         this[0] = document.body;
105                         this.selector = "body";
106                         this.length = 1;
107                         return this;
108                 }
109
110                 // Handle HTML strings
111                 if ( typeof selector === "string" ) {
112                         // Are we dealing with HTML string or an ID?
113                         match = quickExpr.exec( selector );
114
115                         // Verify a match, and that no context was specified for #id
116                         if ( match && (match[1] || !context) ) {
117
118                                 // HANDLE: $(html) -> $(array)
119                                 if ( match[1] ) {
120                                         context = context instanceof jQuery ? context[0] : context;
121                                         doc = (context ? context.ownerDocument || context : document);
122
123                                         // If a single string is passed in and it's a single tag
124                                         // just do a createElement and skip the rest
125                                         ret = rsingleTag.exec( selector );
126
127                                         if ( ret ) {
128                                                 if ( jQuery.isPlainObject( context ) ) {
129                                                         selector = [ document.createElement( ret[1] ) ];
130                                                         jQuery.fn.attr.call( selector, context, true );
131
132                                                 } else {
133                                                         selector = [ doc.createElement( ret[1] ) ];
134                                                 }
135
136                                         } else {
137                                                 ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
138                                                 selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
139                                         }
140
141                                         return jQuery.merge( this, selector );
142
143                                 // HANDLE: $("#id")
144                                 } else {
145                                         elem = document.getElementById( match[2] );
146
147                                         // Check parentNode to catch when Blackberry 4.6 returns
148                                         // nodes that are no longer in the document #6963
149                                         if ( elem && elem.parentNode ) {
150                                                 // Handle the case where IE and Opera return items
151                                                 // by name instead of ID
152                                                 if ( elem.id !== match[2] ) {
153                                                         return rootjQuery.find( selector );
154                                                 }
155
156                                                 // Otherwise, we inject the element directly into the jQuery object
157                                                 this.length = 1;
158                                                 this[0] = elem;
159                                         }
160
161                                         this.context = document;
162                                         this.selector = selector;
163                                         return this;
164                                 }
165
166                         // HANDLE: $(expr, $(...))
167                         } else if ( !context || context.jquery ) {
168                                 return (context || rootjQuery).find( selector );
169
170                         // HANDLE: $(expr, context)
171                         // (which is just equivalent to: $(context).find(expr)
172                         } else {
173                                 return this.constructor( context ).find( selector );
174                         }
175
176                 // HANDLE: $(function)
177                 // Shortcut for document ready
178                 } else if ( jQuery.isFunction( selector ) ) {
179                         return rootjQuery.ready( selector );
180                 }
181
182                 if (selector.selector !== undefined) {
183                         this.selector = selector.selector;
184                         this.context = selector.context;
185                 }
186
187                 return jQuery.makeArray( selector, this );
188         },
189
190         // Start with an empty selector
191         selector: "",
192
193         // The current version of jQuery being used
194         jquery: "@VERSION",
195
196         // The default length of a jQuery object is 0
197         length: 0,
198
199         // The number of elements contained in the matched element set
200         size: function() {
201                 return this.length;
202         },
203
204         toArray: function() {
205                 return slice.call( this, 0 );
206         },
207
208         // Get the Nth element in the matched element set OR
209         // Get the whole matched element set as a clean array
210         get: function( num ) {
211                 return num == null ?
212
213                         // Return a 'clean' array
214                         this.toArray() :
215
216                         // Return just the object
217                         ( num < 0 ? this[ this.length + num ] : this[ num ] );
218         },
219
220         // Take an array of elements and push it onto the stack
221         // (returning the new matched element set)
222         pushStack: function( elems, name, selector ) {
223                 // Build a new jQuery matched element set
224                 var ret = this.constructor();
225
226                 if ( jQuery.isArray( elems ) ) {
227                         push.apply( ret, elems );
228
229                 } else {
230                         jQuery.merge( ret, elems );
231                 }
232
233                 // Add the old object onto the stack (as a reference)
234                 ret.prevObject = this;
235
236                 ret.context = this.context;
237
238                 if ( name === "find" ) {
239                         ret.selector = this.selector + (this.selector ? " " : "") + selector;
240                 } else if ( name ) {
241                         ret.selector = this.selector + "." + name + "(" + selector + ")";
242                 }
243
244                 // Return the newly-formed element set
245                 return ret;
246         },
247
248         // Execute a callback for every element in the matched set.
249         // (You can seed the arguments with an array of args, but this is
250         // only used internally.)
251         each: function( callback, args ) {
252                 return jQuery.each( this, callback, args );
253         },
254
255         ready: function( fn ) {
256                 // Attach the listeners
257                 jQuery.bindReady();
258
259                 // Add the callback
260                 readyList.done( fn );
261
262                 return this;
263         },
264
265         eq: function( i ) {
266                 return i === -1 ?
267                         this.slice( i ) :
268                         this.slice( i, +i + 1 );
269         },
270
271         first: function() {
272                 return this.eq( 0 );
273         },
274
275         last: function() {
276                 return this.eq( -1 );
277         },
278
279         slice: function() {
280                 return this.pushStack( slice.apply( this, arguments ),
281                         "slice", slice.call(arguments).join(",") );
282         },
283
284         map: function( callback ) {
285                 return this.pushStack( jQuery.map(this, function( elem, i ) {
286                         return callback.call( elem, i, elem );
287                 }));
288         },
289
290         end: function() {
291                 return this.prevObject || this.constructor(null);
292         },
293
294         // For internal use only.
295         // Behaves like an Array's method, not like a jQuery method.
296         push: push,
297         sort: [].sort,
298         splice: [].splice
299 };
300
301 // Give the init function the jQuery prototype for later instantiation
302 jQuery.fn.init.prototype = jQuery.fn;
303
304 jQuery.extend = jQuery.fn.extend = function() {
305          var options, name, src, copy, copyIsArray, clone,
306                 target = arguments[0] || {},
307                 i = 1,
308                 length = arguments.length,
309                 deep = false;
310
311         // Handle a deep copy situation
312         if ( typeof target === "boolean" ) {
313                 deep = target;
314                 target = arguments[1] || {};
315                 // skip the boolean and the target
316                 i = 2;
317         }
318
319         // Handle case when target is a string or something (possible in deep copy)
320         if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
321                 target = {};
322         }
323
324         // extend jQuery itself if only one argument is passed
325         if ( length === i ) {
326                 target = this;
327                 --i;
328         }
329
330         for ( ; i < length; i++ ) {
331                 // Only deal with non-null/undefined values
332                 if ( (options = arguments[ i ]) != null ) {
333                         // Extend the base object
334                         for ( name in options ) {
335                                 src = target[ name ];
336                                 copy = options[ name ];
337
338                                 // Prevent never-ending loop
339                                 if ( target === copy ) {
340                                         continue;
341                                 }
342
343                                 // Recurse if we're merging plain objects or arrays
344                                 if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
345                                         if ( copyIsArray ) {
346                                                 copyIsArray = false;
347                                                 clone = src && jQuery.isArray(src) ? src : [];
348
349                                         } else {
350                                                 clone = src && jQuery.isPlainObject(src) ? src : {};
351                                         }
352
353                                         // Never move original objects, clone them
354                                         target[ name ] = jQuery.extend( deep, clone, copy );
355
356                                 // Don't bring in undefined values
357                                 } else if ( copy !== undefined ) {
358                                         target[ name ] = copy;
359                                 }
360                         }
361                 }
362         }
363
364         // Return the modified object
365         return target;
366 };
367
368 jQuery.extend({
369         noConflict: function( deep ) {
370                 window.$ = _$;
371
372                 if ( deep ) {
373                         window.jQuery = _jQuery;
374                 }
375
376                 return jQuery;
377         },
378
379         // Is the DOM ready to be used? Set to true once it occurs.
380         isReady: false,
381
382         // A counter to track how many items to wait for before
383         // the ready event fires. See #6781
384         readyWait: 1,
385
386         // Handle when the DOM is ready
387         ready: function( wait ) {
388                 // A third-party is pushing the ready event forwards
389                 if ( wait === true ) {
390                         jQuery.readyWait--;
391                 }
392
393                 // Make sure that the DOM is not already loaded
394                 if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) {
395                         // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
396                         if ( !document.body ) {
397                                 return setTimeout( jQuery.ready, 1 );
398                         }
399
400                         // Remember that the DOM is ready
401                         jQuery.isReady = true;
402
403                         // If a normal DOM Ready event fired, decrement, and wait if need be
404                         if ( wait !== true && --jQuery.readyWait > 0 ) {
405                                 return;
406                         }
407
408                         // If there are functions bound, to execute
409                         readyList.resolveWith( document, [ jQuery ] );
410
411                         // Trigger any bound ready events
412                         if ( jQuery.fn.trigger ) {
413                                 jQuery( document ).trigger( "ready" ).unbind( "ready" );
414                         }
415                 }
416         },
417
418         bindReady: function() {
419                 if ( readyBound ) {
420                         return;
421                 }
422
423                 readyBound = true;
424
425                 // Catch cases where $(document).ready() is called after the
426                 // browser event has already occurred.
427                 if ( document.readyState === "complete" ) {
428                         // Handle it asynchronously to allow scripts the opportunity to delay ready
429                         return setTimeout( jQuery.ready, 1 );
430                 }
431
432                 // Mozilla, Opera and webkit nightlies currently support this event
433                 if ( document.addEventListener ) {
434                         // Use the handy event callback
435                         document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
436
437                         // A fallback to window.onload, that will always work
438                         window.addEventListener( "load", jQuery.ready, false );
439
440                 // If IE event model is used
441                 } else if ( document.attachEvent ) {
442                         // ensure firing before onload,
443                         // maybe late but safe also for iframes
444                         document.attachEvent("onreadystatechange", DOMContentLoaded);
445
446                         // A fallback to window.onload, that will always work
447                         window.attachEvent( "onload", jQuery.ready );
448
449                         // If IE and not a frame
450                         // continually check to see if the document is ready
451                         var toplevel = false;
452
453                         try {
454                                 toplevel = window.frameElement == null;
455                         } catch(e) {}
456
457                         if ( document.documentElement.doScroll && toplevel ) {
458                                 doScrollCheck();
459                         }
460                 }
461         },
462
463         // See test/unit/core.js for details concerning isFunction.
464         // Since version 1.3, DOM methods and functions like alert
465         // aren't supported. They return false on IE (#2968).
466         isFunction: function( obj ) {
467                 return jQuery.type(obj) === "function";
468         },
469
470         isArray: Array.isArray || function( obj ) {
471                 return jQuery.type(obj) === "array";
472         },
473
474         // A crude way of determining if an object is a window
475         isWindow: function( obj ) {
476                 return obj && typeof obj === "object" && "setInterval" in obj;
477         },
478
479         isNaN: function( obj ) {
480                 return obj == null || !rdigit.test( obj ) || isNaN( obj );
481         },
482
483         type: function( obj ) {
484                 return obj == null ?
485                         String( obj ) :
486                         class2type[ toString.call(obj) ] || "object";
487         },
488
489         isPlainObject: function( obj ) {
490                 // Must be an Object.
491                 // Because of IE, we also have to check the presence of the constructor property.
492                 // Make sure that DOM nodes and window objects don't pass through, as well
493                 if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
494                         return false;
495                 }
496
497                 // Not own constructor property must be Object
498                 if ( obj.constructor &&
499                         !hasOwn.call(obj, "constructor") &&
500                         !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
501                         return false;
502                 }
503
504                 // Own properties are enumerated firstly, so to speed up,
505                 // if last one is own, then all properties are own.
506
507                 var key;
508                 for ( key in obj ) {}
509
510                 return key === undefined || hasOwn.call( obj, key );
511         },
512
513         isEmptyObject: function( obj ) {
514                 for ( var name in obj ) {
515                         return false;
516                 }
517                 return true;
518         },
519
520         error: function( msg ) {
521                 throw msg;
522         },
523
524         parseJSON: function( data ) {
525                 if ( typeof data !== "string" || !data ) {
526                         return null;
527                 }
528
529                 // Make sure leading/trailing whitespace is removed (IE can't handle it)
530                 data = jQuery.trim( data );
531
532                 // Make sure the incoming data is actual JSON
533                 // Logic borrowed from http://json.org/json2.js
534                 if ( rvalidchars.test(data.replace(rvalidescape, "@")
535                         .replace(rvalidtokens, "]")
536                         .replace(rvalidbraces, "")) ) {
537
538                         // Try to use the native JSON parser first
539                         return window.JSON && window.JSON.parse ?
540                                 window.JSON.parse( data ) :
541                                 (new Function("return " + data))();
542
543                 } else {
544                         jQuery.error( "Invalid JSON: " + data );
545                 }
546         },
547
548         // Cross-browser xml parsing
549         // (xml & tmp used internally)
550         parseXML: function( data , xml , tmp ) {
551
552                 if ( window.DOMParser ) { // Standard
553                         tmp = new DOMParser();
554                         xml = tmp.parseFromString( data , "text/xml" );
555                 } else { // IE
556                         xml = new ActiveXObject( "Microsoft.XMLDOM" );
557                         xml.async = "false";
558                         xml.loadXML( data );
559                 }
560
561                 tmp = xml.documentElement;
562
563                 if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
564                         jQuery.error( "Invalid XML: " + data );
565                 }
566
567                 return xml;
568         },
569
570         noop: function() {},
571
572         // Evalulates a script in a global context
573         globalEval: function( data ) {
574                 if ( data && rnotwhite.test(data) ) {
575                         // Inspired by code by Andrea Giammarchi
576                         // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
577                         var head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement,
578                                 script = document.createElement( "script" );
579
580                         if ( jQuery.support.scriptEval() ) {
581                                 script.appendChild( document.createTextNode( data ) );
582                         } else {
583                                 script.text = data;
584                         }
585
586                         // Use insertBefore instead of appendChild to circumvent an IE6 bug.
587                         // This arises when a base node is used (#2709).
588                         head.insertBefore( script, head.firstChild );
589                         head.removeChild( script );
590                 }
591         },
592
593         nodeName: function( elem, name ) {
594                 return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
595         },
596
597         // args is for internal usage only
598         each: function( object, callback, args ) {
599                 var name, i = 0,
600                         length = object.length,
601                         isObj = length === undefined || jQuery.isFunction(object);
602
603                 if ( args ) {
604                         if ( isObj ) {
605                                 for ( name in object ) {
606                                         if ( callback.apply( object[ name ], args ) === false ) {
607                                                 break;
608                                         }
609                                 }
610                         } else {
611                                 for ( ; i < length; ) {
612                                         if ( callback.apply( object[ i++ ], args ) === false ) {
613                                                 break;
614                                         }
615                                 }
616                         }
617
618                 // A special, fast, case for the most common use of each
619                 } else {
620                         if ( isObj ) {
621                                 for ( name in object ) {
622                                         if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
623                                                 break;
624                                         }
625                                 }
626                         } else {
627                                 for ( var value = object[0];
628                                         i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
629                         }
630                 }
631
632                 return object;
633         },
634
635         // Use native String.trim function wherever possible
636         trim: trim ?
637                 function( text ) {
638                         return text == null ?
639                                 "" :
640                                 trim.call( text );
641                 } :
642
643                 // Otherwise use our own trimming functionality
644                 function( text ) {
645                         return text == null ?
646                                 "" :
647                                 text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
648                 },
649
650         // results is for internal usage only
651         makeArray: function( array, results ) {
652                 var ret = results || [];
653
654                 if ( array != null ) {
655                         // The window, strings (and functions) also have 'length'
656                         // The extra typeof function check is to prevent crashes
657                         // in Safari 2 (See: #3039)
658                         // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
659                         var type = jQuery.type(array);
660
661                         if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
662                                 push.call( ret, array );
663                         } else {
664                                 jQuery.merge( ret, array );
665                         }
666                 }
667
668                 return ret;
669         },
670
671         inArray: function( elem, array ) {
672                 if ( array.indexOf ) {
673                         return array.indexOf( elem );
674                 }
675
676                 for ( var i = 0, length = array.length; i < length; i++ ) {
677                         if ( array[ i ] === elem ) {
678                                 return i;
679                         }
680                 }
681
682                 return -1;
683         },
684
685         merge: function( first, second ) {
686                 var i = first.length,
687                         j = 0;
688
689                 if ( typeof second.length === "number" ) {
690                         for ( var l = second.length; j < l; j++ ) {
691                                 first[ i++ ] = second[ j ];
692                         }
693
694                 } else {
695                         while ( second[j] !== undefined ) {
696                                 first[ i++ ] = second[ j++ ];
697                         }
698                 }
699
700                 first.length = i;
701
702                 return first;
703         },
704
705         grep: function( elems, callback, inv ) {
706                 var ret = [], retVal;
707                 inv = !!inv;
708
709                 // Go through the array, only saving the items
710                 // that pass the validator function
711                 for ( var i = 0, length = elems.length; i < length; i++ ) {
712                         retVal = !!callback( elems[ i ], i );
713                         if ( inv !== retVal ) {
714                                 ret.push( elems[ i ] );
715                         }
716                 }
717
718                 return ret;
719         },
720
721         // arg is for internal usage only
722         map: function( elems, callback, arg ) {
723                 var ret = [], value;
724
725                 // Go through the array, translating each of the items to their
726                 // new value (or values).
727                 for ( var i = 0, length = elems.length; i < length; i++ ) {
728                         value = callback( elems[ i ], i, arg );
729
730                         if ( value != null ) {
731                                 ret[ ret.length ] = value;
732                         }
733                 }
734
735                 // Flatten any nested arrays
736                 return ret.concat.apply( [], ret );
737         },
738
739         // A global GUID counter for objects
740         guid: 1,
741
742         proxy: function( fn, proxy, thisObject ) {
743                 if ( arguments.length === 2 ) {
744                         if ( typeof proxy === "string" ) {
745                                 thisObject = fn;
746                                 fn = thisObject[ proxy ];
747                                 proxy = undefined;
748
749                         } else if ( proxy && !jQuery.isFunction( proxy ) ) {
750                                 thisObject = proxy;
751                                 proxy = undefined;
752                         }
753                 }
754
755                 if ( !proxy && fn ) {
756                         proxy = function() {
757                                 return fn.apply( thisObject || this, arguments );
758                         };
759                 }
760
761                 // Set the guid of unique handler to the same of original handler, so it can be removed
762                 if ( fn ) {
763                         proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
764                 }
765
766                 // So proxy can be declared as an argument
767                 return proxy;
768         },
769
770         // Mutifunctional method to get and set values to a collection
771         // The value/s can be optionally by executed if its a function
772         access: function( elems, key, value, exec, fn, pass ) {
773                 var length = elems.length;
774
775                 // Setting many attributes
776                 if ( typeof key === "object" ) {
777                         for ( var k in key ) {
778                                 jQuery.access( elems, k, key[k], exec, fn, value );
779                         }
780                         return elems;
781                 }
782
783                 // Setting one attribute
784                 if ( value !== undefined ) {
785                         // Optionally, function values get executed if exec is true
786                         exec = !pass && exec && jQuery.isFunction(value);
787
788                         for ( var i = 0; i < length; i++ ) {
789                                 fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
790                         }
791
792                         return elems;
793                 }
794
795                 // Getting an attribute
796                 return length ? fn( elems[0], key ) : undefined;
797         },
798
799         now: function() {
800                 return (new Date()).getTime();
801         },
802
803         // Create a simple deferred (one callbacks list)
804         _Deferred: function() {
805                 var // callbacks list
806                         callbacks = [],
807                         // stored [ context , args ]
808                         fired,
809                         // to avoid firing when already doing so
810                         firing,
811                         // flag to know if the deferred has been cancelled
812                         cancelled,
813                         // the deferred itself
814                         deferred  = {
815
816                                 // done( f1, f2, ...)
817                                 done: function() {
818                                         if ( !cancelled ) {
819                                                 var args = arguments,
820                                                         i,
821                                                         length,
822                                                         elem,
823                                                         type,
824                                                         _fired;
825                                                 if ( fired ) {
826                                                         _fired = fired;
827                                                         fired = 0;
828                                                 }
829                                                 for ( i = 0, length = args.length; i < length; i++ ) {
830                                                         elem = args[ i ];
831                                                         type = jQuery.type( elem );
832                                                         if ( type === "array" ) {
833                                                                 deferred.done.apply( deferred, elem );
834                                                         } else if ( type === "function" ) {
835                                                                 callbacks.push( elem );
836                                                         }
837                                                 }
838                                                 if ( _fired ) {
839                                                         deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
840                                                 }
841                                         }
842                                         return this;
843                                 },
844
845                                 // resolve with given context and args
846                                 resolveWith: function( context, args ) {
847                                         if ( !cancelled && !fired && !firing ) {
848                                                 firing = 1;
849                                                 try {
850                                                         while( callbacks[ 0 ] ) {
851                                                                 callbacks.shift().apply( context, args );
852                                                         }
853                                                 }
854                                                 finally {
855                                                         fired = [ context, args ];
856                                                         firing = 0;
857                                                 }
858                                         }
859                                         return this;
860                                 },
861
862                                 // resolve with this as context and given arguments
863                                 resolve: function() {
864                                         deferred.resolveWith( jQuery.isFunction( this.promise ) ? this.promise() : this, arguments );
865                                         return this;
866                                 },
867
868                                 // Has this deferred been resolved?
869                                 isResolved: function() {
870                                         return !!( firing || fired );
871                                 },
872
873                                 // Cancel
874                                 cancel: function() {
875                                         cancelled = 1;
876                                         callbacks = [];
877                                         return this;
878                                 }
879                         };
880
881                 return deferred;
882         },
883
884         // Full fledged deferred (two callbacks list)
885         Deferred: function( func ) {
886                 var deferred = jQuery._Deferred(),
887                         failDeferred = jQuery._Deferred(),
888                         promise,
889                         invert;
890                 // Add errorDeferred methods, then, promise and invert
891                 jQuery.extend( deferred, {
892                         then: function( doneCallbacks, failCallbacks ) {
893                                 deferred.done( doneCallbacks ).fail( failCallbacks );
894                                 return this;
895                         },
896                         fail: failDeferred.done,
897                         rejectWith: failDeferred.resolveWith,
898                         reject: failDeferred.resolve,
899                         isRejected: failDeferred.isResolved,
900                         // Get a promise for this deferred
901                         // If obj is provided, the promise aspect is added to the object
902                         promise: function( obj ) {
903                                 if ( obj == null ) {
904                                         if ( promise ) {
905                                                 return promise;
906                                         }
907                                         promise = obj = {};
908                                 }
909                                 for( var methodName in promiseMethods ) {
910                                         obj[ methodName ] = deferred[ methodName ];
911                                 }
912                                 return obj;
913                         },
914                         // Get the invert promise for this deferred
915                         // If obj is provided, the invert promise aspect is added to the object
916                         invert: function( obj ) {
917                                 if ( obj == null ) {
918                                         if ( invert ) {
919                                                 return invert;
920                                         }
921                                         invert = obj = {};
922                                 }
923                                 for( var methodName in promiseMethods ) {
924                                         obj[ methodName ] = promiseMethods[ methodName ] && deferred[ promiseMethods[methodName] ];
925                                 }
926                                 obj.then = invert.then || function( doneCallbacks, failCallbacks ) {
927                                         deferred.done( failCallbacks ).fail( doneCallbacks );
928                                         return this;
929                                 };
930                                 return obj;
931                         }
932                 } );
933                 // Make sure only one callback list will be used
934                 deferred.then( failDeferred.cancel, deferred.cancel );
935                 // Unexpose cancel
936                 delete deferred.cancel;
937                 // Call given func if any
938                 if ( func ) {
939                         func.call( deferred, deferred );
940                 }
941                 return deferred;
942         },
943
944         // Deferred helper
945         when: function( object ) {
946                 var args = arguments,
947                         length = args.length,
948                         deferred = length <= 1 && object && jQuery.isFunction( object.promise ) ?
949                                 object :
950                                 jQuery.Deferred(),
951                         promise = deferred.promise(),
952                         resolveArray;
953
954                 if ( length > 1 ) {
955                         resolveArray = new Array( length );
956                         jQuery.each( args, function( index, element ) {
957                                 jQuery.when( element ).then( function( value ) {
958                                         resolveArray[ index ] = arguments.length > 1 ? slice.call( arguments, 0 ) : value;
959                                         if( ! --length ) {
960                                                 deferred.resolveWith( promise, resolveArray );
961                                         }
962                                 }, deferred.reject );
963                         } );
964                 } else if ( deferred !== object ) {
965                         deferred.resolve( object );
966                 }
967                 return promise;
968         },
969
970         // Use of jQuery.browser is frowned upon.
971         // More details: http://docs.jquery.com/Utilities/jQuery.browser
972         uaMatch: function( ua ) {
973                 ua = ua.toLowerCase();
974
975                 var match = rwebkit.exec( ua ) ||
976                         ropera.exec( ua ) ||
977                         rmsie.exec( ua ) ||
978                         ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
979                         [];
980
981                 return { browser: match[1] || "", version: match[2] || "0" };
982         },
983
984         sub: function() {
985                 function jQuerySubclass( selector, context ) {
986                         return new jQuerySubclass.fn.init( selector, context );
987                 }
988                 jQuery.extend( true, jQuerySubclass, this );
989                 jQuerySubclass.superclass = this;
990                 jQuerySubclass.fn = jQuerySubclass.prototype = this();
991                 jQuerySubclass.fn.constructor = jQuerySubclass;
992                 jQuerySubclass.subclass = this.subclass;
993                 jQuerySubclass.fn.init = function init( selector, context ) {
994                         if ( context && context instanceof jQuery && !(context instanceof jQuerySubclass) ) {
995                                 context = jQuerySubclass(context);
996                         }
997
998                         return jQuery.fn.init.call( this, selector, context, rootjQuerySubclass );
999                 };
1000                 jQuerySubclass.fn.init.prototype = jQuerySubclass.fn;
1001                 var rootjQuerySubclass = jQuerySubclass(document);
1002                 return jQuerySubclass;
1003         },
1004
1005         browser: {}
1006 });
1007
1008 // Create readyList deferred
1009 readyList = jQuery._Deferred();
1010
1011 // Populate the class2type map
1012 jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
1013         class2type[ "[object " + name + "]" ] = name.toLowerCase();
1014 });
1015
1016 browserMatch = jQuery.uaMatch( userAgent );
1017 if ( browserMatch.browser ) {
1018         jQuery.browser[ browserMatch.browser ] = true;
1019         jQuery.browser.version = browserMatch.version;
1020 }
1021
1022 // Deprecated, use jQuery.browser.webkit instead
1023 if ( jQuery.browser.webkit ) {
1024         jQuery.browser.safari = true;
1025 }
1026
1027 if ( indexOf ) {
1028         jQuery.inArray = function( elem, array ) {
1029                 return indexOf.call( array, elem );
1030         };
1031 }
1032
1033 // IE doesn't match non-breaking spaces with \s
1034 if ( rnotwhite.test( "\xA0" ) ) {
1035         trimLeft = /^[\s\xA0]+/;
1036         trimRight = /[\s\xA0]+$/;
1037 }
1038
1039 // All jQuery objects should point back to these
1040 rootjQuery = jQuery(document);
1041
1042 // Cleanup functions for the document ready method
1043 if ( document.addEventListener ) {
1044         DOMContentLoaded = function() {
1045                 document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
1046                 jQuery.ready();
1047         };
1048
1049 } else if ( document.attachEvent ) {
1050         DOMContentLoaded = function() {
1051                 // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
1052                 if ( document.readyState === "complete" ) {
1053                         document.detachEvent( "onreadystatechange", DOMContentLoaded );
1054                         jQuery.ready();
1055                 }
1056         };
1057 }
1058
1059 // The DOM ready check for Internet Explorer
1060 function doScrollCheck() {
1061         if ( jQuery.isReady ) {
1062                 return;
1063         }
1064
1065         try {
1066                 // If IE is used, use the trick by Diego Perini
1067                 // http://javascript.nwbox.com/IEContentLoaded/
1068                 document.documentElement.doScroll("left");
1069         } catch(e) {
1070                 setTimeout( doScrollCheck, 1 );
1071                 return;
1072         }
1073
1074         // and execute any waiting functions
1075         jQuery.ready();
1076 }
1077
1078 // Expose jQuery to the global object
1079 return (window.jQuery = window.$ = jQuery);
1080
1081 })();