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