Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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