]> ToastFreeware Gitweb - philipp/winterrodeln/wradmin.git/blob - wradmin_/wradmin/public/yui/datasource/datasource-debug.js
Intermediate rename to restructure package.
[philipp/winterrodeln/wradmin.git] / wradmin_ / wradmin / public / yui / datasource / datasource-debug.js
1 /*
2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
5 version: 2.7.0
6 */
7 (function () {
8
9 var lang   = YAHOO.lang,
10     util   = YAHOO.util,
11     Ev     = util.Event;
12
13 /**
14  * The DataSource utility provides a common configurable interface for widgets to
15  * access a variety of data, from JavaScript arrays to online database servers.
16  *
17  * @module datasource
18  * @requires yahoo, event
19  * @optional json, get, connection 
20  * @title DataSource Utility
21  */
22
23 /****************************************************************************/
24 /****************************************************************************/
25 /****************************************************************************/
26
27 /**
28  * Base class for the YUI DataSource utility.
29  *
30  * @namespace YAHOO.util
31  * @class YAHOO.util.DataSourceBase
32  * @constructor
33  * @param oLiveData {HTMLElement}  Pointer to live data.
34  * @param oConfigs {object} (optional) Object literal of configuration values.
35  */
36 util.DataSourceBase = function(oLiveData, oConfigs) {
37     if(oLiveData === null || oLiveData === undefined) {
38         YAHOO.log("Could not instantiate DataSource due to invalid live database",
39                 "error", this.toString());
40         return;
41     }
42     
43     this.liveData = oLiveData;
44     this._oQueue = {interval:null, conn:null, requests:[]};
45     this.responseSchema = {};   
46
47     // Set any config params passed in to override defaults
48     if(oConfigs && (oConfigs.constructor == Object)) {
49         for(var sConfig in oConfigs) {
50             if(sConfig) {
51                 this[sConfig] = oConfigs[sConfig];
52             }
53         }
54     }
55     
56     // Validate and initialize public configs
57     var maxCacheEntries = this.maxCacheEntries;
58     if(!lang.isNumber(maxCacheEntries) || (maxCacheEntries < 0)) {
59         maxCacheEntries = 0;
60     }
61
62     // Initialize interval tracker
63     this._aIntervals = [];
64
65     /////////////////////////////////////////////////////////////////////////////
66     //
67     // Custom Events
68     //
69     /////////////////////////////////////////////////////////////////////////////
70
71     /**
72      * Fired when a request is made to the local cache.
73      *
74      * @event cacheRequestEvent
75      * @param oArgs.request {Object} The request object.
76      * @param oArgs.callback {Object} The callback object.
77      * @param oArgs.caller {Object} (deprecated) Use callback.scope.
78      */
79     this.createEvent("cacheRequestEvent");
80
81     /**
82      * Fired when data is retrieved from the local cache.
83      *
84      * @event cacheResponseEvent
85      * @param oArgs.request {Object} The request object.
86      * @param oArgs.response {Object} The response object.
87      * @param oArgs.callback {Object} The callback object.
88      * @param oArgs.caller {Object} (deprecated) Use callback.scope.
89      */
90     this.createEvent("cacheResponseEvent");
91
92     /**
93      * Fired when a request is sent to the live data source.
94      *
95      * @event requestEvent
96      * @param oArgs.request {Object} The request object.
97      * @param oArgs.callback {Object} The callback object.
98      * @param oArgs.tId {Number} Transaction ID.     
99      * @param oArgs.caller {Object} (deprecated) Use callback.scope.
100      */
101     this.createEvent("requestEvent");
102
103     /**
104      * Fired when live data source sends response.
105      *
106      * @event responseEvent
107      * @param oArgs.request {Object} The request object.
108      * @param oArgs.response {Object} The raw response object.
109      * @param oArgs.callback {Object} The callback object.
110      * @param oArgs.tId {Number} Transaction ID.     
111      * @param oArgs.caller {Object} (deprecated) Use callback.scope.
112      */
113     this.createEvent("responseEvent");
114
115     /**
116      * Fired when response is parsed.
117      *
118      * @event responseParseEvent
119      * @param oArgs.request {Object} The request object.
120      * @param oArgs.response {Object} The parsed response object.
121      * @param oArgs.callback {Object} The callback object.
122      * @param oArgs.caller {Object} (deprecated) Use callback.scope.
123      */
124     this.createEvent("responseParseEvent");
125
126     /**
127      * Fired when response is cached.
128      *
129      * @event responseCacheEvent
130      * @param oArgs.request {Object} The request object.
131      * @param oArgs.response {Object} The parsed response object.
132      * @param oArgs.callback {Object} The callback object.
133      * @param oArgs.caller {Object} (deprecated) Use callback.scope.
134      */
135     this.createEvent("responseCacheEvent");
136     /**
137      * Fired when an error is encountered with the live data source.
138      *
139      * @event dataErrorEvent
140      * @param oArgs.request {Object} The request object.
141      * @param oArgs.callback {Object} The callback object.
142      * @param oArgs.caller {Object} (deprecated) Use callback.scope.
143      * @param oArgs.message {String} The error message.
144      */
145     this.createEvent("dataErrorEvent");
146
147     /**
148      * Fired when the local cache is flushed.
149      *
150      * @event cacheFlushEvent
151      */
152     this.createEvent("cacheFlushEvent");
153
154     var DS = util.DataSourceBase;
155     this._sName = "DataSource instance" + DS._nIndex;
156     DS._nIndex++;
157     YAHOO.log("DataSource initialized", "info", this.toString());
158 };
159
160 var DS = util.DataSourceBase;
161
162 lang.augmentObject(DS, {
163
164 /////////////////////////////////////////////////////////////////////////////
165 //
166 // DataSourceBase public constants
167 //
168 /////////////////////////////////////////////////////////////////////////////
169
170 /**
171  * Type is unknown.
172  *
173  * @property TYPE_UNKNOWN
174  * @type Number
175  * @final
176  * @default -1
177  */
178 TYPE_UNKNOWN : -1,
179
180 /**
181  * Type is a JavaScript Array.
182  *
183  * @property TYPE_JSARRAY
184  * @type Number
185  * @final
186  * @default 0
187  */
188 TYPE_JSARRAY : 0,
189
190 /**
191  * Type is a JavaScript Function.
192  *
193  * @property TYPE_JSFUNCTION
194  * @type Number
195  * @final
196  * @default 1
197  */
198 TYPE_JSFUNCTION : 1,
199
200 /**
201  * Type is hosted on a server via an XHR connection.
202  *
203  * @property TYPE_XHR
204  * @type Number
205  * @final
206  * @default 2
207  */
208 TYPE_XHR : 2,
209
210 /**
211  * Type is JSON.
212  *
213  * @property TYPE_JSON
214  * @type Number
215  * @final
216  * @default 3
217  */
218 TYPE_JSON : 3,
219
220 /**
221  * Type is XML.
222  *
223  * @property TYPE_XML
224  * @type Number
225  * @final
226  * @default 4
227  */
228 TYPE_XML : 4,
229
230 /**
231  * Type is plain text.
232  *
233  * @property TYPE_TEXT
234  * @type Number
235  * @final
236  * @default 5
237  */
238 TYPE_TEXT : 5,
239
240 /**
241  * Type is an HTML TABLE element. Data is parsed out of TR elements from all TBODY elements.
242  *
243  * @property TYPE_HTMLTABLE
244  * @type Number
245  * @final
246  * @default 6
247  */
248 TYPE_HTMLTABLE : 6,
249
250 /**
251  * Type is hosted on a server via a dynamic script node.
252  *
253  * @property TYPE_SCRIPTNODE
254  * @type Number
255  * @final
256  * @default 7
257  */
258 TYPE_SCRIPTNODE : 7,
259
260 /**
261  * Type is local.
262  *
263  * @property TYPE_LOCAL
264  * @type Number
265  * @final
266  * @default 8
267  */
268 TYPE_LOCAL : 8,
269
270 /**
271  * Error message for invalid dataresponses.
272  *
273  * @property ERROR_DATAINVALID
274  * @type String
275  * @final
276  * @default "Invalid data"
277  */
278 ERROR_DATAINVALID : "Invalid data",
279
280 /**
281  * Error message for null data responses.
282  *
283  * @property ERROR_DATANULL
284  * @type String
285  * @final
286  * @default "Null data"
287  */
288 ERROR_DATANULL : "Null data",
289
290 /////////////////////////////////////////////////////////////////////////////
291 //
292 // DataSourceBase private static properties
293 //
294 /////////////////////////////////////////////////////////////////////////////
295
296 /**
297  * Internal class variable to index multiple DataSource instances.
298  *
299  * @property DataSourceBase._nIndex
300  * @type Number
301  * @private
302  * @static
303  */
304 _nIndex : 0,
305
306 /**
307  * Internal class variable to assign unique transaction IDs.
308  *
309  * @property DataSourceBase._nTransactionId
310  * @type Number
311  * @private
312  * @static
313  */
314 _nTransactionId : 0,
315
316 /////////////////////////////////////////////////////////////////////////////
317 //
318 // DataSourceBase public static methods
319 //
320 /////////////////////////////////////////////////////////////////////////////
321
322 /**
323  * Executes a configured callback.  For object literal callbacks, the third
324  * param determines whether to execute the success handler or failure handler.
325  *  
326  * @method issueCallback
327  * @param callback {Function|Object} the callback to execute
328  * @param params {Array} params to be passed to the callback method
329  * @param error {Boolean} whether an error occurred
330  * @param scope {Object} the scope from which to execute the callback
331  * (deprecated - use an object literal callback)
332  * @static     
333  */
334 issueCallback : function (callback,params,error,scope) {
335     if (lang.isFunction(callback)) {
336         callback.apply(scope, params);
337     } else if (lang.isObject(callback)) {
338         scope = callback.scope || scope || window;
339         var callbackFunc = callback.success;
340         if (error) {
341             callbackFunc = callback.failure;
342         }
343         if (callbackFunc) {
344             callbackFunc.apply(scope, params.concat([callback.argument]));
345         }
346     }
347 },
348
349 /**
350  * Converts data to type String.
351  *
352  * @method DataSourceBase.parseString
353  * @param oData {String | Number | Boolean | Date | Array | Object} Data to parse.
354  * The special values null and undefined will return null.
355  * @return {String} A string, or null.
356  * @static
357  */
358 parseString : function(oData) {
359     // Special case null and undefined
360     if(!lang.isValue(oData)) {
361         return null;
362     }
363     
364     //Convert to string
365     var string = oData + "";
366
367     // Validate
368     if(lang.isString(string)) {
369         return string;
370     }
371     else {
372         YAHOO.log("Could not convert data " + lang.dump(oData) + " to type String", "warn", this.toString());
373         return null;
374     }
375 },
376
377 /**
378  * Converts data to type Number.
379  *
380  * @method DataSourceBase.parseNumber
381  * @param oData {String | Number | Boolean} Data to convert. Note, the following
382  * values return as null: null, undefined, NaN, "". 
383  * @return {Number} A number, or null.
384  * @static
385  */
386 parseNumber : function(oData) {
387     if(!lang.isValue(oData) || (oData === "")) {
388         return null;
389     }
390
391     //Convert to number
392     var number = oData * 1;
393     
394     // Validate
395     if(lang.isNumber(number)) {
396         return number;
397     }
398     else {
399         YAHOO.log("Could not convert data " + lang.dump(oData) + " to type Number", "warn", this.toString());
400         return null;
401     }
402 },
403 // Backward compatibility
404 convertNumber : function(oData) {
405     YAHOO.log("The method YAHOO.util.DataSourceBase.convertNumber() has been" +
406     " deprecated in favor of YAHOO.util.DataSourceBase.parseNumber()", "warn",
407     this.toString());
408     return DS.parseNumber(oData);
409 },
410
411 /**
412  * Converts data to type Date.
413  *
414  * @method DataSourceBase.parseDate
415  * @param oData {Date | String | Number} Data to convert.
416  * @return {Date} A Date instance.
417  * @static
418  */
419 parseDate : function(oData) {
420     var date = null;
421     
422     //Convert to date
423     if(!(oData instanceof Date)) {
424         date = new Date(oData);
425     }
426     else {
427         return oData;
428     }
429     
430     // Validate
431     if(date instanceof Date) {
432         return date;
433     }
434     else {
435         YAHOO.log("Could not convert data " + lang.dump(oData) + " to type Date", "warn", this.toString());
436         return null;
437     }
438 },
439 // Backward compatibility
440 convertDate : function(oData) {
441     YAHOO.log("The method YAHOO.util.DataSourceBase.convertDate() has been" +
442     " deprecated in favor of YAHOO.util.DataSourceBase.parseDate()", "warn",
443     this.toString());
444     return DS.parseDate(oData);
445 }
446
447 });
448
449 // Done in separate step so referenced functions are defined.
450 /**
451  * Data parsing functions.
452  * @property DataSource.Parser
453  * @type Object
454  * @static
455  */
456 DS.Parser = {
457     string   : DS.parseString,
458     number   : DS.parseNumber,
459     date     : DS.parseDate
460 };
461
462 // Prototype properties and methods
463 DS.prototype = {
464
465 /////////////////////////////////////////////////////////////////////////////
466 //
467 // DataSourceBase private properties
468 //
469 /////////////////////////////////////////////////////////////////////////////
470
471 /**
472  * Name of DataSource instance.
473  *
474  * @property _sName
475  * @type String
476  * @private
477  */
478 _sName : null,
479
480 /**
481  * Local cache of data result object literals indexed chronologically.
482  *
483  * @property _aCache
484  * @type Object[]
485  * @private
486  */
487 _aCache : null,
488
489 /**
490  * Local queue of request connections, enabled if queue needs to be managed.
491  *
492  * @property _oQueue
493  * @type Object
494  * @private
495  */
496 _oQueue : null,
497
498 /**
499  * Array of polling interval IDs that have been enabled, needed to clear all intervals.
500  *
501  * @property _aIntervals
502  * @type Array
503  * @private
504  */
505 _aIntervals : null,
506
507 /////////////////////////////////////////////////////////////////////////////
508 //
509 // DataSourceBase public properties
510 //
511 /////////////////////////////////////////////////////////////////////////////
512
513 /**
514  * Max size of the local cache.  Set to 0 to turn off caching.  Caching is
515  * useful to reduce the number of server connections.  Recommended only for data
516  * sources that return comprehensive results for queries or when stale data is
517  * not an issue.
518  *
519  * @property maxCacheEntries
520  * @type Number
521  * @default 0
522  */
523 maxCacheEntries : 0,
524
525  /**
526  * Pointer to live database.
527  *
528  * @property liveData
529  * @type Object
530  */
531 liveData : null,
532
533 /**
534  * Where the live data is held:
535  * 
536  * <dl>  
537  *    <dt>TYPE_UNKNOWN</dt>
538  *    <dt>TYPE_LOCAL</dt>
539  *    <dt>TYPE_XHR</dt>
540  *    <dt>TYPE_SCRIPTNODE</dt>
541  *    <dt>TYPE_JSFUNCTION</dt>
542  * </dl> 
543  *  
544  * @property dataType
545  * @type Number
546  * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN
547  *
548  */
549 dataType : DS.TYPE_UNKNOWN,
550
551 /**
552  * Format of response:
553  *  
554  * <dl>  
555  *    <dt>TYPE_UNKNOWN</dt>
556  *    <dt>TYPE_JSARRAY</dt>
557  *    <dt>TYPE_JSON</dt>
558  *    <dt>TYPE_XML</dt>
559  *    <dt>TYPE_TEXT</dt>
560  *    <dt>TYPE_HTMLTABLE</dt> 
561  * </dl> 
562  *
563  * @property responseType
564  * @type Number
565  * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN
566  */
567 responseType : DS.TYPE_UNKNOWN,
568
569 /**
570  * Response schema object literal takes a combination of the following properties:
571  *
572  * <dl>
573  * <dt>resultsList</dt> <dd>Pointer to array of tabular data</dd>
574  * <dt>resultNode</dt> <dd>Pointer to node name of row data (XML data only)</dd>
575  * <dt>recordDelim</dt> <dd>Record delimiter (text data only)</dd>
576  * <dt>fieldDelim</dt> <dd>Field delimiter (text data only)</dd>
577  * <dt>fields</dt> <dd>Array of field names (aka keys), or array of object literals
578  * such as: {key:"fieldname",parser:YAHOO.util.DataSourceBase.parseDate}</dd>
579  * <dt>metaFields</dt> <dd>Object literal of keys to include in the oParsedResponse.meta collection</dd>
580  * <dt>metaNode</dt> <dd>Name of the node under which to search for meta information in XML response data</dd>
581  * </dl>
582  *
583  * @property responseSchema
584  * @type Object
585  */
586 responseSchema : null,
587
588 /**
589  * Additional arguments passed to the JSON parse routine.  The JSON string
590  * is the assumed first argument (where applicable).  This property is not
591  * set by default, but the parse methods will use it if present.
592  *
593  * @property parseJSONArgs
594  * @type {MIXED|Array} If an Array, contents are used as individual arguments.
595  *                     Otherwise, value is used as an additional argument.
596  */
597 // property intentionally undefined
598  
599 /////////////////////////////////////////////////////////////////////////////
600 //
601 // DataSourceBase public methods
602 //
603 /////////////////////////////////////////////////////////////////////////////
604
605 /**
606  * Public accessor to the unique name of the DataSource instance.
607  *
608  * @method toString
609  * @return {String} Unique name of the DataSource instance.
610  */
611 toString : function() {
612     return this._sName;
613 },
614
615 /**
616  * Overridable method passes request to cache and returns cached response if any,
617  * refreshing the hit in the cache as the newest item. Returns null if there is
618  * no cache hit.
619  *
620  * @method getCachedResponse
621  * @param oRequest {Object} Request object.
622  * @param oCallback {Object} Callback object.
623  * @param oCaller {Object} (deprecated) Use callback object.
624  * @return {Object} Cached response object or null.
625  */
626 getCachedResponse : function(oRequest, oCallback, oCaller) {
627     var aCache = this._aCache;
628
629     // If cache is enabled...
630     if(this.maxCacheEntries > 0) {        
631         // Initialize local cache
632         if(!aCache) {
633             this._aCache = [];
634             YAHOO.log("Cache initialized", "info", this.toString());
635         }
636         // Look in local cache
637         else {
638             var nCacheLength = aCache.length;
639             if(nCacheLength > 0) {
640                 var oResponse = null;
641                 this.fireEvent("cacheRequestEvent", {request:oRequest,callback:oCallback,caller:oCaller});
642         
643                 // Loop through each cached element
644                 for(var i = nCacheLength-1; i >= 0; i--) {
645                     var oCacheElem = aCache[i];
646         
647                     // Defer cache hit logic to a public overridable method
648                     if(this.isCacheHit(oRequest,oCacheElem.request)) {
649                         // The cache returned a hit!
650                         // Grab the cached response
651                         oResponse = oCacheElem.response;
652                         this.fireEvent("cacheResponseEvent", {request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});
653                         
654                         // Refresh the position of the cache hit
655                         if(i < nCacheLength-1) {
656                             // Remove element from its original location
657                             aCache.splice(i,1);
658                             // Add as newest
659                             this.addToCache(oRequest, oResponse);
660                             YAHOO.log("Refreshed cache position of the response for \"" +  oRequest + "\"", "info", this.toString());
661                         }
662                         
663                         // Add a cache flag
664                         oResponse.cached = true;
665                         break;
666                     }
667                 }
668                 YAHOO.log("The cached response for \"" + lang.dump(oRequest) +
669                         "\" is " + lang.dump(oResponse), "info", this.toString());
670                 return oResponse;
671             }
672         }
673     }
674     else if(aCache) {
675         this._aCache = null;
676         YAHOO.log("Cache destroyed", "info", this.toString());
677     }
678     return null;
679 },
680
681 /**
682  * Default overridable method matches given request to given cached request.
683  * Returns true if is a hit, returns false otherwise.  Implementers should
684  * override this method to customize the cache-matching algorithm.
685  *
686  * @method isCacheHit
687  * @param oRequest {Object} Request object.
688  * @param oCachedRequest {Object} Cached request object.
689  * @return {Boolean} True if given request matches cached request, false otherwise.
690  */
691 isCacheHit : function(oRequest, oCachedRequest) {
692     return (oRequest === oCachedRequest);
693 },
694
695 /**
696  * Adds a new item to the cache. If cache is full, evicts the stalest item
697  * before adding the new item.
698  *
699  * @method addToCache
700  * @param oRequest {Object} Request object.
701  * @param oResponse {Object} Response object to cache.
702  */
703 addToCache : function(oRequest, oResponse) {
704     var aCache = this._aCache;
705     if(!aCache) {
706         return;
707     }
708
709     // If the cache is full, make room by removing stalest element (index=0)
710     while(aCache.length >= this.maxCacheEntries) {
711         aCache.shift();
712     }
713
714     // Add to cache in the newest position, at the end of the array
715     var oCacheElem = {request:oRequest,response:oResponse};
716     aCache[aCache.length] = oCacheElem;
717     this.fireEvent("responseCacheEvent", {request:oRequest,response:oResponse});
718     YAHOO.log("Cached the response for \"" +  oRequest + "\"", "info", this.toString());
719 },
720
721 /**
722  * Flushes cache.
723  *
724  * @method flushCache
725  */
726 flushCache : function() {
727     if(this._aCache) {
728         this._aCache = [];
729         this.fireEvent("cacheFlushEvent");
730         YAHOO.log("Flushed the cache", "info", this.toString());
731     }
732 },
733
734 /**
735  * Sets up a polling mechanism to send requests at set intervals and forward
736  * responses to given callback.
737  *
738  * @method setInterval
739  * @param nMsec {Number} Length of interval in milliseconds.
740  * @param oRequest {Object} Request object.
741  * @param oCallback {Function} Handler function to receive the response.
742  * @param oCaller {Object} (deprecated) Use oCallback.scope.
743  * @return {Number} Interval ID.
744  */
745 setInterval : function(nMsec, oRequest, oCallback, oCaller) {
746     if(lang.isNumber(nMsec) && (nMsec >= 0)) {
747         YAHOO.log("Enabling polling to live data for \"" + oRequest + "\" at interval " + nMsec, "info", this.toString());
748         var oSelf = this;
749         var nId = setInterval(function() {
750             oSelf.makeConnection(oRequest, oCallback, oCaller);
751         }, nMsec);
752         this._aIntervals.push(nId);
753         return nId;
754     }
755     else {
756         YAHOO.log("Could not enable polling to live data for \"" + oRequest + "\" at interval " + nMsec, "info", this.toString());
757     }
758 },
759
760 /**
761  * Disables polling mechanism associated with the given interval ID.
762  *
763  * @method clearInterval
764  * @param nId {Number} Interval ID.
765  */
766 clearInterval : function(nId) {
767     // Remove from tracker if there
768     var tracker = this._aIntervals || [];
769     for(var i=tracker.length-1; i>-1; i--) {
770         if(tracker[i] === nId) {
771             tracker.splice(i,1);
772             clearInterval(nId);
773         }
774     }
775 },
776
777 /**
778  * Disables all known polling intervals.
779  *
780  * @method clearAllIntervals
781  */
782 clearAllIntervals : function() {
783     var tracker = this._aIntervals || [];
784     for(var i=tracker.length-1; i>-1; i--) {
785         clearInterval(tracker[i]);
786     }
787     tracker = [];
788 },
789
790 /**
791  * First looks for cached response, then sends request to live data. The
792  * following arguments are passed to the callback function:
793  *     <dl>
794  *     <dt><code>oRequest</code></dt>
795  *     <dd>The same value that was passed in as the first argument to sendRequest.</dd>
796  *     <dt><code>oParsedResponse</code></dt>
797  *     <dd>An object literal containing the following properties:
798  *         <dl>
799  *         <dt><code>tId</code></dt>
800  *         <dd>Unique transaction ID number.</dd>
801  *         <dt><code>results</code></dt>
802  *         <dd>Schema-parsed data results.</dd>
803  *         <dt><code>error</code></dt>
804  *         <dd>True in cases of data error.</dd>
805  *         <dt><code>cached</code></dt>
806  *         <dd>True when response is returned from DataSource cache.</dd> 
807  *         <dt><code>meta</code></dt>
808  *         <dd>Schema-parsed meta data.</dd>
809  *         </dl>
810  *     <dt><code>oPayload</code></dt>
811  *     <dd>The same value as was passed in as <code>argument</code> in the oCallback object literal.</dd>
812  *     </dl> 
813  *
814  * @method sendRequest
815  * @param oRequest {Object} Request object.
816  * @param oCallback {Object} An object literal with the following properties:
817  *     <dl>
818  *     <dt><code>success</code></dt>
819  *     <dd>The function to call when the data is ready.</dd>
820  *     <dt><code>failure</code></dt>
821  *     <dd>The function to call upon a response failure condition.</dd>
822  *     <dt><code>scope</code></dt>
823  *     <dd>The object to serve as the scope for the success and failure handlers.</dd>
824  *     <dt><code>argument</code></dt>
825  *     <dd>Arbitrary data that will be passed back to the success and failure handlers.</dd>
826  *     </dl> 
827  * @param oCaller {Object} (deprecated) Use oCallback.scope.
828  * @return {Number} Transaction ID, or null if response found in cache.
829  */
830 sendRequest : function(oRequest, oCallback, oCaller) {
831     // First look in cache
832     var oCachedResponse = this.getCachedResponse(oRequest, oCallback, oCaller);
833     if(oCachedResponse) {
834         DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller);
835         return null;
836     }
837
838
839     // Not in cache, so forward request to live data
840     YAHOO.log("Making connection to live data for \"" + oRequest + "\"", "info", this.toString());
841     return this.makeConnection(oRequest, oCallback, oCaller);
842 },
843
844 /**
845  * Overridable default method generates a unique transaction ID and passes 
846  * the live data reference directly to the  handleResponse function. This
847  * method should be implemented by subclasses to achieve more complex behavior
848  * or to access remote data.          
849  *
850  * @method makeConnection
851  * @param oRequest {Object} Request object.
852  * @param oCallback {Object} Callback object literal.
853  * @param oCaller {Object} (deprecated) Use oCallback.scope.
854  * @return {Number} Transaction ID.
855  */
856 makeConnection : function(oRequest, oCallback, oCaller) {
857     var tId = DS._nTransactionId++;
858     this.fireEvent("requestEvent", {tId:tId, request:oRequest,callback:oCallback,caller:oCaller});
859
860     /* accounts for the following cases:
861     YAHOO.util.DataSourceBase.TYPE_UNKNOWN
862     YAHOO.util.DataSourceBase.TYPE_JSARRAY
863     YAHOO.util.DataSourceBase.TYPE_JSON
864     YAHOO.util.DataSourceBase.TYPE_HTMLTABLE
865     YAHOO.util.DataSourceBase.TYPE_XML
866     YAHOO.util.DataSourceBase.TYPE_TEXT
867     */
868     var oRawResponse = this.liveData;
869     
870     this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
871     return tId;
872 },
873
874 /**
875  * Receives raw data response and type converts to XML, JSON, etc as necessary.
876  * Forwards oFullResponse to appropriate parsing function to get turned into
877  * oParsedResponse. Calls doBeforeCallback() and adds oParsedResponse to 
878  * the cache when appropriate before calling issueCallback().
879  * 
880  * The oParsedResponse object literal has the following properties:
881  * <dl>
882  *     <dd><dt>tId {Number}</dt> Unique transaction ID</dd>
883  *     <dd><dt>results {Array}</dt> Array of parsed data results</dd>
884  *     <dd><dt>meta {Object}</dt> Object literal of meta values</dd> 
885  *     <dd><dt>error {Boolean}</dt> (optional) True if there was an error</dd>
886  *     <dd><dt>cached {Boolean}</dt> (optional) True if response was cached</dd>
887  * </dl>
888  *
889  * @method handleResponse
890  * @param oRequest {Object} Request object
891  * @param oRawResponse {Object} The raw response from the live database.
892  * @param oCallback {Object} Callback object literal.
893  * @param oCaller {Object} (deprecated) Use oCallback.scope.
894  * @param tId {Number} Transaction ID.
895  */
896 handleResponse : function(oRequest, oRawResponse, oCallback, oCaller, tId) {
897     this.fireEvent("responseEvent", {tId:tId, request:oRequest, response:oRawResponse,
898             callback:oCallback, caller:oCaller});
899     YAHOO.log("Received live data response for \"" + oRequest + "\"", "info", this.toString());
900     var xhr = (this.dataType == DS.TYPE_XHR) ? true : false;
901     var oParsedResponse = null;
902     var oFullResponse = oRawResponse;
903     
904     // Try to sniff data type if it has not been defined
905     if(this.responseType === DS.TYPE_UNKNOWN) {
906         var ctype = (oRawResponse && oRawResponse.getResponseHeader) ? oRawResponse.getResponseHeader["Content-Type"] : null;
907         if(ctype) {
908              // xml
909             if(ctype.indexOf("text/xml") > -1) {
910                 this.responseType = DS.TYPE_XML;
911             }
912             else if(ctype.indexOf("application/json") > -1) { // json
913                 this.responseType = DS.TYPE_JSON;
914             }
915             else if(ctype.indexOf("text/plain") > -1) { // text
916                 this.responseType = DS.TYPE_TEXT;
917             }
918         }
919         else {
920             if(YAHOO.lang.isArray(oRawResponse)) { // array
921                 this.responseType = DS.TYPE_JSARRAY;
922             }
923              // xml
924             else if(oRawResponse && oRawResponse.nodeType && oRawResponse.nodeType == 9) {
925                 this.responseType = DS.TYPE_XML;
926             }
927             else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
928                 this.responseType = DS.TYPE_HTMLTABLE;
929             }    
930             else if(YAHOO.lang.isObject(oRawResponse)) { // json
931                 this.responseType = DS.TYPE_JSON;
932             }
933             else if(YAHOO.lang.isString(oRawResponse)) { // text
934                 this.responseType = DS.TYPE_TEXT;
935             }
936         }
937     }
938
939     switch(this.responseType) {
940         case DS.TYPE_JSARRAY:
941             if(xhr && oRawResponse && oRawResponse.responseText) {
942                 oFullResponse = oRawResponse.responseText; 
943             }
944             try {
945                 // Convert to JS array if it's a string
946                 if(lang.isString(oFullResponse)) {
947                     var parseArgs = [oFullResponse].concat(this.parseJSONArgs);
948                     // Check for YUI JSON Util
949                     if(lang.JSON) {
950                         oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs);
951                     }
952                     // Look for JSON parsers using an API similar to json2.js
953                     else if(window.JSON && JSON.parse) {
954                         oFullResponse = JSON.parse.apply(JSON,parseArgs);
955                     }
956                     // Look for JSON parsers using an API similar to json.js
957                     else if(oFullResponse.parseJSON) {
958                         oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1));
959                     }
960                     // No JSON lib found so parse the string
961                     else {
962                         // Trim leading spaces
963                         while (oFullResponse.length > 0 &&
964                                 (oFullResponse.charAt(0) != "{") &&
965                                 (oFullResponse.charAt(0) != "[")) {
966                             oFullResponse = oFullResponse.substring(1, oFullResponse.length);
967                         }
968
969                         if(oFullResponse.length > 0) {
970                             // Strip extraneous stuff at the end
971                             var arrayEnd =
972 Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));
973                             oFullResponse = oFullResponse.substring(0,arrayEnd+1);
974
975                             // Turn the string into an object literal...
976                             // ...eval is necessary here
977                             oFullResponse = eval("(" + oFullResponse + ")");
978
979                         }
980                     }
981                 }
982             }
983             catch(e1) {
984             }
985             oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
986             oParsedResponse = this.parseArrayData(oRequest, oFullResponse);
987             break;
988         case DS.TYPE_JSON:
989             if(xhr && oRawResponse && oRawResponse.responseText) {
990                 oFullResponse = oRawResponse.responseText;
991             }
992             try {
993                 // Convert to JSON object if it's a string
994                 if(lang.isString(oFullResponse)) {
995                     var parseArgs = [oFullResponse].concat(this.parseJSONArgs);
996                     // Check for YUI JSON Util
997                     if(lang.JSON) {
998                         oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs);
999                     }
1000                     // Look for JSON parsers using an API similar to json2.js
1001                     else if(window.JSON && JSON.parse) {
1002                         oFullResponse = JSON.parse.apply(JSON,parseArgs);
1003                     }
1004                     // Look for JSON parsers using an API similar to json.js
1005                     else if(oFullResponse.parseJSON) {
1006                         oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1));
1007                     }
1008                     // No JSON lib found so parse the string
1009                     else {
1010                         // Trim leading spaces
1011                         while (oFullResponse.length > 0 &&
1012                                 (oFullResponse.charAt(0) != "{") &&
1013                                 (oFullResponse.charAt(0) != "[")) {
1014                             oFullResponse = oFullResponse.substring(1, oFullResponse.length);
1015                         }
1016     
1017                         if(oFullResponse.length > 0) {
1018                             // Strip extraneous stuff at the end
1019                             var objEnd = Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));
1020                             oFullResponse = oFullResponse.substring(0,objEnd+1);
1021     
1022                             // Turn the string into an object literal...
1023                             // ...eval is necessary here
1024                             oFullResponse = eval("(" + oFullResponse + ")");
1025     
1026                         }
1027                     }
1028                 }
1029             }
1030             catch(e) {
1031             }
1032
1033             oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1034             oParsedResponse = this.parseJSONData(oRequest, oFullResponse);
1035             break;
1036         case DS.TYPE_HTMLTABLE:
1037             if(xhr && oRawResponse.responseText) {
1038                 var el = document.createElement('div');
1039                 el.innerHTML = oRawResponse.responseText;
1040                 oFullResponse = el.getElementsByTagName('table')[0];
1041             }
1042             oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1043             oParsedResponse = this.parseHTMLTableData(oRequest, oFullResponse);
1044             break;
1045         case DS.TYPE_XML:
1046             if(xhr && oRawResponse.responseXML) {
1047                 oFullResponse = oRawResponse.responseXML;
1048             }
1049             oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1050             oParsedResponse = this.parseXMLData(oRequest, oFullResponse);
1051             break;
1052         case DS.TYPE_TEXT:
1053             if(xhr && lang.isString(oRawResponse.responseText)) {
1054                 oFullResponse = oRawResponse.responseText;
1055             }
1056             oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1057             oParsedResponse = this.parseTextData(oRequest, oFullResponse);
1058             break;
1059         default:
1060             oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1061             oParsedResponse = this.parseData(oRequest, oFullResponse);
1062             break;
1063     }
1064
1065
1066     // Clean up for consistent signature
1067     oParsedResponse = oParsedResponse || {};
1068     if(!oParsedResponse.results) {
1069         oParsedResponse.results = [];
1070     }
1071     if(!oParsedResponse.meta) {
1072         oParsedResponse.meta = {};
1073     }
1074
1075     // Success
1076     if(oParsedResponse && !oParsedResponse.error) {
1077         // Last chance to touch the raw response or the parsed response
1078         oParsedResponse = this.doBeforeCallback(oRequest, oFullResponse, oParsedResponse, oCallback);
1079         this.fireEvent("responseParseEvent", {request:oRequest,
1080                 response:oParsedResponse, callback:oCallback, caller:oCaller});
1081         // Cache the response
1082         this.addToCache(oRequest, oParsedResponse);
1083     }
1084     // Error
1085     else {
1086         // Be sure the error flag is on
1087         oParsedResponse.error = true;
1088         this.fireEvent("dataErrorEvent", {request:oRequest, response: oRawResponse, callback:oCallback, 
1089                 caller:oCaller, message:DS.ERROR_DATANULL});
1090         YAHOO.log(DS.ERROR_DATANULL, "error", this.toString());
1091     }
1092
1093     // Send the response back to the caller
1094     oParsedResponse.tId = tId;
1095     DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller);
1096 },
1097
1098 /**
1099  * Overridable method gives implementers access to the original full response
1100  * before the data gets parsed. Implementers should take care not to return an
1101  * unparsable or otherwise invalid response.
1102  *
1103  * @method doBeforeParseData
1104  * @param oRequest {Object} Request object.
1105  * @param oFullResponse {Object} The full response from the live database.
1106  * @param oCallback {Object} The callback object.  
1107  * @return {Object} Full response for parsing.
1108   
1109  */
1110 doBeforeParseData : function(oRequest, oFullResponse, oCallback) {
1111     return oFullResponse;
1112 },
1113
1114 /**
1115  * Overridable method gives implementers access to the original full response and
1116  * the parsed response (parsed against the given schema) before the data
1117  * is added to the cache (if applicable) and then sent back to callback function.
1118  * This is your chance to access the raw response and/or populate the parsed
1119  * response with any custom data.
1120  *
1121  * @method doBeforeCallback
1122  * @param oRequest {Object} Request object.
1123  * @param oFullResponse {Object} The full response from the live database.
1124  * @param oParsedResponse {Object} The parsed response to return to calling object.
1125  * @param oCallback {Object} The callback object. 
1126  * @return {Object} Parsed response object.
1127  */
1128 doBeforeCallback : function(oRequest, oFullResponse, oParsedResponse, oCallback) {
1129     return oParsedResponse;
1130 },
1131
1132 /**
1133  * Overridable method parses data of generic RESPONSE_TYPE into a response object.
1134  *
1135  * @method parseData
1136  * @param oRequest {Object} Request object.
1137  * @param oFullResponse {Object} The full Array from the live database.
1138  * @return {Object} Parsed response object with the following properties:<br>
1139  *     - results {Array} Array of parsed data results<br>
1140  *     - meta {Object} Object literal of meta values<br>
1141  *     - error {Boolean} (optional) True if there was an error<br>
1142  */
1143 parseData : function(oRequest, oFullResponse) {
1144     if(lang.isValue(oFullResponse)) {
1145         var oParsedResponse = {results:oFullResponse,meta:{}};
1146         YAHOO.log("Parsed generic data is " +
1147                 lang.dump(oParsedResponse), "info", this.toString());
1148         return oParsedResponse;
1149
1150     }
1151     YAHOO.log("Generic data could not be parsed: " + lang.dump(oFullResponse), 
1152             "error", this.toString());
1153     return null;
1154 },
1155
1156 /**
1157  * Overridable method parses Array data into a response object.
1158  *
1159  * @method parseArrayData
1160  * @param oRequest {Object} Request object.
1161  * @param oFullResponse {Object} The full Array from the live database.
1162  * @return {Object} Parsed response object with the following properties:<br>
1163  *     - results (Array) Array of parsed data results<br>
1164  *     - error (Boolean) True if there was an error
1165  */
1166 parseArrayData : function(oRequest, oFullResponse) {
1167     if(lang.isArray(oFullResponse)) {
1168         var results = [],
1169             i, j,
1170             rec, field, data;
1171         
1172         // Parse for fields
1173         if(lang.isArray(this.responseSchema.fields)) {
1174             var fields = this.responseSchema.fields;
1175             for (i = fields.length - 1; i >= 0; --i) {
1176                 if (typeof fields[i] !== 'object') {
1177                     fields[i] = { key : fields[i] };
1178                 }
1179             }
1180
1181             var parsers = {}, p;
1182             for (i = fields.length - 1; i >= 0; --i) {
1183                 p = (typeof fields[i].parser === 'function' ?
1184                           fields[i].parser :
1185                           DS.Parser[fields[i].parser+'']) || fields[i].converter;
1186                 if (p) {
1187                     parsers[fields[i].key] = p;
1188                 }
1189             }
1190
1191             var arrType = lang.isArray(oFullResponse[0]);
1192             for(i=oFullResponse.length-1; i>-1; i--) {
1193                 var oResult = {};
1194                 rec = oFullResponse[i];
1195                 if (typeof rec === 'object') {
1196                     for(j=fields.length-1; j>-1; j--) {
1197                         field = fields[j];
1198                         data = arrType ? rec[j] : rec[field.key];
1199
1200                         if (parsers[field.key]) {
1201                             data = parsers[field.key].call(this,data);
1202                         }
1203
1204                         // Safety measure
1205                         if(data === undefined) {
1206                             data = null;
1207                         }
1208
1209                         oResult[field.key] = data;
1210                     }
1211                 }
1212                 else if (lang.isString(rec)) {
1213                     for(j=fields.length-1; j>-1; j--) {
1214                         field = fields[j];
1215                         data = rec;
1216
1217                         if (parsers[field.key]) {
1218                             data = parsers[field.key].call(this,data);
1219                         }
1220
1221                         // Safety measure
1222                         if(data === undefined) {
1223                             data = null;
1224                         }
1225
1226                         oResult[field.key] = data;
1227                     }                
1228                 }
1229                 results[i] = oResult;
1230             }    
1231         }
1232         // Return entire data set
1233         else {
1234             results = oFullResponse;
1235         }
1236         var oParsedResponse = {results:results};
1237         YAHOO.log("Parsed array data is " +
1238                 lang.dump(oParsedResponse), "info", this.toString());
1239         return oParsedResponse;
1240
1241     }
1242     YAHOO.log("Array data could not be parsed: " + lang.dump(oFullResponse), 
1243             "error", this.toString());
1244     return null;
1245 },
1246
1247 /**
1248  * Overridable method parses plain text data into a response object.
1249  *
1250  * @method parseTextData
1251  * @param oRequest {Object} Request object.
1252  * @param oFullResponse {Object} The full text response from the live database.
1253  * @return {Object} Parsed response object with the following properties:<br>
1254  *     - results (Array) Array of parsed data results<br>
1255  *     - error (Boolean) True if there was an error
1256  */
1257 parseTextData : function(oRequest, oFullResponse) {
1258     if(lang.isString(oFullResponse)) {
1259         if(lang.isString(this.responseSchema.recordDelim) &&
1260                 lang.isString(this.responseSchema.fieldDelim)) {
1261             var oParsedResponse = {results:[]};
1262             var recDelim = this.responseSchema.recordDelim;
1263             var fieldDelim = this.responseSchema.fieldDelim;
1264             if(oFullResponse.length > 0) {
1265                 // Delete the last line delimiter at the end of the data if it exists
1266                 var newLength = oFullResponse.length-recDelim.length;
1267                 if(oFullResponse.substr(newLength) == recDelim) {
1268                     oFullResponse = oFullResponse.substr(0, newLength);
1269                 }
1270                 if(oFullResponse.length > 0) {
1271                     // Split along record delimiter to get an array of strings
1272                     var recordsarray = oFullResponse.split(recDelim);
1273                     // Cycle through each record
1274                     for(var i = 0, len = recordsarray.length, recIdx = 0; i < len; ++i) {
1275                         var bError = false,
1276                             sRecord = recordsarray[i];
1277                         if (lang.isString(sRecord) && (sRecord.length > 0)) {
1278                             // Split each record along field delimiter to get data
1279                             var fielddataarray = recordsarray[i].split(fieldDelim);
1280                             var oResult = {};
1281                             
1282                             // Filter for fields data
1283                             if(lang.isArray(this.responseSchema.fields)) {
1284                                 var fields = this.responseSchema.fields;
1285                                 for(var j=fields.length-1; j>-1; j--) {
1286                                     try {
1287                                         // Remove quotation marks from edges, if applicable
1288                                         var data = fielddataarray[j];
1289                                         if (lang.isString(data)) {
1290                                             if(data.charAt(0) == "\"") {
1291                                                 data = data.substr(1);
1292                                             }
1293                                             if(data.charAt(data.length-1) == "\"") {
1294                                                 data = data.substr(0,data.length-1);
1295                                             }
1296                                             var field = fields[j];
1297                                             var key = (lang.isValue(field.key)) ? field.key : field;
1298                                             // Backward compatibility
1299                                             if(!field.parser && field.converter) {
1300                                                 field.parser = field.converter;
1301                                                 YAHOO.log("The field property converter has been deprecated" +
1302                                                         " in favor of parser", "warn", this.toString());
1303                                             }
1304                                             var parser = (typeof field.parser === 'function') ?
1305                                                 field.parser :
1306                                                 DS.Parser[field.parser+''];
1307                                             if(parser) {
1308                                                 data = parser.call(this, data);
1309                                             }
1310                                             // Safety measure
1311                                             if(data === undefined) {
1312                                                 data = null;
1313                                             }
1314                                             oResult[key] = data;
1315                                         }
1316                                         else {
1317                                             bError = true;
1318                                         }
1319                                     }
1320                                     catch(e) {
1321                                         bError = true;
1322                                     }
1323                                 }
1324                             }            
1325                             // No fields defined so pass along all data as an array
1326                             else {
1327                                 oResult = fielddataarray;
1328                             }
1329                             if(!bError) {
1330                                 oParsedResponse.results[recIdx++] = oResult;
1331                             }
1332                         }
1333                     }
1334                 }
1335             }
1336             YAHOO.log("Parsed text data is " +
1337                     lang.dump(oParsedResponse), "info", this.toString());
1338             return oParsedResponse;
1339         }
1340     }
1341     YAHOO.log("Text data could not be parsed: " + lang.dump(oFullResponse), 
1342             "error", this.toString());
1343     return null;
1344             
1345 },
1346
1347
1348 /**
1349  * Overridable method parses XML data for one result into an object literal.
1350  *
1351  * @method parseXMLResult
1352  * @param result {XML} XML for one result.
1353  * @return {Object} Object literal of data for one result.
1354  */
1355 parseXMLResult : function(result) {
1356     var oResult = {},
1357         schema = this.responseSchema;
1358         
1359     try {
1360         // Loop through each data field in each result using the schema
1361         for(var m = schema.fields.length-1; m >= 0 ; m--) {
1362             var field = schema.fields[m];
1363             var key = (lang.isValue(field.key)) ? field.key : field;
1364             var data = null;
1365             // Values may be held in an attribute...
1366             var xmlAttr = result.attributes.getNamedItem(key);
1367             if(xmlAttr) {
1368                 data = xmlAttr.value;
1369             }
1370             // ...or in a node
1371             else {
1372                 var xmlNode = result.getElementsByTagName(key);
1373                 if(xmlNode && xmlNode.item(0)) {
1374                     var item = xmlNode.item(0);
1375                     // For IE, then DOM...
1376                     data = (item) ? ((item.text) ? item.text : (item.textContent) ? item.textContent : null) : null;
1377                     // ...then fallback, but check for multiple child nodes
1378                     if(!data) {
1379                         var datapieces = [];
1380                         for(var j=0, len=item.childNodes.length; j<len; j++) {
1381                             if(item.childNodes[j].nodeValue) {
1382                                 datapieces[datapieces.length] = item.childNodes[j].nodeValue;
1383                             }
1384                         }
1385                         if(datapieces.length > 0) {
1386                             data = datapieces.join("");
1387                         }
1388                     }
1389                 }
1390             }
1391             // Safety net
1392             if(data === null) {
1393                    data = "";
1394             }
1395             // Backward compatibility
1396             if(!field.parser && field.converter) {
1397                 field.parser = field.converter;
1398                 YAHOO.log("The field property converter has been deprecated" +
1399                         " in favor of parser", "warn", this.toString());
1400             }
1401             var parser = (typeof field.parser === 'function') ?
1402                 field.parser :
1403                 DS.Parser[field.parser+''];
1404             if(parser) {
1405                 data = parser.call(this, data);
1406             }
1407             // Safety measure
1408             if(data === undefined) {
1409                 data = null;
1410             }
1411             oResult[key] = data;
1412         }
1413     }
1414     catch(e) {
1415         YAHOO.log("Error while parsing XML result: " + e.message);
1416     }
1417
1418     return oResult;
1419 },
1420
1421
1422
1423 /**
1424  * Overridable method parses XML data into a response object.
1425  *
1426  * @method parseXMLData
1427  * @param oRequest {Object} Request object.
1428  * @param oFullResponse {Object} The full XML response from the live database.
1429  * @return {Object} Parsed response object with the following properties<br>
1430  *     - results (Array) Array of parsed data results<br>
1431  *     - error (Boolean) True if there was an error
1432  */
1433 parseXMLData : function(oRequest, oFullResponse) {
1434     var bError = false,
1435         schema = this.responseSchema,
1436         oParsedResponse = {meta:{}},
1437         xmlList = null,
1438         metaNode      = schema.metaNode,
1439         metaLocators  = schema.metaFields || {},
1440         i,k,loc,v;
1441
1442     // In case oFullResponse is something funky
1443     try {
1444         xmlList = (schema.resultNode) ?
1445             oFullResponse.getElementsByTagName(schema.resultNode) :
1446             null;
1447
1448         // Pull any meta identified
1449         metaNode = metaNode ? oFullResponse.getElementsByTagName(metaNode)[0] :
1450                    oFullResponse;
1451
1452         if (metaNode) {
1453             for (k in metaLocators) {
1454                 if (lang.hasOwnProperty(metaLocators, k)) {
1455                     loc = metaLocators[k];
1456                     // Look for a node
1457                     v = metaNode.getElementsByTagName(loc)[0];
1458
1459                     if (v) {
1460                         v = v.firstChild.nodeValue;
1461                     } else {
1462                         // Look for an attribute
1463                         v = metaNode.attributes.getNamedItem(loc);
1464                         if (v) {
1465                             v = v.value;
1466                         }
1467                     }
1468
1469                     if (lang.isValue(v)) {
1470                         oParsedResponse.meta[k] = v;
1471                     }
1472                 }
1473                 
1474             }
1475         }
1476     }
1477     catch(e) {
1478         YAHOO.log("Error while parsing XML data: " + e.message);
1479     }
1480     if(!xmlList || !lang.isArray(schema.fields)) {
1481         bError = true;
1482     }
1483     // Loop through each result
1484     else {
1485         oParsedResponse.results = [];
1486         for(i = xmlList.length-1; i >= 0 ; --i) {
1487             var oResult = this.parseXMLResult(xmlList.item(i));
1488             // Capture each array of values into an array of results
1489             oParsedResponse.results[i] = oResult;
1490         }
1491     }
1492     if(bError) {
1493         YAHOO.log("XML data could not be parsed: " +
1494                 lang.dump(oFullResponse), "error", this.toString());
1495         oParsedResponse.error = true;
1496     }
1497     else {
1498         YAHOO.log("Parsed XML data is " +
1499                 lang.dump(oParsedResponse), "info", this.toString());
1500     }
1501     return oParsedResponse;
1502 },
1503
1504 /**
1505  * Overridable method parses JSON data into a response object.
1506  *
1507  * @method parseJSONData
1508  * @param oRequest {Object} Request object.
1509  * @param oFullResponse {Object} The full JSON from the live database.
1510  * @return {Object} Parsed response object with the following properties<br>
1511  *     - results (Array) Array of parsed data results<br>
1512  *     - error (Boolean) True if there was an error
1513  */
1514 parseJSONData : function(oRequest, oFullResponse) {
1515     var oParsedResponse = {results:[],meta:{}};
1516     
1517     if(lang.isObject(oFullResponse) && this.responseSchema.resultsList) {
1518         var schema = this.responseSchema,
1519             fields          = schema.fields,
1520             resultsList     = oFullResponse,
1521             results         = [],
1522             metaFields      = schema.metaFields || {},
1523             fieldParsers    = [],
1524             fieldPaths      = [],
1525             simpleFields    = [],
1526             bError          = false,
1527             i,len,j,v,key,parser,path;
1528
1529         // Function to convert the schema's fields into walk paths
1530         var buildPath = function (needle) {
1531             var path = null, keys = [], i = 0;
1532             if (needle) {
1533                 // Strip the ["string keys"] and [1] array indexes
1534                 needle = needle.
1535                     replace(/\[(['"])(.*?)\1\]/g,
1536                     function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}).
1537                     replace(/\[(\d+)\]/g,
1538                     function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}).
1539                     replace(/^\./,''); // remove leading dot
1540
1541                 // If the cleaned needle contains invalid characters, the
1542                 // path is invalid
1543                 if (!/[^\w\.\$@]/.test(needle)) {
1544                     path = needle.split('.');
1545                     for (i=path.length-1; i >= 0; --i) {
1546                         if (path[i].charAt(0) === '@') {
1547                             path[i] = keys[parseInt(path[i].substr(1),10)];
1548                         }
1549                     }
1550                 }
1551                 else {
1552                     YAHOO.log("Invalid locator: " + needle, "error", this.toString());
1553                 }
1554             }
1555             return path;
1556         };
1557
1558
1559         // Function to walk a path and return the pot of gold
1560         var walkPath = function (path, origin) {
1561             var v=origin,i=0,len=path.length;
1562             for (;i<len && v;++i) {
1563                 v = v[path[i]];
1564             }
1565             return v;
1566         };
1567
1568         // Parse the response
1569         // Step 1. Pull the resultsList from oFullResponse (default assumes
1570         // oFullResponse IS the resultsList)
1571         path = buildPath(schema.resultsList);
1572         if (path) {
1573             resultsList = walkPath(path, oFullResponse);
1574             if (resultsList === undefined) {
1575                 bError = true;
1576             }
1577         } else {
1578             bError = true;
1579         }
1580         
1581         if (!resultsList) {
1582             resultsList = [];
1583         }
1584
1585         if (!lang.isArray(resultsList)) {
1586             resultsList = [resultsList];
1587         }
1588
1589         if (!bError) {
1590             // Step 2. Parse out field data if identified
1591             if(schema.fields) {
1592                 var field;
1593                 // Build the field parser map and location paths
1594                 for (i=0, len=fields.length; i<len; i++) {
1595                     field = fields[i];
1596                     key    = field.key || field;
1597                     parser = ((typeof field.parser === 'function') ?
1598                         field.parser :
1599                         DS.Parser[field.parser+'']) || field.converter;
1600                     path   = buildPath(key);
1601     
1602                     if (parser) {
1603                         fieldParsers[fieldParsers.length] = {key:key,parser:parser};
1604                     }
1605     
1606                     if (path) {
1607                         if (path.length > 1) {
1608                             fieldPaths[fieldPaths.length] = {key:key,path:path};
1609                         } else {
1610                             simpleFields[simpleFields.length] = {key:key,path:path[0]};
1611                         }
1612                     } else {
1613                         YAHOO.log("Invalid key syntax: " + key,"warn",this.toString());
1614                     }
1615                 }
1616
1617                 // Process the results, flattening the records and/or applying parsers if needed
1618                 for (i = resultsList.length - 1; i >= 0; --i) {
1619                     var r = resultsList[i], rec = {};
1620                     if(r) {
1621                         for (j = simpleFields.length - 1; j >= 0; --j) {
1622                             // Bug 1777850: data might be held in an array
1623                             rec[simpleFields[j].key] =
1624                                     (r[simpleFields[j].path] !== undefined) ?
1625                                     r[simpleFields[j].path] : r[j];
1626                         }
1627
1628                         for (j = fieldPaths.length - 1; j >= 0; --j) {
1629                             rec[fieldPaths[j].key] = walkPath(fieldPaths[j].path,r);
1630                         }
1631
1632                         for (j = fieldParsers.length - 1; j >= 0; --j) {
1633                             var p = fieldParsers[j].key;
1634                             rec[p] = fieldParsers[j].parser(rec[p]);
1635                             if (rec[p] === undefined) {
1636                                 rec[p] = null;
1637                             }
1638                         }
1639                     }
1640                     results[i] = rec;
1641                 }
1642             }
1643             else {
1644                 results = resultsList;
1645             }
1646
1647             for (key in metaFields) {
1648                 if (lang.hasOwnProperty(metaFields,key)) {
1649                     path = buildPath(metaFields[key]);
1650                     if (path) {
1651                         v = walkPath(path, oFullResponse);
1652                         oParsedResponse.meta[key] = v;
1653                     }
1654                 }
1655             }
1656
1657         } else {
1658             YAHOO.log("JSON data could not be parsed due to invalid responseSchema.resultsList or invalid response: " +
1659                     lang.dump(oFullResponse), "error", this.toString());
1660
1661             oParsedResponse.error = true;
1662         }
1663
1664         oParsedResponse.results = results;
1665     }
1666     else {
1667         YAHOO.log("JSON data could not be parsed: " +
1668                 lang.dump(oFullResponse), "error", this.toString());
1669         oParsedResponse.error = true;
1670     }
1671
1672     return oParsedResponse;
1673 },
1674
1675 /**
1676  * Overridable method parses an HTML TABLE element reference into a response object.
1677  * Data is parsed out of TR elements from all TBODY elements. 
1678  *
1679  * @method parseHTMLTableData
1680  * @param oRequest {Object} Request object.
1681  * @param oFullResponse {Object} The full HTML element reference from the live database.
1682  * @return {Object} Parsed response object with the following properties<br>
1683  *     - results (Array) Array of parsed data results<br>
1684  *     - error (Boolean) True if there was an error
1685  */
1686 parseHTMLTableData : function(oRequest, oFullResponse) {
1687     var bError = false;
1688     var elTable = oFullResponse;
1689     var fields = this.responseSchema.fields;
1690     var oParsedResponse = {results:[]};
1691
1692     if(lang.isArray(fields)) {
1693         // Iterate through each TBODY
1694         for(var i=0; i<elTable.tBodies.length; i++) {
1695             var elTbody = elTable.tBodies[i];
1696     
1697             // Iterate through each TR
1698             for(var j=elTbody.rows.length-1; j>-1; j--) {
1699                 var elRow = elTbody.rows[j];
1700                 var oResult = {};
1701                 
1702                 for(var k=fields.length-1; k>-1; k--) {
1703                     var field = fields[k];
1704                     var key = (lang.isValue(field.key)) ? field.key : field;
1705                     var data = elRow.cells[k].innerHTML;
1706     
1707                     // Backward compatibility
1708                     if(!field.parser && field.converter) {
1709                         field.parser = field.converter;
1710                         YAHOO.log("The field property converter has been deprecated" +
1711                                 " in favor of parser", "warn", this.toString());
1712                     }
1713                     var parser = (typeof field.parser === 'function') ?
1714                         field.parser :
1715                         DS.Parser[field.parser+''];
1716                     if(parser) {
1717                         data = parser.call(this, data);
1718                     }
1719                     // Safety measure
1720                     if(data === undefined) {
1721                         data = null;
1722                     }
1723                     oResult[key] = data;
1724                 }
1725                 oParsedResponse.results[j] = oResult;
1726             }
1727         }
1728     }
1729     else {
1730         bError = true;
1731         YAHOO.log("Invalid responseSchema.fields", "error", this.toString());
1732     }
1733
1734     if(bError) {
1735         YAHOO.log("HTML TABLE data could not be parsed: " +
1736                 lang.dump(oFullResponse), "error", this.toString());
1737         oParsedResponse.error = true;
1738     }
1739     else {
1740         YAHOO.log("Parsed HTML TABLE data is " +
1741                 lang.dump(oParsedResponse), "info", this.toString());
1742     }
1743     return oParsedResponse;
1744 }
1745
1746 };
1747
1748 // DataSourceBase uses EventProvider
1749 lang.augmentProto(DS, util.EventProvider);
1750
1751
1752
1753 /****************************************************************************/
1754 /****************************************************************************/
1755 /****************************************************************************/
1756
1757 /**
1758  * LocalDataSource class for in-memory data structs including JavaScript arrays,
1759  * JavaScript object literals (JSON), XML documents, and HTML tables.
1760  *
1761  * @namespace YAHOO.util
1762  * @class YAHOO.util.LocalDataSource
1763  * @extends YAHOO.util.DataSourceBase 
1764  * @constructor
1765  * @param oLiveData {HTMLElement}  Pointer to live data.
1766  * @param oConfigs {object} (optional) Object literal of configuration values.
1767  */
1768 util.LocalDataSource = function(oLiveData, oConfigs) {
1769     this.dataType = DS.TYPE_LOCAL;
1770     
1771     if(oLiveData) {
1772         if(YAHOO.lang.isArray(oLiveData)) { // array
1773             this.responseType = DS.TYPE_JSARRAY;
1774         }
1775          // xml
1776         else if(oLiveData.nodeType && oLiveData.nodeType == 9) {
1777             this.responseType = DS.TYPE_XML;
1778         }
1779         else if(oLiveData.nodeName && (oLiveData.nodeName.toLowerCase() == "table")) { // table
1780             this.responseType = DS.TYPE_HTMLTABLE;
1781             oLiveData = oLiveData.cloneNode(true);
1782         }    
1783         else if(YAHOO.lang.isString(oLiveData)) { // text
1784             this.responseType = DS.TYPE_TEXT;
1785         }
1786         else if(YAHOO.lang.isObject(oLiveData)) { // json
1787             this.responseType = DS.TYPE_JSON;
1788         }
1789     }
1790     else {
1791         oLiveData = [];
1792         this.responseType = DS.TYPE_JSARRAY;
1793     }
1794     
1795     util.LocalDataSource.superclass.constructor.call(this, oLiveData, oConfigs); 
1796 };
1797
1798 // LocalDataSource extends DataSourceBase
1799 lang.extend(util.LocalDataSource, DS);
1800
1801 // Copy static members to LocalDataSource class
1802 lang.augmentObject(util.LocalDataSource, DS);
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816 /****************************************************************************/
1817 /****************************************************************************/
1818 /****************************************************************************/
1819
1820 /**
1821  * FunctionDataSource class for JavaScript functions.
1822  *
1823  * @namespace YAHOO.util
1824  * @class YAHOO.util.FunctionDataSource
1825  * @extends YAHOO.util.DataSourceBase  
1826  * @constructor
1827  * @param oLiveData {HTMLElement}  Pointer to live data.
1828  * @param oConfigs {object} (optional) Object literal of configuration values.
1829  */
1830 util.FunctionDataSource = function(oLiveData, oConfigs) {
1831     this.dataType = DS.TYPE_JSFUNCTION;
1832     oLiveData = oLiveData || function() {};
1833     
1834     util.FunctionDataSource.superclass.constructor.call(this, oLiveData, oConfigs); 
1835 };
1836
1837 // FunctionDataSource extends DataSourceBase
1838 lang.extend(util.FunctionDataSource, DS, {
1839
1840 /////////////////////////////////////////////////////////////////////////////
1841 //
1842 // FunctionDataSource public properties
1843 //
1844 /////////////////////////////////////////////////////////////////////////////
1845
1846 /**
1847  * Context in which to execute the function. By default, is the DataSource
1848  * instance itself. If set, the function will receive the DataSource instance
1849  * as an additional argument. 
1850  *
1851  * @property scope
1852  * @type Object
1853  * @default null
1854  */
1855 scope : null,
1856
1857
1858 /////////////////////////////////////////////////////////////////////////////
1859 //
1860 // FunctionDataSource public methods
1861 //
1862 /////////////////////////////////////////////////////////////////////////////
1863
1864 /**
1865  * Overriding method passes query to a function. The returned response is then
1866  * forwarded to the handleResponse function.
1867  *
1868  * @method makeConnection
1869  * @param oRequest {Object} Request object.
1870  * @param oCallback {Object} Callback object literal.
1871  * @param oCaller {Object} (deprecated) Use oCallback.scope.
1872  * @return {Number} Transaction ID.
1873  */
1874 makeConnection : function(oRequest, oCallback, oCaller) {
1875     var tId = DS._nTransactionId++;
1876     this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
1877
1878     // Pass the request in as a parameter and
1879     // forward the return value to the handler
1880     
1881     
1882     var oRawResponse = (this.scope) ? this.liveData.call(this.scope, oRequest, this) : this.liveData(oRequest);
1883     
1884     // Try to sniff data type if it has not been defined
1885     if(this.responseType === DS.TYPE_UNKNOWN) {
1886         if(YAHOO.lang.isArray(oRawResponse)) { // array
1887             this.responseType = DS.TYPE_JSARRAY;
1888         }
1889          // xml
1890         else if(oRawResponse && oRawResponse.nodeType && oRawResponse.nodeType == 9) {
1891             this.responseType = DS.TYPE_XML;
1892         }
1893         else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
1894             this.responseType = DS.TYPE_HTMLTABLE;
1895         }    
1896         else if(YAHOO.lang.isObject(oRawResponse)) { // json
1897             this.responseType = DS.TYPE_JSON;
1898         }
1899         else if(YAHOO.lang.isString(oRawResponse)) { // text
1900             this.responseType = DS.TYPE_TEXT;
1901         }
1902     }
1903
1904     this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
1905     return tId;
1906 }
1907
1908 });
1909
1910 // Copy static members to FunctionDataSource class
1911 lang.augmentObject(util.FunctionDataSource, DS);
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925 /****************************************************************************/
1926 /****************************************************************************/
1927 /****************************************************************************/
1928
1929 /**
1930  * ScriptNodeDataSource class for accessing remote data via the YUI Get Utility. 
1931  *
1932  * @namespace YAHOO.util
1933  * @class YAHOO.util.ScriptNodeDataSource
1934  * @extends YAHOO.util.DataSourceBase  
1935  * @constructor
1936  * @param oLiveData {HTMLElement}  Pointer to live data.
1937  * @param oConfigs {object} (optional) Object literal of configuration values.
1938  */
1939 util.ScriptNodeDataSource = function(oLiveData, oConfigs) {
1940     this.dataType = DS.TYPE_SCRIPTNODE;
1941     oLiveData = oLiveData || "";
1942     
1943     util.ScriptNodeDataSource.superclass.constructor.call(this, oLiveData, oConfigs); 
1944 };
1945
1946 // ScriptNodeDataSource extends DataSourceBase
1947 lang.extend(util.ScriptNodeDataSource, DS, {
1948
1949 /////////////////////////////////////////////////////////////////////////////
1950 //
1951 // ScriptNodeDataSource public properties
1952 //
1953 /////////////////////////////////////////////////////////////////////////////
1954
1955 /**
1956  * Alias to YUI Get Utility, to allow implementers to use a custom class.
1957  *
1958  * @property getUtility
1959  * @type Object
1960  * @default YAHOO.util.Get
1961  */
1962 getUtility : util.Get,
1963
1964 /**
1965  * Defines request/response management in the following manner:
1966  * <dl>
1967  *     <!--<dt>queueRequests</dt>
1968  *     <dd>If a request is already in progress, wait until response is returned before sending the next request.</dd>
1969  *     <dt>cancelStaleRequests</dt>
1970  *     <dd>If a request is already in progress, cancel it before sending the next request.</dd>-->
1971  *     <dt>ignoreStaleResponses</dt>
1972  *     <dd>Send all requests, but handle only the response for the most recently sent request.</dd>
1973  *     <dt>allowAll</dt>
1974  *     <dd>Send all requests and handle all responses.</dd>
1975  * </dl>
1976  *
1977  * @property asyncMode
1978  * @type String
1979  * @default "allowAll"
1980  */
1981 asyncMode : "allowAll",
1982
1983 /**
1984  * Callback string parameter name sent to the remote script. By default,
1985  * requests are sent to
1986  * &#60;URI&#62;?&#60;scriptCallbackParam&#62;=callbackFunction
1987  *
1988  * @property scriptCallbackParam
1989  * @type String
1990  * @default "callback"
1991  */
1992 scriptCallbackParam : "callback",
1993
1994
1995 /////////////////////////////////////////////////////////////////////////////
1996 //
1997 // ScriptNodeDataSource public methods
1998 //
1999 /////////////////////////////////////////////////////////////////////////////
2000
2001 /**
2002  * Creates a request callback that gets appended to the script URI. Implementers
2003  * can customize this string to match their server's query syntax.
2004  *
2005  * @method generateRequestCallback
2006  * @return {String} String fragment that gets appended to script URI that 
2007  * specifies the callback function 
2008  */
2009 generateRequestCallback : function(id) {
2010     return "&" + this.scriptCallbackParam + "=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]" ;
2011 },
2012
2013 /**
2014  * Overridable method gives implementers access to modify the URI before the dynamic
2015  * script node gets inserted. Implementers should take care not to return an
2016  * invalid URI.
2017  *
2018  * @method doBeforeGetScriptNode
2019  * @param {String} URI to the script 
2020  * @return {String} URI to the script
2021  */
2022 doBeforeGetScriptNode : function(sUri) {
2023     return sUri;
2024 },
2025
2026 /**
2027  * Overriding method passes query to Get Utility. The returned
2028  * response is then forwarded to the handleResponse function.
2029  *
2030  * @method makeConnection
2031  * @param oRequest {Object} Request object.
2032  * @param oCallback {Object} Callback object literal.
2033  * @param oCaller {Object} (deprecated) Use oCallback.scope.
2034  * @return {Number} Transaction ID.
2035  */
2036 makeConnection : function(oRequest, oCallback, oCaller) {
2037     var tId = DS._nTransactionId++;
2038     this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
2039     
2040     // If there are no global pending requests, it is safe to purge global callback stack and global counter
2041     if(util.ScriptNodeDataSource._nPending === 0) {
2042         util.ScriptNodeDataSource.callbacks = [];
2043         util.ScriptNodeDataSource._nId = 0;
2044     }
2045     
2046     // ID for this request
2047     var id = util.ScriptNodeDataSource._nId;
2048     util.ScriptNodeDataSource._nId++;
2049     
2050     // Dynamically add handler function with a closure to the callback stack
2051     var oSelf = this;
2052     util.ScriptNodeDataSource.callbacks[id] = function(oRawResponse) {
2053         if((oSelf.asyncMode !== "ignoreStaleResponses")||
2054                 (id === util.ScriptNodeDataSource.callbacks.length-1)) { // Must ignore stale responses
2055                 
2056             // Try to sniff data type if it has not been defined
2057             if(oSelf.responseType === DS.TYPE_UNKNOWN) {
2058                 if(YAHOO.lang.isArray(oRawResponse)) { // array
2059                     oSelf.responseType = DS.TYPE_JSARRAY;
2060                 }
2061                  // xml
2062                 else if(oRawResponse.nodeType && oRawResponse.nodeType == 9) {
2063                     oSelf.responseType = DS.TYPE_XML;
2064                 }
2065                 else if(oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
2066                     oSelf.responseType = DS.TYPE_HTMLTABLE;
2067                 }    
2068                 else if(YAHOO.lang.isObject(oRawResponse)) { // json
2069                     oSelf.responseType = DS.TYPE_JSON;
2070                 }
2071                 else if(YAHOO.lang.isString(oRawResponse)) { // text
2072                     oSelf.responseType = DS.TYPE_TEXT;
2073                 }
2074             }
2075
2076             oSelf.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
2077         }
2078         else {
2079             YAHOO.log("DataSource ignored stale response for tId " + tId + "(" + oRequest + ")", "info", oSelf.toString());
2080         }
2081     
2082         delete util.ScriptNodeDataSource.callbacks[id];
2083     };
2084     
2085     // We are now creating a request
2086     util.ScriptNodeDataSource._nPending++;
2087     var sUri = this.liveData + oRequest + this.generateRequestCallback(id);
2088     sUri = this.doBeforeGetScriptNode(sUri);
2089     YAHOO.log("DataSource is querying URL " + sUri, "info", this.toString());
2090     this.getUtility.script(sUri,
2091             {autopurge: true,
2092             onsuccess: util.ScriptNodeDataSource._bumpPendingDown,
2093             onfail: util.ScriptNodeDataSource._bumpPendingDown});
2094
2095     return tId;
2096 }
2097
2098 });
2099
2100 // Copy static members to ScriptNodeDataSource class
2101 lang.augmentObject(util.ScriptNodeDataSource, DS);
2102
2103 // Copy static members to ScriptNodeDataSource class
2104 lang.augmentObject(util.ScriptNodeDataSource,  {
2105
2106 /////////////////////////////////////////////////////////////////////////////
2107 //
2108 // ScriptNodeDataSource private static properties
2109 //
2110 /////////////////////////////////////////////////////////////////////////////
2111
2112 /**
2113  * Unique ID to track requests.
2114  *
2115  * @property _nId
2116  * @type Number
2117  * @private
2118  * @static
2119  */
2120 _nId : 0,
2121
2122 /**
2123  * Counter for pending requests. When this is 0, it is safe to purge callbacks
2124  * array.
2125  *
2126  * @property _nPending
2127  * @type Number
2128  * @private
2129  * @static
2130  */
2131 _nPending : 0,
2132
2133 /**
2134  * Global array of callback functions, one for each request sent.
2135  *
2136  * @property callbacks
2137  * @type Function[]
2138  * @static
2139  */
2140 callbacks : []
2141
2142 });
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157 /****************************************************************************/
2158 /****************************************************************************/
2159 /****************************************************************************/
2160
2161 /**
2162  * XHRDataSource class for accessing remote data via the YUI Connection Manager
2163  * Utility
2164  *
2165  * @namespace YAHOO.util
2166  * @class YAHOO.util.XHRDataSource
2167  * @extends YAHOO.util.DataSourceBase  
2168  * @constructor
2169  * @param oLiveData {HTMLElement}  Pointer to live data.
2170  * @param oConfigs {object} (optional) Object literal of configuration values.
2171  */
2172 util.XHRDataSource = function(oLiveData, oConfigs) {
2173     this.dataType = DS.TYPE_XHR;
2174     this.connMgr = this.connMgr || util.Connect;
2175     oLiveData = oLiveData || "";
2176     
2177     util.XHRDataSource.superclass.constructor.call(this, oLiveData, oConfigs); 
2178 };
2179
2180 // XHRDataSource extends DataSourceBase
2181 lang.extend(util.XHRDataSource, DS, {
2182
2183 /////////////////////////////////////////////////////////////////////////////
2184 //
2185 // XHRDataSource public properties
2186 //
2187 /////////////////////////////////////////////////////////////////////////////
2188
2189  /**
2190  * Alias to YUI Connection Manager, to allow implementers to use a custom class.
2191  *
2192  * @property connMgr
2193  * @type Object
2194  * @default YAHOO.util.Connect
2195  */
2196 connMgr: null,
2197
2198  /**
2199  * Defines request/response management in the following manner:
2200  * <dl>
2201  *     <dt>queueRequests</dt>
2202  *     <dd>If a request is already in progress, wait until response is returned
2203  *     before sending the next request.</dd>
2204  *
2205  *     <dt>cancelStaleRequests</dt>
2206  *     <dd>If a request is already in progress, cancel it before sending the next
2207  *     request.</dd>
2208  *
2209  *     <dt>ignoreStaleResponses</dt>
2210  *     <dd>Send all requests, but handle only the response for the most recently
2211  *     sent request.</dd>
2212  *
2213  *     <dt>allowAll</dt>
2214  *     <dd>Send all requests and handle all responses.</dd>
2215  *
2216  * </dl>
2217  *
2218  * @property connXhrMode
2219  * @type String
2220  * @default "allowAll"
2221  */
2222 connXhrMode: "allowAll",
2223
2224  /**
2225  * True if data is to be sent via POST. By default, data will be sent via GET.
2226  *
2227  * @property connMethodPost
2228  * @type Boolean
2229  * @default false
2230  */
2231 connMethodPost: false,
2232
2233  /**
2234  * The connection timeout defines how many  milliseconds the XHR connection will
2235  * wait for a server response. Any non-zero value will enable the Connection Manager's
2236  * Auto-Abort feature.
2237  *
2238  * @property connTimeout
2239  * @type Number
2240  * @default 0
2241  */
2242 connTimeout: 0,
2243
2244 /////////////////////////////////////////////////////////////////////////////
2245 //
2246 // XHRDataSource public methods
2247 //
2248 /////////////////////////////////////////////////////////////////////////////
2249
2250 /**
2251  * Overriding method passes query to Connection Manager. The returned
2252  * response is then forwarded to the handleResponse function.
2253  *
2254  * @method makeConnection
2255  * @param oRequest {Object} Request object.
2256  * @param oCallback {Object} Callback object literal.
2257  * @param oCaller {Object} (deprecated) Use oCallback.scope.
2258  * @return {Number} Transaction ID.
2259  */
2260 makeConnection : function(oRequest, oCallback, oCaller) {
2261
2262     var oRawResponse = null;
2263     var tId = DS._nTransactionId++;
2264     this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
2265
2266     // Set up the callback object and
2267     // pass the request in as a URL query and
2268     // forward the response to the handler
2269     var oSelf = this;
2270     var oConnMgr = this.connMgr;
2271     var oQueue = this._oQueue;
2272
2273     /**
2274      * Define Connection Manager success handler
2275      *
2276      * @method _xhrSuccess
2277      * @param oResponse {Object} HTTPXMLRequest object
2278      * @private
2279      */
2280     var _xhrSuccess = function(oResponse) {
2281         // If response ID does not match last made request ID,
2282         // silently fail and wait for the next response
2283         if(oResponse && (this.connXhrMode == "ignoreStaleResponses") &&
2284                 (oResponse.tId != oQueue.conn.tId)) {
2285             YAHOO.log("Ignored stale response", "warn", this.toString());
2286             return null;
2287         }
2288         // Error if no response
2289         else if(!oResponse) {
2290             this.fireEvent("dataErrorEvent", {request:oRequest,
2291                     callback:oCallback, caller:oCaller,
2292                     message:DS.ERROR_DATANULL});
2293             YAHOO.log(DS.ERROR_DATANULL, "error", this.toString());
2294
2295             // Send error response back to the caller with the error flag on
2296             DS.issueCallback(oCallback,[oRequest, {error:true}], true, oCaller);
2297
2298             return null;
2299         }
2300         // Forward to handler
2301         else {
2302             // Try to sniff data type if it has not been defined
2303             if(this.responseType === DS.TYPE_UNKNOWN) {
2304                 var ctype = (oResponse.getResponseHeader) ? oResponse.getResponseHeader["Content-Type"] : null;
2305                 if(ctype) {
2306                     // xml
2307                     if(ctype.indexOf("text/xml") > -1) {
2308                         this.responseType = DS.TYPE_XML;
2309                     }
2310                     else if(ctype.indexOf("application/json") > -1) { // json
2311                         this.responseType = DS.TYPE_JSON;
2312                     }
2313                     else if(ctype.indexOf("text/plain") > -1) { // text
2314                         this.responseType = DS.TYPE_TEXT;
2315                     }
2316                 }
2317             }
2318             this.handleResponse(oRequest, oResponse, oCallback, oCaller, tId);
2319         }
2320     };
2321
2322     /**
2323      * Define Connection Manager failure handler
2324      *
2325      * @method _xhrFailure
2326      * @param oResponse {Object} HTTPXMLRequest object
2327      * @private
2328      */
2329     var _xhrFailure = function(oResponse) {
2330         this.fireEvent("dataErrorEvent", {request:oRequest,
2331                 callback:oCallback, caller:oCaller,
2332                 message:DS.ERROR_DATAINVALID});
2333         YAHOO.log(DS.ERROR_DATAINVALID + ": " +
2334                 oResponse.statusText, "error", this.toString());
2335
2336         // Backward compatibility
2337         if(lang.isString(this.liveData) && lang.isString(oRequest) &&
2338             (this.liveData.lastIndexOf("?") !== this.liveData.length-1) &&
2339             (oRequest.indexOf("?") !== 0)){
2340                 YAHOO.log("DataSources using XHR no longer automatically supply " + 
2341                 "a \"?\" between the host and query parameters" +
2342                 " -- please check that the request URL is correct", "warn", this.toString());
2343         }
2344
2345         // Send failure response back to the caller with the error flag on
2346         oResponse = oResponse || {};
2347         oResponse.error = true;
2348         DS.issueCallback(oCallback,[oRequest,oResponse],true, oCaller);
2349
2350         return null;
2351     };
2352
2353     /**
2354      * Define Connection Manager callback object
2355      *
2356      * @property _xhrCallback
2357      * @param oResponse {Object} HTTPXMLRequest object
2358      * @private
2359      */
2360      var _xhrCallback = {
2361         success:_xhrSuccess,
2362         failure:_xhrFailure,
2363         scope: this
2364     };
2365
2366     // Apply Connection Manager timeout
2367     if(lang.isNumber(this.connTimeout)) {
2368         _xhrCallback.timeout = this.connTimeout;
2369     }
2370
2371     // Cancel stale requests
2372     if(this.connXhrMode == "cancelStaleRequests") {
2373             // Look in queue for stale requests
2374             if(oQueue.conn) {
2375                 if(oConnMgr.abort) {
2376                     oConnMgr.abort(oQueue.conn);
2377                     oQueue.conn = null;
2378                     YAHOO.log("Canceled stale request", "warn", this.toString());
2379                 }
2380                 else {
2381                     YAHOO.log("Could not find Connection Manager abort() function", "error", this.toString());
2382                 }
2383             }
2384     }
2385
2386     // Get ready to send the request URL
2387     if(oConnMgr && oConnMgr.asyncRequest) {
2388         var sLiveData = this.liveData;
2389         var isPost = this.connMethodPost;
2390         var sMethod = (isPost) ? "POST" : "GET";
2391         // Validate request
2392         var sUri = (isPost || !lang.isValue(oRequest)) ? sLiveData : sLiveData+oRequest;
2393         var sRequest = (isPost) ? oRequest : null;
2394
2395         // Send the request right away
2396         if(this.connXhrMode != "queueRequests") {
2397             oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest);
2398         }
2399         // Queue up then send the request
2400         else {
2401             // Found a request already in progress
2402             if(oQueue.conn) {
2403                 var allRequests = oQueue.requests;
2404                 // Add request to queue
2405                 allRequests.push({request:oRequest, callback:_xhrCallback});
2406
2407                 // Interval needs to be started
2408                 if(!oQueue.interval) {
2409                     oQueue.interval = setInterval(function() {
2410                         // Connection is in progress
2411                         if(oConnMgr.isCallInProgress(oQueue.conn)) {
2412                             return;
2413                         }
2414                         else {
2415                             // Send next request
2416                             if(allRequests.length > 0) {
2417                                 // Validate request
2418                                 sUri = (isPost || !lang.isValue(allRequests[0].request)) ? sLiveData : sLiveData+allRequests[0].request;
2419                                 sRequest = (isPost) ? allRequests[0].request : null;
2420                                 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, allRequests[0].callback, sRequest);
2421
2422                                 // Remove request from queue
2423                                 allRequests.shift();
2424                             }
2425                             // No more requests
2426                             else {
2427                                 clearInterval(oQueue.interval);
2428                                 oQueue.interval = null;
2429                             }
2430                         }
2431                     }, 50);
2432                 }
2433             }
2434             // Nothing is in progress
2435             else {
2436                 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest);
2437             }
2438         }
2439     }
2440     else {
2441         YAHOO.log("Could not find Connection Manager asyncRequest() function", "error", this.toString());
2442         // Send null response back to the caller with the error flag on
2443         DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller);
2444     }
2445
2446     return tId;
2447 }
2448
2449 });
2450
2451 // Copy static members to XHRDataSource class
2452 lang.augmentObject(util.XHRDataSource, DS);
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466 /****************************************************************************/
2467 /****************************************************************************/
2468 /****************************************************************************/
2469
2470 /**
2471  * Factory class for creating a BaseDataSource subclass instance. The sublcass is
2472  * determined by oLiveData's type, unless the dataType config is explicitly passed in.  
2473  *
2474  * @namespace YAHOO.util
2475  * @class YAHOO.util.DataSource
2476  * @constructor
2477  * @param oLiveData {HTMLElement}  Pointer to live data.
2478  * @param oConfigs {object} (optional) Object literal of configuration values.
2479  */
2480 util.DataSource = function(oLiveData, oConfigs) {
2481     oConfigs = oConfigs || {};
2482     
2483     // Point to one of the subclasses, first by dataType if given, then by sniffing oLiveData type.
2484     var dataType = oConfigs.dataType;
2485     if(dataType) {
2486         if(dataType == DS.TYPE_LOCAL) {
2487             lang.augmentObject(util.DataSource, util.LocalDataSource);
2488             return new util.LocalDataSource(oLiveData, oConfigs);            
2489         }
2490         else if(dataType == DS.TYPE_XHR) {
2491             lang.augmentObject(util.DataSource, util.XHRDataSource);
2492             return new util.XHRDataSource(oLiveData, oConfigs);            
2493         }
2494         else if(dataType == DS.TYPE_SCRIPTNODE) {
2495             lang.augmentObject(util.DataSource, util.ScriptNodeDataSource);
2496             return new util.ScriptNodeDataSource(oLiveData, oConfigs);            
2497         }
2498         else if(dataType == DS.TYPE_JSFUNCTION) {
2499             lang.augmentObject(util.DataSource, util.FunctionDataSource);
2500             return new util.FunctionDataSource(oLiveData, oConfigs);            
2501         }
2502     }
2503     
2504     if(YAHOO.lang.isString(oLiveData)) { // strings default to xhr
2505         lang.augmentObject(util.DataSource, util.XHRDataSource);
2506         return new util.XHRDataSource(oLiveData, oConfigs);
2507     }
2508     else if(YAHOO.lang.isFunction(oLiveData)) {
2509         lang.augmentObject(util.DataSource, util.FunctionDataSource);
2510         return new util.FunctionDataSource(oLiveData, oConfigs);
2511     }
2512     else { // ultimate default is local
2513         lang.augmentObject(util.DataSource, util.LocalDataSource);
2514         return new util.LocalDataSource(oLiveData, oConfigs);
2515     }
2516 };
2517
2518 // Copy static members to DataSource class
2519 lang.augmentObject(util.DataSource, DS);
2520
2521 })();
2522
2523 /****************************************************************************/
2524 /****************************************************************************/
2525 /****************************************************************************/
2526
2527 /**
2528  * The static Number class provides helper functions to deal with data of type
2529  * Number.
2530  *
2531  * @namespace YAHOO.util
2532  * @requires yahoo
2533  * @class Number
2534  * @static
2535  */
2536  YAHOO.util.Number = {
2537  
2538      /**
2539      * Takes a native JavaScript Number and formats to string for display to user.
2540      *
2541      * @method format
2542      * @param nData {Number} Number.
2543      * @param oConfig {Object} (Optional) Optional configuration values:
2544      *  <dl>
2545      *   <dt>prefix {String}</dd>
2546      *   <dd>String prepended before each number, like a currency designator "$"</dd>
2547      *   <dt>decimalPlaces {Number}</dd>
2548      *   <dd>Number of decimal places to round.</dd>
2549      *   <dt>decimalSeparator {String}</dd>
2550      *   <dd>Decimal separator</dd>
2551      *   <dt>thousandsSeparator {String}</dd>
2552      *   <dd>Thousands separator</dd>
2553      *   <dt>suffix {String}</dd>
2554      *   <dd>String appended after each number, like " items" (note the space)</dd>
2555      *  </dl>
2556      * @return {String} Formatted number for display. Note, the following values
2557      * return as "": null, undefined, NaN, "".     
2558      */
2559     format : function(nData, oConfig) {
2560         var lang = YAHOO.lang;
2561         if(!lang.isValue(nData) || (nData === "")) {
2562             return "";
2563         }
2564
2565         oConfig = oConfig || {};
2566         
2567         if(!lang.isNumber(nData)) {
2568             nData *= 1;
2569         }
2570
2571         if(lang.isNumber(nData)) {
2572             var bNegative = (nData < 0);
2573             var sOutput = nData + "";
2574             var sDecimalSeparator = (oConfig.decimalSeparator) ? oConfig.decimalSeparator : ".";
2575             var nDotIndex;
2576
2577             // Manage decimals
2578             if(lang.isNumber(oConfig.decimalPlaces)) {
2579                 // Round to the correct decimal place
2580                 var nDecimalPlaces = oConfig.decimalPlaces;
2581                 var nDecimal = Math.pow(10, nDecimalPlaces);
2582                 sOutput = Math.round(nData*nDecimal)/nDecimal + "";
2583                 nDotIndex = sOutput.lastIndexOf(".");
2584
2585                 if(nDecimalPlaces > 0) {
2586                     // Add the decimal separator
2587                     if(nDotIndex < 0) {
2588                         sOutput += sDecimalSeparator;
2589                         nDotIndex = sOutput.length-1;
2590                     }
2591                     // Replace the "."
2592                     else if(sDecimalSeparator !== "."){
2593                         sOutput = sOutput.replace(".",sDecimalSeparator);
2594                     }
2595                     // Add missing zeros
2596                     while((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) {
2597                         sOutput += "0";
2598                     }
2599                 }
2600             }
2601             
2602             // Add the thousands separator
2603             if(oConfig.thousandsSeparator) {
2604                 var sThousandsSeparator = oConfig.thousandsSeparator;
2605                 nDotIndex = sOutput.lastIndexOf(sDecimalSeparator);
2606                 nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length;
2607                 var sNewOutput = sOutput.substring(nDotIndex);
2608                 var nCount = -1;
2609                 for (var i=nDotIndex; i>0; i--) {
2610                     nCount++;
2611                     if ((nCount%3 === 0) && (i !== nDotIndex) && (!bNegative || (i > 1))) {
2612                         sNewOutput = sThousandsSeparator + sNewOutput;
2613                     }
2614                     sNewOutput = sOutput.charAt(i-1) + sNewOutput;
2615                 }
2616                 sOutput = sNewOutput;
2617             }
2618
2619             // Prepend prefix
2620             sOutput = (oConfig.prefix) ? oConfig.prefix + sOutput : sOutput;
2621
2622             // Append suffix
2623             sOutput = (oConfig.suffix) ? sOutput + oConfig.suffix : sOutput;
2624
2625             return sOutput;
2626         }
2627         // Still not a Number, just return unaltered
2628         else {
2629             return nData;
2630         }
2631     }
2632  };
2633
2634
2635
2636 /****************************************************************************/
2637 /****************************************************************************/
2638 /****************************************************************************/
2639
2640 (function () {
2641
2642 var xPad=function (x, pad, r)
2643 {
2644     if(typeof r === 'undefined')
2645     {
2646         r=10;
2647     }
2648     for( ; parseInt(x, 10)<r && r>1; r/=10) {
2649         x = pad.toString() + x;
2650     }
2651     return x.toString();
2652 };
2653
2654
2655 /**
2656  * The static Date class provides helper functions to deal with data of type Date.
2657  *
2658  * @namespace YAHOO.util
2659  * @requires yahoo
2660  * @class Date
2661  * @static
2662  */
2663  var Dt = {
2664     formats: {
2665         a: function (d, l) { return l.a[d.getDay()]; },
2666         A: function (d, l) { return l.A[d.getDay()]; },
2667         b: function (d, l) { return l.b[d.getMonth()]; },
2668         B: function (d, l) { return l.B[d.getMonth()]; },
2669         C: function (d) { return xPad(parseInt(d.getFullYear()/100, 10), 0); },
2670         d: ['getDate', '0'],
2671         e: ['getDate', ' '],
2672         g: function (d) { return xPad(parseInt(Dt.formats.G(d)%100, 10), 0); },
2673         G: function (d) {
2674                 var y = d.getFullYear();
2675                 var V = parseInt(Dt.formats.V(d), 10);
2676                 var W = parseInt(Dt.formats.W(d), 10);
2677     
2678                 if(W > V) {
2679                     y++;
2680                 } else if(W===0 && V>=52) {
2681                     y--;
2682                 }
2683     
2684                 return y;
2685             },
2686         H: ['getHours', '0'],
2687         I: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, 0); },
2688         j: function (d) {
2689                 var gmd_1 = new Date('' + d.getFullYear() + '/1/1 GMT');
2690                 var gmdate = new Date('' + d.getFullYear() + '/' + (d.getMonth()+1) + '/' + d.getDate() + ' GMT');
2691                 var ms = gmdate - gmd_1;
2692                 var doy = parseInt(ms/60000/60/24, 10)+1;
2693                 return xPad(doy, 0, 100);
2694             },
2695         k: ['getHours', ' '],
2696         l: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, ' '); },
2697         m: function (d) { return xPad(d.getMonth()+1, 0); },
2698         M: ['getMinutes', '0'],
2699         p: function (d, l) { return l.p[d.getHours() >= 12 ? 1 : 0 ]; },
2700         P: function (d, l) { return l.P[d.getHours() >= 12 ? 1 : 0 ]; },
2701         s: function (d, l) { return parseInt(d.getTime()/1000, 10); },
2702         S: ['getSeconds', '0'],
2703         u: function (d) { var dow = d.getDay(); return dow===0?7:dow; },
2704         U: function (d) {
2705                 var doy = parseInt(Dt.formats.j(d), 10);
2706                 var rdow = 6-d.getDay();
2707                 var woy = parseInt((doy+rdow)/7, 10);
2708                 return xPad(woy, 0);
2709             },
2710         V: function (d) {
2711                 var woy = parseInt(Dt.formats.W(d), 10);
2712                 var dow1_1 = (new Date('' + d.getFullYear() + '/1/1')).getDay();
2713                 // First week is 01 and not 00 as in the case of %U and %W,
2714                 // so we add 1 to the final result except if day 1 of the year
2715                 // is a Monday (then %W returns 01).
2716                 // We also need to subtract 1 if the day 1 of the year is 
2717                 // Friday-Sunday, so the resulting equation becomes:
2718                 var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1);
2719                 if(idow === 53 && (new Date('' + d.getFullYear() + '/12/31')).getDay() < 4)
2720                 {
2721                     idow = 1;
2722                 }
2723                 else if(idow === 0)
2724                 {
2725                     idow = Dt.formats.V(new Date('' + (d.getFullYear()-1) + '/12/31'));
2726                 }
2727     
2728                 return xPad(idow, 0);
2729             },
2730         w: 'getDay',
2731         W: function (d) {
2732                 var doy = parseInt(Dt.formats.j(d), 10);
2733                 var rdow = 7-Dt.formats.u(d);
2734                 var woy = parseInt((doy+rdow)/7, 10);
2735                 return xPad(woy, 0, 10);
2736             },
2737         y: function (d) { return xPad(d.getFullYear()%100, 0); },
2738         Y: 'getFullYear',
2739         z: function (d) {
2740                 var o = d.getTimezoneOffset();
2741                 var H = xPad(parseInt(Math.abs(o/60), 10), 0);
2742                 var M = xPad(Math.abs(o%60), 0);
2743                 return (o>0?'-':'+') + H + M;
2744             },
2745         Z: function (d) {
2746                 var tz = d.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/, '$2').replace(/[a-z ]/g, '');
2747                 if(tz.length > 4) {
2748                         tz = Dt.formats.z(d);
2749                 }
2750                 return tz;
2751         },
2752         '%': function (d) { return '%'; }
2753     },
2754
2755     aggregates: {
2756         c: 'locale',
2757         D: '%m/%d/%y',
2758         F: '%Y-%m-%d',
2759         h: '%b',
2760         n: '\n',
2761         r: 'locale',
2762         R: '%H:%M',
2763         t: '\t',
2764         T: '%H:%M:%S',
2765         x: 'locale',
2766         X: 'locale'
2767         //'+': '%a %b %e %T %Z %Y'
2768     },
2769
2770      /**
2771      * Takes a native JavaScript Date and formats to string for display to user.
2772      *
2773      * @method format
2774      * @param oDate {Date} Date.
2775      * @param oConfig {Object} (Optional) Object literal of configuration values:
2776      *  <dl>
2777      *   <dt>format &lt;String&gt;</dt>
2778      *   <dd>
2779      *   <p>
2780      *   Any strftime string is supported, such as "%I:%M:%S %p". strftime has several format specifiers defined by the Open group at 
2781      *   <a href="http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html">http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html</a>
2782      *   </p>
2783      *   <p>   
2784      *   PHP added a few of its own, defined at <a href="http://www.php.net/strftime">http://www.php.net/strftime</a>
2785      *   </p>
2786      *   <p>
2787      *   This javascript implementation supports all the PHP specifiers and a few more.  The full list is below:
2788      *   </p>
2789      *   <dl>
2790      *    <dt>%a</dt> <dd>abbreviated weekday name according to the current locale</dd>
2791      *    <dt>%A</dt> <dd>full weekday name according to the current locale</dd>
2792      *    <dt>%b</dt> <dd>abbreviated month name according to the current locale</dd>
2793      *    <dt>%B</dt> <dd>full month name according to the current locale</dd>
2794      *    <dt>%c</dt> <dd>preferred date and time representation for the current locale</dd>
2795      *    <dt>%C</dt> <dd>century number (the year divided by 100 and truncated to an integer, range 00 to 99)</dd>
2796      *    <dt>%d</dt> <dd>day of the month as a decimal number (range 01 to 31)</dd>
2797      *    <dt>%D</dt> <dd>same as %m/%d/%y</dd>
2798      *    <dt>%e</dt> <dd>day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')</dd>
2799      *    <dt>%F</dt> <dd>same as %Y-%m-%d (ISO 8601 date format)</dd>
2800      *    <dt>%g</dt> <dd>like %G, but without the century</dd>
2801      *    <dt>%G</dt> <dd>The 4-digit year corresponding to the ISO week number</dd>
2802      *    <dt>%h</dt> <dd>same as %b</dd>
2803      *    <dt>%H</dt> <dd>hour as a decimal number using a 24-hour clock (range 00 to 23)</dd>
2804      *    <dt>%I</dt> <dd>hour as a decimal number using a 12-hour clock (range 01 to 12)</dd>
2805      *    <dt>%j</dt> <dd>day of the year as a decimal number (range 001 to 366)</dd>
2806      *    <dt>%k</dt> <dd>hour as a decimal number using a 24-hour clock (range 0 to 23); single digits are preceded by a blank. (See also %H.)</dd>
2807      *    <dt>%l</dt> <dd>hour as a decimal number using a 12-hour clock (range 1 to 12); single digits are preceded by a blank. (See also %I.) </dd>
2808      *    <dt>%m</dt> <dd>month as a decimal number (range 01 to 12)</dd>
2809      *    <dt>%M</dt> <dd>minute as a decimal number</dd>
2810      *    <dt>%n</dt> <dd>newline character</dd>
2811      *    <dt>%p</dt> <dd>either `AM' or `PM' according to the given time value, or the corresponding strings for the current locale</dd>
2812      *    <dt>%P</dt> <dd>like %p, but lower case</dd>
2813      *    <dt>%r</dt> <dd>time in a.m. and p.m. notation equal to %I:%M:%S %p</dd>
2814      *    <dt>%R</dt> <dd>time in 24 hour notation equal to %H:%M</dd>
2815      *    <dt>%s</dt> <dd>number of seconds since the Epoch, ie, since 1970-01-01 00:00:00 UTC</dd>
2816      *    <dt>%S</dt> <dd>second as a decimal number</dd>
2817      *    <dt>%t</dt> <dd>tab character</dd>
2818      *    <dt>%T</dt> <dd>current time, equal to %H:%M:%S</dd>
2819      *    <dt>%u</dt> <dd>weekday as a decimal number [1,7], with 1 representing Monday</dd>
2820      *    <dt>%U</dt> <dd>week number of the current year as a decimal number, starting with the
2821      *            first Sunday as the first day of the first week</dd>
2822      *    <dt>%V</dt> <dd>The ISO 8601:1988 week number of the current year as a decimal number,
2823      *            range 01 to 53, where week 1 is the first week that has at least 4 days
2824      *            in the current year, and with Monday as the first day of the week.</dd>
2825      *    <dt>%w</dt> <dd>day of the week as a decimal, Sunday being 0</dd>
2826      *    <dt>%W</dt> <dd>week number of the current year as a decimal number, starting with the
2827      *            first Monday as the first day of the first week</dd>
2828      *    <dt>%x</dt> <dd>preferred date representation for the current locale without the time</dd>
2829      *    <dt>%X</dt> <dd>preferred time representation for the current locale without the date</dd>
2830      *    <dt>%y</dt> <dd>year as a decimal number without a century (range 00 to 99)</dd>
2831      *    <dt>%Y</dt> <dd>year as a decimal number including the century</dd>
2832      *    <dt>%z</dt> <dd>numerical time zone representation</dd>
2833      *    <dt>%Z</dt> <dd>time zone name or abbreviation</dd>
2834      *    <dt>%%</dt> <dd>a literal `%' character</dd>
2835      *   </dl>
2836      *  </dd>
2837      * </dl>
2838      * @param sLocale {String} (Optional) The locale to use when displaying days of week,
2839      *  months of the year, and other locale specific strings.  The following locales are
2840      *  built in:
2841      *  <dl>
2842      *   <dt>en</dt>
2843      *   <dd>English</dd>
2844      *   <dt>en-US</dt>
2845      *   <dd>US English</dd>
2846      *   <dt>en-GB</dt>
2847      *   <dd>British English</dd>
2848      *   <dt>en-AU</dt>
2849      *   <dd>Australian English (identical to British English)</dd>
2850      *  </dl>
2851      *  More locales may be added by subclassing of YAHOO.util.DateLocale.
2852      *  See YAHOO.util.DateLocale for more information.
2853      * @return {String} Formatted date for display.
2854      * @sa YAHOO.util.DateLocale
2855      */
2856     format : function (oDate, oConfig, sLocale) {
2857         oConfig = oConfig || {};
2858         
2859         if(!(oDate instanceof Date)) {
2860             return YAHOO.lang.isValue(oDate) ? oDate : "";
2861         }
2862
2863         var format = oConfig.format || "%m/%d/%Y";
2864
2865         // Be backwards compatible, support strings that are
2866         // exactly equal to YYYY/MM/DD, DD/MM/YYYY and MM/DD/YYYY
2867         if(format === 'YYYY/MM/DD') {
2868             format = '%Y/%m/%d';
2869         } else if(format === 'DD/MM/YYYY') {
2870             format = '%d/%m/%Y';
2871         } else if(format === 'MM/DD/YYYY') {
2872             format = '%m/%d/%Y';
2873         }
2874         // end backwards compatibility block
2875  
2876         sLocale = sLocale || "en";
2877
2878         // Make sure we have a definition for the requested locale, or default to en.
2879         if(!(sLocale in YAHOO.util.DateLocale)) {
2880             if(sLocale.replace(/-[a-zA-Z]+$/, '') in YAHOO.util.DateLocale) {
2881                 sLocale = sLocale.replace(/-[a-zA-Z]+$/, '');
2882             } else {
2883                 sLocale = "en";
2884             }
2885         }
2886
2887         var aLocale = YAHOO.util.DateLocale[sLocale];
2888
2889         var replace_aggs = function (m0, m1) {
2890             var f = Dt.aggregates[m1];
2891             return (f === 'locale' ? aLocale[m1] : f);
2892         };
2893
2894         var replace_formats = function (m0, m1) {
2895             var f = Dt.formats[m1];
2896             if(typeof f === 'string') {             // string => built in date function
2897                 return oDate[f]();
2898             } else if(typeof f === 'function') {    // function => our own function
2899                 return f.call(oDate, oDate, aLocale);
2900             } else if(typeof f === 'object' && typeof f[0] === 'string') {  // built in function with padding
2901                 return xPad(oDate[f[0]](), f[1]);
2902             } else {
2903                 return m1;
2904             }
2905         };
2906
2907         // First replace aggregates (run in a loop because an agg may be made up of other aggs)
2908         while(format.match(/%[cDFhnrRtTxX]/)) {
2909             format = format.replace(/%([cDFhnrRtTxX])/g, replace_aggs);
2910         }
2911
2912         // Now replace formats (do not run in a loop otherwise %%a will be replace with the value of %a)
2913         var str = format.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g, replace_formats);
2914
2915         replace_aggs = replace_formats = undefined;
2916
2917         return str;
2918     }
2919  };
2920  
2921  YAHOO.namespace("YAHOO.util");
2922  YAHOO.util.Date = Dt;
2923
2924 /**
2925  * The DateLocale class is a container and base class for all
2926  * localised date strings used by YAHOO.util.Date. It is used
2927  * internally, but may be extended to provide new date localisations.
2928  *
2929  * To create your own DateLocale, follow these steps:
2930  * <ol>
2931  *  <li>Find an existing locale that matches closely with your needs</li>
2932  *  <li>Use this as your base class.  Use YAHOO.util.DateLocale if nothing
2933  *   matches.</li>
2934  *  <li>Create your own class as an extension of the base class using
2935  *   YAHOO.lang.merge, and add your own localisations where needed.</li>
2936  * </ol>
2937  * See the YAHOO.util.DateLocale['en-US'] and YAHOO.util.DateLocale['en-GB']
2938  * classes which extend YAHOO.util.DateLocale['en'].
2939  *
2940  * For example, to implement locales for French french and Canadian french,
2941  * we would do the following:
2942  * <ol>
2943  *  <li>For French french, we have no existing similar locale, so use
2944  *   YAHOO.util.DateLocale as the base, and extend it:
2945  *   <pre>
2946  *      YAHOO.util.DateLocale['fr'] = YAHOO.lang.merge(YAHOO.util.DateLocale, {
2947  *          a: ['dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam'],
2948  *          A: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
2949  *          b: ['jan', 'f&eacute;v', 'mar', 'avr', 'mai', 'jun', 'jui', 'ao&ucirc;', 'sep', 'oct', 'nov', 'd&eacute;c'],
2950  *          B: ['janvier', 'f&eacute;vrier', 'mars', 'avril', 'mai', 'juin', 'juillet', 'ao&ucirc;t', 'septembre', 'octobre', 'novembre', 'd&eacute;cembre'],
2951  *          c: '%a %d %b %Y %T %Z',
2952  *          p: ['', ''],
2953  *          P: ['', ''],
2954  *          x: '%d.%m.%Y',
2955  *          X: '%T'
2956  *      });
2957  *   </pre>
2958  *  </li>
2959  *  <li>For Canadian french, we start with French french and change the meaning of \%x:
2960  *   <pre>
2961  *      YAHOO.util.DateLocale['fr-CA'] = YAHOO.lang.merge(YAHOO.util.DateLocale['fr'], {
2962  *          x: '%Y-%m-%d'
2963  *      });
2964  *   </pre>
2965  *  </li>
2966  * </ol>
2967  *
2968  * With that, you can use your new locales:
2969  * <pre>
2970  *    var d = new Date("2008/04/22");
2971  *    YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr");
2972  * </pre>
2973  * will return:
2974  * <pre>
2975  *    mardi, 22 avril == 22.04.2008
2976  * </pre>
2977  * And
2978  * <pre>
2979  *    YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr-CA");
2980  * </pre>
2981  * Will return:
2982  * <pre>
2983  *   mardi, 22 avril == 2008-04-22
2984  * </pre>
2985  * @namespace YAHOO.util
2986  * @requires yahoo
2987  * @class DateLocale
2988  */
2989  YAHOO.util.DateLocale = {
2990         a: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
2991         A: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
2992         b: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
2993         B: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
2994         c: '%a %d %b %Y %T %Z',
2995         p: ['AM', 'PM'],
2996         P: ['am', 'pm'],
2997         r: '%I:%M:%S %p',
2998         x: '%d/%m/%y',
2999         X: '%T'
3000  };
3001
3002  YAHOO.util.DateLocale['en'] = YAHOO.lang.merge(YAHOO.util.DateLocale, {});
3003
3004  YAHOO.util.DateLocale['en-US'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], {
3005         c: '%a %d %b %Y %I:%M:%S %p %Z',
3006         x: '%m/%d/%Y',
3007         X: '%I:%M:%S %p'
3008  });
3009
3010  YAHOO.util.DateLocale['en-GB'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], {
3011         r: '%l:%M:%S %P %Z'
3012  });
3013  YAHOO.util.DateLocale['en-AU'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en']);
3014
3015 })();
3016
3017 YAHOO.register("datasource", YAHOO.util.DataSource, {version: "2.7.0", build: "1799"});