efb168306de86316036a563437e6eba5079c0091
[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         // Cross-browser xml parsing
551         // (xml & tmp used internally)
552         parseXML: function( data , xml , tmp ) {
553
554                 if ( window.DOMParser ) { // Standard
555                         tmp = new DOMParser();
556                         xml = tmp.parseFromString( data , "text/xml" );
557                 } else { // IE
558                         xml = new ActiveXObject( "Microsoft.XMLDOM" );
559                         xml.async = "false";
560                         xml.loadXML( data );
561                 }
562                 
563                 tmp = xml.documentElement;
564                 
565                 if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
566                         jQuery.error( "Invalid XML: " + data );
567                 }
568                 
569                 return xml;
570         },
571
572         noop: function() {},
573
574         // Evalulates a script in a global context
575         globalEval: function( data ) {
576                 if ( data && rnotwhite.test(data) ) {
577                         // Inspired by code by Andrea Giammarchi
578                         // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
579                         var head = document.getElementsByTagName("head")[0] || document.documentElement,
580                                 script = document.createElement("script");
581
582                         script.type = "text/javascript";
583
584                         if ( jQuery.support.scriptEval ) {
585                                 script.appendChild( document.createTextNode( data ) );
586                         } else {
587                                 script.text = data;
588                         }
589
590                         // Use insertBefore instead of appendChild to circumvent an IE6 bug.
591                         // This arises when a base node is used (#2709).
592                         head.insertBefore( script, head.firstChild );
593                         head.removeChild( script );
594                 }
595         },
596
597         nodeName: function( elem, name ) {
598                 return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
599         },
600
601         // args is for internal usage only
602         each: function( object, callback, args ) {
603                 var name, i = 0,
604                         length = object.length,
605                         isObj = length === undefined || jQuery.isFunction(object);
606
607                 if ( args ) {
608                         if ( isObj ) {
609                                 for ( name in object ) {
610                                         if ( callback.apply( object[ name ], args ) === false ) {
611                                                 break;
612                                         }
613                                 }
614                         } else {
615                                 for ( ; i < length; ) {
616                                         if ( callback.apply( object[ i++ ], args ) === false ) {
617                                                 break;
618                                         }
619                                 }
620                         }
621
622                 // A special, fast, case for the most common use of each
623                 } else {
624                         if ( isObj ) {
625                                 for ( name in object ) {
626                                         if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
627                                                 break;
628                                         }
629                                 }
630                         } else {
631                                 for ( var value = object[0];
632                                         i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
633                         }
634                 }
635
636                 return object;
637         },
638
639         // Use native String.trim function wherever possible
640         trim: trim ?
641                 function( text ) {
642                         return text == null ?
643                                 "" :
644                                 trim.call( text );
645                 } :
646
647                 // Otherwise use our own trimming functionality
648                 function( text ) {
649                         return text == null ?
650                                 "" :
651                                 text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
652                 },
653
654         // results is for internal usage only
655         makeArray: function( array, results ) {
656                 var ret = results || [];
657
658                 if ( array != null ) {
659                         // The window, strings (and functions) also have 'length'
660                         // The extra typeof function check is to prevent crashes
661                         // in Safari 2 (See: #3039)
662                         // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
663                         var type = jQuery.type(array);
664
665                         if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
666                                 push.call( ret, array );
667                         } else {
668                                 jQuery.merge( ret, array );
669                         }
670                 }
671
672                 return ret;
673         },
674
675         inArray: function( elem, array ) {
676                 if ( array.indexOf ) {
677                         return array.indexOf( elem );
678                 }
679
680                 for ( var i = 0, length = array.length; i < length; i++ ) {
681                         if ( array[ i ] === elem ) {
682                                 return i;
683                         }
684                 }
685
686                 return -1;
687         },
688
689         merge: function( first, second ) {
690                 var i = first.length,
691                         j = 0;
692
693                 if ( typeof second.length === "number" ) {
694                         for ( var l = second.length; j < l; j++ ) {
695                                 first[ i++ ] = second[ j ];
696                         }
697
698                 } else {
699                         while ( second[j] !== undefined ) {
700                                 first[ i++ ] = second[ j++ ];
701                         }
702                 }
703
704                 first.length = i;
705
706                 return first;
707         },
708
709         grep: function( elems, callback, inv ) {
710                 var ret = [], retVal;
711                 inv = !!inv;
712
713                 // Go through the array, only saving the items
714                 // that pass the validator function
715                 for ( var i = 0, length = elems.length; i < length; i++ ) {
716                         retVal = !!callback( elems[ i ], i );
717                         if ( inv !== retVal ) {
718                                 ret.push( elems[ i ] );
719                         }
720                 }
721
722                 return ret;
723         },
724
725         // arg is for internal usage only
726         map: function( elems, callback, arg ) {
727                 var ret = [], value;
728
729                 // Go through the array, translating each of the items to their
730                 // new value (or values).
731                 for ( var i = 0, length = elems.length; i < length; i++ ) {
732                         value = callback( elems[ i ], i, arg );
733
734                         if ( value != null ) {
735                                 ret[ ret.length ] = value;
736                         }
737                 }
738
739                 // Flatten any nested arrays
740                 return ret.concat.apply( [], ret );
741         },
742
743         // A global GUID counter for objects
744         guid: 1,
745
746         proxy: function( fn, proxy, thisObject ) {
747                 if ( arguments.length === 2 ) {
748                         if ( typeof proxy === "string" ) {
749                                 thisObject = fn;
750                                 fn = thisObject[ proxy ];
751                                 proxy = undefined;
752
753                         } else if ( proxy && !jQuery.isFunction( proxy ) ) {
754                                 thisObject = proxy;
755                                 proxy = undefined;
756                         }
757                 }
758
759                 if ( !proxy && fn ) {
760                         proxy = function() {
761                                 return fn.apply( thisObject || this, arguments );
762                         };
763                 }
764
765                 // Set the guid of unique handler to the same of original handler, so it can be removed
766                 if ( fn ) {
767                         proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
768                 }
769
770                 // So proxy can be declared as an argument
771                 return proxy;
772         },
773
774         // Mutifunctional method to get and set values to a collection
775         // The value/s can be optionally by executed if its a function
776         access: function( elems, key, value, exec, fn, pass ) {
777                 var length = elems.length;
778
779                 // Setting many attributes
780                 if ( typeof key === "object" ) {
781                         for ( var k in key ) {
782                                 jQuery.access( elems, k, key[k], exec, fn, value );
783                         }
784                         return elems;
785                 }
786
787                 // Setting one attribute
788                 if ( value !== undefined ) {
789                         // Optionally, function values get executed if exec is true
790                         exec = !pass && exec && jQuery.isFunction(value);
791
792                         for ( var i = 0; i < length; i++ ) {
793                                 fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
794                         }
795
796                         return elems;
797                 }
798
799                 // Getting an attribute
800                 return length ? fn( elems[0], key ) : undefined;
801         },
802
803         now: function() {
804                 return (new Date()).getTime();
805         },
806         
807         // Create a simple deferred (one callbacks list)
808         _Deferred: function() {
809                 
810                 var // callbacks list
811                         callbacks = [],
812                         // stored [ context , args ]
813                         fired,
814                         // to avoid firing when already doing so
815                         firing,
816                         // flag to know if the deferred has been cancelled
817                         cancelled,
818                         // the deferred itself
819                         deferred  = {
820                                 
821                                 // then( f1, f2, ...)
822                                 then: function () {
823                                         
824                                         if ( ! cancelled ) {
825                                                 
826                                                 var args = arguments,
827                                                         i,
828                                                         length,
829                                                         elem,
830                                                         type,
831                                                         _fired;
832                                                         
833                                                 if ( fired ) {
834                                                         _fired = fired;
835                                                         fired = 0;
836                                                 }
837                                                 
838                                                 for ( i = 0, length = args.length ; i < length ; i++ ) {
839                                                         elem = args[ i ];
840                                                         type = jQuery.type( elem );
841                                                         if ( type === "array" ) {
842                                                                 deferred.then.apply( deferred , elem );
843                                                         } else if ( type === "function" ) {
844                                                                 callbacks.push( elem );
845                                                         }
846                                                 }
847                                                 
848                                                 if ( _fired ) {
849                                                         deferred.fire( _fired[ 0 ] , _fired[ 1 ] );
850                                                 }
851                                         }
852                                         
853                                         return this;
854                                 },
855                                 
856                                 // resolve with given context and args
857                                 fire: function( context , args ) {
858                                         if ( ! cancelled && ! fired && ! firing ) {
859                                                 
860                                                 firing = 1;
861                                                 
862                                                 try {
863                                                         while( callbacks[ 0 ] ) {
864                                                                 callbacks.shift().apply( context , args );
865                                                         }
866                                                 }
867                                                 finally {
868                                                         fired = [ context , args ];
869                                                         firing = 0;
870                                                 }
871                                         }
872                                         return this;
873                                 },
874                                 
875                                 // resolve with this as context and given arguments
876                                 resolve: function() {
877                                         deferred.fire( this , arguments );
878                                         return this;
879                                 },
880                                 
881                                 // Has this deferred been resolved?
882                                 isResolved: function() {
883                                         return !!( firing || fired );
884                                 },
885                                 
886                                 // Cancel
887                                 cancel: function() {
888                                         cancelled = 1;
889                                         callbacks = [];
890                                         return this;
891                                 },
892                                 
893                                 // Has this deferred been cancelled?
894                                 isCancelled: function() {
895                                         return !!cancelled;
896                                 }
897                         };
898                 
899                 // Add the deferred marker
900                 deferred.then._ = deferredMarker;
901                 
902                 return deferred;
903         },
904         
905         // Full fledged deferred (two callbacks list)
906         // Typical success/error system
907         Deferred: function( func ) {
908                 
909                 var errorDeferred = jQuery._Deferred(),
910                         deferred = jQuery._Deferred(),
911                         successCancel = deferred.cancel;
912                         
913                 // Add errorDeferred methods and redefine cancel                        
914                 jQuery.extend( deferred , {
915
916                                 fail: errorDeferred.then,
917                                 fireReject: errorDeferred.fire,
918                                 reject: errorDeferred.resolve,
919                                 isRejected: errorDeferred.isResolved
920
921                 } );
922                 
923                 // Remove cancel related
924                 delete deferred.cancel;
925                 delete deferred.isCancelled;
926                 
927                 // Make sure only one callback list will be used
928                 deferred.then( errorDeferred.cancel ).fail( successCancel );
929                 
930                 // Call given func if any
931                 if ( func ) {
932                         func.call( deferred , deferred );
933                 }
934                 
935                 return deferred;
936         },
937
938         // Check if an object is a deferred
939         isDeferred: function( object , method ) {
940                 method = method || "then";
941                 return !!( object && object[ method ] && object[ method ]._ === deferredMarker );
942         },
943         
944         // Deferred helper
945         when: function( object , method ) {
946                 method = method || "then";
947                 object = jQuery.isDeferred( object , method ) ?
948                         object :
949                         jQuery.Deferred().resolve( object );
950                 object.fail = object.fail || function() { return this; };
951                 object[ method ] = object[ method ] || object.then;
952                 object.then = object.then || object[ method ];
953                 return object;
954         },
955
956         // Use of jQuery.browser is frowned upon.
957         // More details: http://docs.jquery.com/Utilities/jQuery.browser
958         uaMatch: function( ua ) {
959                 ua = ua.toLowerCase();
960
961                 var match = rwebkit.exec( ua ) ||
962                         ropera.exec( ua ) ||
963                         rmsie.exec( ua ) ||
964                         ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
965                         [];
966
967                 return { browser: match[1] || "", version: match[2] || "0" };
968         },
969
970         browser: {}
971 });
972
973 // Create readyList deferred
974 // also force $.fn.ready to be recognized as a defer
975 readyList = jQuery._Deferred();
976 jQuery.fn.ready._ = deferredMarker;
977
978 // Populate the class2type map
979 jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
980         class2type[ "[object " + name + "]" ] = name.toLowerCase();
981 });
982
983 browserMatch = jQuery.uaMatch( userAgent );
984 if ( browserMatch.browser ) {
985         jQuery.browser[ browserMatch.browser ] = true;
986         jQuery.browser.version = browserMatch.version;
987 }
988
989 // Deprecated, use jQuery.browser.webkit instead
990 if ( jQuery.browser.webkit ) {
991         jQuery.browser.safari = true;
992 }
993
994 if ( indexOf ) {
995         jQuery.inArray = function( elem, array ) {
996                 return indexOf.call( array, elem );
997         };
998 }
999
1000 // Verify that \s matches non-breaking spaces
1001 // (IE fails on this test)
1002 if ( !rwhite.test( "\xA0" ) ) {
1003         trimLeft = /^[\s\xA0]+/;
1004         trimRight = /[\s\xA0]+$/;
1005 }
1006
1007 // All jQuery objects should point back to these
1008 rootjQuery = jQuery(document);
1009
1010 // Cleanup functions for the document ready method
1011 if ( document.addEventListener ) {
1012         DOMContentLoaded = function() {
1013                 document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
1014                 jQuery.ready();
1015         };
1016
1017 } else if ( document.attachEvent ) {
1018         DOMContentLoaded = function() {
1019                 // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
1020                 if ( document.readyState === "complete" ) {
1021                         document.detachEvent( "onreadystatechange", DOMContentLoaded );
1022                         jQuery.ready();
1023                 }
1024         };
1025 }
1026
1027 // The DOM ready check for Internet Explorer
1028 function doScrollCheck() {
1029         if ( jQuery.isReady ) {
1030                 return;
1031         }
1032
1033         try {
1034                 // If IE is used, use the trick by Diego Perini
1035                 // http://javascript.nwbox.com/IEContentLoaded/
1036                 document.documentElement.doScroll("left");
1037         } catch(e) {
1038                 setTimeout( doScrollCheck, 1 );
1039                 return;
1040         }
1041
1042         // and execute any waiting functions
1043         jQuery.ready();
1044 }
1045
1046 // Expose jQuery as an Asynchronous Module
1047 if ( typeof define === "function" ) {
1048         define( "jquery", [], function () { return jQuery; } );
1049 }
1050
1051 // Expose jQuery to the global object
1052 return (window.jQuery = window.$ = jQuery);
1053
1054 })();