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