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