Remove the need for the internal setArray method, it was only really used by pushStac...
[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();
201
202                 if ( jQuery.isArray( elems ) ) {
203                         push.apply( ret, elems );
204                 
205                 } else {
206                         jQuery.merge( ret, elems );
207                 }
208
209                 // Add the old object onto the stack (as a reference)
210                 ret.prevObject = this;
211
212                 ret.context = this.context;
213
214                 if ( name === "find" ) {
215                         ret.selector = this.selector + (this.selector ? " " : "") + selector;
216                 } else if ( name ) {
217                         ret.selector = this.selector + "." + name + "(" + selector + ")";
218                 }
219
220                 // Return the newly-formed element set
221                 return ret;
222         },
223
224         // Execute a callback for every element in the matched set.
225         // (You can seed the arguments with an array of args, but this is
226         // only used internally.)
227         each: function( callback, args ) {
228                 return jQuery.each( this, callback, args );
229         },
230         
231         ready: function( fn ) {
232                 // Attach the listeners
233                 jQuery.bindReady();
234
235                 // If the DOM is already ready
236                 if ( jQuery.isReady ) {
237                         // Execute the function immediately
238                         fn.call( document, jQuery );
239
240                 // Otherwise, remember the function for later
241                 } else if ( readyList ) {
242                         // Add the function to the wait list
243                         readyList.push( fn );
244                 }
245
246                 return this;
247         },
248         
249         eq: function( i ) {
250                 return i === -1 ?
251                         this.slice( i ) :
252                         this.slice( i, +i + 1 );
253         },
254
255         first: function() {
256                 return this.eq( 0 );
257         },
258
259         last: function() {
260                 return this.eq( -1 );
261         },
262
263         slice: function() {
264                 return this.pushStack( slice.apply( this, arguments ),
265                         "slice", slice.call(arguments).join(",") );
266         },
267
268         map: function( callback ) {
269                 return this.pushStack( jQuery.map(this, function( elem, i ) {
270                         return callback.call( elem, i, elem );
271                 }));
272         },
273         
274         end: function() {
275                 return this.prevObject || jQuery(null);
276         },
277
278         // For internal use only.
279         // Behaves like an Array's method, not like a jQuery method.
280         push: push,
281         sort: [].sort,
282         splice: [].splice
283 };
284
285 // Give the init function the jQuery prototype for later instantiation
286 jQuery.fn.init.prototype = jQuery.fn;
287
288 jQuery.extend = jQuery.fn.extend = function() {
289         // copy reference to target object
290         var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
291
292         // Handle a deep copy situation
293         if ( typeof target === "boolean" ) {
294                 deep = target;
295                 target = arguments[1] || {};
296                 // skip the boolean and the target
297                 i = 2;
298         }
299
300         // Handle case when target is a string or something (possible in deep copy)
301         if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
302                 target = {};
303         }
304
305         // extend jQuery itself if only one argument is passed
306         if ( length === i ) {
307                 target = this;
308                 --i;
309         }
310
311         for ( ; i < length; i++ ) {
312                 // Only deal with non-null/undefined values
313                 if ( (options = arguments[ i ]) != null ) {
314                         // Extend the base object
315                         for ( name in options ) {
316                                 src = target[ name ];
317                                 copy = options[ name ];
318
319                                 // Prevent never-ending loop
320                                 if ( target === copy ) {
321                                         continue;
322                                 }
323
324                                 // Recurse if we're merging object literal values or arrays
325                                 if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) {
326                                         var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src
327                                                 : jQuery.isArray(copy) ? [] : {};
328
329                                         // Never move original objects, clone them
330                                         target[ name ] = jQuery.extend( deep, clone, copy );
331
332                                 // Don't bring in undefined values
333                                 } else if ( copy !== undefined ) {
334                                         target[ name ] = copy;
335                                 }
336                         }
337                 }
338         }
339
340         // Return the modified object
341         return target;
342 };
343
344 jQuery.extend({
345         noConflict: function( deep ) {
346                 window.$ = _$;
347
348                 if ( deep ) {
349                         window.jQuery = _jQuery;
350                 }
351
352                 return jQuery;
353         },
354         
355         // Is the DOM ready to be used? Set to true once it occurs.
356         isReady: false,
357         
358         // Handle when the DOM is ready
359         ready: function() {
360                 // Make sure that the DOM is not already loaded
361                 if ( !jQuery.isReady ) {
362                         // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
363                         if ( !document.body ) {
364                                 return setTimeout( jQuery.ready, 13 );
365                         }
366
367                         // Remember that the DOM is ready
368                         jQuery.isReady = true;
369
370                         // If there are functions bound, to execute
371                         if ( readyList ) {
372                                 // Execute all of them
373                                 var fn, i = 0;
374                                 while ( (fn = readyList[ i++ ]) ) {
375                                         fn.call( document, jQuery );
376                                 }
377
378                                 // Reset the list of functions
379                                 readyList = null;
380                         }
381
382                         // Trigger any bound ready events
383                         if ( jQuery.fn.triggerHandler ) {
384                                 jQuery( document ).triggerHandler( "ready" );
385                         }
386                 }
387         },
388         
389         bindReady: function() {
390                 if ( readyBound ) {
391                         return;
392                 }
393
394                 readyBound = true;
395
396                 // Catch cases where $(document).ready() is called after the
397                 // browser event has already occurred.
398                 if ( document.readyState === "complete" ) {
399                         return jQuery.ready();
400                 }
401
402                 // Mozilla, Opera and webkit nightlies currently support this event
403                 if ( document.addEventListener ) {
404                         // Use the handy event callback
405                         document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
406                         
407                         // A fallback to window.onload, that will always work
408                         window.addEventListener( "load", jQuery.ready, false );
409
410                 // If IE event model is used
411                 } else if ( document.attachEvent ) {
412                         // ensure firing before onload,
413                         // maybe late but safe also for iframes
414                         document.attachEvent("onreadystatechange", DOMContentLoaded);
415                         
416                         // A fallback to window.onload, that will always work
417                         window.attachEvent( "onload", jQuery.ready );
418
419                         // If IE and not a frame
420                         // continually check to see if the document is ready
421                         var toplevel = false;
422
423                         try {
424                                 toplevel = window.frameElement == null;
425                         } catch(e) {}
426
427                         if ( document.documentElement.doScroll && toplevel ) {
428                                 doScrollCheck();
429                         }
430                 }
431         },
432
433         // See test/unit/core.js for details concerning isFunction.
434         // Since version 1.3, DOM methods and functions like alert
435         // aren't supported. They return false on IE (#2968).
436         isFunction: function( obj ) {
437                 return toString.call(obj) === "[object Function]";
438         },
439
440         isArray: function( obj ) {
441                 return toString.call(obj) === "[object Array]";
442         },
443
444         isPlainObject: function( obj ) {
445                 // Must be an Object.
446                 // Because of IE, we also have to check the presence of the constructor property.
447                 // Make sure that DOM nodes and window objects don't pass through, as well
448                 if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) {
449                         return false;
450                 }
451                 
452                 // Not own constructor property must be Object
453                 if ( obj.constructor
454                         && !hasOwnProperty.call(obj, "constructor")
455                         && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) {
456                         return false;
457                 }
458                 
459                 // Own properties are enumerated firstly, so to speed up,
460                 // if last one is own, then all properties are own.
461         
462                 var key;
463                 for ( key in obj ) {}
464                 
465                 return key === undefined || hasOwnProperty.call( obj, key );
466         },
467
468         isEmptyObject: function( obj ) {
469                 for ( var name in obj ) {
470                         return false;
471                 }
472                 return true;
473         },
474         
475         error: function( msg ) {
476                 throw msg;
477         },
478         
479         parseJSON: function( data ) {
480                 if ( typeof data !== "string" || !data ) {
481                         return null;
482                 }
483                 
484                 // Make sure the incoming data is actual JSON
485                 // Logic borrowed from http://json.org/json2.js
486                 if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
487                         .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
488                         .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
489
490                         // Try to use the native JSON parser first
491                         return window.JSON && window.JSON.parse ?
492                                 window.JSON.parse( data ) :
493                                 (new Function("return " + data))();
494
495                 } else {
496                         jQuery.error( "Invalid JSON: " + data );
497                 }
498         },
499
500         noop: function() {},
501
502         // Evalulates a script in a global context
503         globalEval: function( data ) {
504                 if ( data && rnotwhite.test(data) ) {
505                         // Inspired by code by Andrea Giammarchi
506                         // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
507                         var head = document.getElementsByTagName("head")[0] || document.documentElement,
508                                 script = document.createElement("script");
509
510                         script.type = "text/javascript";
511
512                         if ( jQuery.support.scriptEval ) {
513                                 script.appendChild( document.createTextNode( data ) );
514                         } else {
515                                 script.text = data;
516                         }
517
518                         // Use insertBefore instead of appendChild to circumvent an IE6 bug.
519                         // This arises when a base node is used (#2709).
520                         head.insertBefore( script, head.firstChild );
521                         head.removeChild( script );
522                 }
523         },
524
525         nodeName: function( elem, name ) {
526                 return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
527         },
528
529         // args is for internal usage only
530         each: function( object, callback, args ) {
531                 var name, i = 0,
532                         length = object.length,
533                         isObj = length === undefined || jQuery.isFunction(object);
534
535                 if ( args ) {
536                         if ( isObj ) {
537                                 for ( name in object ) {
538                                         if ( callback.apply( object[ name ], args ) === false ) {
539                                                 break;
540                                         }
541                                 }
542                         } else {
543                                 for ( ; i < length; ) {
544                                         if ( callback.apply( object[ i++ ], args ) === false ) {
545                                                 break;
546                                         }
547                                 }
548                         }
549
550                 // A special, fast, case for the most common use of each
551                 } else {
552                         if ( isObj ) {
553                                 for ( name in object ) {
554                                         if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
555                                                 break;
556                                         }
557                                 }
558                         } else {
559                                 for ( var value = object[0];
560                                         i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
561                         }
562                 }
563
564                 return object;
565         },
566
567         trim: function( text ) {
568                 return (text || "").replace( rtrim, "" );
569         },
570
571         // results is for internal usage only
572         makeArray: function( array, results ) {
573                 var ret = results || [];
574
575                 if ( array != null ) {
576                         // The window, strings (and functions) also have 'length'
577                         // The extra typeof function check is to prevent crashes
578                         // in Safari 2 (See: #3039)
579                         if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) {
580                                 push.call( ret, array );
581                         } else {
582                                 jQuery.merge( ret, array );
583                         }
584                 }
585
586                 return ret;
587         },
588
589         inArray: function( elem, array ) {
590                 if ( array.indexOf ) {
591                         return array.indexOf( elem );
592                 }
593
594                 for ( var i = 0, length = array.length; i < length; i++ ) {
595                         if ( array[ i ] === elem ) {
596                                 return i;
597                         }
598                 }
599
600                 return -1;
601         },
602
603         merge: function( first, second ) {
604                 var i = first.length, j = 0;
605
606                 if ( typeof second.length === "number" ) {
607                         for ( var l = second.length; j < l; j++ ) {
608                                 first[ i++ ] = second[ j ];
609                         }
610                 
611                 } else {
612                         while ( second[j] !== undefined ) {
613                                 first[ i++ ] = second[ j++ ];
614                         }
615                 }
616
617                 first.length = i;
618
619                 return first;
620         },
621
622         grep: function( elems, callback, inv ) {
623                 var ret = [];
624
625                 // Go through the array, only saving the items
626                 // that pass the validator function
627                 for ( var i = 0, length = elems.length; i < length; i++ ) {
628                         if ( !inv !== !callback( elems[ i ], i ) ) {
629                                 ret.push( elems[ i ] );
630                         }
631                 }
632
633                 return ret;
634         },
635
636         // arg is for internal usage only
637         map: function( elems, callback, arg ) {
638                 var ret = [], value;
639
640                 // Go through the array, translating each of the items to their
641                 // new value (or values).
642                 for ( var i = 0, length = elems.length; i < length; i++ ) {
643                         value = callback( elems[ i ], i, arg );
644
645                         if ( value != null ) {
646                                 ret[ ret.length ] = value;
647                         }
648                 }
649
650                 return ret.concat.apply( [], ret );
651         },
652
653         // A global GUID counter for objects
654         guid: 1,
655
656         proxy: function( fn, proxy, thisObject ) {
657                 if ( arguments.length === 2 ) {
658                         if ( typeof proxy === "string" ) {
659                                 thisObject = fn;
660                                 fn = thisObject[ proxy ];
661                                 proxy = undefined;
662
663                         } else if ( proxy && !jQuery.isFunction( proxy ) ) {
664                                 thisObject = proxy;
665                                 proxy = undefined;
666                         }
667                 }
668
669                 if ( !proxy && fn ) {
670                         proxy = function() {
671                                 return fn.apply( thisObject || this, arguments );
672                         };
673                 }
674
675                 // Set the guid of unique handler to the same of original handler, so it can be removed
676                 if ( fn ) {
677                         proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
678                 }
679
680                 // So proxy can be declared as an argument
681                 return proxy;
682         },
683
684         // Use of jQuery.browser is frowned upon.
685         // More details: http://docs.jquery.com/Utilities/jQuery.browser
686         uaMatch: function( ua ) {
687                 ua = ua.toLowerCase();
688
689                 var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
690                         /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) ||
691                         /(msie) ([\w.]+)/.exec( ua ) ||
692                         !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) ||
693                         [];
694
695                 return { browser: match[1] || "", version: match[2] || "0" };
696         },
697
698         browser: {}
699 });
700
701 browserMatch = jQuery.uaMatch( userAgent );
702 if ( browserMatch.browser ) {
703         jQuery.browser[ browserMatch.browser ] = true;
704         jQuery.browser.version = browserMatch.version;
705 }
706
707 // Deprecated, use jQuery.browser.webkit instead
708 if ( jQuery.browser.webkit ) {
709         jQuery.browser.safari = true;
710 }
711
712 if ( indexOf ) {
713         jQuery.inArray = function( elem, array ) {
714                 return indexOf.call( array, elem );
715         };
716 }
717
718 // All jQuery objects should point back to these
719 rootjQuery = jQuery(document);
720
721 // Cleanup functions for the document ready method
722 if ( document.addEventListener ) {
723         DOMContentLoaded = function() {
724                 document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
725                 jQuery.ready();
726         };
727
728 } else if ( document.attachEvent ) {
729         DOMContentLoaded = function() {
730                 // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
731                 if ( document.readyState === "complete" ) {
732                         document.detachEvent( "onreadystatechange", DOMContentLoaded );
733                         jQuery.ready();
734                 }
735         };
736 }
737
738 // The DOM ready check for Internet Explorer
739 function doScrollCheck() {
740         if ( jQuery.isReady ) {
741                 return;
742         }
743
744         try {
745                 // If IE is used, use the trick by Diego Perini
746                 // http://javascript.nwbox.com/IEContentLoaded/
747                 document.documentElement.doScroll("left");
748         } catch( error ) {
749                 setTimeout( doScrollCheck, 1 );
750                 return;
751         }
752
753         // and execute any waiting functions
754         jQuery.ready();
755 }
756
757 function evalScript( i, elem ) {
758         if ( elem.src ) {
759                 jQuery.ajax({
760                         url: elem.src,
761                         async: false,
762                         dataType: "script"
763                 });
764         } else {
765                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
766         }
767
768         if ( elem.parentNode ) {
769                 elem.parentNode.removeChild( elem );
770         }
771 }
772
773 // Mutifunctional method to get and set values to a collection
774 // The value/s can be optionally by executed if its a function
775 function access( elems, key, value, exec, fn, pass ) {
776         var length = elems.length;
777         
778         // Setting many attributes
779         if ( typeof key === "object" ) {
780                 for ( var k in key ) {
781                         access( elems, k, key[k], exec, fn, value );
782                 }
783                 return elems;
784         }
785         
786         // Setting one attribute
787         if ( value !== undefined ) {
788                 // Optionally, function values get executed if exec is true
789                 exec = !pass && exec && jQuery.isFunction(value);
790                 
791                 for ( var i = 0; i < length; i++ ) {
792                         fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
793                 }
794                 
795                 return elems;
796         }
797         
798         // Getting an attribute
799         return length ? fn( elems[0], key ) : null;
800 }
801
802 function now() {
803         return (new Date).getTime();
804 }