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