Added an extra function check to prevent crashes in Safari 2. Fixes #3039.
[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 arguments.length === 0 ?
5                         rootjQuery :
6                         new jQuery.fn.init( selector, context );
7         },
8
9         // Map over jQuery in case of overwrite
10         _jQuery = window.jQuery,
11
12         // Map over the $ in case of overwrite
13         _$ = window.$,
14
15         // Use the correct document accordingly with window argument (sandbox)
16         document = window.document,
17
18         // A central reference to the root jQuery(document)
19         rootjQuery,
20
21         // A simple way to check for HTML strings or ID strings
22         // (both of which we optimize for)
23         quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,
24
25         // Is it a simple selector
26         isSimple = /^.[^:#\[\.,]*$/,
27
28         // Check if a string has a non-whitespace character in it
29         rnotwhite = /\S/,
30
31         // Used for trimming whitespace
32         rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g,
33
34         // Match a standalone tag
35         rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
36
37         // Keep a UserAgent string for use with jQuery.browser
38         userAgent = navigator.userAgent.toLowerCase(),
39
40         // Save a reference to some core methods
41         toString = Object.prototype.toString,
42         hasOwnProperty = Object.prototype.hasOwnProperty,
43         push = Array.prototype.push,
44         slice = Array.prototype.slice,
45         indexOf = Array.prototype.indexOf;
46
47 jQuery.fn = jQuery.prototype = {
48         init: function( selector, context ) {
49                 var match, elem, ret, doc;
50
51                 // Handle $(""), $(null), or $(undefined)
52                 if ( !selector ) {
53                         return this;
54                 }
55
56                 // Handle $(DOMElement)
57                 if ( selector.nodeType ) {
58                         this.context = this[0] = selector;
59                         this.length = 1;
60                         return this;
61                 }
62
63                 // Handle HTML strings
64                 if ( typeof selector === "string" ) {
65                         // Are we dealing with HTML string or an ID?
66                         match = quickExpr.exec( selector );
67
68                         // Verify a match, and that no context was specified for #id
69                         if ( match && (match[1] || !context) ) {
70
71                                 // HANDLE: $(html) -> $(array)
72                                 if ( match[1] ) {
73                                         doc = (context ? context.ownerDocument || context : document);
74
75                                         // If a single string is passed in and it's a single tag
76                                         // just do a createElement and skip the rest
77                                         ret = rsingleTag.exec( selector );
78
79                                         if ( ret ) {
80                                                 selector = [ doc.createElement( ret[1] ) ];
81
82                                         } else {
83                                                 ret = buildFragment( [ match[1] ], [ doc ] );
84                                                 selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
85                                         }
86
87                                 // HANDLE: $("#id")
88                                 } else {
89                                         elem = document.getElementById( match[2] );
90
91                                         if ( elem ) {
92                                                 // Handle the case where IE and Opera return items
93                                                 // by name instead of ID
94                                                 if ( elem.id !== match[2] ) {
95                                                         return rootjQuery.find( selector );
96                                                 }
97
98                                                 // Otherwise, we inject the element directly into the jQuery object
99                                                 this.length = 1;
100                                                 this[0] = elem;
101                                         }
102
103                                         this.context = document;
104                                         this.selector = selector;
105                                         return this;
106                                 }
107
108                         // HANDLE: $("TAG")
109                         } else if ( !context && /^\w+$/.test( selector ) ) {
110                                 this.selector = selector;
111                                 this.context = document;
112                                 selector = document.getElementsByTagName( selector );
113
114                         // HANDLE: $(expr, $(...))
115                         } else if ( !context || context.jquery ) {
116                                 return (context || rootjQuery).find( selector );
117
118                         // HANDLE: $(expr, context)
119                         // (which is just equivalent to: $(context).find(expr)
120                         } else {
121                                 return jQuery( context ).find( selector );
122                         }
123
124                 // HANDLE: $(function)
125                 // Shortcut for document ready
126                 } else if ( jQuery.isFunction( selector ) ) {
127                         return rootjQuery.ready( selector );
128                 }
129
130                 if (selector.selector !== undefined) {
131                         this.selector = selector.selector;
132                         this.context = selector.context;
133                 }
134
135                 return jQuery.isArray( selector ) ?
136                         this.setArray( selector ) :
137                         jQuery.makeArray( selector, this );
138         },
139
140         // Start with an empty selector
141         selector: "",
142
143         // The current version of jQuery being used
144         jquery: "@VERSION",
145
146         // The default length of a jQuery object is 0
147         length: 0,
148
149         // The number of elements contained in the matched element set
150         size: function() {
151                 return this.length;
152         },
153
154         toArray: function(){
155                 return slice.call( this, 0 );
156         },
157
158         // Get the Nth element in the matched element set OR
159         // Get the whole matched element set as a clean array
160         get: function( num ) {
161                 return num == null ?
162
163                         // Return a 'clean' array
164                         this.toArray() :
165
166                         // Return just the object
167                         ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
168         },
169
170         // Take an array of elements and push it onto the stack
171         // (returning the new matched element set)
172         pushStack: function( elems, name, selector ) {
173                 // Build a new jQuery matched element set
174                 var ret = jQuery( elems || null );
175
176                 // Add the old object onto the stack (as a reference)
177                 ret.prevObject = this;
178
179                 ret.context = this.context;
180
181                 if ( name === "find" ) {
182                         ret.selector = this.selector + (this.selector ? " " : "") + selector;
183                 } else if ( name ) {
184                         ret.selector = this.selector + "." + name + "(" + selector + ")";
185                 }
186
187                 // Return the newly-formed element set
188                 return ret;
189         },
190
191         // Force the current matched set of elements to become
192         // the specified array of elements (destroying the stack in the process)
193         // You should use pushStack() in order to do this, but maintain the stack
194         setArray: function( elems ) {
195                 // Resetting the length to 0, then using the native Array push
196                 // is a super-fast way to populate an object with array-like properties
197                 this.length = 0;
198                 push.apply( this, elems );
199
200                 return this;
201         },
202
203         // Execute a callback for every element in the matched set.
204         // (You can seed the arguments with an array of args, but this is
205         // only used internally.)
206         each: function( callback, args ) {
207                 return jQuery.each( this, callback, args );
208         },
209
210         // Determine the position of an element within
211         // the matched set of elements
212         index: function( elem ) {
213                 if ( !elem || typeof elem === "string" ) {
214                         return jQuery.inArray( this[0],
215                                 // If it receives a string, the selector is used
216                                 // If it receives nothing, the siblings are used
217                                 elem ? jQuery( elem ) : this.parent().children() );
218                 }
219                 // Locate the position of the desired element
220                 return jQuery.inArray(
221                         // If it receives a jQuery object, the first element is used
222                         elem.jquery ? elem[0] : elem, this );
223         },
224
225         is: function( selector ) {
226                 return !!selector && jQuery.filter( selector, this ).length > 0;
227         },
228
229         // For internal use only.
230         // Behaves like an Array's method, not like a jQuery method.
231         push: push,
232         sort: [].sort,
233         splice: [].splice
234 };
235
236 // Give the init function the jQuery prototype for later instantiation
237 jQuery.fn.init.prototype = jQuery.fn;
238
239 jQuery.extend = jQuery.fn.extend = function() {
240         // copy reference to target object
241         var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
242
243         // Handle a deep copy situation
244         if ( typeof target === "boolean" ) {
245                 deep = target;
246                 target = arguments[1] || {};
247                 // skip the boolean and the target
248                 i = 2;
249         }
250
251         // Handle case when target is a string or something (possible in deep copy)
252         if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
253                 target = {};
254         }
255
256         // extend jQuery itself if only one argument is passed
257         if ( length === i ) {
258                 target = this;
259                 --i;
260         }
261
262         for ( ; i < length; i++ ) {
263                 // Only deal with non-null/undefined values
264                 if ( (options = arguments[ i ]) != null ) {
265                         // Extend the base object
266                         for ( name in options ) {
267                                 src = target[ name ];
268                                 copy = options[ name ];
269
270                                 // Prevent never-ending loop
271                                 if ( target === copy ) {
272                                         continue;
273                                 }
274
275                                 // Recurse if we're merging object literal values
276                                 if ( deep && copy && jQuery.isPlainObject(copy) ) {
277                                         // Don't extend not object literals
278                                         var clone = src && jQuery.isPlainObject(src) ? src : {};
279
280                                         // Never move original objects, clone them
281                                         target[ name ] = jQuery.extend( deep, clone, copy );
282
283                                 // Don't bring in undefined values
284                                 } else if ( copy !== undefined ) {
285                                         target[ name ] = copy;
286                                 }
287                         }
288                 }
289         }
290
291         // Return the modified object
292         return target;
293 };
294
295 jQuery.extend({
296         noConflict: function( deep ) {
297                 window.$ = _$;
298
299                 if ( deep ) {
300                         window.jQuery = _jQuery;
301                 }
302
303                 return jQuery;
304         },
305
306         // See test/unit/core.js for details concerning isFunction.
307         // Since version 1.3, DOM methods and functions like alert
308         // aren't supported. They return false on IE (#2968).
309         isFunction: function( obj ) {
310                 return toString.call(obj) === "[object Function]";
311         },
312
313         isArray: function( obj ) {
314                 return toString.call(obj) === "[object Array]";
315         },
316
317         isPlainObject: function( obj ) {
318                 if ( toString.call(obj) !== "[object Object]" || typeof obj.nodeType === "number" ) {
319                         return false;
320                 }
321                 
322                 // not own constructor property must be Object
323                 if ( obj.constructor
324                   && !hasOwnProperty.call(obj, "constructor")
325                   && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) {
326                         return false;
327                 }
328                 
329                 //own properties are iterated firstly,
330                 //so to speed up, we can test last one if it is own or not
331         
332                 var key;
333                 for ( key in obj ) {}
334                 
335                 return key === undefined || hasOwnProperty.call( obj, key );
336         },
337
338         isEmptyObject: function( obj ) {
339                 for ( var name in obj ) {
340                         return false;
341                 }
342                 return true;
343         },
344
345         // Evalulates a script in a global context
346         globalEval: function( data ) {
347                 if ( data && rnotwhite.test(data) ) {
348                         // Inspired by code by Andrea Giammarchi
349                         // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
350                         var head = document.getElementsByTagName("head")[0] || document.documentElement,
351                                 script = document.createElement("script");
352
353                         script.type = "text/javascript";
354
355                         if ( jQuery.support.scriptEval ) {
356                                 script.appendChild( document.createTextNode( data ) );
357                         } else {
358                                 script.text = data;
359                         }
360
361                         // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
362                         // This arises when a base node is used (#2709).
363                         head.insertBefore( script, head.firstChild );
364                         head.removeChild( script );
365                 }
366         },
367
368         nodeName: function( elem, name ) {
369                 return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
370         },
371
372         // args is for internal usage only
373         each: function( object, callback, args ) {
374                 var name, i = 0,
375                         length = object.length,
376                         isObj = length === undefined || jQuery.isFunction(object);
377
378                 if ( args ) {
379                         if ( isObj ) {
380                                 for ( name in object ) {
381                                         if ( callback.apply( object[ name ], args ) === false ) {
382                                                 break;
383                                         }
384                                 }
385                         } else {
386                                 for ( ; i < length; ) {
387                                         if ( callback.apply( object[ i++ ], args ) === false ) {
388                                                 break;
389                                         }
390                                 }
391                         }
392
393                 // A special, fast, case for the most common use of each
394                 } else {
395                         if ( isObj ) {
396                                 for ( name in object ) {
397                                         if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
398                                                 break;
399                                         }
400                                 }
401                         } else {
402                                 for ( var value = object[0];
403                                         i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
404                         }
405                 }
406
407                 return object;
408         },
409
410         trim: function( text ) {
411                 return (text || "").replace( rtrim, "" );
412         },
413
414         // results is for internal usage only
415         makeArray: function( array, results ) {
416                 var ret = results || [];
417
418                 if ( array != null ) {
419                         // The window, strings (and functions) also have 'length'
420                         // The extra typeof function check is to prevent crashes
421                         // in Safari 2 (See: #3039)
422                         if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) {
423                                 push.call( ret, array );
424                         } else {
425                                 jQuery.merge( ret, array );
426                         }
427                 }
428
429                 return ret;
430         },
431
432         inArray: function( elem, array ) {
433                 if ( array.indexOf ) {
434                         return array.indexOf( elem );
435                 }
436
437                 for ( var i = 0, length = array.length; i < length; i++ ) {
438                         if ( array[ i ] === elem ) {
439                                 return i;
440                         }
441                 }
442
443                 return -1;
444         },
445
446         merge: function( first, second ) {
447                 var pos, i = second.length;
448
449                 // We have to get length this way when IE & Opera overwrite the length
450                 // expando of getElementsByTagName
451                 if ( i && i.nodeType ) {
452                         for ( i = 0; second[i]; ++i ) {}
453                 }
454                 
455                 pos = i + first.length;
456                 
457                 // Correct length for non Arrays
458                 first.length = pos;
459                 
460                 while ( i ) {
461                         first[ --pos ] = second[ --i ];
462                 }
463
464                 return first;
465         },
466
467         grep: function( elems, callback, inv ) {
468                 var ret = [];
469
470                 // Go through the array, only saving the items
471                 // that pass the validator function
472                 for ( var i = 0, length = elems.length; i < length; i++ ) {
473                         if ( !inv !== !callback( elems[ i ], i ) ) {
474                                 ret.push( elems[ i ] );
475                         }
476                 }
477
478                 return ret;
479         },
480
481         // arg is for internal usage only
482         map: function( elems, callback, arg ) {
483                 var ret = [], value;
484
485                 // Go through the array, translating each of the items to their
486                 // new value (or values).
487                 for ( var i = 0, length = elems.length; i < length; i++ ) {
488                         value = callback( elems[ i ], i, arg );
489
490                         if ( value != null ) {
491                                 ret[ ret.length ] = value;
492                         }
493                 }
494
495                 return ret.concat.apply( [], ret );
496         },
497
498         // Use of jQuery.browser is deprecated.
499         // It's included for backwards compatibility and plugins,
500         // although they should work to migrate away.
501         browser: {
502                 version: (/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/.exec(userAgent) || [0,'0'])[1],
503                 safari: /webkit/.test( userAgent ),
504                 opera: /opera/.test( userAgent ),
505                 msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
506                 mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
507         }
508 });
509
510 if ( indexOf ) {
511         jQuery.inArray = function( elem, array ) {
512                 return indexOf.call( array, elem );
513         };
514 }
515
516 // All jQuery objects should point back to these
517 rootjQuery = jQuery(document);
518
519 function evalScript( i, elem ) {
520         if ( elem.src ) {
521                 jQuery.ajax({
522                         url: elem.src,
523                         async: false,
524                         dataType: "script"
525                 });
526         } else {
527                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
528         }
529
530         if ( elem.parentNode ) {
531                 elem.parentNode.removeChild( elem );
532         }
533 }
534
535 // Mutifunctional method to get and set values to a collection
536 // The value/s can be optionally by executed if its a function
537 function access( elems, key, value, exec, fn ) {
538         var l = elems.length;
539         
540         // Setting many attributes
541         if ( typeof key === "object" ) {
542                         for (var k in key) {
543                                 access(elems, k, key[k], exec, fn);
544                         }
545                 return elems;
546         }
547         
548         // Setting one attribute
549         if (value !== undefined) {
550                 // Optionally, function values get executed if exec is true
551                 exec = exec && jQuery.isFunction(value);
552                 
553                 for (var i = 0; i < l; i++) {
554                         var elem = elems[i],
555                                 val = exec ? value.call(elem, i) : value;
556                         fn(elem, key, val);
557                 }
558                 return elems;
559         }
560         
561         // Getting an attribute
562         return l ? fn(elems[0], key) : null;
563 }
564
565 function now() {
566         return (new Date).getTime();
567 }