The context for 'body' should still be document, in this case.
[jquery.git] / src / core.js
1 // Define a local copy of jQuery
2 var jQuery = function( selector, context ) {
3                 // The jQuery object is actually just the init constructor 'enhanced'
4                 return new jQuery.fn.init( selector, context );
5         },
6
7         // Map over jQuery in case of overwrite
8         _jQuery = window.jQuery,
9
10         // Map over the $ in case of overwrite
11         _$ = window.$,
12
13         // Use the correct document accordingly with window argument (sandbox)
14         document = window.document,
15
16         // A central reference to the root jQuery(document)
17         rootjQuery,
18
19         // A simple way to check for HTML strings or ID strings
20         // (both of which we optimize for)
21         quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,
22
23         // Is it a simple selector
24         isSimple = /^.[^:#\[\.,]*$/,
25
26         // Check if a string has a non-whitespace character in it
27         rnotwhite = /\S/,
28
29         // Used for trimming whitespace
30         rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g,
31
32         // Match a standalone tag
33         rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
34
35         // Keep a UserAgent string for use with jQuery.browser
36         userAgent = navigator.userAgent,
37
38         // For matching the engine and version of the browser
39         browserMatch,
40         
41         // Has the ready events already been bound?
42         readyBound = false,
43         
44         // The functions to execute on DOM ready
45         readyList = [],
46
47         // The ready event handler
48         DOMContentLoaded,
49
50         // Save a reference to some core methods
51         toString = Object.prototype.toString,
52         hasOwnProperty = Object.prototype.hasOwnProperty,
53         push = Array.prototype.push,
54         slice = Array.prototype.slice,
55         indexOf = Array.prototype.indexOf;
56
57 jQuery.fn = jQuery.prototype = {
58         init: function( selector, context ) {
59                 var match, elem, ret, doc;
60
61                 // Handle $(""), $(null), or $(undefined)
62                 if ( !selector ) {
63                         return this;
64                 }
65
66                 // Handle $(DOMElement)
67                 if ( selector.nodeType ) {
68                         this.context = this[0] = selector;
69                         this.length = 1;
70                         return this;
71                 }
72                 
73                 // The body element only exists once, optimize finding it
74                 if ( selector === "body" && !context ) {
75                         this.context = document;
76                         this[0] = document.body;
77                         this.selector = "body";
78                         this.length = 1;
79                         return this;
80                 }
81
82                 // Handle HTML strings
83                 if ( typeof selector === "string" ) {
84                         // Are we dealing with HTML string or an ID?
85                         match = quickExpr.exec( selector );
86
87                         // Verify a match, and that no context was specified for #id
88                         if ( match && (match[1] || !context) ) {
89
90                                 // HANDLE: $(html) -> $(array)
91                                 if ( match[1] ) {
92                                         doc = (context ? context.ownerDocument || context : document);
93
94                                         // If a single string is passed in and it's a single tag
95                                         // just do a createElement and skip the rest
96                                         ret = rsingleTag.exec( selector );
97
98                                         if ( ret ) {
99                                                 if ( jQuery.isPlainObject( context ) ) {
100                                                         selector = [ document.createElement( ret[1] ) ];
101                                                         jQuery.fn.attr.call( selector, context, true );
102
103                                                 } else {
104                                                         selector = [ doc.createElement( ret[1] ) ];
105                                                 }
106
107                                         } else {
108                                                 ret = buildFragment( [ match[1] ], [ doc ] );
109                                                 selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
110                                         }
111                                         
112                                         return jQuery.merge( this, selector );
113                                         
114                                 // HANDLE: $("#id")
115                                 } else {
116                                         elem = document.getElementById( match[2] );
117
118                                         if ( elem ) {
119                                                 // Handle the case where IE and Opera return items
120                                                 // by name instead of ID
121                                                 if ( elem.id !== match[2] ) {
122                                                         return rootjQuery.find( selector );
123                                                 }
124
125                                                 // Otherwise, we inject the element directly into the jQuery object
126                                                 this.length = 1;
127                                                 this[0] = elem;
128                                         }
129
130                                         this.context = document;
131                                         this.selector = selector;
132                                         return this;
133                                 }
134
135                         // HANDLE: $("TAG")
136                         } else if ( !context && /^\w+$/.test( selector ) ) {
137                                 this.selector = selector;
138                                 this.context = document;
139                                 selector = document.getElementsByTagName( selector );
140                                 return jQuery.merge( this, selector );
141
142                         // HANDLE: $(expr, $(...))
143                         } else if ( !context || context.jquery ) {
144                                 return (context || rootjQuery).find( selector );
145
146                         // HANDLE: $(expr, context)
147                         // (which is just equivalent to: $(context).find(expr)
148                         } else {
149                                 return jQuery( context ).find( selector );
150                         }
151
152                 // HANDLE: $(function)
153                 // Shortcut for document ready
154                 } else if ( jQuery.isFunction( selector ) ) {
155                         return rootjQuery.ready( selector );
156                 }
157
158                 if (selector.selector !== undefined) {
159                         this.selector = selector.selector;
160                         this.context = selector.context;
161                 }
162
163                 return jQuery.makeArray( selector, this );
164         },
165
166         // Start with an empty selector
167         selector: "",
168
169         // The current version of jQuery being used
170         jquery: "@VERSION",
171
172         // The default length of a jQuery object is 0
173         length: 0,
174
175         // The number of elements contained in the matched element set
176         size: function() {
177                 return this.length;
178         },
179
180         toArray: function() {
181                 return slice.call( this, 0 );
182         },
183
184         // Get the Nth element in the matched element set OR
185         // Get the whole matched element set as a clean array
186         get: function( num ) {
187                 return num == null ?
188
189                         // Return a 'clean' array
190                         this.toArray() :
191
192                         // Return just the object
193                         ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
194         },
195
196         // Take an array of elements and push it onto the stack
197         // (returning the new matched element set)
198         pushStack: function( elems, name, selector ) {
199                 // Build a new jQuery matched element set
200                 var ret = jQuery( elems || null );
201
202                 // Add the old object onto the stack (as a reference)
203                 ret.prevObject = this;
204
205                 ret.context = this.context;
206
207                 if ( name === "find" ) {
208                         ret.selector = this.selector + (this.selector ? " " : "") + selector;
209                 } else if ( name ) {
210                         ret.selector = this.selector + "." + name + "(" + selector + ")";
211                 }
212
213                 // Return the newly-formed element set
214                 return ret;
215         },
216
217         // Force the current matched set of elements to become
218         // the specified array of elements (destroying the stack in the process)
219         // You should use pushStack() in order to do this, but maintain the stack
220         setArray: function( elems ) {
221                 // Resetting the length to 0, then using the native Array push
222                 // is a super-fast way to populate an object with array-like properties
223                 this.length = 0;
224                 push.apply( this, elems );
225
226                 return this;
227         },
228
229         // Execute a callback for every element in the matched set.
230         // (You can seed the arguments with an array of args, but this is
231         // only used internally.)
232         each: function( callback, args ) {
233                 return jQuery.each( this, callback, args );
234         },
235         
236         ready: function( fn ) {
237                 // Attach the listeners
238                 jQuery.bindReady();
239
240                 // If the DOM is already ready
241                 if ( jQuery.isReady ) {
242                         // Execute the function immediately
243                         fn.call( document, jQuery );
244
245                 // Otherwise, remember the function for later
246                 } else if ( readyList ) {
247                         // Add the function to the wait list
248                         readyList.push( fn );
249                 }
250
251                 return this;
252         },
253         
254         eq: function( i ) {
255                 return i === -1 ?
256                         this.slice( i ) :
257                         this.slice( i, +i + 1 );
258         },
259
260         first: function() {
261                 return this.eq( 0 );
262         },
263
264         last: function() {
265                 return this.eq( -1 );
266         },
267
268         slice: function() {
269                 return this.pushStack( slice.apply( this, arguments ),
270                         "slice", slice.call(arguments).join(",") );
271         },
272
273         map: function( callback ) {
274                 return this.pushStack( jQuery.map(this, function( elem, i ) {
275                         return callback.call( elem, i, elem );
276                 }));
277         },
278         
279         end: function() {
280                 return this.prevObject || jQuery(null);
281         },
282
283         // For internal use only.
284         // Behaves like an Array's method, not like a jQuery method.
285         push: push,
286         sort: [].sort,
287         splice: [].splice
288 };
289
290 // Give the init function the jQuery prototype for later instantiation
291 jQuery.fn.init.prototype = jQuery.fn;
292
293 jQuery.extend = jQuery.fn.extend = function() {
294         // copy reference to target object
295         var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
296
297         // Handle a deep copy situation
298         if ( typeof target === "boolean" ) {
299                 deep = target;
300                 target = arguments[1] || {};
301                 // skip the boolean and the target
302                 i = 2;
303         }
304
305         // Handle case when target is a string or something (possible in deep copy)
306         if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
307                 target = {};
308         }
309
310         // extend jQuery itself if only one argument is passed
311         if ( length === i ) {
312                 target = this;
313                 --i;
314         }
315
316         for ( ; i < length; i++ ) {
317                 // Only deal with non-null/undefined values
318                 if ( (options = arguments[ i ]) != null ) {
319                         // Extend the base object
320                         for ( name in options ) {
321                                 src = target[ name ];
322                                 copy = options[ name ];
323
324                                 // Prevent never-ending loop
325                                 if ( target === copy ) {
326                                         continue;
327                                 }
328
329                                 // Recurse if we're merging object literal values or arrays
330                                 if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) {
331                                         var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src
332                                                 : jQuery.isArray(copy) ? [] : {};
333
334                                         // Never move original objects, clone them
335                                         target[ name ] = jQuery.extend( deep, clone, copy );
336
337                                 // Don't bring in undefined values
338                                 } else if ( copy !== undefined ) {
339                                         target[ name ] = copy;
340                                 }
341                         }
342                 }
343         }
344
345         // Return the modified object
346         return target;
347 };
348
349 jQuery.extend({
350         noConflict: function( deep ) {
351                 window.$ = _$;
352
353                 if ( deep ) {
354                         window.jQuery = _jQuery;
355                 }
356
357                 return jQuery;
358         },
359         
360         // Is the DOM ready to be used? Set to true once it occurs.
361         isReady: false,
362         
363         // Handle when the DOM is ready
364         ready: function() {
365                 // Make sure that the DOM is not already loaded
366                 if ( !jQuery.isReady ) {
367                         // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
368                         if ( !document.body ) {
369                                 return setTimeout( jQuery.ready, 13 );
370                         }
371
372                         // Remember that the DOM is ready
373                         jQuery.isReady = true;
374
375                         // If there are functions bound, to execute
376                         if ( readyList ) {
377                                 // Execute all of them
378                                 var fn, i = 0;
379                                 while ( (fn = readyList[ i++ ]) ) {
380                                         fn.call( document, jQuery );
381                                 }
382
383                                 // Reset the list of functions
384                                 readyList = null;
385                         }
386
387                         // Trigger any bound ready events
388                         if ( jQuery.fn.triggerHandler ) {
389                                 jQuery( document ).triggerHandler( "ready" );
390                         }
391                 }
392         },
393         
394         bindReady: function() {
395                 if ( readyBound ) {
396                         return;
397                 }
398
399                 readyBound = true;
400
401                 // Catch cases where $(document).ready() is called after the
402                 // browser event has already occurred.
403                 if ( document.readyState === "complete" ) {
404                         return jQuery.ready();
405                 }
406
407                 // Mozilla, Opera and webkit nightlies currently support this event
408                 if ( document.addEventListener ) {
409                         // Use the handy event callback
410                         document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
411                         
412                         // A fallback to window.onload, that will always work
413                         window.addEventListener( "load", jQuery.ready, false );
414
415                 // If IE event model is used
416                 } else if ( document.attachEvent ) {
417                         // ensure firing before onload,
418                         // maybe late but safe also for iframes
419                         document.attachEvent("onreadystatechange", DOMContentLoaded);
420                         
421                         // A fallback to window.onload, that will always work
422                         window.attachEvent( "onload", jQuery.ready );
423
424                         // If IE and not a frame
425                         // continually check to see if the document is ready
426                         var toplevel = false;
427
428                         try {
429                                 toplevel = window.frameElement == null;
430                         } catch(e) {}
431
432                         if ( document.documentElement.doScroll && toplevel ) {
433                                 doScrollCheck();
434                         }
435                 }
436         },
437
438         // See test/unit/core.js for details concerning isFunction.
439         // Since version 1.3, DOM methods and functions like alert
440         // aren't supported. They return false on IE (#2968).
441         isFunction: function( obj ) {
442                 return toString.call(obj) === "[object Function]";
443         },
444
445         isArray: function( obj ) {
446                 return toString.call(obj) === "[object Array]";
447         },
448
449         isPlainObject: function( obj ) {
450                 // Must be an Object.
451                 // Because of IE, we also have to check the presence of the constructor property.
452                 // Make sure that DOM nodes and window objects don't pass through, as well
453                 if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) {
454                         return false;
455                 }
456                 
457                 // Not own constructor property must be Object
458                 if ( obj.constructor
459                         && !hasOwnProperty.call(obj, "constructor")
460                         && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) {
461                         return false;
462                 }
463                 
464                 // Own properties are enumerated firstly, so to speed up,
465                 // if last one is own, then all properties are own.
466         
467                 var key;
468                 for ( key in obj ) {}
469                 
470                 return key === undefined || hasOwnProperty.call( obj, key );
471         },
472
473         isEmptyObject: function( obj ) {
474                 for ( var name in obj ) {
475                         return false;
476                 }
477                 return true;
478         },
479         
480         error: function( msg ) {
481                 throw msg;
482         },
483         
484         parseJSON: function( data ) {
485                 if ( typeof data !== "string" || !data ) {
486                         return null;
487                 }
488                 
489                 // Make sure the incoming data is actual JSON
490                 // Logic borrowed from http://json.org/json2.js
491                 if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
492                         .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
493                         .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
494
495                         // Try to use the native JSON parser first
496                         return window.JSON && window.JSON.parse ?
497                                 window.JSON.parse( data ) :
498                                 (new Function("return " + data))();
499
500                 } else {
501                         jQuery.error( "Invalid JSON: " + data );
502                 }
503         },
504
505         noop: function() {},
506
507         // Evalulates a script in a global context
508         globalEval: function( data ) {
509                 if ( data && rnotwhite.test(data) ) {
510                         // Inspired by code by Andrea Giammarchi
511                         // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
512                         var head = document.getElementsByTagName("head")[0] || document.documentElement,
513                                 script = document.createElement("script");
514
515                         script.type = "text/javascript";
516
517                         if ( jQuery.support.scriptEval ) {
518                                 script.appendChild( document.createTextNode( data ) );
519                         } else {
520                                 script.text = data;
521                         }
522
523                         // Use insertBefore instead of appendChild to circumvent an IE6 bug.
524                         // This arises when a base node is used (#2709).
525                         head.insertBefore( script, head.firstChild );
526                         head.removeChild( script );
527                 }
528         },
529
530         nodeName: function( elem, name ) {
531                 return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
532         },
533
534         // args is for internal usage only
535         each: function( object, callback, args ) {
536                 var name, i = 0,
537                         length = object.length,
538                         isObj = length === undefined || jQuery.isFunction(object);
539
540                 if ( args ) {
541                         if ( isObj ) {
542                                 for ( name in object ) {
543                                         if ( callback.apply( object[ name ], args ) === false ) {
544                                                 break;
545                                         }
546                                 }
547                         } else {
548                                 for ( ; i < length; ) {
549                                         if ( callback.apply( object[ i++ ], args ) === false ) {
550                                                 break;
551                                         }
552                                 }
553                         }
554
555                 // A special, fast, case for the most common use of each
556                 } else {
557                         if ( isObj ) {
558                                 for ( name in object ) {
559                                         if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
560                                                 break;
561                                         }
562                                 }
563                         } else {
564                                 for ( var value = object[0];
565                                         i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
566                         }
567                 }
568
569                 return object;
570         },
571
572         trim: function( text ) {
573                 return (text || "").replace( rtrim, "" );
574         },
575
576         // results is for internal usage only
577         makeArray: function( array, results ) {
578                 var ret = results || [];
579
580                 if ( array != null ) {
581                         // The window, strings (and functions) also have 'length'
582                         // The extra typeof function check is to prevent crashes
583                         // in Safari 2 (See: #3039)
584                         if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) {
585                                 push.call( ret, array );
586                         } else {
587                                 jQuery.merge( ret, array );
588                         }
589                 }
590
591                 return ret;
592         },
593
594         inArray: function( elem, array ) {
595                 if ( array.indexOf ) {
596                         return array.indexOf( elem );
597                 }
598
599                 for ( var i = 0, length = array.length; i < length; i++ ) {
600                         if ( array[ i ] === elem ) {
601                                 return i;
602                         }
603                 }
604
605                 return -1;
606         },
607
608         merge: function( first, second ) {
609                 var i = first.length, j = 0;
610
611                 if ( typeof second.length === "number" ) {
612                         for ( var l = second.length; j < l; j++ ) {
613                                 first[ i++ ] = second[ j ];
614                         }
615                 
616                 } else {
617                         while ( second[j] !== undefined ) {
618                                 first[ i++ ] = second[ j++ ];
619                         }
620                 }
621
622                 first.length = i;
623
624                 return first;
625         },
626
627         grep: function( elems, callback, inv ) {
628                 var ret = [];
629
630                 // Go through the array, only saving the items
631                 // that pass the validator function
632                 for ( var i = 0, length = elems.length; i < length; i++ ) {
633                         if ( !inv !== !callback( elems[ i ], i ) ) {
634                                 ret.push( elems[ i ] );
635                         }
636                 }
637
638                 return ret;
639         },
640
641         // arg is for internal usage only
642         map: function( elems, callback, arg ) {
643                 var ret = [], value;
644
645                 // Go through the array, translating each of the items to their
646                 // new value (or values).
647                 for ( var i = 0, length = elems.length; i < length; i++ ) {
648                         value = callback( elems[ i ], i, arg );
649
650                         if ( value != null ) {
651                                 ret[ ret.length ] = value;
652                         }
653                 }
654
655                 return ret.concat.apply( [], ret );
656         },
657
658         // A global GUID counter for objects
659         guid: 1,
660
661         proxy: function( fn, proxy, thisObject ) {
662                 if ( arguments.length === 2 ) {
663                         if ( typeof proxy === "string" ) {
664                                 thisObject = fn;
665                                 fn = thisObject[ proxy ];
666                                 proxy = undefined;
667
668                         } else if ( proxy && !jQuery.isFunction( proxy ) ) {
669                                 thisObject = proxy;
670                                 proxy = undefined;
671                         }
672                 }
673
674                 if ( !proxy && fn ) {
675                         proxy = function() {
676                                 return fn.apply( thisObject || this, arguments );
677                         };
678                 }
679
680                 // Set the guid of unique handler to the same of original handler, so it can be removed
681                 if ( fn ) {
682                         proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
683                 }
684
685                 // So proxy can be declared as an argument
686                 return proxy;
687         },
688
689         // Use of jQuery.browser is frowned upon.
690         // More details: http://docs.jquery.com/Utilities/jQuery.browser
691         uaMatch: function( ua ) {
692                 ua = ua.toLowerCase();
693
694                 var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
695                         /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) ||
696                         /(msie) ([\w.]+)/.exec( ua ) ||
697                         !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) ||
698                         [];
699
700                 return { browser: match[1] || "", version: match[2] || "0" };
701         },
702
703         browser: {}
704 });
705
706 browserMatch = jQuery.uaMatch( userAgent );
707 if ( browserMatch.browser ) {
708         jQuery.browser[ browserMatch.browser ] = true;
709         jQuery.browser.version = browserMatch.version;
710 }
711
712 // Deprecated, use jQuery.browser.webkit instead
713 if ( jQuery.browser.webkit ) {
714         jQuery.browser.safari = true;
715 }
716
717 if ( indexOf ) {
718         jQuery.inArray = function( elem, array ) {
719                 return indexOf.call( array, elem );
720         };
721 }
722
723 // All jQuery objects should point back to these
724 rootjQuery = jQuery(document);
725
726 // Cleanup functions for the document ready method
727 if ( document.addEventListener ) {
728         DOMContentLoaded = function() {
729                 document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
730                 jQuery.ready();
731         };
732
733 } else if ( document.attachEvent ) {
734         DOMContentLoaded = function() {
735                 // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
736                 if ( document.readyState === "complete" ) {
737                         document.detachEvent( "onreadystatechange", DOMContentLoaded );
738                         jQuery.ready();
739                 }
740         };
741 }
742
743 // The DOM ready check for Internet Explorer
744 function doScrollCheck() {
745         if ( jQuery.isReady ) {
746                 return;
747         }
748
749         try {
750                 // If IE is used, use the trick by Diego Perini
751                 // http://javascript.nwbox.com/IEContentLoaded/
752                 document.documentElement.doScroll("left");
753         } catch( error ) {
754                 setTimeout( doScrollCheck, 1 );
755                 return;
756         }
757
758         // and execute any waiting functions
759         jQuery.ready();
760 }
761
762 function evalScript( i, elem ) {
763         if ( elem.src ) {
764                 jQuery.ajax({
765                         url: elem.src,
766                         async: false,
767                         dataType: "script"
768                 });
769         } else {
770                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
771         }
772
773         if ( elem.parentNode ) {
774                 elem.parentNode.removeChild( elem );
775         }
776 }
777
778 // Mutifunctional method to get and set values to a collection
779 // The value/s can be optionally by executed if its a function
780 function access( elems, key, value, exec, fn, pass ) {
781         var length = elems.length;
782         
783         // Setting many attributes
784         if ( typeof key === "object" ) {
785                 for ( var k in key ) {
786                         access( elems, k, key[k], exec, fn, value );
787                 }
788                 return elems;
789         }
790         
791         // Setting one attribute
792         if ( value !== undefined ) {
793                 // Optionally, function values get executed if exec is true
794                 exec = !pass && exec && jQuery.isFunction(value);
795                 
796                 for ( var i = 0; i < length; i++ ) {
797                         fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
798                 }
799                 
800                 return elems;
801         }
802         
803         // Getting an attribute
804         return length ? fn( elems[0], key ) : null;
805 }
806
807 function now() {
808         return (new Date).getTime();
809 }