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