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