2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
14 * The DataSource utility provides a common configurable interface for widgets to
15 * access a variety of data, from JavaScript arrays to online database servers.
18 * @requires yahoo, event
19 * @optional json, get, connection
20 * @title DataSource Utility
23 /****************************************************************************/
24 /****************************************************************************/
25 /****************************************************************************/
28 * Base class for the YUI DataSource utility.
30 * @namespace YAHOO.util
31 * @class YAHOO.util.DataSourceBase
33 * @param oLiveData {HTMLElement} Pointer to live data.
34 * @param oConfigs {object} (optional) Object literal of configuration values.
36 util.DataSourceBase = function(oLiveData, oConfigs) {
37 if(oLiveData === null || oLiveData === undefined) {
38 YAHOO.log("Could not instantiate DataSource due to invalid live database",
39 "error", this.toString());
43 this.liveData = oLiveData;
44 this._oQueue = {interval:null, conn:null, requests:[]};
45 this.responseSchema = {};
47 // Set any config params passed in to override defaults
48 if(oConfigs && (oConfigs.constructor == Object)) {
49 for(var sConfig in oConfigs) {
51 this[sConfig] = oConfigs[sConfig];
56 // Validate and initialize public configs
57 var maxCacheEntries = this.maxCacheEntries;
58 if(!lang.isNumber(maxCacheEntries) || (maxCacheEntries < 0)) {
62 // Initialize interval tracker
63 this._aIntervals = [];
65 /////////////////////////////////////////////////////////////////////////////
69 /////////////////////////////////////////////////////////////////////////////
72 * Fired when a request is made to the local cache.
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.
79 this.createEvent("cacheRequestEvent");
82 * Fired when data is retrieved from the local cache.
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.
90 this.createEvent("cacheResponseEvent");
93 * Fired when a request is sent to the live data source.
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.
101 this.createEvent("requestEvent");
104 * Fired when live data source sends response.
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.
113 this.createEvent("responseEvent");
116 * Fired when response is parsed.
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.
124 this.createEvent("responseParseEvent");
127 * Fired when response is cached.
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.
135 this.createEvent("responseCacheEvent");
137 * Fired when an error is encountered with the live data source.
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.
146 this.createEvent("dataErrorEvent");
149 * Fired when the local cache is flushed.
151 * @event cacheFlushEvent
153 this.createEvent("cacheFlushEvent");
155 var DS = util.DataSourceBase;
156 this._sName = "DataSource instance" + DS._nIndex;
158 YAHOO.log("DataSource initialized", "info", this.toString());
161 var DS = util.DataSourceBase;
163 lang.augmentObject(DS, {
165 /////////////////////////////////////////////////////////////////////////////
167 // DataSourceBase public constants
169 /////////////////////////////////////////////////////////////////////////////
174 * @property TYPE_UNKNOWN
182 * Type is a JavaScript Array.
184 * @property TYPE_JSARRAY
192 * Type is a JavaScript Function.
194 * @property TYPE_JSFUNCTION
202 * Type is hosted on a server via an XHR connection.
214 * @property TYPE_JSON
232 * Type is plain text.
234 * @property TYPE_TEXT
242 * Type is an HTML TABLE element. Data is parsed out of TR elements from all TBODY elements.
244 * @property TYPE_HTMLTABLE
252 * Type is hosted on a server via a dynamic script node.
254 * @property TYPE_SCRIPTNODE
264 * @property TYPE_LOCAL
272 * Error message for invalid dataresponses.
274 * @property ERROR_DATAINVALID
277 * @default "Invalid data"
279 ERROR_DATAINVALID : "Invalid data",
282 * Error message for null data responses.
284 * @property ERROR_DATANULL
287 * @default "Null data"
289 ERROR_DATANULL : "Null data",
291 /////////////////////////////////////////////////////////////////////////////
293 // DataSourceBase private static properties
295 /////////////////////////////////////////////////////////////////////////////
298 * Internal class variable to index multiple DataSource instances.
300 * @property DataSourceBase._nIndex
308 * Internal class variable to assign unique transaction IDs.
310 * @property DataSourceBase._nTransactionId
317 /////////////////////////////////////////////////////////////////////////////
319 // DataSourceBase private static methods
321 /////////////////////////////////////////////////////////////////////////////
324 * Get an XPath-specified value for a given field from an XML node or document.
326 * @method _getLocationValue
327 * @param field {String | Object} Field definition.
328 * @param context {Object} XML node or document to search within.
329 * @return {Object} Data value or null.
333 _getLocationValue: function(field, context) {
334 var locator = field.locator || field.key || field,
335 xmldoc = context.ownerDocument || context,
336 result, res, value = null;
340 if(!lang.isUndefined(xmldoc.evaluate)) {
341 result = xmldoc.evaluate(locator, context, xmldoc.createNSResolver(!context.ownerDocument ? context.documentElement : context.ownerDocument.documentElement), 0, null);
342 while(res = result.iterateNext()) {
343 value = res.textContent;
348 xmldoc.setProperty("SelectionLanguage", "XPath");
349 result = context.selectNodes(locator)[0];
350 value = result.value || result.text || null;
359 /////////////////////////////////////////////////////////////////////////////
361 // DataSourceBase public static methods
363 /////////////////////////////////////////////////////////////////////////////
366 * Executes a configured callback. For object literal callbacks, the third
367 * param determines whether to execute the success handler or failure handler.
369 * @method issueCallback
370 * @param callback {Function|Object} the callback to execute
371 * @param params {Array} params to be passed to the callback method
372 * @param error {Boolean} whether an error occurred
373 * @param scope {Object} the scope from which to execute the callback
374 * (deprecated - use an object literal callback)
377 issueCallback : function (callback,params,error,scope) {
378 if (lang.isFunction(callback)) {
379 callback.apply(scope, params);
380 } else if (lang.isObject(callback)) {
381 scope = callback.scope || scope || window;
382 var callbackFunc = callback.success;
384 callbackFunc = callback.failure;
387 callbackFunc.apply(scope, params.concat([callback.argument]));
393 * Converts data to type String.
395 * @method DataSourceBase.parseString
396 * @param oData {String | Number | Boolean | Date | Array | Object} Data to parse.
397 * The special values null and undefined will return null.
398 * @return {String} A string, or null.
401 parseString : function(oData) {
402 // Special case null and undefined
403 if(!lang.isValue(oData)) {
408 var string = oData + "";
411 if(lang.isString(string)) {
415 YAHOO.log("Could not convert data " + lang.dump(oData) + " to type String", "warn", this.toString());
421 * Converts data to type Number.
423 * @method DataSourceBase.parseNumber
424 * @param oData {String | Number | Boolean} Data to convert. Note, the following
425 * values return as null: null, undefined, NaN, "".
426 * @return {Number} A number, or null.
429 parseNumber : function(oData) {
430 if(!lang.isValue(oData) || (oData === "")) {
435 var number = oData * 1;
438 if(lang.isNumber(number)) {
442 YAHOO.log("Could not convert data " + lang.dump(oData) + " to type Number", "warn", this.toString());
446 // Backward compatibility
447 convertNumber : function(oData) {
448 YAHOO.log("The method YAHOO.util.DataSourceBase.convertNumber() has been" +
449 " deprecated in favor of YAHOO.util.DataSourceBase.parseNumber()", "warn",
451 return DS.parseNumber(oData);
455 * Converts data to type Date.
457 * @method DataSourceBase.parseDate
458 * @param oData {Date | String | Number} Data to convert.
459 * @return {Date} A Date instance.
462 parseDate : function(oData) {
466 if(!(oData instanceof Date)) {
467 date = new Date(oData);
474 if(date instanceof Date) {
478 YAHOO.log("Could not convert data " + lang.dump(oData) + " to type Date", "warn", this.toString());
482 // Backward compatibility
483 convertDate : function(oData) {
484 YAHOO.log("The method YAHOO.util.DataSourceBase.convertDate() has been" +
485 " deprecated in favor of YAHOO.util.DataSourceBase.parseDate()", "warn",
487 return DS.parseDate(oData);
492 // Done in separate step so referenced functions are defined.
494 * Data parsing functions.
495 * @property DataSource.Parser
500 string : DS.parseString,
501 number : DS.parseNumber,
505 // Prototype properties and methods
508 /////////////////////////////////////////////////////////////////////////////
510 // DataSourceBase private properties
512 /////////////////////////////////////////////////////////////////////////////
515 * Name of DataSource instance.
524 * Local cache of data result object literals indexed chronologically.
533 * Local queue of request connections, enabled if queue needs to be managed.
542 * Array of polling interval IDs that have been enabled, needed to clear all intervals.
544 * @property _aIntervals
550 /////////////////////////////////////////////////////////////////////////////
552 // DataSourceBase public properties
554 /////////////////////////////////////////////////////////////////////////////
557 * Max size of the local cache. Set to 0 to turn off caching. Caching is
558 * useful to reduce the number of server connections. Recommended only for data
559 * sources that return comprehensive results for queries or when stale data is
562 * @property maxCacheEntries
569 * Pointer to live database.
577 * Where the live data is held:
580 * <dt>TYPE_UNKNOWN</dt>
581 * <dt>TYPE_LOCAL</dt>
583 * <dt>TYPE_SCRIPTNODE</dt>
584 * <dt>TYPE_JSFUNCTION</dt>
589 * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN
592 dataType : DS.TYPE_UNKNOWN,
595 * Format of response:
598 * <dt>TYPE_UNKNOWN</dt>
599 * <dt>TYPE_JSARRAY</dt>
603 * <dt>TYPE_HTMLTABLE</dt>
606 * @property responseType
608 * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN
610 responseType : DS.TYPE_UNKNOWN,
613 * Response schema object literal takes a combination of the following properties:
616 * <dt>resultsList</dt> <dd>Pointer to array of tabular data</dd>
617 * <dt>resultNode</dt> <dd>Pointer to node name of row data (XML data only)</dd>
618 * <dt>recordDelim</dt> <dd>Record delimiter (text data only)</dd>
619 * <dt>fieldDelim</dt> <dd>Field delimiter (text data only)</dd>
620 * <dt>fields</dt> <dd>Array of field names (aka keys), or array of object literals
621 * such as: {key:"fieldname",parser:YAHOO.util.DataSourceBase.parseDate}</dd>
622 * <dt>metaFields</dt> <dd>Object literal of keys to include in the oParsedResponse.meta collection</dd>
623 * <dt>metaNode</dt> <dd>Name of the node under which to search for meta information in XML response data</dd>
626 * @property responseSchema
629 responseSchema : null,
632 * Additional arguments passed to the JSON parse routine. The JSON string
633 * is the assumed first argument (where applicable). This property is not
634 * set by default, but the parse methods will use it if present.
636 * @property parseJSONArgs
637 * @type {MIXED|Array} If an Array, contents are used as individual arguments.
638 * Otherwise, value is used as an additional argument.
640 // property intentionally undefined
643 * When working with XML data, setting this property to true enables support for
644 * XPath-syntaxed locators in schema definitions.
652 /////////////////////////////////////////////////////////////////////////////
654 // DataSourceBase public methods
656 /////////////////////////////////////////////////////////////////////////////
659 * Public accessor to the unique name of the DataSource instance.
662 * @return {String} Unique name of the DataSource instance.
664 toString : function() {
669 * Overridable method passes request to cache and returns cached response if any,
670 * refreshing the hit in the cache as the newest item. Returns null if there is
673 * @method getCachedResponse
674 * @param oRequest {Object} Request object.
675 * @param oCallback {Object} Callback object.
676 * @param oCaller {Object} (deprecated) Use callback object.
677 * @return {Object} Cached response object or null.
679 getCachedResponse : function(oRequest, oCallback, oCaller) {
680 var aCache = this._aCache;
682 // If cache is enabled...
683 if(this.maxCacheEntries > 0) {
684 // Initialize local cache
687 YAHOO.log("Cache initialized", "info", this.toString());
689 // Look in local cache
691 var nCacheLength = aCache.length;
692 if(nCacheLength > 0) {
693 var oResponse = null;
694 this.fireEvent("cacheRequestEvent", {request:oRequest,callback:oCallback,caller:oCaller});
696 // Loop through each cached element
697 for(var i = nCacheLength-1; i >= 0; i--) {
698 var oCacheElem = aCache[i];
700 // Defer cache hit logic to a public overridable method
701 if(this.isCacheHit(oRequest,oCacheElem.request)) {
702 // The cache returned a hit!
703 // Grab the cached response
704 oResponse = oCacheElem.response;
705 this.fireEvent("cacheResponseEvent", {request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});
707 // Refresh the position of the cache hit
708 if(i < nCacheLength-1) {
709 // Remove element from its original location
712 this.addToCache(oRequest, oResponse);
713 YAHOO.log("Refreshed cache position of the response for \"" + oRequest + "\"", "info", this.toString());
717 oResponse.cached = true;
721 YAHOO.log("The cached response for \"" + lang.dump(oRequest) +
722 "\" is " + lang.dump(oResponse), "info", this.toString());
729 YAHOO.log("Cache destroyed", "info", this.toString());
735 * Default overridable method matches given request to given cached request.
736 * Returns true if is a hit, returns false otherwise. Implementers should
737 * override this method to customize the cache-matching algorithm.
740 * @param oRequest {Object} Request object.
741 * @param oCachedRequest {Object} Cached request object.
742 * @return {Boolean} True if given request matches cached request, false otherwise.
744 isCacheHit : function(oRequest, oCachedRequest) {
745 return (oRequest === oCachedRequest);
749 * Adds a new item to the cache. If cache is full, evicts the stalest item
750 * before adding the new item.
753 * @param oRequest {Object} Request object.
754 * @param oResponse {Object} Response object to cache.
756 addToCache : function(oRequest, oResponse) {
757 var aCache = this._aCache;
762 // If the cache is full, make room by removing stalest element (index=0)
763 while(aCache.length >= this.maxCacheEntries) {
767 // Add to cache in the newest position, at the end of the array
768 var oCacheElem = {request:oRequest,response:oResponse};
769 aCache[aCache.length] = oCacheElem;
770 this.fireEvent("responseCacheEvent", {request:oRequest,response:oResponse});
771 YAHOO.log("Cached the response for \"" + oRequest + "\"", "info", this.toString());
779 flushCache : function() {
782 this.fireEvent("cacheFlushEvent");
783 YAHOO.log("Flushed the cache", "info", this.toString());
788 * Sets up a polling mechanism to send requests at set intervals and forward
789 * responses to given callback.
791 * @method setInterval
792 * @param nMsec {Number} Length of interval in milliseconds.
793 * @param oRequest {Object} Request object.
794 * @param oCallback {Function} Handler function to receive the response.
795 * @param oCaller {Object} (deprecated) Use oCallback.scope.
796 * @return {Number} Interval ID.
798 setInterval : function(nMsec, oRequest, oCallback, oCaller) {
799 if(lang.isNumber(nMsec) && (nMsec >= 0)) {
800 YAHOO.log("Enabling polling to live data for \"" + oRequest + "\" at interval " + nMsec, "info", this.toString());
802 var nId = setInterval(function() {
803 oSelf.makeConnection(oRequest, oCallback, oCaller);
805 this._aIntervals.push(nId);
809 YAHOO.log("Could not enable polling to live data for \"" + oRequest + "\" at interval " + nMsec, "info", this.toString());
814 * Disables polling mechanism associated with the given interval ID.
816 * @method clearInterval
817 * @param nId {Number} Interval ID.
819 clearInterval : function(nId) {
820 // Remove from tracker if there
821 var tracker = this._aIntervals || [];
822 for(var i=tracker.length-1; i>-1; i--) {
823 if(tracker[i] === nId) {
831 * Disables all known polling intervals.
833 * @method clearAllIntervals
835 clearAllIntervals : function() {
836 var tracker = this._aIntervals || [];
837 for(var i=tracker.length-1; i>-1; i--) {
838 clearInterval(tracker[i]);
844 * First looks for cached response, then sends request to live data. The
845 * following arguments are passed to the callback function:
847 * <dt><code>oRequest</code></dt>
848 * <dd>The same value that was passed in as the first argument to sendRequest.</dd>
849 * <dt><code>oParsedResponse</code></dt>
850 * <dd>An object literal containing the following properties:
852 * <dt><code>tId</code></dt>
853 * <dd>Unique transaction ID number.</dd>
854 * <dt><code>results</code></dt>
855 * <dd>Schema-parsed data results.</dd>
856 * <dt><code>error</code></dt>
857 * <dd>True in cases of data error.</dd>
858 * <dt><code>cached</code></dt>
859 * <dd>True when response is returned from DataSource cache.</dd>
860 * <dt><code>meta</code></dt>
861 * <dd>Schema-parsed meta data.</dd>
863 * <dt><code>oPayload</code></dt>
864 * <dd>The same value as was passed in as <code>argument</code> in the oCallback object literal.</dd>
867 * @method sendRequest
868 * @param oRequest {Object} Request object.
869 * @param oCallback {Object} An object literal with the following properties:
871 * <dt><code>success</code></dt>
872 * <dd>The function to call when the data is ready.</dd>
873 * <dt><code>failure</code></dt>
874 * <dd>The function to call upon a response failure condition.</dd>
875 * <dt><code>scope</code></dt>
876 * <dd>The object to serve as the scope for the success and failure handlers.</dd>
877 * <dt><code>argument</code></dt>
878 * <dd>Arbitrary data that will be passed back to the success and failure handlers.</dd>
880 * @param oCaller {Object} (deprecated) Use oCallback.scope.
881 * @return {Number} Transaction ID, or null if response found in cache.
883 sendRequest : function(oRequest, oCallback, oCaller) {
884 // First look in cache
885 var oCachedResponse = this.getCachedResponse(oRequest, oCallback, oCaller);
886 if(oCachedResponse) {
887 DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller);
892 // Not in cache, so forward request to live data
893 YAHOO.log("Making connection to live data for \"" + oRequest + "\"", "info", this.toString());
894 return this.makeConnection(oRequest, oCallback, oCaller);
898 * Overridable default method generates a unique transaction ID and passes
899 * the live data reference directly to the handleResponse function. This
900 * method should be implemented by subclasses to achieve more complex behavior
901 * or to access remote data.
903 * @method makeConnection
904 * @param oRequest {Object} Request object.
905 * @param oCallback {Object} Callback object literal.
906 * @param oCaller {Object} (deprecated) Use oCallback.scope.
907 * @return {Number} Transaction ID.
909 makeConnection : function(oRequest, oCallback, oCaller) {
910 var tId = DS._nTransactionId++;
911 this.fireEvent("requestEvent", {tId:tId, request:oRequest,callback:oCallback,caller:oCaller});
913 /* accounts for the following cases:
914 YAHOO.util.DataSourceBase.TYPE_UNKNOWN
915 YAHOO.util.DataSourceBase.TYPE_JSARRAY
916 YAHOO.util.DataSourceBase.TYPE_JSON
917 YAHOO.util.DataSourceBase.TYPE_HTMLTABLE
918 YAHOO.util.DataSourceBase.TYPE_XML
919 YAHOO.util.DataSourceBase.TYPE_TEXT
921 var oRawResponse = this.liveData;
923 this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
928 * Receives raw data response and type converts to XML, JSON, etc as necessary.
929 * Forwards oFullResponse to appropriate parsing function to get turned into
930 * oParsedResponse. Calls doBeforeCallback() and adds oParsedResponse to
931 * the cache when appropriate before calling issueCallback().
933 * The oParsedResponse object literal has the following properties:
935 * <dd><dt>tId {Number}</dt> Unique transaction ID</dd>
936 * <dd><dt>results {Array}</dt> Array of parsed data results</dd>
937 * <dd><dt>meta {Object}</dt> Object literal of meta values</dd>
938 * <dd><dt>error {Boolean}</dt> (optional) True if there was an error</dd>
939 * <dd><dt>cached {Boolean}</dt> (optional) True if response was cached</dd>
942 * @method handleResponse
943 * @param oRequest {Object} Request object
944 * @param oRawResponse {Object} The raw response from the live database.
945 * @param oCallback {Object} Callback object literal.
946 * @param oCaller {Object} (deprecated) Use oCallback.scope.
947 * @param tId {Number} Transaction ID.
949 handleResponse : function(oRequest, oRawResponse, oCallback, oCaller, tId) {
950 this.fireEvent("responseEvent", {tId:tId, request:oRequest, response:oRawResponse,
951 callback:oCallback, caller:oCaller});
952 YAHOO.log("Received live data response for \"" + oRequest + "\"", "info", this.toString());
953 var xhr = (this.dataType == DS.TYPE_XHR) ? true : false;
954 var oParsedResponse = null;
955 var oFullResponse = oRawResponse;
957 // Try to sniff data type if it has not been defined
958 if(this.responseType === DS.TYPE_UNKNOWN) {
959 var ctype = (oRawResponse && oRawResponse.getResponseHeader) ? oRawResponse.getResponseHeader["Content-Type"] : null;
962 if(ctype.indexOf("text/xml") > -1) {
963 this.responseType = DS.TYPE_XML;
965 else if(ctype.indexOf("application/json") > -1) { // json
966 this.responseType = DS.TYPE_JSON;
968 else if(ctype.indexOf("text/plain") > -1) { // text
969 this.responseType = DS.TYPE_TEXT;
973 if(YAHOO.lang.isArray(oRawResponse)) { // array
974 this.responseType = DS.TYPE_JSARRAY;
977 else if(oRawResponse && oRawResponse.nodeType && (oRawResponse.nodeType === 9 || oRawResponse.nodeType === 1 || oRawResponse.nodeType === 11)) {
978 this.responseType = DS.TYPE_XML;
980 else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
981 this.responseType = DS.TYPE_HTMLTABLE;
983 else if(YAHOO.lang.isObject(oRawResponse)) { // json
984 this.responseType = DS.TYPE_JSON;
986 else if(YAHOO.lang.isString(oRawResponse)) { // text
987 this.responseType = DS.TYPE_TEXT;
992 switch(this.responseType) {
993 case DS.TYPE_JSARRAY:
994 if(xhr && oRawResponse && oRawResponse.responseText) {
995 oFullResponse = oRawResponse.responseText;
998 // Convert to JS array if it's a string
999 if(lang.isString(oFullResponse)) {
1000 var parseArgs = [oFullResponse].concat(this.parseJSONArgs);
1001 // Check for YUI JSON Util
1003 oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs);
1005 // Look for JSON parsers using an API similar to json2.js
1006 else if(window.JSON && JSON.parse) {
1007 oFullResponse = JSON.parse.apply(JSON,parseArgs);
1009 // Look for JSON parsers using an API similar to json.js
1010 else if(oFullResponse.parseJSON) {
1011 oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1));
1013 // No JSON lib found so parse the string
1015 // Trim leading spaces
1016 while (oFullResponse.length > 0 &&
1017 (oFullResponse.charAt(0) != "{") &&
1018 (oFullResponse.charAt(0) != "[")) {
1019 oFullResponse = oFullResponse.substring(1, oFullResponse.length);
1022 if(oFullResponse.length > 0) {
1023 // Strip extraneous stuff at the end
1025 Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));
1026 oFullResponse = oFullResponse.substring(0,arrayEnd+1);
1028 // Turn the string into an object literal...
1029 // ...eval is necessary here
1030 oFullResponse = eval("(" + oFullResponse + ")");
1038 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1039 oParsedResponse = this.parseArrayData(oRequest, oFullResponse);
1042 if(xhr && oRawResponse && oRawResponse.responseText) {
1043 oFullResponse = oRawResponse.responseText;
1046 // Convert to JSON object if it's a string
1047 if(lang.isString(oFullResponse)) {
1048 var parseArgs = [oFullResponse].concat(this.parseJSONArgs);
1049 // Check for YUI JSON Util
1051 oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs);
1053 // Look for JSON parsers using an API similar to json2.js
1054 else if(window.JSON && JSON.parse) {
1055 oFullResponse = JSON.parse.apply(JSON,parseArgs);
1057 // Look for JSON parsers using an API similar to json.js
1058 else if(oFullResponse.parseJSON) {
1059 oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1));
1061 // No JSON lib found so parse the string
1063 // Trim leading spaces
1064 while (oFullResponse.length > 0 &&
1065 (oFullResponse.charAt(0) != "{") &&
1066 (oFullResponse.charAt(0) != "[")) {
1067 oFullResponse = oFullResponse.substring(1, oFullResponse.length);
1070 if(oFullResponse.length > 0) {
1071 // Strip extraneous stuff at the end
1072 var objEnd = Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));
1073 oFullResponse = oFullResponse.substring(0,objEnd+1);
1075 // Turn the string into an object literal...
1076 // ...eval is necessary here
1077 oFullResponse = eval("(" + oFullResponse + ")");
1086 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1087 oParsedResponse = this.parseJSONData(oRequest, oFullResponse);
1089 case DS.TYPE_HTMLTABLE:
1090 if(xhr && oRawResponse.responseText) {
1091 var el = document.createElement('div');
1092 el.innerHTML = oRawResponse.responseText;
1093 oFullResponse = el.getElementsByTagName('table')[0];
1095 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1096 oParsedResponse = this.parseHTMLTableData(oRequest, oFullResponse);
1099 if(xhr && oRawResponse.responseXML) {
1100 oFullResponse = oRawResponse.responseXML;
1102 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1103 oParsedResponse = this.parseXMLData(oRequest, oFullResponse);
1106 if(xhr && lang.isString(oRawResponse.responseText)) {
1107 oFullResponse = oRawResponse.responseText;
1109 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1110 oParsedResponse = this.parseTextData(oRequest, oFullResponse);
1113 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1114 oParsedResponse = this.parseData(oRequest, oFullResponse);
1119 // Clean up for consistent signature
1120 oParsedResponse = oParsedResponse || {};
1121 if(!oParsedResponse.results) {
1122 oParsedResponse.results = [];
1124 if(!oParsedResponse.meta) {
1125 oParsedResponse.meta = {};
1129 if(!oParsedResponse.error) {
1130 // Last chance to touch the raw response or the parsed response
1131 oParsedResponse = this.doBeforeCallback(oRequest, oFullResponse, oParsedResponse, oCallback);
1132 this.fireEvent("responseParseEvent", {request:oRequest,
1133 response:oParsedResponse, callback:oCallback, caller:oCaller});
1134 // Cache the response
1135 this.addToCache(oRequest, oParsedResponse);
1139 // Be sure the error flag is on
1140 oParsedResponse.error = true;
1141 this.fireEvent("dataErrorEvent", {request:oRequest, response: oRawResponse, callback:oCallback,
1142 caller:oCaller, message:DS.ERROR_DATANULL});
1143 YAHOO.log(DS.ERROR_DATANULL, "error", this.toString());
1146 // Send the response back to the caller
1147 oParsedResponse.tId = tId;
1148 DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller);
1152 * Overridable method gives implementers access to the original full response
1153 * before the data gets parsed. Implementers should take care not to return an
1154 * unparsable or otherwise invalid response.
1156 * @method doBeforeParseData
1157 * @param oRequest {Object} Request object.
1158 * @param oFullResponse {Object} The full response from the live database.
1159 * @param oCallback {Object} The callback object.
1160 * @return {Object} Full response for parsing.
1163 doBeforeParseData : function(oRequest, oFullResponse, oCallback) {
1164 return oFullResponse;
1168 * Overridable method gives implementers access to the original full response and
1169 * the parsed response (parsed against the given schema) before the data
1170 * is added to the cache (if applicable) and then sent back to callback function.
1171 * This is your chance to access the raw response and/or populate the parsed
1172 * response with any custom data.
1174 * @method doBeforeCallback
1175 * @param oRequest {Object} Request object.
1176 * @param oFullResponse {Object} The full response from the live database.
1177 * @param oParsedResponse {Object} The parsed response to return to calling object.
1178 * @param oCallback {Object} The callback object.
1179 * @return {Object} Parsed response object.
1181 doBeforeCallback : function(oRequest, oFullResponse, oParsedResponse, oCallback) {
1182 return oParsedResponse;
1186 * Overridable method parses data of generic RESPONSE_TYPE into a response object.
1189 * @param oRequest {Object} Request object.
1190 * @param oFullResponse {Object} The full Array from the live database.
1191 * @return {Object} Parsed response object with the following properties:<br>
1192 * - results {Array} Array of parsed data results<br>
1193 * - meta {Object} Object literal of meta values<br>
1194 * - error {Boolean} (optional) True if there was an error<br>
1196 parseData : function(oRequest, oFullResponse) {
1197 if(lang.isValue(oFullResponse)) {
1198 var oParsedResponse = {results:oFullResponse,meta:{}};
1199 YAHOO.log("Parsed generic data is " +
1200 lang.dump(oParsedResponse), "info", this.toString());
1201 return oParsedResponse;
1204 YAHOO.log("Generic data could not be parsed: " + lang.dump(oFullResponse),
1205 "error", this.toString());
1210 * Overridable method parses Array data into a response object.
1212 * @method parseArrayData
1213 * @param oRequest {Object} Request object.
1214 * @param oFullResponse {Object} The full Array from the live database.
1215 * @return {Object} Parsed response object with the following properties:<br>
1216 * - results (Array) Array of parsed data results<br>
1217 * - error (Boolean) True if there was an error
1219 parseArrayData : function(oRequest, oFullResponse) {
1220 if(lang.isArray(oFullResponse)) {
1226 if(lang.isArray(this.responseSchema.fields)) {
1227 var fields = this.responseSchema.fields;
1228 for (i = fields.length - 1; i >= 0; --i) {
1229 if (typeof fields[i] !== 'object') {
1230 fields[i] = { key : fields[i] };
1234 var parsers = {}, p;
1235 for (i = fields.length - 1; i >= 0; --i) {
1236 p = (typeof fields[i].parser === 'function' ?
1238 DS.Parser[fields[i].parser+'']) || fields[i].converter;
1240 parsers[fields[i].key] = p;
1244 var arrType = lang.isArray(oFullResponse[0]);
1245 for(i=oFullResponse.length-1; i>-1; i--) {
1247 rec = oFullResponse[i];
1248 if (typeof rec === 'object') {
1249 for(j=fields.length-1; j>-1; j--) {
1251 data = arrType ? rec[j] : rec[field.key];
1253 if (parsers[field.key]) {
1254 data = parsers[field.key].call(this,data);
1258 if(data === undefined) {
1262 oResult[field.key] = data;
1265 else if (lang.isString(rec)) {
1266 for(j=fields.length-1; j>-1; j--) {
1270 if (parsers[field.key]) {
1271 data = parsers[field.key].call(this,data);
1275 if(data === undefined) {
1279 oResult[field.key] = data;
1282 results[i] = oResult;
1285 // Return entire data set
1287 results = oFullResponse;
1289 var oParsedResponse = {results:results};
1290 YAHOO.log("Parsed array data is " +
1291 lang.dump(oParsedResponse), "info", this.toString());
1292 return oParsedResponse;
1295 YAHOO.log("Array data could not be parsed: " + lang.dump(oFullResponse),
1296 "error", this.toString());
1301 * Overridable method parses plain text data into a response object.
1303 * @method parseTextData
1304 * @param oRequest {Object} Request object.
1305 * @param oFullResponse {Object} The full text response from the live database.
1306 * @return {Object} Parsed response object with the following properties:<br>
1307 * - results (Array) Array of parsed data results<br>
1308 * - error (Boolean) True if there was an error
1310 parseTextData : function(oRequest, oFullResponse) {
1311 if(lang.isString(oFullResponse)) {
1312 if(lang.isString(this.responseSchema.recordDelim) &&
1313 lang.isString(this.responseSchema.fieldDelim)) {
1314 var oParsedResponse = {results:[]};
1315 var recDelim = this.responseSchema.recordDelim;
1316 var fieldDelim = this.responseSchema.fieldDelim;
1317 if(oFullResponse.length > 0) {
1318 // Delete the last line delimiter at the end of the data if it exists
1319 var newLength = oFullResponse.length-recDelim.length;
1320 if(oFullResponse.substr(newLength) == recDelim) {
1321 oFullResponse = oFullResponse.substr(0, newLength);
1323 if(oFullResponse.length > 0) {
1324 // Split along record delimiter to get an array of strings
1325 var recordsarray = oFullResponse.split(recDelim);
1326 // Cycle through each record
1327 for(var i = 0, len = recordsarray.length, recIdx = 0; i < len; ++i) {
1329 sRecord = recordsarray[i];
1330 if (lang.isString(sRecord) && (sRecord.length > 0)) {
1331 // Split each record along field delimiter to get data
1332 var fielddataarray = recordsarray[i].split(fieldDelim);
1335 // Filter for fields data
1336 if(lang.isArray(this.responseSchema.fields)) {
1337 var fields = this.responseSchema.fields;
1338 for(var j=fields.length-1; j>-1; j--) {
1340 // Remove quotation marks from edges, if applicable
1341 var data = fielddataarray[j];
1342 if (lang.isString(data)) {
1343 if(data.charAt(0) == "\"") {
1344 data = data.substr(1);
1346 if(data.charAt(data.length-1) == "\"") {
1347 data = data.substr(0,data.length-1);
1349 var field = fields[j];
1350 var key = (lang.isValue(field.key)) ? field.key : field;
1351 // Backward compatibility
1352 if(!field.parser && field.converter) {
1353 field.parser = field.converter;
1354 YAHOO.log("The field property converter has been deprecated" +
1355 " in favor of parser", "warn", this.toString());
1357 var parser = (typeof field.parser === 'function') ?
1359 DS.Parser[field.parser+''];
1361 data = parser.call(this, data);
1364 if(data === undefined) {
1367 oResult[key] = data;
1378 // No fields defined so pass along all data as an array
1380 oResult = fielddataarray;
1383 oParsedResponse.results[recIdx++] = oResult;
1389 YAHOO.log("Parsed text data is " +
1390 lang.dump(oParsedResponse), "info", this.toString());
1391 return oParsedResponse;
1394 YAHOO.log("Text data could not be parsed: " + lang.dump(oFullResponse),
1395 "error", this.toString());
1401 * Overridable method parses XML data for one result into an object literal.
1403 * @method parseXMLResult
1404 * @param result {XML} XML for one result.
1405 * @return {Object} Object literal of data for one result.
1407 parseXMLResult : function(result) {
1409 schema = this.responseSchema;
1412 // Loop through each data field in each result using the schema
1413 for(var m = schema.fields.length-1; m >= 0 ; m--) {
1414 var field = schema.fields[m];
1415 var key = (lang.isValue(field.key)) ? field.key : field;
1419 data = YAHOO.util.DataSource._getLocationValue(field, result);
1422 // Values may be held in an attribute...
1423 var xmlAttr = result.attributes.getNamedItem(key);
1425 data = xmlAttr.value;
1429 var xmlNode = result.getElementsByTagName(key);
1430 if(xmlNode && xmlNode.item(0)) {
1431 var item = xmlNode.item(0);
1432 // For IE, then DOM...
1433 data = (item) ? ((item.text) ? item.text : (item.textContent) ? item.textContent : null) : null;
1434 // ...then fallback, but check for multiple child nodes
1436 var datapieces = [];
1437 for(var j=0, len=item.childNodes.length; j<len; j++) {
1438 if(item.childNodes[j].nodeValue) {
1439 datapieces[datapieces.length] = item.childNodes[j].nodeValue;
1442 if(datapieces.length > 0) {
1443 data = datapieces.join("");
1455 // Backward compatibility
1456 if(!field.parser && field.converter) {
1457 field.parser = field.converter;
1458 YAHOO.log("The field property converter has been deprecated" +
1459 " in favor of parser", "warn", this.toString());
1461 var parser = (typeof field.parser === 'function') ?
1463 DS.Parser[field.parser+''];
1465 data = parser.call(this, data);
1468 if(data === undefined) {
1471 oResult[key] = data;
1475 YAHOO.log("Error while parsing XML result: " + e.message);
1484 * Overridable method parses XML data into a response object.
1486 * @method parseXMLData
1487 * @param oRequest {Object} Request object.
1488 * @param oFullResponse {Object} The full XML response from the live database.
1489 * @return {Object} Parsed response object with the following properties<br>
1490 * - results (Array) Array of parsed data results<br>
1491 * - error (Boolean) True if there was an error
1493 parseXMLData : function(oRequest, oFullResponse) {
1495 schema = this.responseSchema,
1496 oParsedResponse = {meta:{}},
1498 metaNode = schema.metaNode,
1499 metaLocators = schema.metaFields || {},
1502 // In case oFullResponse is something funky
1504 // Pull any meta identified
1506 for (k in metaLocators) {
1507 oParsedResponse.meta[k] = YAHOO.util.DataSource._getLocationValue(metaLocators[k], oFullResponse);
1511 metaNode = metaNode ? oFullResponse.getElementsByTagName(metaNode)[0] :
1515 for (k in metaLocators) {
1516 if (lang.hasOwnProperty(metaLocators, k)) {
1517 loc = metaLocators[k];
1519 v = metaNode.getElementsByTagName(loc)[0];
1522 v = v.firstChild.nodeValue;
1524 // Look for an attribute
1525 v = metaNode.attributes.getNamedItem(loc);
1531 if (lang.isValue(v)) {
1532 oParsedResponse.meta[k] = v;
1540 xmlList = (schema.resultNode) ?
1541 oFullResponse.getElementsByTagName(schema.resultNode) :
1545 YAHOO.log("Error while parsing XML data: " + e.message);
1547 if(!xmlList || !lang.isArray(schema.fields)) {
1550 // Loop through each result
1552 oParsedResponse.results = [];
1553 for(i = xmlList.length-1; i >= 0 ; --i) {
1554 var oResult = this.parseXMLResult(xmlList.item(i));
1555 // Capture each array of values into an array of results
1556 oParsedResponse.results[i] = oResult;
1560 YAHOO.log("XML data could not be parsed: " +
1561 lang.dump(oFullResponse), "error", this.toString());
1562 oParsedResponse.error = true;
1565 YAHOO.log("Parsed XML data is " +
1566 lang.dump(oParsedResponse), "info", this.toString());
1568 return oParsedResponse;
1572 * Overridable method parses JSON data into a response object.
1574 * @method parseJSONData
1575 * @param oRequest {Object} Request object.
1576 * @param oFullResponse {Object} The full JSON from the live database.
1577 * @return {Object} Parsed response object with the following properties<br>
1578 * - results (Array) Array of parsed data results<br>
1579 * - error (Boolean) True if there was an error
1581 parseJSONData : function(oRequest, oFullResponse) {
1582 var oParsedResponse = {results:[],meta:{}};
1584 if(lang.isObject(oFullResponse) && this.responseSchema.resultsList) {
1585 var schema = this.responseSchema,
1586 fields = schema.fields,
1587 resultsList = oFullResponse,
1589 metaFields = schema.metaFields || {},
1594 i,len,j,v,key,parser,path;
1596 // Function to convert the schema's fields into walk paths
1597 var buildPath = function (needle) {
1598 var path = null, keys = [], i = 0;
1600 // Strip the ["string keys"] and [1] array indexes
1602 replace(/\[(['"])(.*?)\1\]/g,
1603 function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}).
1604 replace(/\[(\d+)\]/g,
1605 function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}).
1606 replace(/^\./,''); // remove leading dot
1608 // If the cleaned needle contains invalid characters, the
1610 if (!/[^\w\.\$@]/.test(needle)) {
1611 path = needle.split('.');
1612 for (i=path.length-1; i >= 0; --i) {
1613 if (path[i].charAt(0) === '@') {
1614 path[i] = keys[parseInt(path[i].substr(1),10)];
1619 YAHOO.log("Invalid locator: " + needle, "error", this.toString());
1626 // Function to walk a path and return the pot of gold
1627 var walkPath = function (path, origin) {
1628 var v=origin,i=0,len=path.length;
1629 for (;i<len && v;++i) {
1635 // Parse the response
1636 // Step 1. Pull the resultsList from oFullResponse (default assumes
1637 // oFullResponse IS the resultsList)
1638 path = buildPath(schema.resultsList);
1640 resultsList = walkPath(path, oFullResponse);
1641 if (resultsList === undefined) {
1652 if (!lang.isArray(resultsList)) {
1653 resultsList = [resultsList];
1657 // Step 2. Parse out field data if identified
1660 // Build the field parser map and location paths
1661 for (i=0, len=fields.length; i<len; i++) {
1663 key = field.key || field;
1664 parser = ((typeof field.parser === 'function') ?
1666 DS.Parser[field.parser+'']) || field.converter;
1667 path = buildPath(key);
1670 fieldParsers[fieldParsers.length] = {key:key,parser:parser};
1674 if (path.length > 1) {
1675 fieldPaths[fieldPaths.length] = {key:key,path:path};
1677 simpleFields[simpleFields.length] = {key:key,path:path[0]};
1680 YAHOO.log("Invalid key syntax: " + key,"warn",this.toString());
1684 // Process the results, flattening the records and/or applying parsers if needed
1685 for (i = resultsList.length - 1; i >= 0; --i) {
1686 var r = resultsList[i], rec = {};
1688 for (j = simpleFields.length - 1; j >= 0; --j) {
1689 // Bug 1777850: data might be held in an array
1690 rec[simpleFields[j].key] =
1691 (r[simpleFields[j].path] !== undefined) ?
1692 r[simpleFields[j].path] : r[j];
1695 for (j = fieldPaths.length - 1; j >= 0; --j) {
1696 rec[fieldPaths[j].key] = walkPath(fieldPaths[j].path,r);
1699 for (j = fieldParsers.length - 1; j >= 0; --j) {
1700 var p = fieldParsers[j].key;
1701 rec[p] = fieldParsers[j].parser(rec[p]);
1702 if (rec[p] === undefined) {
1711 results = resultsList;
1714 for (key in metaFields) {
1715 if (lang.hasOwnProperty(metaFields,key)) {
1716 path = buildPath(metaFields[key]);
1718 v = walkPath(path, oFullResponse);
1719 oParsedResponse.meta[key] = v;
1725 YAHOO.log("JSON data could not be parsed due to invalid responseSchema.resultsList or invalid response: " +
1726 lang.dump(oFullResponse), "error", this.toString());
1728 oParsedResponse.error = true;
1731 oParsedResponse.results = results;
1734 YAHOO.log("JSON data could not be parsed: " +
1735 lang.dump(oFullResponse), "error", this.toString());
1736 oParsedResponse.error = true;
1739 return oParsedResponse;
1743 * Overridable method parses an HTML TABLE element reference into a response object.
1744 * Data is parsed out of TR elements from all TBODY elements.
1746 * @method parseHTMLTableData
1747 * @param oRequest {Object} Request object.
1748 * @param oFullResponse {Object} The full HTML element reference from the live database.
1749 * @return {Object} Parsed response object with the following properties<br>
1750 * - results (Array) Array of parsed data results<br>
1751 * - error (Boolean) True if there was an error
1753 parseHTMLTableData : function(oRequest, oFullResponse) {
1755 var elTable = oFullResponse;
1756 var fields = this.responseSchema.fields;
1757 var oParsedResponse = {results:[]};
1759 if(lang.isArray(fields)) {
1760 // Iterate through each TBODY
1761 for(var i=0; i<elTable.tBodies.length; i++) {
1762 var elTbody = elTable.tBodies[i];
1764 // Iterate through each TR
1765 for(var j=elTbody.rows.length-1; j>-1; j--) {
1766 var elRow = elTbody.rows[j];
1769 for(var k=fields.length-1; k>-1; k--) {
1770 var field = fields[k];
1771 var key = (lang.isValue(field.key)) ? field.key : field;
1772 var data = elRow.cells[k].innerHTML;
1774 // Backward compatibility
1775 if(!field.parser && field.converter) {
1776 field.parser = field.converter;
1777 YAHOO.log("The field property converter has been deprecated" +
1778 " in favor of parser", "warn", this.toString());
1780 var parser = (typeof field.parser === 'function') ?
1782 DS.Parser[field.parser+''];
1784 data = parser.call(this, data);
1787 if(data === undefined) {
1790 oResult[key] = data;
1792 oParsedResponse.results[j] = oResult;
1798 YAHOO.log("Invalid responseSchema.fields", "error", this.toString());
1802 YAHOO.log("HTML TABLE data could not be parsed: " +
1803 lang.dump(oFullResponse), "error", this.toString());
1804 oParsedResponse.error = true;
1807 YAHOO.log("Parsed HTML TABLE data is " +
1808 lang.dump(oParsedResponse), "info", this.toString());
1810 return oParsedResponse;
1815 // DataSourceBase uses EventProvider
1816 lang.augmentProto(DS, util.EventProvider);
1820 /****************************************************************************/
1821 /****************************************************************************/
1822 /****************************************************************************/
1825 * LocalDataSource class for in-memory data structs including JavaScript arrays,
1826 * JavaScript object literals (JSON), XML documents, and HTML tables.
1828 * @namespace YAHOO.util
1829 * @class YAHOO.util.LocalDataSource
1830 * @extends YAHOO.util.DataSourceBase
1832 * @param oLiveData {HTMLElement} Pointer to live data.
1833 * @param oConfigs {object} (optional) Object literal of configuration values.
1835 util.LocalDataSource = function(oLiveData, oConfigs) {
1836 this.dataType = DS.TYPE_LOCAL;
1839 if(YAHOO.lang.isArray(oLiveData)) { // array
1840 this.responseType = DS.TYPE_JSARRAY;
1843 else if(oLiveData.nodeType && oLiveData.nodeType == 9) {
1844 this.responseType = DS.TYPE_XML;
1846 else if(oLiveData.nodeName && (oLiveData.nodeName.toLowerCase() == "table")) { // table
1847 this.responseType = DS.TYPE_HTMLTABLE;
1848 oLiveData = oLiveData.cloneNode(true);
1850 else if(YAHOO.lang.isString(oLiveData)) { // text
1851 this.responseType = DS.TYPE_TEXT;
1853 else if(YAHOO.lang.isObject(oLiveData)) { // json
1854 this.responseType = DS.TYPE_JSON;
1859 this.responseType = DS.TYPE_JSARRAY;
1862 util.LocalDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
1865 // LocalDataSource extends DataSourceBase
1866 lang.extend(util.LocalDataSource, DS);
1868 // Copy static members to LocalDataSource class
1869 lang.augmentObject(util.LocalDataSource, DS);
1883 /****************************************************************************/
1884 /****************************************************************************/
1885 /****************************************************************************/
1888 * FunctionDataSource class for JavaScript functions.
1890 * @namespace YAHOO.util
1891 * @class YAHOO.util.FunctionDataSource
1892 * @extends YAHOO.util.DataSourceBase
1894 * @param oLiveData {HTMLElement} Pointer to live data.
1895 * @param oConfigs {object} (optional) Object literal of configuration values.
1897 util.FunctionDataSource = function(oLiveData, oConfigs) {
1898 this.dataType = DS.TYPE_JSFUNCTION;
1899 oLiveData = oLiveData || function() {};
1901 util.FunctionDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
1904 // FunctionDataSource extends DataSourceBase
1905 lang.extend(util.FunctionDataSource, DS, {
1907 /////////////////////////////////////////////////////////////////////////////
1909 // FunctionDataSource public properties
1911 /////////////////////////////////////////////////////////////////////////////
1914 * Context in which to execute the function. By default, is the DataSource
1915 * instance itself. If set, the function will receive the DataSource instance
1916 * as an additional argument.
1925 /////////////////////////////////////////////////////////////////////////////
1927 // FunctionDataSource public methods
1929 /////////////////////////////////////////////////////////////////////////////
1932 * Overriding method passes query to a function. The returned response is then
1933 * forwarded to the handleResponse function.
1935 * @method makeConnection
1936 * @param oRequest {Object} Request object.
1937 * @param oCallback {Object} Callback object literal.
1938 * @param oCaller {Object} (deprecated) Use oCallback.scope.
1939 * @return {Number} Transaction ID.
1941 makeConnection : function(oRequest, oCallback, oCaller) {
1942 var tId = DS._nTransactionId++;
1943 this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
1945 // Pass the request in as a parameter and
1946 // forward the return value to the handler
1949 var oRawResponse = (this.scope) ? this.liveData.call(this.scope, oRequest, this) : this.liveData(oRequest);
1951 // Try to sniff data type if it has not been defined
1952 if(this.responseType === DS.TYPE_UNKNOWN) {
1953 if(YAHOO.lang.isArray(oRawResponse)) { // array
1954 this.responseType = DS.TYPE_JSARRAY;
1957 else if(oRawResponse && oRawResponse.nodeType && oRawResponse.nodeType == 9) {
1958 this.responseType = DS.TYPE_XML;
1960 else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
1961 this.responseType = DS.TYPE_HTMLTABLE;
1963 else if(YAHOO.lang.isObject(oRawResponse)) { // json
1964 this.responseType = DS.TYPE_JSON;
1966 else if(YAHOO.lang.isString(oRawResponse)) { // text
1967 this.responseType = DS.TYPE_TEXT;
1971 this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
1977 // Copy static members to FunctionDataSource class
1978 lang.augmentObject(util.FunctionDataSource, DS);
1992 /****************************************************************************/
1993 /****************************************************************************/
1994 /****************************************************************************/
1997 * ScriptNodeDataSource class for accessing remote data via the YUI Get Utility.
1999 * @namespace YAHOO.util
2000 * @class YAHOO.util.ScriptNodeDataSource
2001 * @extends YAHOO.util.DataSourceBase
2003 * @param oLiveData {HTMLElement} Pointer to live data.
2004 * @param oConfigs {object} (optional) Object literal of configuration values.
2006 util.ScriptNodeDataSource = function(oLiveData, oConfigs) {
2007 this.dataType = DS.TYPE_SCRIPTNODE;
2008 oLiveData = oLiveData || "";
2010 util.ScriptNodeDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
2013 // ScriptNodeDataSource extends DataSourceBase
2014 lang.extend(util.ScriptNodeDataSource, DS, {
2016 /////////////////////////////////////////////////////////////////////////////
2018 // ScriptNodeDataSource public properties
2020 /////////////////////////////////////////////////////////////////////////////
2023 * Alias to YUI Get Utility, to allow implementers to use a custom class.
2025 * @property getUtility
2027 * @default YAHOO.util.Get
2029 getUtility : util.Get,
2032 * Defines request/response management in the following manner:
2034 * <!--<dt>queueRequests</dt>
2035 * <dd>If a request is already in progress, wait until response is returned before sending the next request.</dd>
2036 * <dt>cancelStaleRequests</dt>
2037 * <dd>If a request is already in progress, cancel it before sending the next request.</dd>-->
2038 * <dt>ignoreStaleResponses</dt>
2039 * <dd>Send all requests, but handle only the response for the most recently sent request.</dd>
2041 * <dd>Send all requests and handle all responses.</dd>
2044 * @property asyncMode
2046 * @default "allowAll"
2048 asyncMode : "allowAll",
2051 * Callback string parameter name sent to the remote script. By default,
2052 * requests are sent to
2053 * <URI>?<scriptCallbackParam>=callbackFunction
2055 * @property scriptCallbackParam
2057 * @default "callback"
2059 scriptCallbackParam : "callback",
2062 /////////////////////////////////////////////////////////////////////////////
2064 // ScriptNodeDataSource public methods
2066 /////////////////////////////////////////////////////////////////////////////
2069 * Creates a request callback that gets appended to the script URI. Implementers
2070 * can customize this string to match their server's query syntax.
2072 * @method generateRequestCallback
2073 * @return {String} String fragment that gets appended to script URI that
2074 * specifies the callback function
2076 generateRequestCallback : function(id) {
2077 return "&" + this.scriptCallbackParam + "=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]" ;
2081 * Overridable method gives implementers access to modify the URI before the dynamic
2082 * script node gets inserted. Implementers should take care not to return an
2085 * @method doBeforeGetScriptNode
2086 * @param {String} URI to the script
2087 * @return {String} URI to the script
2089 doBeforeGetScriptNode : function(sUri) {
2094 * Overriding method passes query to Get Utility. The returned
2095 * response is then forwarded to the handleResponse function.
2097 * @method makeConnection
2098 * @param oRequest {Object} Request object.
2099 * @param oCallback {Object} Callback object literal.
2100 * @param oCaller {Object} (deprecated) Use oCallback.scope.
2101 * @return {Number} Transaction ID.
2103 makeConnection : function(oRequest, oCallback, oCaller) {
2104 var tId = DS._nTransactionId++;
2105 this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
2107 // If there are no global pending requests, it is safe to purge global callback stack and global counter
2108 if(util.ScriptNodeDataSource._nPending === 0) {
2109 util.ScriptNodeDataSource.callbacks = [];
2110 util.ScriptNodeDataSource._nId = 0;
2113 // ID for this request
2114 var id = util.ScriptNodeDataSource._nId;
2115 util.ScriptNodeDataSource._nId++;
2117 // Dynamically add handler function with a closure to the callback stack
2119 util.ScriptNodeDataSource.callbacks[id] = function(oRawResponse) {
2120 if((oSelf.asyncMode !== "ignoreStaleResponses")||
2121 (id === util.ScriptNodeDataSource.callbacks.length-1)) { // Must ignore stale responses
2123 // Try to sniff data type if it has not been defined
2124 if(oSelf.responseType === DS.TYPE_UNKNOWN) {
2125 if(YAHOO.lang.isArray(oRawResponse)) { // array
2126 oSelf.responseType = DS.TYPE_JSARRAY;
2129 else if(oRawResponse.nodeType && oRawResponse.nodeType == 9) {
2130 oSelf.responseType = DS.TYPE_XML;
2132 else if(oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
2133 oSelf.responseType = DS.TYPE_HTMLTABLE;
2135 else if(YAHOO.lang.isObject(oRawResponse)) { // json
2136 oSelf.responseType = DS.TYPE_JSON;
2138 else if(YAHOO.lang.isString(oRawResponse)) { // text
2139 oSelf.responseType = DS.TYPE_TEXT;
2143 oSelf.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
2146 YAHOO.log("DataSource ignored stale response for tId " + tId + "(" + oRequest + ")", "info", oSelf.toString());
2149 delete util.ScriptNodeDataSource.callbacks[id];
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 YAHOO.log("DataSource is querying URL " + sUri, "info", this.toString());
2157 this.getUtility.script(sUri,
2159 onsuccess: util.ScriptNodeDataSource._bumpPendingDown,
2160 onfail: util.ScriptNodeDataSource._bumpPendingDown});
2167 // Copy static members to ScriptNodeDataSource class
2168 lang.augmentObject(util.ScriptNodeDataSource, DS);
2170 // Copy static members to ScriptNodeDataSource class
2171 lang.augmentObject(util.ScriptNodeDataSource, {
2173 /////////////////////////////////////////////////////////////////////////////
2175 // ScriptNodeDataSource private static properties
2177 /////////////////////////////////////////////////////////////////////////////
2180 * Unique ID to track requests.
2190 * Counter for pending requests. When this is 0, it is safe to purge callbacks
2193 * @property _nPending
2201 * Global array of callback functions, one for each request sent.
2203 * @property callbacks
2224 /****************************************************************************/
2225 /****************************************************************************/
2226 /****************************************************************************/
2229 * XHRDataSource class for accessing remote data via the YUI Connection Manager
2232 * @namespace YAHOO.util
2233 * @class YAHOO.util.XHRDataSource
2234 * @extends YAHOO.util.DataSourceBase
2236 * @param oLiveData {HTMLElement} Pointer to live data.
2237 * @param oConfigs {object} (optional) Object literal of configuration values.
2239 util.XHRDataSource = function(oLiveData, oConfigs) {
2240 this.dataType = DS.TYPE_XHR;
2241 this.connMgr = this.connMgr || util.Connect;
2242 oLiveData = oLiveData || "";
2244 util.XHRDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
2247 // XHRDataSource extends DataSourceBase
2248 lang.extend(util.XHRDataSource, DS, {
2250 /////////////////////////////////////////////////////////////////////////////
2252 // XHRDataSource public properties
2254 /////////////////////////////////////////////////////////////////////////////
2257 * Alias to YUI Connection Manager, to allow implementers to use a custom class.
2261 * @default YAHOO.util.Connect
2266 * Defines request/response management in the following manner:
2268 * <dt>queueRequests</dt>
2269 * <dd>If a request is already in progress, wait until response is returned
2270 * before sending the next request.</dd>
2272 * <dt>cancelStaleRequests</dt>
2273 * <dd>If a request is already in progress, cancel it before sending the next
2276 * <dt>ignoreStaleResponses</dt>
2277 * <dd>Send all requests, but handle only the response for the most recently
2278 * sent request.</dd>
2281 * <dd>Send all requests and handle all responses.</dd>
2285 * @property connXhrMode
2287 * @default "allowAll"
2289 connXhrMode: "allowAll",
2292 * True if data is to be sent via POST. By default, data will be sent via GET.
2294 * @property connMethodPost
2298 connMethodPost: false,
2301 * The connection timeout defines how many milliseconds the XHR connection will
2302 * wait for a server response. Any non-zero value will enable the Connection Manager's
2303 * Auto-Abort feature.
2305 * @property connTimeout
2311 /////////////////////////////////////////////////////////////////////////////
2313 // XHRDataSource public methods
2315 /////////////////////////////////////////////////////////////////////////////
2318 * Overriding method passes query to Connection Manager. The returned
2319 * response is then forwarded to the handleResponse function.
2321 * @method makeConnection
2322 * @param oRequest {Object} Request object.
2323 * @param oCallback {Object} Callback object literal.
2324 * @param oCaller {Object} (deprecated) Use oCallback.scope.
2325 * @return {Number} Transaction ID.
2327 makeConnection : function(oRequest, oCallback, oCaller) {
2329 var oRawResponse = null;
2330 var tId = DS._nTransactionId++;
2331 this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
2333 // Set up the callback object and
2334 // pass the request in as a URL query and
2335 // forward the response to the handler
2337 var oConnMgr = this.connMgr;
2338 var oQueue = this._oQueue;
2341 * Define Connection Manager success handler
2343 * @method _xhrSuccess
2344 * @param oResponse {Object} HTTPXMLRequest object
2347 var _xhrSuccess = function(oResponse) {
2348 // If response ID does not match last made request ID,
2349 // silently fail and wait for the next response
2350 if(oResponse && (this.connXhrMode == "ignoreStaleResponses") &&
2351 (oResponse.tId != oQueue.conn.tId)) {
2352 YAHOO.log("Ignored stale response", "warn", this.toString());
2355 // Error if no response
2356 else if(!oResponse) {
2357 this.fireEvent("dataErrorEvent", {request:oRequest, response:null,
2358 callback:oCallback, caller:oCaller,
2359 message:DS.ERROR_DATANULL});
2360 YAHOO.log(DS.ERROR_DATANULL, "error", this.toString());
2362 // Send error response back to the caller with the error flag on
2363 DS.issueCallback(oCallback,[oRequest, {error:true}], true, oCaller);
2367 // Forward to handler
2369 // Try to sniff data type if it has not been defined
2370 if(this.responseType === DS.TYPE_UNKNOWN) {
2371 var ctype = (oResponse.getResponseHeader) ? oResponse.getResponseHeader["Content-Type"] : null;
2374 if(ctype.indexOf("text/xml") > -1) {
2375 this.responseType = DS.TYPE_XML;
2377 else if(ctype.indexOf("application/json") > -1) { // json
2378 this.responseType = DS.TYPE_JSON;
2380 else if(ctype.indexOf("text/plain") > -1) { // text
2381 this.responseType = DS.TYPE_TEXT;
2385 this.handleResponse(oRequest, oResponse, oCallback, oCaller, tId);
2390 * Define Connection Manager failure handler
2392 * @method _xhrFailure
2393 * @param oResponse {Object} HTTPXMLRequest object
2396 var _xhrFailure = function(oResponse) {
2397 this.fireEvent("dataErrorEvent", {request:oRequest, response: oResponse,
2398 callback:oCallback, caller:oCaller,
2399 message:DS.ERROR_DATAINVALID});
2400 YAHOO.log(DS.ERROR_DATAINVALID + ": " +
2401 oResponse.statusText, "error", this.toString());
2403 // Backward compatibility
2404 if(lang.isString(this.liveData) && lang.isString(oRequest) &&
2405 (this.liveData.lastIndexOf("?") !== this.liveData.length-1) &&
2406 (oRequest.indexOf("?") !== 0)){
2407 YAHOO.log("DataSources using XHR no longer automatically supply " +
2408 "a \"?\" between the host and query parameters" +
2409 " -- please check that the request URL is correct", "warn", this.toString());
2412 // Send failure response back to the caller with the error flag on
2413 oResponse = oResponse || {};
2414 oResponse.error = true;
2415 DS.issueCallback(oCallback,[oRequest,oResponse],true, oCaller);
2421 * Define Connection Manager callback object
2423 * @property _xhrCallback
2424 * @param oResponse {Object} HTTPXMLRequest object
2427 var _xhrCallback = {
2428 success:_xhrSuccess,
2429 failure:_xhrFailure,
2433 // Apply Connection Manager timeout
2434 if(lang.isNumber(this.connTimeout)) {
2435 _xhrCallback.timeout = this.connTimeout;
2438 // Cancel stale requests
2439 if(this.connXhrMode == "cancelStaleRequests") {
2440 // Look in queue for stale requests
2442 if(oConnMgr.abort) {
2443 oConnMgr.abort(oQueue.conn);
2445 YAHOO.log("Canceled stale request", "warn", this.toString());
2448 YAHOO.log("Could not find Connection Manager abort() function", "error", this.toString());
2453 // Get ready to send the request URL
2454 if(oConnMgr && oConnMgr.asyncRequest) {
2455 var sLiveData = this.liveData;
2456 var isPost = this.connMethodPost;
2457 var sMethod = (isPost) ? "POST" : "GET";
2459 var sUri = (isPost || !lang.isValue(oRequest)) ? sLiveData : sLiveData+oRequest;
2460 var sRequest = (isPost) ? oRequest : null;
2462 // Send the request right away
2463 if(this.connXhrMode != "queueRequests") {
2464 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest);
2466 // Queue up then send the request
2468 // Found a request already in progress
2470 var allRequests = oQueue.requests;
2471 // Add request to queue
2472 allRequests.push({request:oRequest, callback:_xhrCallback});
2474 // Interval needs to be started
2475 if(!oQueue.interval) {
2476 oQueue.interval = setInterval(function() {
2477 // Connection is in progress
2478 if(oConnMgr.isCallInProgress(oQueue.conn)) {
2482 // Send next request
2483 if(allRequests.length > 0) {
2485 sUri = (isPost || !lang.isValue(allRequests[0].request)) ? sLiveData : sLiveData+allRequests[0].request;
2486 sRequest = (isPost) ? allRequests[0].request : null;
2487 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, allRequests[0].callback, sRequest);
2489 // Remove request from queue
2490 allRequests.shift();
2494 clearInterval(oQueue.interval);
2495 oQueue.interval = null;
2501 // Nothing is in progress
2503 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest);
2508 YAHOO.log("Could not find Connection Manager asyncRequest() function", "error", this.toString());
2509 // Send null response back to the caller with the error flag on
2510 DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller);
2518 // Copy static members to XHRDataSource class
2519 lang.augmentObject(util.XHRDataSource, DS);
2533 /****************************************************************************/
2534 /****************************************************************************/
2535 /****************************************************************************/
2538 * Factory class for creating a BaseDataSource subclass instance. The sublcass is
2539 * determined by oLiveData's type, unless the dataType config is explicitly passed in.
2541 * @namespace YAHOO.util
2542 * @class YAHOO.util.DataSource
2544 * @param oLiveData {HTMLElement} Pointer to live data.
2545 * @param oConfigs {object} (optional) Object literal of configuration values.
2547 util.DataSource = function(oLiveData, oConfigs) {
2548 oConfigs = oConfigs || {};
2550 // Point to one of the subclasses, first by dataType if given, then by sniffing oLiveData type.
2551 var dataType = oConfigs.dataType;
2553 if(dataType == DS.TYPE_LOCAL) {
2554 lang.augmentObject(util.DataSource, util.LocalDataSource);
2555 return new util.LocalDataSource(oLiveData, oConfigs);
2557 else if(dataType == DS.TYPE_XHR) {
2558 lang.augmentObject(util.DataSource, util.XHRDataSource);
2559 return new util.XHRDataSource(oLiveData, oConfigs);
2561 else if(dataType == DS.TYPE_SCRIPTNODE) {
2562 lang.augmentObject(util.DataSource, util.ScriptNodeDataSource);
2563 return new util.ScriptNodeDataSource(oLiveData, oConfigs);
2565 else if(dataType == DS.TYPE_JSFUNCTION) {
2566 lang.augmentObject(util.DataSource, util.FunctionDataSource);
2567 return new util.FunctionDataSource(oLiveData, oConfigs);
2571 if(YAHOO.lang.isString(oLiveData)) { // strings default to xhr
2572 lang.augmentObject(util.DataSource, util.XHRDataSource);
2573 return new util.XHRDataSource(oLiveData, oConfigs);
2575 else if(YAHOO.lang.isFunction(oLiveData)) {
2576 lang.augmentObject(util.DataSource, util.FunctionDataSource);
2577 return new util.FunctionDataSource(oLiveData, oConfigs);
2579 else { // ultimate default is local
2580 lang.augmentObject(util.DataSource, util.LocalDataSource);
2581 return new util.LocalDataSource(oLiveData, oConfigs);
2585 // Copy static members to DataSource class
2586 lang.augmentObject(util.DataSource, DS);
2590 /****************************************************************************/
2591 /****************************************************************************/
2592 /****************************************************************************/
2595 * The static Number class provides helper functions to deal with data of type
2598 * @namespace YAHOO.util
2603 YAHOO.util.Number = {
2606 * Takes a native JavaScript Number and formats to string for display to user.
2609 * @param nData {Number} Number.
2610 * @param oConfig {Object} (Optional) Optional configuration values:
2612 * <dt>prefix {String}</dd>
2613 * <dd>String prepended before each number, like a currency designator "$"</dd>
2614 * <dt>decimalPlaces {Number}</dd>
2615 * <dd>Number of decimal places to round.</dd>
2616 * <dt>decimalSeparator {String}</dd>
2617 * <dd>Decimal separator</dd>
2618 * <dt>thousandsSeparator {String}</dd>
2619 * <dd>Thousands separator</dd>
2620 * <dt>suffix {String}</dd>
2621 * <dd>String appended after each number, like " items" (note the space)</dd>
2622 * <dt>negativeFormat</dt>
2623 * <dd>String used as a guide for how to indicate negative numbers. The first '#' character in the string will be replaced by the number. Default '-#'.</dd>
2625 * @return {String} Formatted number for display. Note, the following values
2626 * return as "": null, undefined, NaN, "".
2628 format : function(n, cfg) {
2629 if (!isFinite(+n)) {
2633 n = !isFinite(+n) ? 0 : +n;
2634 cfg = YAHOO.lang.merge(YAHOO.util.Number.format.defaults, (cfg || {}));
2636 var neg = n < 0, absN = Math.abs(n),
2637 places = cfg.decimalPlaces,
2638 sep = cfg.thousandsSeparator,
2642 // Get rid of the decimal info
2643 s = absN - (absN % 1) + '';
2644 i = s.length + places;
2646 // avoid 123 vs decimalPlaces -4 (should return "0")
2648 // leverage toFixed by making 123 => 0.123 for the rounding
2649 // operation, then add the appropriate number of zeros back on
2650 s = Number('.' + s).toFixed(i).slice(2) +
2651 new Array(s.length - i + 1).join('0');
2655 } else { // There is a bug in IE's toFixed implementation:
2656 // for n in {(-0.94, -0.5], [0.5, 0.94)} n.toFixed() returns 0
2657 // instead of -1 and 1. Manually handle that case.
2658 s = absN < 1 && absN >= 0.5 && !places ? '1' : absN.toFixed(places);
2662 bits = s.split(/\D/);
2663 i = bits[0].length % 3 || 3;
2665 bits[0] = bits[0].slice(0,i) +
2666 bits[0].slice(i).replace(/(\d{3})/g, sep + '$1');
2668 s = bits.join(cfg.decimalSeparator);
2671 s = cfg.prefix + s + cfg.suffix;
2673 return neg ? cfg.negativeFormat.replace(/#/,s) : s;
2676 YAHOO.util.Number.format.defaults = {
2677 decimalSeparator : '.',
2678 decimalPlaces : null,
2679 thousandsSeparator : '',
2682 negativeFormat : '-#'
2686 /****************************************************************************/
2687 /****************************************************************************/
2688 /****************************************************************************/
2692 var xPad=function (x, pad, r)
2694 if(typeof r === 'undefined')
2698 for( ; parseInt(x, 10)<r && r>1; r/=10) {
2699 x = pad.toString() + x;
2701 return x.toString();
2706 * The static Date class provides helper functions to deal with data of type Date.
2708 * @namespace YAHOO.util
2715 a: function (d, l) { return l.a[d.getDay()]; },
2716 A: function (d, l) { return l.A[d.getDay()]; },
2717 b: function (d, l) { return l.b[d.getMonth()]; },
2718 B: function (d, l) { return l.B[d.getMonth()]; },
2719 C: function (d) { return xPad(parseInt(d.getFullYear()/100, 10), 0); },
2720 d: ['getDate', '0'],
2721 e: ['getDate', ' '],
2722 g: function (d) { return xPad(parseInt(Dt.formats.G(d)%100, 10), 0); },
2724 var y = d.getFullYear();
2725 var V = parseInt(Dt.formats.V(d), 10);
2726 var W = parseInt(Dt.formats.W(d), 10);
2730 } else if(W===0 && V>=52) {
2736 H: ['getHours', '0'],
2737 I: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, 0); },
2739 var gmd_1 = new Date('' + d.getFullYear() + '/1/1 GMT');
2740 var gmdate = new Date('' + d.getFullYear() + '/' + (d.getMonth()+1) + '/' + d.getDate() + ' GMT');
2741 var ms = gmdate - gmd_1;
2742 var doy = parseInt(ms/60000/60/24, 10)+1;
2743 return xPad(doy, 0, 100);
2745 k: ['getHours', ' '],
2746 l: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, ' '); },
2747 m: function (d) { return xPad(d.getMonth()+1, 0); },
2748 M: ['getMinutes', '0'],
2749 p: function (d, l) { return l.p[d.getHours() >= 12 ? 1 : 0 ]; },
2750 P: function (d, l) { return l.P[d.getHours() >= 12 ? 1 : 0 ]; },
2751 s: function (d, l) { return parseInt(d.getTime()/1000, 10); },
2752 S: ['getSeconds', '0'],
2753 u: function (d) { var dow = d.getDay(); return dow===0?7:dow; },
2755 var doy = parseInt(Dt.formats.j(d), 10);
2756 var rdow = 6-d.getDay();
2757 var woy = parseInt((doy+rdow)/7, 10);
2758 return xPad(woy, 0);
2761 var woy = parseInt(Dt.formats.W(d), 10);
2762 var dow1_1 = (new Date('' + d.getFullYear() + '/1/1')).getDay();
2763 // First week is 01 and not 00 as in the case of %U and %W,
2764 // so we add 1 to the final result except if day 1 of the year
2765 // is a Monday (then %W returns 01).
2766 // We also need to subtract 1 if the day 1 of the year is
2767 // Friday-Sunday, so the resulting equation becomes:
2768 var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1);
2769 if(idow === 53 && (new Date('' + d.getFullYear() + '/12/31')).getDay() < 4)
2775 idow = Dt.formats.V(new Date('' + (d.getFullYear()-1) + '/12/31'));
2778 return xPad(idow, 0);
2782 var doy = parseInt(Dt.formats.j(d), 10);
2783 var rdow = 7-Dt.formats.u(d);
2784 var woy = parseInt((doy+rdow)/7, 10);
2785 return xPad(woy, 0, 10);
2787 y: function (d) { return xPad(d.getFullYear()%100, 0); },
2790 var o = d.getTimezoneOffset();
2791 var H = xPad(parseInt(Math.abs(o/60), 10), 0);
2792 var M = xPad(Math.abs(o%60), 0);
2793 return (o>0?'-':'+') + H + M;
2796 var tz = d.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/, '$2').replace(/[a-z ]/g, '');
2798 tz = Dt.formats.z(d);
2802 '%': function (d) { return '%'; }
2817 //'+': '%a %b %e %T %Z %Y'
2821 * Takes a native JavaScript Date and formats to string for display to user.
2824 * @param oDate {Date} Date.
2825 * @param oConfig {Object} (Optional) Object literal of configuration values:
2827 * <dt>format <String></dt>
2830 * Any strftime string is supported, such as "%I:%M:%S %p". strftime has several format specifiers defined by the Open group at
2831 * <a href="http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html">http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html</a>
2834 * PHP added a few of its own, defined at <a href="http://www.php.net/strftime">http://www.php.net/strftime</a>
2837 * This javascript implementation supports all the PHP specifiers and a few more. The full list is below:
2840 * <dt>%a</dt> <dd>abbreviated weekday name according to the current locale</dd>
2841 * <dt>%A</dt> <dd>full weekday name according to the current locale</dd>
2842 * <dt>%b</dt> <dd>abbreviated month name according to the current locale</dd>
2843 * <dt>%B</dt> <dd>full month name according to the current locale</dd>
2844 * <dt>%c</dt> <dd>preferred date and time representation for the current locale</dd>
2845 * <dt>%C</dt> <dd>century number (the year divided by 100 and truncated to an integer, range 00 to 99)</dd>
2846 * <dt>%d</dt> <dd>day of the month as a decimal number (range 01 to 31)</dd>
2847 * <dt>%D</dt> <dd>same as %m/%d/%y</dd>
2848 * <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>
2849 * <dt>%F</dt> <dd>same as %Y-%m-%d (ISO 8601 date format)</dd>
2850 * <dt>%g</dt> <dd>like %G, but without the century</dd>
2851 * <dt>%G</dt> <dd>The 4-digit year corresponding to the ISO week number</dd>
2852 * <dt>%h</dt> <dd>same as %b</dd>
2853 * <dt>%H</dt> <dd>hour as a decimal number using a 24-hour clock (range 00 to 23)</dd>
2854 * <dt>%I</dt> <dd>hour as a decimal number using a 12-hour clock (range 01 to 12)</dd>
2855 * <dt>%j</dt> <dd>day of the year as a decimal number (range 001 to 366)</dd>
2856 * <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>
2857 * <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>
2858 * <dt>%m</dt> <dd>month as a decimal number (range 01 to 12)</dd>
2859 * <dt>%M</dt> <dd>minute as a decimal number</dd>
2860 * <dt>%n</dt> <dd>newline character</dd>
2861 * <dt>%p</dt> <dd>either `AM' or `PM' according to the given time value, or the corresponding strings for the current locale</dd>
2862 * <dt>%P</dt> <dd>like %p, but lower case</dd>
2863 * <dt>%r</dt> <dd>time in a.m. and p.m. notation equal to %I:%M:%S %p</dd>
2864 * <dt>%R</dt> <dd>time in 24 hour notation equal to %H:%M</dd>
2865 * <dt>%s</dt> <dd>number of seconds since the Epoch, ie, since 1970-01-01 00:00:00 UTC</dd>
2866 * <dt>%S</dt> <dd>second as a decimal number</dd>
2867 * <dt>%t</dt> <dd>tab character</dd>
2868 * <dt>%T</dt> <dd>current time, equal to %H:%M:%S</dd>
2869 * <dt>%u</dt> <dd>weekday as a decimal number [1,7], with 1 representing Monday</dd>
2870 * <dt>%U</dt> <dd>week number of the current year as a decimal number, starting with the
2871 * first Sunday as the first day of the first week</dd>
2872 * <dt>%V</dt> <dd>The ISO 8601:1988 week number of the current year as a decimal number,
2873 * range 01 to 53, where week 1 is the first week that has at least 4 days
2874 * in the current year, and with Monday as the first day of the week.</dd>
2875 * <dt>%w</dt> <dd>day of the week as a decimal, Sunday being 0</dd>
2876 * <dt>%W</dt> <dd>week number of the current year as a decimal number, starting with the
2877 * first Monday as the first day of the first week</dd>
2878 * <dt>%x</dt> <dd>preferred date representation for the current locale without the time</dd>
2879 * <dt>%X</dt> <dd>preferred time representation for the current locale without the date</dd>
2880 * <dt>%y</dt> <dd>year as a decimal number without a century (range 00 to 99)</dd>
2881 * <dt>%Y</dt> <dd>year as a decimal number including the century</dd>
2882 * <dt>%z</dt> <dd>numerical time zone representation</dd>
2883 * <dt>%Z</dt> <dd>time zone name or abbreviation</dd>
2884 * <dt>%%</dt> <dd>a literal `%' character</dd>
2888 * @param sLocale {String} (Optional) The locale to use when displaying days of week,
2889 * months of the year, and other locale specific strings. The following locales are
2895 * <dd>US English</dd>
2897 * <dd>British English</dd>
2899 * <dd>Australian English (identical to British English)</dd>
2901 * More locales may be added by subclassing of YAHOO.util.DateLocale.
2902 * See YAHOO.util.DateLocale for more information.
2903 * @return {String} Formatted date for display.
2904 * @sa YAHOO.util.DateLocale
2906 format : function (oDate, oConfig, sLocale) {
2907 oConfig = oConfig || {};
2909 if(!(oDate instanceof Date)) {
2910 return YAHOO.lang.isValue(oDate) ? oDate : "";
2913 var format = oConfig.format || "%m/%d/%Y";
2915 // Be backwards compatible, support strings that are
2916 // exactly equal to YYYY/MM/DD, DD/MM/YYYY and MM/DD/YYYY
2917 if(format === 'YYYY/MM/DD') {
2918 format = '%Y/%m/%d';
2919 } else if(format === 'DD/MM/YYYY') {
2920 format = '%d/%m/%Y';
2921 } else if(format === 'MM/DD/YYYY') {
2922 format = '%m/%d/%Y';
2924 // end backwards compatibility block
2926 sLocale = sLocale || "en";
2928 // Make sure we have a definition for the requested locale, or default to en.
2929 if(!(sLocale in YAHOO.util.DateLocale)) {
2930 if(sLocale.replace(/-[a-zA-Z]+$/, '') in YAHOO.util.DateLocale) {
2931 sLocale = sLocale.replace(/-[a-zA-Z]+$/, '');
2937 var aLocale = YAHOO.util.DateLocale[sLocale];
2939 var replace_aggs = function (m0, m1) {
2940 var f = Dt.aggregates[m1];
2941 return (f === 'locale' ? aLocale[m1] : f);
2944 var replace_formats = function (m0, m1) {
2945 var f = Dt.formats[m1];
2946 if(typeof f === 'string') { // string => built in date function
2948 } else if(typeof f === 'function') { // function => our own function
2949 return f.call(oDate, oDate, aLocale);
2950 } else if(typeof f === 'object' && typeof f[0] === 'string') { // built in function with padding
2951 return xPad(oDate[f[0]](), f[1]);
2957 // First replace aggregates (run in a loop because an agg may be made up of other aggs)
2958 while(format.match(/%[cDFhnrRtTxX]/)) {
2959 format = format.replace(/%([cDFhnrRtTxX])/g, replace_aggs);
2962 // Now replace formats (do not run in a loop otherwise %%a will be replace with the value of %a)
2963 var str = format.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g, replace_formats);
2965 replace_aggs = replace_formats = undefined;
2971 YAHOO.namespace("YAHOO.util");
2972 YAHOO.util.Date = Dt;
2975 * The DateLocale class is a container and base class for all
2976 * localised date strings used by YAHOO.util.Date. It is used
2977 * internally, but may be extended to provide new date localisations.
2979 * To create your own DateLocale, follow these steps:
2981 * <li>Find an existing locale that matches closely with your needs</li>
2982 * <li>Use this as your base class. Use YAHOO.util.DateLocale if nothing
2984 * <li>Create your own class as an extension of the base class using
2985 * YAHOO.lang.merge, and add your own localisations where needed.</li>
2987 * See the YAHOO.util.DateLocale['en-US'] and YAHOO.util.DateLocale['en-GB']
2988 * classes which extend YAHOO.util.DateLocale['en'].
2990 * For example, to implement locales for French french and Canadian french,
2991 * we would do the following:
2993 * <li>For French french, we have no existing similar locale, so use
2994 * YAHOO.util.DateLocale as the base, and extend it:
2996 * YAHOO.util.DateLocale['fr'] = YAHOO.lang.merge(YAHOO.util.DateLocale, {
2997 * a: ['dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam'],
2998 * A: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
2999 * b: ['jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jui', 'aoû', 'sep', 'oct', 'nov', 'déc'],
3000 * B: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
3001 * c: '%a %d %b %Y %T %Z',
3009 * <li>For Canadian french, we start with French french and change the meaning of \%x:
3011 * YAHOO.util.DateLocale['fr-CA'] = YAHOO.lang.merge(YAHOO.util.DateLocale['fr'], {
3018 * With that, you can use your new locales:
3020 * var d = new Date("2008/04/22");
3021 * YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr");
3025 * mardi, 22 avril == 22.04.2008
3029 * YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr-CA");
3033 * mardi, 22 avril == 2008-04-22
3035 * @namespace YAHOO.util
3039 YAHOO.util.DateLocale = {
3040 a: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
3041 A: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
3042 b: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
3043 B: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
3044 c: '%a %d %b %Y %T %Z',
3052 YAHOO.util.DateLocale['en'] = YAHOO.lang.merge(YAHOO.util.DateLocale, {});
3054 YAHOO.util.DateLocale['en-US'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], {
3055 c: '%a %d %b %Y %I:%M:%S %p %Z',
3060 YAHOO.util.DateLocale['en-GB'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], {
3063 YAHOO.util.DateLocale['en-AU'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en']);
3067 YAHOO.register("datasource", YAHOO.util.DataSource, {version: "2.8.0r4", build: "2449"});