2 Copyright (c) 2011, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
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) {
41 this.liveData = oLiveData;
42 this._oQueue = {interval:null, conn:null, requests:[]};
43 this.responseSchema = {};
45 // Set any config params passed in to override defaults
46 if(oConfigs && (oConfigs.constructor == Object)) {
47 for(var sConfig in oConfigs) {
49 this[sConfig] = oConfigs[sConfig];
54 // Validate and initialize public configs
55 var maxCacheEntries = this.maxCacheEntries;
56 if(!lang.isNumber(maxCacheEntries) || (maxCacheEntries < 0)) {
60 // Initialize interval tracker
61 this._aIntervals = [];
63 /////////////////////////////////////////////////////////////////////////////
67 /////////////////////////////////////////////////////////////////////////////
70 * Fired when a request is made to the local cache.
72 * @event cacheRequestEvent
73 * @param oArgs.request {Object} The request object.
74 * @param oArgs.callback {Object} The callback object.
75 * @param oArgs.caller {Object} (deprecated) Use callback.scope.
77 this.createEvent("cacheRequestEvent");
80 * Fired when data is retrieved from the local cache.
82 * @event cacheResponseEvent
83 * @param oArgs.request {Object} The request object.
84 * @param oArgs.response {Object} The response object.
85 * @param oArgs.callback {Object} The callback object.
86 * @param oArgs.caller {Object} (deprecated) Use callback.scope.
88 this.createEvent("cacheResponseEvent");
91 * Fired when a request is sent to the live data source.
94 * @param oArgs.request {Object} The request object.
95 * @param oArgs.callback {Object} The callback object.
96 * @param oArgs.tId {Number} Transaction ID.
97 * @param oArgs.caller {Object} (deprecated) Use callback.scope.
99 this.createEvent("requestEvent");
102 * Fired when live data source sends response.
104 * @event responseEvent
105 * @param oArgs.request {Object} The request object.
106 * @param oArgs.response {Object} The raw response object.
107 * @param oArgs.callback {Object} The callback object.
108 * @param oArgs.tId {Number} Transaction ID.
109 * @param oArgs.caller {Object} (deprecated) Use callback.scope.
111 this.createEvent("responseEvent");
114 * Fired when response is parsed.
116 * @event responseParseEvent
117 * @param oArgs.request {Object} The request object.
118 * @param oArgs.response {Object} The parsed response object.
119 * @param oArgs.callback {Object} The callback object.
120 * @param oArgs.caller {Object} (deprecated) Use callback.scope.
122 this.createEvent("responseParseEvent");
125 * Fired when response is cached.
127 * @event responseCacheEvent
128 * @param oArgs.request {Object} The request object.
129 * @param oArgs.response {Object} The parsed response object.
130 * @param oArgs.callback {Object} The callback object.
131 * @param oArgs.caller {Object} (deprecated) Use callback.scope.
133 this.createEvent("responseCacheEvent");
135 * Fired when an error is encountered with the live data source.
137 * @event dataErrorEvent
138 * @param oArgs.request {Object} The request object.
139 * @param oArgs.response {String} The response object (if available).
140 * @param oArgs.callback {Object} The callback object.
141 * @param oArgs.caller {Object} (deprecated) Use callback.scope.
142 * @param oArgs.message {String} The error message.
144 this.createEvent("dataErrorEvent");
147 * Fired when the local cache is flushed.
149 * @event cacheFlushEvent
151 this.createEvent("cacheFlushEvent");
153 var DS = util.DataSourceBase;
154 this._sName = "DataSource instance" + DS._nIndex;
158 var DS = util.DataSourceBase;
160 lang.augmentObject(DS, {
162 /////////////////////////////////////////////////////////////////////////////
164 // DataSourceBase public constants
166 /////////////////////////////////////////////////////////////////////////////
171 * @property TYPE_UNKNOWN
179 * Type is a JavaScript Array.
181 * @property TYPE_JSARRAY
189 * Type is a JavaScript Function.
191 * @property TYPE_JSFUNCTION
199 * Type is hosted on a server via an XHR connection.
211 * @property TYPE_JSON
229 * Type is plain text.
231 * @property TYPE_TEXT
239 * Type is an HTML TABLE element. Data is parsed out of TR elements from all TBODY elements.
241 * @property TYPE_HTMLTABLE
249 * Type is hosted on a server via a dynamic script node.
251 * @property TYPE_SCRIPTNODE
261 * @property TYPE_LOCAL
269 * Error message for invalid dataresponses.
271 * @property ERROR_DATAINVALID
274 * @default "Invalid data"
276 ERROR_DATAINVALID : "Invalid data",
279 * Error message for null data responses.
281 * @property ERROR_DATANULL
284 * @default "Null data"
286 ERROR_DATANULL : "Null data",
288 /////////////////////////////////////////////////////////////////////////////
290 // DataSourceBase private static properties
292 /////////////////////////////////////////////////////////////////////////////
295 * Internal class variable to index multiple DataSource instances.
297 * @property DataSourceBase._nIndex
305 * Internal class variable to assign unique transaction IDs.
307 * @property DataSourceBase._nTransactionId
314 /////////////////////////////////////////////////////////////////////////////
316 // DataSourceBase private static methods
318 /////////////////////////////////////////////////////////////////////////////
320 * Clones object literal or array of object literals.
322 * @method DataSourceBase._cloneObject
323 * @param o {Object} Object.
327 _cloneObject: function(o) {
328 if(!lang.isValue(o)) {
334 if(Object.prototype.toString.apply(o) === "[object RegExp]") {
337 else if(lang.isFunction(o)) {
340 else if(lang.isArray(o)) {
342 for(var i=0,len=o.length;i<len;i++) {
343 array[i] = DS._cloneObject(o[i]);
347 else if(lang.isObject(o)) {
349 if(lang.hasOwnProperty(o, x)) {
350 if(lang.isValue(o[x]) && lang.isObject(o[x]) || lang.isArray(o[x])) {
351 copy[x] = DS._cloneObject(o[x]);
367 * Get an XPath-specified value for a given field from an XML node or document.
369 * @method _getLocationValue
370 * @param field {String | Object} Field definition.
371 * @param context {Object} XML node or document to search within.
372 * @return {Object} Data value or null.
376 _getLocationValue: function(field, context) {
377 var locator = field.locator || field.key || field,
378 xmldoc = context.ownerDocument || context,
379 result, res, value = null;
383 if(!lang.isUndefined(xmldoc.evaluate)) {
384 result = xmldoc.evaluate(locator, context, xmldoc.createNSResolver(!context.ownerDocument ? context.documentElement : context.ownerDocument.documentElement), 0, null);
385 while(res = result.iterateNext()) {
386 value = res.textContent;
391 xmldoc.setProperty("SelectionLanguage", "XPath");
392 result = context.selectNodes(locator)[0];
393 value = result.value || result.text || null;
402 /////////////////////////////////////////////////////////////////////////////
404 // DataSourceBase public static methods
406 /////////////////////////////////////////////////////////////////////////////
409 * Executes a configured callback. For object literal callbacks, the third
410 * param determines whether to execute the success handler or failure handler.
412 * @method issueCallback
413 * @param callback {Function|Object} the callback to execute
414 * @param params {Array} params to be passed to the callback method
415 * @param error {Boolean} whether an error occurred
416 * @param scope {Object} the scope from which to execute the callback
417 * (deprecated - use an object literal callback)
420 issueCallback : function (callback,params,error,scope) {
421 if (lang.isFunction(callback)) {
422 callback.apply(scope, params);
423 } else if (lang.isObject(callback)) {
424 scope = callback.scope || scope || window;
425 var callbackFunc = callback.success;
427 callbackFunc = callback.failure;
430 callbackFunc.apply(scope, params.concat([callback.argument]));
436 * Converts data to type String.
438 * @method DataSourceBase.parseString
439 * @param oData {String | Number | Boolean | Date | Array | Object} Data to parse.
440 * The special values null and undefined will return null.
441 * @return {String} A string, or null.
444 parseString : function(oData) {
445 // Special case null and undefined
446 if(!lang.isValue(oData)) {
451 var string = oData + "";
454 if(lang.isString(string)) {
463 * Converts data to type Number.
465 * @method DataSourceBase.parseNumber
466 * @param oData {String | Number | Boolean} Data to convert. Note, the following
467 * values return as null: null, undefined, NaN, "".
468 * @return {Number} A number, or null.
471 parseNumber : function(oData) {
472 if(!lang.isValue(oData) || (oData === "")) {
477 var number = oData * 1;
480 if(lang.isNumber(number)) {
487 // Backward compatibility
488 convertNumber : function(oData) {
489 return DS.parseNumber(oData);
493 * Converts data to type Date.
495 * @method DataSourceBase.parseDate
496 * @param oData {Date | String | Number} Data to convert.
497 * @return {Date} A Date instance.
500 parseDate : function(oData) {
504 if(lang.isValue(oData) && !(oData instanceof Date)) {
505 date = new Date(oData);
512 if(date instanceof Date) {
519 // Backward compatibility
520 convertDate : function(oData) {
521 return DS.parseDate(oData);
526 // Done in separate step so referenced functions are defined.
528 * Data parsing functions.
529 * @property DataSource.Parser
534 string : DS.parseString,
535 number : DS.parseNumber,
539 // Prototype properties and methods
542 /////////////////////////////////////////////////////////////////////////////
544 // DataSourceBase private properties
546 /////////////////////////////////////////////////////////////////////////////
549 * Name of DataSource instance.
558 * Local cache of data result object literals indexed chronologically.
567 * Local queue of request connections, enabled if queue needs to be managed.
576 * Array of polling interval IDs that have been enabled, needed to clear all intervals.
578 * @property _aIntervals
584 /////////////////////////////////////////////////////////////////////////////
586 // DataSourceBase public properties
588 /////////////////////////////////////////////////////////////////////////////
591 * Max size of the local cache. Set to 0 to turn off caching. Caching is
592 * useful to reduce the number of server connections. Recommended only for data
593 * sources that return comprehensive results for queries or when stale data is
596 * @property maxCacheEntries
603 * Pointer to live database.
611 * Where the live data is held:
614 * <dt>TYPE_UNKNOWN</dt>
615 * <dt>TYPE_LOCAL</dt>
617 * <dt>TYPE_SCRIPTNODE</dt>
618 * <dt>TYPE_JSFUNCTION</dt>
623 * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN
626 dataType : DS.TYPE_UNKNOWN,
629 * Format of response:
632 * <dt>TYPE_UNKNOWN</dt>
633 * <dt>TYPE_JSARRAY</dt>
637 * <dt>TYPE_HTMLTABLE</dt>
640 * @property responseType
642 * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN
644 responseType : DS.TYPE_UNKNOWN,
647 * Response schema object literal takes a combination of the following properties:
650 * <dt>resultsList</dt> <dd>Pointer to array of tabular data</dd>
651 * <dt>resultNode</dt> <dd>Pointer to node name of row data (XML data only)</dd>
652 * <dt>recordDelim</dt> <dd>Record delimiter (text data only)</dd>
653 * <dt>fieldDelim</dt> <dd>Field delimiter (text data only)</dd>
654 * <dt>fields</dt> <dd>Array of field names (aka keys), or array of object literals
655 * such as: {key:"fieldname",parser:YAHOO.util.DataSourceBase.parseDate}</dd>
656 * <dt>metaFields</dt> <dd>Object literal of keys to include in the oParsedResponse.meta collection</dd>
657 * <dt>metaNode</dt> <dd>Name of the node under which to search for meta information in XML response data</dd>
660 * @property responseSchema
663 responseSchema : null,
666 * Additional arguments passed to the JSON parse routine. The JSON string
667 * is the assumed first argument (where applicable). This property is not
668 * set by default, but the parse methods will use it if present.
670 * @property parseJSONArgs
671 * @type {MIXED|Array} If an Array, contents are used as individual arguments.
672 * Otherwise, value is used as an additional argument.
674 // property intentionally undefined
677 * When working with XML data, setting this property to true enables support for
678 * XPath-syntaxed locators in schema definitions.
687 * Clones entries before adding to cache.
689 * @property cloneBeforeCaching
693 cloneBeforeCaching : false,
695 /////////////////////////////////////////////////////////////////////////////
697 // DataSourceBase public methods
699 /////////////////////////////////////////////////////////////////////////////
702 * Public accessor to the unique name of the DataSource instance.
705 * @return {String} Unique name of the DataSource instance.
707 toString : function() {
712 * Overridable method passes request to cache and returns cached response if any,
713 * refreshing the hit in the cache as the newest item. Returns null if there is
716 * @method getCachedResponse
717 * @param oRequest {Object} Request object.
718 * @param oCallback {Object} Callback object.
719 * @param oCaller {Object} (deprecated) Use callback object.
720 * @return {Object} Cached response object or null.
722 getCachedResponse : function(oRequest, oCallback, oCaller) {
723 var aCache = this._aCache;
725 // If cache is enabled...
726 if(this.maxCacheEntries > 0) {
727 // Initialize local cache
731 // Look in local cache
733 var nCacheLength = aCache.length;
734 if(nCacheLength > 0) {
735 var oResponse = null;
736 this.fireEvent("cacheRequestEvent", {request:oRequest,callback:oCallback,caller:oCaller});
738 // Loop through each cached element
739 for(var i = nCacheLength-1; i >= 0; i--) {
740 var oCacheElem = aCache[i];
742 // Defer cache hit logic to a public overridable method
743 if(this.isCacheHit(oRequest,oCacheElem.request)) {
744 // The cache returned a hit!
745 // Grab the cached response
746 oResponse = oCacheElem.response;
747 this.fireEvent("cacheResponseEvent", {request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});
749 // Refresh the position of the cache hit
750 if(i < nCacheLength-1) {
751 // Remove element from its original location
754 this.addToCache(oRequest, oResponse);
758 oResponse.cached = true;
773 * Default overridable method matches given request to given cached request.
774 * Returns true if is a hit, returns false otherwise. Implementers should
775 * override this method to customize the cache-matching algorithm.
778 * @param oRequest {Object} Request object.
779 * @param oCachedRequest {Object} Cached request object.
780 * @return {Boolean} True if given request matches cached request, false otherwise.
782 isCacheHit : function(oRequest, oCachedRequest) {
783 return (oRequest === oCachedRequest);
787 * Adds a new item to the cache. If cache is full, evicts the stalest item
788 * before adding the new item.
791 * @param oRequest {Object} Request object.
792 * @param oResponse {Object} Response object to cache.
794 addToCache : function(oRequest, oResponse) {
795 var aCache = this._aCache;
800 // If the cache is full, make room by removing stalest element (index=0)
801 while(aCache.length >= this.maxCacheEntries) {
805 // Add to cache in the newest position, at the end of the array
806 oResponse = (this.cloneBeforeCaching) ? DS._cloneObject(oResponse) : oResponse;
807 var oCacheElem = {request:oRequest,response:oResponse};
808 aCache[aCache.length] = oCacheElem;
809 this.fireEvent("responseCacheEvent", {request:oRequest,response:oResponse});
817 flushCache : function() {
820 this.fireEvent("cacheFlushEvent");
825 * Sets up a polling mechanism to send requests at set intervals and forward
826 * responses to given callback.
828 * @method setInterval
829 * @param nMsec {Number} Length of interval in milliseconds.
830 * @param oRequest {Object} Request object.
831 * @param oCallback {Function} Handler function to receive the response.
832 * @param oCaller {Object} (deprecated) Use oCallback.scope.
833 * @return {Number} Interval ID.
835 setInterval : function(nMsec, oRequest, oCallback, oCaller) {
836 if(lang.isNumber(nMsec) && (nMsec >= 0)) {
838 var nId = setInterval(function() {
839 oSelf.makeConnection(oRequest, oCallback, oCaller);
841 this._aIntervals.push(nId);
849 * Disables polling mechanism associated with the given interval ID. Does not
850 * affect transactions that are in progress.
852 * @method clearInterval
853 * @param nId {Number} Interval ID.
855 clearInterval : function(nId) {
856 // Remove from tracker if there
857 var tracker = this._aIntervals || [];
858 for(var i=tracker.length-1; i>-1; i--) {
859 if(tracker[i] === nId) {
867 * Disables all known polling intervals. Does not affect transactions that are
870 * @method clearAllIntervals
872 clearAllIntervals : function() {
873 var tracker = this._aIntervals || [];
874 for(var i=tracker.length-1; i>-1; i--) {
875 clearInterval(tracker[i]);
881 * First looks for cached response, then sends request to live data. The
882 * following arguments are passed to the callback function:
884 * <dt><code>oRequest</code></dt>
885 * <dd>The same value that was passed in as the first argument to sendRequest.</dd>
886 * <dt><code>oParsedResponse</code></dt>
887 * <dd>An object literal containing the following properties:
889 * <dt><code>tId</code></dt>
890 * <dd>Unique transaction ID number.</dd>
891 * <dt><code>results</code></dt>
892 * <dd>Schema-parsed data results.</dd>
893 * <dt><code>error</code></dt>
894 * <dd>True in cases of data error.</dd>
895 * <dt><code>cached</code></dt>
896 * <dd>True when response is returned from DataSource cache.</dd>
897 * <dt><code>meta</code></dt>
898 * <dd>Schema-parsed meta data.</dd>
900 * <dt><code>oPayload</code></dt>
901 * <dd>The same value as was passed in as <code>argument</code> in the oCallback object literal.</dd>
904 * @method sendRequest
905 * @param oRequest {Object} Request object.
906 * @param oCallback {Object} An object literal with the following properties:
908 * <dt><code>success</code></dt>
909 * <dd>The function to call when the data is ready.</dd>
910 * <dt><code>failure</code></dt>
911 * <dd>The function to call upon a response failure condition.</dd>
912 * <dt><code>scope</code></dt>
913 * <dd>The object to serve as the scope for the success and failure handlers.</dd>
914 * <dt><code>argument</code></dt>
915 * <dd>Arbitrary data that will be passed back to the success and failure handlers.</dd>
917 * @param oCaller {Object} (deprecated) Use oCallback.scope.
918 * @return {Number} Transaction ID, or null if response found in cache.
920 sendRequest : function(oRequest, oCallback, oCaller) {
921 // First look in cache
922 var oCachedResponse = this.getCachedResponse(oRequest, oCallback, oCaller);
923 if(oCachedResponse) {
924 DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller);
929 // Not in cache, so forward request to live data
930 return this.makeConnection(oRequest, oCallback, oCaller);
934 * Overridable default method generates a unique transaction ID and passes
935 * the live data reference directly to the handleResponse function. This
936 * method should be implemented by subclasses to achieve more complex behavior
937 * or to access remote data.
939 * @method makeConnection
940 * @param oRequest {Object} Request object.
941 * @param oCallback {Object} Callback object literal.
942 * @param oCaller {Object} (deprecated) Use oCallback.scope.
943 * @return {Number} Transaction ID.
945 makeConnection : function(oRequest, oCallback, oCaller) {
946 var tId = DS._nTransactionId++;
947 this.fireEvent("requestEvent", {tId:tId, request:oRequest,callback:oCallback,caller:oCaller});
949 /* accounts for the following cases:
950 YAHOO.util.DataSourceBase.TYPE_UNKNOWN
951 YAHOO.util.DataSourceBase.TYPE_JSARRAY
952 YAHOO.util.DataSourceBase.TYPE_JSON
953 YAHOO.util.DataSourceBase.TYPE_HTMLTABLE
954 YAHOO.util.DataSourceBase.TYPE_XML
955 YAHOO.util.DataSourceBase.TYPE_TEXT
957 var oRawResponse = this.liveData;
959 this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
964 * Receives raw data response and type converts to XML, JSON, etc as necessary.
965 * Forwards oFullResponse to appropriate parsing function to get turned into
966 * oParsedResponse. Calls doBeforeCallback() and adds oParsedResponse to
967 * the cache when appropriate before calling issueCallback().
969 * The oParsedResponse object literal has the following properties:
971 * <dd><dt>tId {Number}</dt> Unique transaction ID</dd>
972 * <dd><dt>results {Array}</dt> Array of parsed data results</dd>
973 * <dd><dt>meta {Object}</dt> Object literal of meta values</dd>
974 * <dd><dt>error {Boolean}</dt> (optional) True if there was an error</dd>
975 * <dd><dt>cached {Boolean}</dt> (optional) True if response was cached</dd>
978 * @method handleResponse
979 * @param oRequest {Object} Request object
980 * @param oRawResponse {Object} The raw response from the live database.
981 * @param oCallback {Object} Callback object literal.
982 * @param oCaller {Object} (deprecated) Use oCallback.scope.
983 * @param tId {Number} Transaction ID.
985 handleResponse : function(oRequest, oRawResponse, oCallback, oCaller, tId) {
986 this.fireEvent("responseEvent", {tId:tId, request:oRequest, response:oRawResponse,
987 callback:oCallback, caller:oCaller});
988 var xhr = (this.dataType == DS.TYPE_XHR) ? true : false;
989 var oParsedResponse = null;
990 var oFullResponse = oRawResponse;
992 // Try to sniff data type if it has not been defined
993 if(this.responseType === DS.TYPE_UNKNOWN) {
994 var ctype = (oRawResponse && oRawResponse.getResponseHeader) ? oRawResponse.getResponseHeader["Content-Type"] : null;
997 if(ctype.indexOf("text/xml") > -1) {
998 this.responseType = DS.TYPE_XML;
1000 else if(ctype.indexOf("application/json") > -1) { // json
1001 this.responseType = DS.TYPE_JSON;
1003 else if(ctype.indexOf("text/plain") > -1) { // text
1004 this.responseType = DS.TYPE_TEXT;
1008 if(YAHOO.lang.isArray(oRawResponse)) { // array
1009 this.responseType = DS.TYPE_JSARRAY;
1012 else if(oRawResponse && oRawResponse.nodeType && (oRawResponse.nodeType === 9 || oRawResponse.nodeType === 1 || oRawResponse.nodeType === 11)) {
1013 this.responseType = DS.TYPE_XML;
1015 else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
1016 this.responseType = DS.TYPE_HTMLTABLE;
1018 else if(YAHOO.lang.isObject(oRawResponse)) { // json
1019 this.responseType = DS.TYPE_JSON;
1021 else if(YAHOO.lang.isString(oRawResponse)) { // text
1022 this.responseType = DS.TYPE_TEXT;
1027 switch(this.responseType) {
1028 case DS.TYPE_JSARRAY:
1029 if(xhr && oRawResponse && oRawResponse.responseText) {
1030 oFullResponse = oRawResponse.responseText;
1033 // Convert to JS array if it's a string
1034 if(lang.isString(oFullResponse)) {
1035 var parseArgs = [oFullResponse].concat(this.parseJSONArgs);
1036 // Check for YUI JSON Util
1038 oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs);
1040 // Look for JSON parsers using an API similar to json2.js
1041 else if(window.JSON && JSON.parse) {
1042 oFullResponse = JSON.parse.apply(JSON,parseArgs);
1044 // Look for JSON parsers using an API similar to json.js
1045 else if(oFullResponse.parseJSON) {
1046 oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1));
1048 // No JSON lib found so parse the string
1050 // Trim leading spaces
1051 while (oFullResponse.length > 0 &&
1052 (oFullResponse.charAt(0) != "{") &&
1053 (oFullResponse.charAt(0) != "[")) {
1054 oFullResponse = oFullResponse.substring(1, oFullResponse.length);
1057 if(oFullResponse.length > 0) {
1058 // Strip extraneous stuff at the end
1060 Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));
1061 oFullResponse = oFullResponse.substring(0,arrayEnd+1);
1063 // Turn the string into an object literal...
1064 // ...eval is necessary here
1065 oFullResponse = eval("(" + oFullResponse + ")");
1073 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1074 oParsedResponse = this.parseArrayData(oRequest, oFullResponse);
1077 if(xhr && oRawResponse && oRawResponse.responseText) {
1078 oFullResponse = oRawResponse.responseText;
1081 // Convert to JSON object if it's a string
1082 if(lang.isString(oFullResponse)) {
1083 var parseArgs = [oFullResponse].concat(this.parseJSONArgs);
1084 // Check for YUI JSON Util
1086 oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs);
1088 // Look for JSON parsers using an API similar to json2.js
1089 else if(window.JSON && JSON.parse) {
1090 oFullResponse = JSON.parse.apply(JSON,parseArgs);
1092 // Look for JSON parsers using an API similar to json.js
1093 else if(oFullResponse.parseJSON) {
1094 oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1));
1096 // No JSON lib found so parse the string
1098 // Trim leading spaces
1099 while (oFullResponse.length > 0 &&
1100 (oFullResponse.charAt(0) != "{") &&
1101 (oFullResponse.charAt(0) != "[")) {
1102 oFullResponse = oFullResponse.substring(1, oFullResponse.length);
1105 if(oFullResponse.length > 0) {
1106 // Strip extraneous stuff at the end
1107 var objEnd = Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));
1108 oFullResponse = oFullResponse.substring(0,objEnd+1);
1110 // Turn the string into an object literal...
1111 // ...eval is necessary here
1112 oFullResponse = eval("(" + oFullResponse + ")");
1121 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1122 oParsedResponse = this.parseJSONData(oRequest, oFullResponse);
1124 case DS.TYPE_HTMLTABLE:
1125 if(xhr && oRawResponse.responseText) {
1126 var el = document.createElement('div');
1127 el.innerHTML = oRawResponse.responseText;
1128 oFullResponse = el.getElementsByTagName('table')[0];
1130 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1131 oParsedResponse = this.parseHTMLTableData(oRequest, oFullResponse);
1134 if(xhr && oRawResponse.responseXML) {
1135 oFullResponse = oRawResponse.responseXML;
1137 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1138 oParsedResponse = this.parseXMLData(oRequest, oFullResponse);
1141 if(xhr && lang.isString(oRawResponse.responseText)) {
1142 oFullResponse = oRawResponse.responseText;
1144 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1145 oParsedResponse = this.parseTextData(oRequest, oFullResponse);
1148 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1149 oParsedResponse = this.parseData(oRequest, oFullResponse);
1154 // Clean up for consistent signature
1155 oParsedResponse = oParsedResponse || {};
1156 if(!oParsedResponse.results) {
1157 oParsedResponse.results = [];
1159 if(!oParsedResponse.meta) {
1160 oParsedResponse.meta = {};
1164 if(!oParsedResponse.error) {
1165 // Last chance to touch the raw response or the parsed response
1166 oParsedResponse = this.doBeforeCallback(oRequest, oFullResponse, oParsedResponse, oCallback);
1167 this.fireEvent("responseParseEvent", {request:oRequest,
1168 response:oParsedResponse, callback:oCallback, caller:oCaller});
1169 // Cache the response
1170 this.addToCache(oRequest, oParsedResponse);
1174 // Be sure the error flag is on
1175 oParsedResponse.error = true;
1176 this.fireEvent("dataErrorEvent", {request:oRequest, response: oRawResponse, callback:oCallback,
1177 caller:oCaller, message:DS.ERROR_DATANULL});
1180 // Send the response back to the caller
1181 oParsedResponse.tId = tId;
1182 DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller);
1186 * Overridable method gives implementers access to the original full response
1187 * before the data gets parsed. Implementers should take care not to return an
1188 * unparsable or otherwise invalid response.
1190 * @method doBeforeParseData
1191 * @param oRequest {Object} Request object.
1192 * @param oFullResponse {Object} The full response from the live database.
1193 * @param oCallback {Object} The callback object.
1194 * @return {Object} Full response for parsing.
1197 doBeforeParseData : function(oRequest, oFullResponse, oCallback) {
1198 return oFullResponse;
1202 * Overridable method gives implementers access to the original full response and
1203 * the parsed response (parsed against the given schema) before the data
1204 * is added to the cache (if applicable) and then sent back to callback function.
1205 * This is your chance to access the raw response and/or populate the parsed
1206 * response with any custom data.
1208 * @method doBeforeCallback
1209 * @param oRequest {Object} Request object.
1210 * @param oFullResponse {Object} The full response from the live database.
1211 * @param oParsedResponse {Object} The parsed response to return to calling object.
1212 * @param oCallback {Object} The callback object.
1213 * @return {Object} Parsed response object.
1215 doBeforeCallback : function(oRequest, oFullResponse, oParsedResponse, oCallback) {
1216 return oParsedResponse;
1220 * Overridable method parses data of generic RESPONSE_TYPE into a response object.
1223 * @param oRequest {Object} Request object.
1224 * @param oFullResponse {Object} The full Array from the live database.
1225 * @return {Object} Parsed response object with the following properties:<br>
1226 * - results {Array} Array of parsed data results<br>
1227 * - meta {Object} Object literal of meta values<br>
1228 * - error {Boolean} (optional) True if there was an error<br>
1230 parseData : function(oRequest, oFullResponse) {
1231 if(lang.isValue(oFullResponse)) {
1232 var oParsedResponse = {results:oFullResponse,meta:{}};
1233 return oParsedResponse;
1240 * Overridable method parses Array data into a response object.
1242 * @method parseArrayData
1243 * @param oRequest {Object} Request object.
1244 * @param oFullResponse {Object} The full Array from the live database.
1245 * @return {Object} Parsed response object with the following properties:<br>
1246 * - results (Array) Array of parsed data results<br>
1247 * - error (Boolean) True if there was an error
1249 parseArrayData : function(oRequest, oFullResponse) {
1250 if(lang.isArray(oFullResponse)) {
1256 if(lang.isArray(this.responseSchema.fields)) {
1257 var fields = this.responseSchema.fields;
1258 for (i = fields.length - 1; i >= 0; --i) {
1259 if (typeof fields[i] !== 'object') {
1260 fields[i] = { key : fields[i] };
1264 var parsers = {}, p;
1265 for (i = fields.length - 1; i >= 0; --i) {
1266 p = (typeof fields[i].parser === 'function' ?
1268 DS.Parser[fields[i].parser+'']) || fields[i].converter;
1270 parsers[fields[i].key] = p;
1274 var arrType = lang.isArray(oFullResponse[0]);
1275 for(i=oFullResponse.length-1; i>-1; i--) {
1277 rec = oFullResponse[i];
1278 if (typeof rec === 'object') {
1279 for(j=fields.length-1; j>-1; j--) {
1281 data = arrType ? rec[j] : rec[field.key];
1283 if (parsers[field.key]) {
1284 data = parsers[field.key].call(this,data);
1288 if(data === undefined) {
1292 oResult[field.key] = data;
1295 else if (lang.isString(rec)) {
1296 for(j=fields.length-1; j>-1; j--) {
1300 if (parsers[field.key]) {
1301 data = parsers[field.key].call(this,data);
1305 if(data === undefined) {
1309 oResult[field.key] = data;
1312 results[i] = oResult;
1315 // Return entire data set
1317 results = oFullResponse;
1319 var oParsedResponse = {results:results};
1320 return oParsedResponse;
1327 * Overridable method parses plain text data into a response object.
1329 * @method parseTextData
1330 * @param oRequest {Object} Request object.
1331 * @param oFullResponse {Object} The full text response from the live database.
1332 * @return {Object} Parsed response object with the following properties:<br>
1333 * - results (Array) Array of parsed data results<br>
1334 * - error (Boolean) True if there was an error
1336 parseTextData : function(oRequest, oFullResponse) {
1337 if(lang.isString(oFullResponse)) {
1338 if(lang.isString(this.responseSchema.recordDelim) &&
1339 lang.isString(this.responseSchema.fieldDelim)) {
1340 var oParsedResponse = {results:[]};
1341 var recDelim = this.responseSchema.recordDelim;
1342 var fieldDelim = this.responseSchema.fieldDelim;
1343 if(oFullResponse.length > 0) {
1344 // Delete the last line delimiter at the end of the data if it exists
1345 var newLength = oFullResponse.length-recDelim.length;
1346 if(oFullResponse.substr(newLength) == recDelim) {
1347 oFullResponse = oFullResponse.substr(0, newLength);
1349 if(oFullResponse.length > 0) {
1350 // Split along record delimiter to get an array of strings
1351 var recordsarray = oFullResponse.split(recDelim);
1352 // Cycle through each record
1353 for(var i = 0, len = recordsarray.length, recIdx = 0; i < len; ++i) {
1355 sRecord = recordsarray[i];
1356 if (lang.isString(sRecord) && (sRecord.length > 0)) {
1357 // Split each record along field delimiter to get data
1358 var fielddataarray = recordsarray[i].split(fieldDelim);
1361 // Filter for fields data
1362 if(lang.isArray(this.responseSchema.fields)) {
1363 var fields = this.responseSchema.fields;
1364 for(var j=fields.length-1; j>-1; j--) {
1366 // Remove quotation marks from edges, if applicable
1367 var data = fielddataarray[j];
1368 if (lang.isString(data)) {
1369 if(data.charAt(0) == "\"") {
1370 data = data.substr(1);
1372 if(data.charAt(data.length-1) == "\"") {
1373 data = data.substr(0,data.length-1);
1375 var field = fields[j];
1376 var key = (lang.isValue(field.key)) ? field.key : field;
1377 // Backward compatibility
1378 if(!field.parser && field.converter) {
1379 field.parser = field.converter;
1381 var parser = (typeof field.parser === 'function') ?
1383 DS.Parser[field.parser+''];
1385 data = parser.call(this, data);
1388 if(data === undefined) {
1391 oResult[key] = data;
1402 // No fields defined so pass along all data as an array
1404 oResult = fielddataarray;
1407 oParsedResponse.results[recIdx++] = oResult;
1413 return oParsedResponse;
1421 * Overridable method parses XML data for one result into an object literal.
1423 * @method parseXMLResult
1424 * @param result {XML} XML for one result.
1425 * @return {Object} Object literal of data for one result.
1427 parseXMLResult : function(result) {
1429 schema = this.responseSchema;
1432 // Loop through each data field in each result using the schema
1433 for(var m = schema.fields.length-1; m >= 0 ; m--) {
1434 var field = schema.fields[m];
1435 var key = (lang.isValue(field.key)) ? field.key : field;
1439 data = YAHOO.util.DataSource._getLocationValue(field, result);
1442 // Values may be held in an attribute...
1443 var xmlAttr = result.attributes.getNamedItem(key);
1445 data = xmlAttr.value;
1449 var xmlNode = result.getElementsByTagName(key);
1450 if(xmlNode && xmlNode.item(0)) {
1451 var item = xmlNode.item(0);
1452 // For IE, then DOM...
1453 data = (item) ? ((item.text) ? item.text : (item.textContent) ? item.textContent : null) : null;
1454 // ...then fallback, but check for multiple child nodes
1456 var datapieces = [];
1457 for(var j=0, len=item.childNodes.length; j<len; j++) {
1458 if(item.childNodes[j].nodeValue) {
1459 datapieces[datapieces.length] = item.childNodes[j].nodeValue;
1462 if(datapieces.length > 0) {
1463 data = datapieces.join("");
1475 // Backward compatibility
1476 if(!field.parser && field.converter) {
1477 field.parser = field.converter;
1479 var parser = (typeof field.parser === 'function') ?
1481 DS.Parser[field.parser+''];
1483 data = parser.call(this, data);
1486 if(data === undefined) {
1489 oResult[key] = data;
1501 * Overridable method parses XML data into a response object.
1503 * @method parseXMLData
1504 * @param oRequest {Object} Request object.
1505 * @param oFullResponse {Object} The full XML response from the live database.
1506 * @return {Object} Parsed response object with the following properties<br>
1507 * - results (Array) Array of parsed data results<br>
1508 * - error (Boolean) True if there was an error
1510 parseXMLData : function(oRequest, oFullResponse) {
1512 schema = this.responseSchema,
1513 oParsedResponse = {meta:{}},
1515 metaNode = schema.metaNode,
1516 metaLocators = schema.metaFields || {},
1519 // In case oFullResponse is something funky
1521 // Pull any meta identified
1523 for (k in metaLocators) {
1524 oParsedResponse.meta[k] = YAHOO.util.DataSource._getLocationValue(metaLocators[k], oFullResponse);
1528 metaNode = metaNode ? oFullResponse.getElementsByTagName(metaNode)[0] :
1532 for (k in metaLocators) {
1533 if (lang.hasOwnProperty(metaLocators, k)) {
1534 loc = metaLocators[k];
1536 v = metaNode.getElementsByTagName(loc)[0];
1539 v = v.firstChild.nodeValue;
1541 // Look for an attribute
1542 v = metaNode.attributes.getNamedItem(loc);
1548 if (lang.isValue(v)) {
1549 oParsedResponse.meta[k] = v;
1557 xmlList = (schema.resultNode) ?
1558 oFullResponse.getElementsByTagName(schema.resultNode) :
1563 if(!xmlList || !lang.isArray(schema.fields)) {
1566 // Loop through each result
1568 oParsedResponse.results = [];
1569 for(i = xmlList.length-1; i >= 0 ; --i) {
1570 var oResult = this.parseXMLResult(xmlList.item(i));
1571 // Capture each array of values into an array of results
1572 oParsedResponse.results[i] = oResult;
1576 oParsedResponse.error = true;
1580 return oParsedResponse;
1584 * Overridable method parses JSON data into a response object.
1586 * @method parseJSONData
1587 * @param oRequest {Object} Request object.
1588 * @param oFullResponse {Object} The full JSON from the live database.
1589 * @return {Object} Parsed response object with the following properties<br>
1590 * - results (Array) Array of parsed data results<br>
1591 * - error (Boolean) True if there was an error
1593 parseJSONData : function(oRequest, oFullResponse) {
1594 var oParsedResponse = {results:[],meta:{}};
1596 if(lang.isObject(oFullResponse) && this.responseSchema.resultsList) {
1597 var schema = this.responseSchema,
1598 fields = schema.fields,
1599 resultsList = oFullResponse,
1601 metaFields = schema.metaFields || {},
1606 i,len,j,v,key,parser,path;
1608 // Function to convert the schema's fields into walk paths
1609 var buildPath = function (needle) {
1610 var path = null, keys = [], i = 0;
1612 // Strip the ["string keys"] and [1] array indexes
1614 replace(/\[(['"])(.*?)\1\]/g,
1615 function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}).
1616 replace(/\[(\d+)\]/g,
1617 function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}).
1618 replace(/^\./,''); // remove leading dot
1620 // If the cleaned needle contains invalid characters, the
1622 if (!/[^\w\.\$@]/.test(needle)) {
1623 path = needle.split('.');
1624 for (i=path.length-1; i >= 0; --i) {
1625 if (path[i].charAt(0) === '@') {
1626 path[i] = keys[parseInt(path[i].substr(1),10)];
1637 // Function to walk a path and return the pot of gold
1638 var walkPath = function (path, origin) {
1639 var v=origin,i=0,len=path.length;
1640 for (;i<len && v;++i) {
1646 // Parse the response
1647 // Step 1. Pull the resultsList from oFullResponse (default assumes
1648 // oFullResponse IS the resultsList)
1649 path = buildPath(schema.resultsList);
1651 resultsList = walkPath(path, oFullResponse);
1652 if (resultsList === undefined) {
1663 if (!lang.isArray(resultsList)) {
1664 resultsList = [resultsList];
1668 // Step 2. Parse out field data if identified
1671 // Build the field parser map and location paths
1672 for (i=0, len=fields.length; i<len; i++) {
1674 key = field.key || field;
1675 parser = ((typeof field.parser === 'function') ?
1677 DS.Parser[field.parser+'']) || field.converter;
1678 path = buildPath(key);
1681 fieldParsers[fieldParsers.length] = {key:key,parser:parser};
1685 if (path.length > 1) {
1686 fieldPaths[fieldPaths.length] = {key:key,path:path};
1688 simpleFields[simpleFields.length] = {key:key,path:path[0]};
1694 // Process the results, flattening the records and/or applying parsers if needed
1695 for (i = resultsList.length - 1; i >= 0; --i) {
1696 var r = resultsList[i], rec = {};
1698 for (j = simpleFields.length - 1; j >= 0; --j) {
1699 // Bug 1777850: data might be held in an array
1700 rec[simpleFields[j].key] =
1701 (r[simpleFields[j].path] !== undefined) ?
1702 r[simpleFields[j].path] : r[j];
1705 for (j = fieldPaths.length - 1; j >= 0; --j) {
1706 rec[fieldPaths[j].key] = walkPath(fieldPaths[j].path,r);
1709 for (j = fieldParsers.length - 1; j >= 0; --j) {
1710 var p = fieldParsers[j].key;
1711 rec[p] = fieldParsers[j].parser.call(this, rec[p]);
1712 if (rec[p] === undefined) {
1721 results = resultsList;
1724 for (key in metaFields) {
1725 if (lang.hasOwnProperty(metaFields,key)) {
1726 path = buildPath(metaFields[key]);
1728 v = walkPath(path, oFullResponse);
1729 oParsedResponse.meta[key] = v;
1736 oParsedResponse.error = true;
1739 oParsedResponse.results = results;
1742 oParsedResponse.error = true;
1745 return oParsedResponse;
1749 * Overridable method parses an HTML TABLE element reference into a response object.
1750 * Data is parsed out of TR elements from all TBODY elements.
1752 * @method parseHTMLTableData
1753 * @param oRequest {Object} Request object.
1754 * @param oFullResponse {Object} The full HTML element reference from the live database.
1755 * @return {Object} Parsed response object with the following properties<br>
1756 * - results (Array) Array of parsed data results<br>
1757 * - error (Boolean) True if there was an error
1759 parseHTMLTableData : function(oRequest, oFullResponse) {
1761 var elTable = oFullResponse;
1762 var fields = this.responseSchema.fields;
1763 var oParsedResponse = {results:[]};
1765 if(lang.isArray(fields)) {
1766 // Iterate through each TBODY
1767 for(var i=0; i<elTable.tBodies.length; i++) {
1768 var elTbody = elTable.tBodies[i];
1770 // Iterate through each TR
1771 for(var j=elTbody.rows.length-1; j>-1; j--) {
1772 var elRow = elTbody.rows[j];
1775 for(var k=fields.length-1; k>-1; k--) {
1776 var field = fields[k];
1777 var key = (lang.isValue(field.key)) ? field.key : field;
1778 var data = elRow.cells[k].innerHTML;
1780 // Backward compatibility
1781 if(!field.parser && field.converter) {
1782 field.parser = field.converter;
1784 var parser = (typeof field.parser === 'function') ?
1786 DS.Parser[field.parser+''];
1788 data = parser.call(this, data);
1791 if(data === undefined) {
1794 oResult[key] = data;
1796 oParsedResponse.results[j] = oResult;
1805 oParsedResponse.error = true;
1809 return oParsedResponse;
1814 // DataSourceBase uses EventProvider
1815 lang.augmentProto(DS, util.EventProvider);
1819 /****************************************************************************/
1820 /****************************************************************************/
1821 /****************************************************************************/
1824 * LocalDataSource class for in-memory data structs including JavaScript arrays,
1825 * JavaScript object literals (JSON), XML documents, and HTML tables.
1827 * @namespace YAHOO.util
1828 * @class YAHOO.util.LocalDataSource
1829 * @extends YAHOO.util.DataSourceBase
1831 * @param oLiveData {HTMLElement} Pointer to live data.
1832 * @param oConfigs {object} (optional) Object literal of configuration values.
1834 util.LocalDataSource = function(oLiveData, oConfigs) {
1835 this.dataType = DS.TYPE_LOCAL;
1838 if(YAHOO.lang.isArray(oLiveData)) { // array
1839 this.responseType = DS.TYPE_JSARRAY;
1842 else if(oLiveData.nodeType && oLiveData.nodeType == 9) {
1843 this.responseType = DS.TYPE_XML;
1845 else if(oLiveData.nodeName && (oLiveData.nodeName.toLowerCase() == "table")) { // table
1846 this.responseType = DS.TYPE_HTMLTABLE;
1847 oLiveData = oLiveData.cloneNode(true);
1849 else if(YAHOO.lang.isString(oLiveData)) { // text
1850 this.responseType = DS.TYPE_TEXT;
1852 else if(YAHOO.lang.isObject(oLiveData)) { // json
1853 this.responseType = DS.TYPE_JSON;
1858 this.responseType = DS.TYPE_JSARRAY;
1861 util.LocalDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
1864 // LocalDataSource extends DataSourceBase
1865 lang.extend(util.LocalDataSource, DS);
1867 // Copy static members to LocalDataSource class
1868 lang.augmentObject(util.LocalDataSource, DS);
1882 /****************************************************************************/
1883 /****************************************************************************/
1884 /****************************************************************************/
1887 * FunctionDataSource class for JavaScript functions.
1889 * @namespace YAHOO.util
1890 * @class YAHOO.util.FunctionDataSource
1891 * @extends YAHOO.util.DataSourceBase
1893 * @param oLiveData {HTMLElement} Pointer to live data.
1894 * @param oConfigs {object} (optional) Object literal of configuration values.
1896 util.FunctionDataSource = function(oLiveData, oConfigs) {
1897 this.dataType = DS.TYPE_JSFUNCTION;
1898 oLiveData = oLiveData || function() {};
1900 util.FunctionDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
1903 // FunctionDataSource extends DataSourceBase
1904 lang.extend(util.FunctionDataSource, DS, {
1906 /////////////////////////////////////////////////////////////////////////////
1908 // FunctionDataSource public properties
1910 /////////////////////////////////////////////////////////////////////////////
1913 * Context in which to execute the function. By default, is the DataSource
1914 * instance itself. If set, the function will receive the DataSource instance
1915 * as an additional argument.
1924 /////////////////////////////////////////////////////////////////////////////
1926 // FunctionDataSource public methods
1928 /////////////////////////////////////////////////////////////////////////////
1931 * Overriding method passes query to a function. The returned response is then
1932 * forwarded to the handleResponse function.
1934 * @method makeConnection
1935 * @param oRequest {Object} Request object.
1936 * @param oCallback {Object} Callback object literal.
1937 * @param oCaller {Object} (deprecated) Use oCallback.scope.
1938 * @return {Number} Transaction ID.
1940 makeConnection : function(oRequest, oCallback, oCaller) {
1941 var tId = DS._nTransactionId++;
1942 this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
1944 // Pass the request in as a parameter and
1945 // forward the return value to the handler
1948 var oRawResponse = (this.scope) ? this.liveData.call(this.scope, oRequest, this, oCallback) : this.liveData(oRequest, oCallback);
1950 // Try to sniff data type if it has not been defined
1951 if(this.responseType === DS.TYPE_UNKNOWN) {
1952 if(YAHOO.lang.isArray(oRawResponse)) { // array
1953 this.responseType = DS.TYPE_JSARRAY;
1956 else if(oRawResponse && oRawResponse.nodeType && oRawResponse.nodeType == 9) {
1957 this.responseType = DS.TYPE_XML;
1959 else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
1960 this.responseType = DS.TYPE_HTMLTABLE;
1962 else if(YAHOO.lang.isObject(oRawResponse)) { // json
1963 this.responseType = DS.TYPE_JSON;
1965 else if(YAHOO.lang.isString(oRawResponse)) { // text
1966 this.responseType = DS.TYPE_TEXT;
1970 this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
1976 // Copy static members to FunctionDataSource class
1977 lang.augmentObject(util.FunctionDataSource, DS);
1991 /****************************************************************************/
1992 /****************************************************************************/
1993 /****************************************************************************/
1996 * ScriptNodeDataSource class for accessing remote data via the YUI Get Utility.
1998 * @namespace YAHOO.util
1999 * @class YAHOO.util.ScriptNodeDataSource
2000 * @extends YAHOO.util.DataSourceBase
2002 * @param oLiveData {HTMLElement} Pointer to live data.
2003 * @param oConfigs {object} (optional) Object literal of configuration values.
2005 util.ScriptNodeDataSource = function(oLiveData, oConfigs) {
2006 this.dataType = DS.TYPE_SCRIPTNODE;
2007 oLiveData = oLiveData || "";
2009 util.ScriptNodeDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
2012 // ScriptNodeDataSource extends DataSourceBase
2013 lang.extend(util.ScriptNodeDataSource, DS, {
2015 /////////////////////////////////////////////////////////////////////////////
2017 // ScriptNodeDataSource public properties
2019 /////////////////////////////////////////////////////////////////////////////
2022 * Alias to YUI Get Utility, to allow implementers to use a custom class.
2024 * @property getUtility
2026 * @default YAHOO.util.Get
2028 getUtility : util.Get,
2031 * Defines request/response management in the following manner:
2033 * <!--<dt>queueRequests</dt>
2034 * <dd>If a request is already in progress, wait until response is returned before sending the next request.</dd>
2035 * <dt>cancelStaleRequests</dt>
2036 * <dd>If a request is already in progress, cancel it before sending the next request.</dd>-->
2037 * <dt>ignoreStaleResponses</dt>
2038 * <dd>Send all requests, but handle only the response for the most recently sent request.</dd>
2040 * <dd>Send all requests and handle all responses.</dd>
2043 * @property asyncMode
2045 * @default "allowAll"
2047 asyncMode : "allowAll",
2050 * Callback string parameter name sent to the remote script. By default,
2051 * requests are sent to
2052 * <URI>?<scriptCallbackParam>=callback
2054 * @property scriptCallbackParam
2056 * @default "callback"
2058 scriptCallbackParam : "callback",
2061 /////////////////////////////////////////////////////////////////////////////
2063 // ScriptNodeDataSource public methods
2065 /////////////////////////////////////////////////////////////////////////////
2068 * Creates a request callback that gets appended to the script URI. Implementers
2069 * can customize this string to match their server's query syntax.
2071 * @method generateRequestCallback
2072 * @return {String} String fragment that gets appended to script URI that
2073 * specifies the callback function
2075 generateRequestCallback : function(id) {
2076 return "&" + this.scriptCallbackParam + "=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]" ;
2080 * Overridable method gives implementers access to modify the URI before the dynamic
2081 * script node gets inserted. Implementers should take care not to return an
2084 * @method doBeforeGetScriptNode
2085 * @param {String} URI to the script
2086 * @return {String} URI to the script
2088 doBeforeGetScriptNode : function(sUri) {
2093 * Overriding method passes query to Get Utility. The returned
2094 * response is then forwarded to the handleResponse function.
2096 * @method makeConnection
2097 * @param oRequest {Object} Request object.
2098 * @param oCallback {Object} Callback object literal.
2099 * @param oCaller {Object} (deprecated) Use oCallback.scope.
2100 * @return {Number} Transaction ID.
2102 makeConnection : function(oRequest, oCallback, oCaller) {
2103 var tId = DS._nTransactionId++;
2104 this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
2106 // If there are no global pending requests, it is safe to purge global callback stack and global counter
2107 if(util.ScriptNodeDataSource._nPending === 0) {
2108 util.ScriptNodeDataSource.callbacks = [];
2109 util.ScriptNodeDataSource._nId = 0;
2112 // ID for this request
2113 var id = util.ScriptNodeDataSource._nId;
2114 util.ScriptNodeDataSource._nId++;
2116 // Dynamically add handler function with a closure to the callback stack
2118 util.ScriptNodeDataSource.callbacks[id] = function(oRawResponse) {
2119 if((oSelf.asyncMode !== "ignoreStaleResponses")||
2120 (id === util.ScriptNodeDataSource.callbacks.length-1)) { // Must ignore stale responses
2122 // Try to sniff data type if it has not been defined
2123 if(oSelf.responseType === DS.TYPE_UNKNOWN) {
2124 if(YAHOO.lang.isArray(oRawResponse)) { // array
2125 oSelf.responseType = DS.TYPE_JSARRAY;
2128 else if(oRawResponse.nodeType && oRawResponse.nodeType == 9) {
2129 oSelf.responseType = DS.TYPE_XML;
2131 else if(oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
2132 oSelf.responseType = DS.TYPE_HTMLTABLE;
2134 else if(YAHOO.lang.isObject(oRawResponse)) { // json
2135 oSelf.responseType = DS.TYPE_JSON;
2137 else if(YAHOO.lang.isString(oRawResponse)) { // text
2138 oSelf.responseType = DS.TYPE_TEXT;
2142 oSelf.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
2147 delete util.ScriptNodeDataSource.callbacks[id];
2150 // We are now creating a request
2151 util.ScriptNodeDataSource._nPending++;
2152 var sUri = this.liveData + oRequest + this.generateRequestCallback(id);
2153 sUri = this.doBeforeGetScriptNode(sUri);
2154 this.getUtility.script(sUri,
2156 onsuccess: util.ScriptNodeDataSource._bumpPendingDown,
2157 onfail: util.ScriptNodeDataSource._bumpPendingDown});
2164 // Copy static members to ScriptNodeDataSource class
2165 lang.augmentObject(util.ScriptNodeDataSource, DS);
2167 // Copy static members to ScriptNodeDataSource class
2168 lang.augmentObject(util.ScriptNodeDataSource, {
2170 /////////////////////////////////////////////////////////////////////////////
2172 // ScriptNodeDataSource private static properties
2174 /////////////////////////////////////////////////////////////////////////////
2177 * Unique ID to track requests.
2187 * Counter for pending requests. When this is 0, it is safe to purge callbacks
2190 * @property _nPending
2198 * Global array of callback functions, one for each request sent.
2200 * @property callbacks
2221 /****************************************************************************/
2222 /****************************************************************************/
2223 /****************************************************************************/
2226 * XHRDataSource class for accessing remote data via the YUI Connection Manager
2229 * @namespace YAHOO.util
2230 * @class YAHOO.util.XHRDataSource
2231 * @extends YAHOO.util.DataSourceBase
2233 * @param oLiveData {HTMLElement} Pointer to live data.
2234 * @param oConfigs {object} (optional) Object literal of configuration values.
2236 util.XHRDataSource = function(oLiveData, oConfigs) {
2237 this.dataType = DS.TYPE_XHR;
2238 this.connMgr = this.connMgr || util.Connect;
2239 oLiveData = oLiveData || "";
2241 util.XHRDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
2244 // XHRDataSource extends DataSourceBase
2245 lang.extend(util.XHRDataSource, DS, {
2247 /////////////////////////////////////////////////////////////////////////////
2249 // XHRDataSource public properties
2251 /////////////////////////////////////////////////////////////////////////////
2254 * Alias to YUI Connection Manager, to allow implementers to use a custom class.
2258 * @default YAHOO.util.Connect
2263 * Defines request/response management in the following manner:
2265 * <dt>queueRequests</dt>
2266 * <dd>If a request is already in progress, wait until response is returned
2267 * before sending the next request.</dd>
2269 * <dt>cancelStaleRequests</dt>
2270 * <dd>If a request is already in progress, cancel it before sending the next
2273 * <dt>ignoreStaleResponses</dt>
2274 * <dd>Send all requests, but handle only the response for the most recently
2275 * sent request.</dd>
2278 * <dd>Send all requests and handle all responses.</dd>
2282 * @property connXhrMode
2284 * @default "allowAll"
2286 connXhrMode: "allowAll",
2289 * True if data is to be sent via POST. By default, data will be sent via GET.
2291 * @property connMethodPost
2295 connMethodPost: false,
2298 * The connection timeout defines how many milliseconds the XHR connection will
2299 * wait for a server response. Any non-zero value will enable the Connection Manager's
2300 * Auto-Abort feature.
2302 * @property connTimeout
2308 /////////////////////////////////////////////////////////////////////////////
2310 // XHRDataSource public methods
2312 /////////////////////////////////////////////////////////////////////////////
2315 * Overriding method passes query to Connection Manager. The returned
2316 * response is then forwarded to the handleResponse function.
2318 * @method makeConnection
2319 * @param oRequest {Object} Request object.
2320 * @param oCallback {Object} Callback object literal.
2321 * @param oCaller {Object} (deprecated) Use oCallback.scope.
2322 * @return {Number} Transaction ID.
2324 makeConnection : function(oRequest, oCallback, oCaller) {
2326 var oRawResponse = null;
2327 var tId = DS._nTransactionId++;
2328 this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
2330 // Set up the callback object and
2331 // pass the request in as a URL query and
2332 // forward the response to the handler
2334 var oConnMgr = this.connMgr;
2335 var oQueue = this._oQueue;
2338 * Define Connection Manager success handler
2340 * @method _xhrSuccess
2341 * @param oResponse {Object} HTTPXMLRequest object
2344 var _xhrSuccess = function(oResponse) {
2345 // If response ID does not match last made request ID,
2346 // silently fail and wait for the next response
2347 if(oResponse && (this.connXhrMode == "ignoreStaleResponses") &&
2348 (oResponse.tId != oQueue.conn.tId)) {
2351 // Error if no response
2352 else if(!oResponse) {
2353 this.fireEvent("dataErrorEvent", {request:oRequest, response:null,
2354 callback:oCallback, caller:oCaller,
2355 message:DS.ERROR_DATANULL});
2357 // Send error response back to the caller with the error flag on
2358 DS.issueCallback(oCallback,[oRequest, {error:true}], true, oCaller);
2362 // Forward to handler
2364 // Try to sniff data type if it has not been defined
2365 if(this.responseType === DS.TYPE_UNKNOWN) {
2366 var ctype = (oResponse.getResponseHeader) ? oResponse.getResponseHeader["Content-Type"] : null;
2369 if(ctype.indexOf("text/xml") > -1) {
2370 this.responseType = DS.TYPE_XML;
2372 else if(ctype.indexOf("application/json") > -1) { // json
2373 this.responseType = DS.TYPE_JSON;
2375 else if(ctype.indexOf("text/plain") > -1) { // text
2376 this.responseType = DS.TYPE_TEXT;
2380 this.handleResponse(oRequest, oResponse, oCallback, oCaller, tId);
2385 * Define Connection Manager failure handler
2387 * @method _xhrFailure
2388 * @param oResponse {Object} HTTPXMLRequest object
2391 var _xhrFailure = function(oResponse) {
2392 this.fireEvent("dataErrorEvent", {request:oRequest, response: oResponse,
2393 callback:oCallback, caller:oCaller,
2394 message:DS.ERROR_DATAINVALID});
2396 // Backward compatibility
2397 if(lang.isString(this.liveData) && lang.isString(oRequest) &&
2398 (this.liveData.lastIndexOf("?") !== this.liveData.length-1) &&
2399 (oRequest.indexOf("?") !== 0)){
2402 // Send failure response back to the caller with the error flag on
2403 oResponse = oResponse || {};
2404 oResponse.error = true;
2405 DS.issueCallback(oCallback,[oRequest,oResponse],true, oCaller);
2411 * Define Connection Manager callback object
2413 * @property _xhrCallback
2414 * @param oResponse {Object} HTTPXMLRequest object
2417 var _xhrCallback = {
2418 success:_xhrSuccess,
2419 failure:_xhrFailure,
2423 // Apply Connection Manager timeout
2424 if(lang.isNumber(this.connTimeout)) {
2425 _xhrCallback.timeout = this.connTimeout;
2428 // Cancel stale requests
2429 if(this.connXhrMode == "cancelStaleRequests") {
2430 // Look in queue for stale requests
2432 if(oConnMgr.abort) {
2433 oConnMgr.abort(oQueue.conn);
2441 // Get ready to send the request URL
2442 if(oConnMgr && oConnMgr.asyncRequest) {
2443 var sLiveData = this.liveData;
2444 var isPost = this.connMethodPost;
2445 var sMethod = (isPost) ? "POST" : "GET";
2447 var sUri = (isPost || !lang.isValue(oRequest)) ? sLiveData : sLiveData+oRequest;
2448 var sRequest = (isPost) ? oRequest : null;
2450 // Send the request right away
2451 if(this.connXhrMode != "queueRequests") {
2452 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest);
2454 // Queue up then send the request
2456 // Found a request already in progress
2458 var allRequests = oQueue.requests;
2459 // Add request to queue
2460 allRequests.push({request:oRequest, callback:_xhrCallback});
2462 // Interval needs to be started
2463 if(!oQueue.interval) {
2464 oQueue.interval = setInterval(function() {
2465 // Connection is in progress
2466 if(oConnMgr.isCallInProgress(oQueue.conn)) {
2470 // Send next request
2471 if(allRequests.length > 0) {
2473 sUri = (isPost || !lang.isValue(allRequests[0].request)) ? sLiveData : sLiveData+allRequests[0].request;
2474 sRequest = (isPost) ? allRequests[0].request : null;
2475 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, allRequests[0].callback, sRequest);
2477 // Remove request from queue
2478 allRequests.shift();
2482 clearInterval(oQueue.interval);
2483 oQueue.interval = null;
2489 // Nothing is in progress
2491 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest);
2496 // Send null response back to the caller with the error flag on
2497 DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller);
2505 // Copy static members to XHRDataSource class
2506 lang.augmentObject(util.XHRDataSource, DS);
2520 /****************************************************************************/
2521 /****************************************************************************/
2522 /****************************************************************************/
2525 * Factory class for creating a BaseDataSource subclass instance. The sublcass is
2526 * determined by oLiveData's type, unless the dataType config is explicitly passed in.
2528 * @namespace YAHOO.util
2529 * @class YAHOO.util.DataSource
2531 * @param oLiveData {HTMLElement} Pointer to live data.
2532 * @param oConfigs {object} (optional) Object literal of configuration values.
2534 util.DataSource = function(oLiveData, oConfigs) {
2535 oConfigs = oConfigs || {};
2537 // Point to one of the subclasses, first by dataType if given, then by sniffing oLiveData type.
2538 var dataType = oConfigs.dataType;
2540 if(dataType == DS.TYPE_LOCAL) {
2541 return new util.LocalDataSource(oLiveData, oConfigs);
2543 else if(dataType == DS.TYPE_XHR) {
2544 return new util.XHRDataSource(oLiveData, oConfigs);
2546 else if(dataType == DS.TYPE_SCRIPTNODE) {
2547 return new util.ScriptNodeDataSource(oLiveData, oConfigs);
2549 else if(dataType == DS.TYPE_JSFUNCTION) {
2550 return new util.FunctionDataSource(oLiveData, oConfigs);
2554 if(YAHOO.lang.isString(oLiveData)) { // strings default to xhr
2555 return new util.XHRDataSource(oLiveData, oConfigs);
2557 else if(YAHOO.lang.isFunction(oLiveData)) {
2558 return new util.FunctionDataSource(oLiveData, oConfigs);
2560 else { // ultimate default is local
2561 return new util.LocalDataSource(oLiveData, oConfigs);
2565 // Copy static members to DataSource class
2566 lang.augmentObject(util.DataSource, DS);
2570 /****************************************************************************/
2571 /****************************************************************************/
2572 /****************************************************************************/
2575 * The static Number class provides helper functions to deal with data of type
2578 * @namespace YAHOO.util
2583 YAHOO.util.Number = {
2586 * Takes a native JavaScript Number and formats to a string for display.
2589 * @param nData {Number} Number.
2590 * @param oConfig {Object} (Optional) Optional configuration values:
2593 * <dd>String used as a template for formatting positive numbers.
2594 * {placeholders} in the string are applied from the values in this
2595 * config object. {number} is used to indicate where the numeric portion
2596 * of the output goes. For example "{prefix}{number} per item"
2597 * might yield "$5.25 per item". The only required
2598 * {placeholder} is {number}.</dd>
2600 * <dt>negativeFormat</dt>
2601 * <dd>Like format, but applied to negative numbers. If set to null,
2602 * defaults from the configured format, prefixed with -. This is
2603 * separate from format to support formats like "($12,345.67)".
2605 * <dt>prefix {String} (deprecated, use format/negativeFormat)</dt>
2606 * <dd>String prepended before each number, like a currency designator "$"</dd>
2607 * <dt>decimalPlaces {Number}</dt>
2608 * <dd>Number of decimal places to round.</dd>
2610 * <dt>decimalSeparator {String}</dt>
2611 * <dd>Decimal separator</dd>
2613 * <dt>thousandsSeparator {String}</dt>
2614 * <dd>Thousands separator</dd>
2616 * <dt>suffix {String} (deprecated, use format/negativeFormat)</dt>
2617 * <dd>String appended after each number, like " items" (note the space)</dd>
2619 * @return {String} Formatted number for display. Note, the following values
2620 * return as "": null, undefined, NaN, "".
2622 format : function(n, cfg) {
2623 if (n === '' || n === null || !isFinite(n)) {
2628 cfg = YAHOO.lang.merge(YAHOO.util.Number.format.defaults, (cfg || {}));
2632 places = cfg.decimalPlaces || 0,
2633 sep = cfg.thousandsSeparator,
2634 negFmt = cfg.negativeFormat || ('-' + cfg.format),
2635 s, bits, i, precision;
2637 if (negFmt.indexOf('#') > -1) {
2638 // for backward compatibility of negativeFormat supporting '-#'
2639 negFmt = negFmt.replace(/#/, cfg.format);
2643 // Get rid of the decimal info
2644 s = absN - (absN % 1) + '';
2645 i = s.length + places;
2647 // avoid 123 vs decimalPlaces -4 (should return "0")
2649 // leverage toFixed by making 123 => 0.123 for the rounding
2650 // operation, then add the appropriate number of zeros back on
2651 s = Number('.' + s).toFixed(i).slice(2) +
2652 new Array(s.length - i + 1).join('0');
2657 // Avoid toFixed on floats:
2660 var unfloatedN = absN+'';
2661 if(places > 0 || unfloatedN.indexOf('.') > 0) {
2662 var power = Math.pow(10, places);
2663 s = Math.round(absN * power) / power + '';
2664 var dot = s.indexOf('.'),
2670 zeroes = (Math.pow(10, padding) + '').substring(1);
2672 s = s + '.' + zeroes;
2676 padding = places - (s.length - dot - 1);
2677 zeroes = (Math.pow(10, padding) + '').substring(1);
2682 s = absN.toFixed(places)+'';
2686 bits = s.split(/\D/);
2689 i = bits[0].length % 3 || 3;
2691 bits[0] = bits[0].slice(0,i) +
2692 bits[0].slice(i).replace(/(\d{3})/g, sep + '$1');
2696 return YAHOO.util.Number.format._applyFormat(
2697 (n < 0 ? negFmt : cfg.format),
2698 bits.join(cfg.decimalSeparator),
2704 * <p>Default values for Number.format behavior. Override properties of this
2705 * object if you want every call to Number.format in your system to use
2706 * specific presets.</p>
2708 * <p>Available keys include:</p>
2711 * <li>negativeFormat</li>
2712 * <li>decimalSeparator</li>
2713 * <li>decimalPlaces</li>
2714 * <li>thousandsSeparator</li>
2715 * <li>prefix/suffix or any other token you want to use in the format templates</li>
2718 * @property Number.format.defaults
2722 YAHOO.util.Number.format.defaults = {
2723 format : '{prefix}{number}{suffix}',
2724 negativeFormat : null, // defaults to -(format)
2725 decimalSeparator : '.',
2726 decimalPlaces : null,
2727 thousandsSeparator : ''
2731 * Apply any special formatting to the "d,ddd.dd" string. Takes either the
2732 * cfg.format or cfg.negativeFormat template and replaces any {placeholders}
2733 * with either the number or a value from a so-named property of the config
2736 * @method Number.format._applyFormat
2738 * @param tmpl {String} the cfg.format or cfg.numberFormat template string
2739 * @param num {String} the number with separators and decimalPlaces applied
2740 * @param data {Object} the config object, used here to populate {placeholder}s
2741 * @return {String} the number with any decorators added
2743 YAHOO.util.Number.format._applyFormat = function (tmpl, num, data) {
2744 return tmpl.replace(/\{(\w+)\}/g, function (_, token) {
2745 return token === 'number' ? num :
2746 token in data ? data[token] : '';
2751 /****************************************************************************/
2752 /****************************************************************************/
2753 /****************************************************************************/
2757 var xPad=function (x, pad, r)
2759 if(typeof r === 'undefined')
2763 for( ; parseInt(x, 10)<r && r>1; r/=10) {
2764 x = pad.toString() + x;
2766 return x.toString();
2771 * The static Date class provides helper functions to deal with data of type Date.
2773 * @namespace YAHOO.util
2780 a: function (d, l) { return l.a[d.getDay()]; },
2781 A: function (d, l) { return l.A[d.getDay()]; },
2782 b: function (d, l) { return l.b[d.getMonth()]; },
2783 B: function (d, l) { return l.B[d.getMonth()]; },
2784 C: function (d) { return xPad(parseInt(d.getFullYear()/100, 10), 0); },
2785 d: ['getDate', '0'],
2786 e: ['getDate', ' '],
2787 g: function (d) { return xPad(parseInt(Dt.formats.G(d)%100, 10), 0); },
2789 var y = d.getFullYear();
2790 var V = parseInt(Dt.formats.V(d), 10);
2791 var W = parseInt(Dt.formats.W(d), 10);
2795 } else if(W===0 && V>=52) {
2801 H: ['getHours', '0'],
2802 I: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, 0); },
2804 var gmd_1 = new Date('' + d.getFullYear() + '/1/1 GMT');
2805 var gmdate = new Date('' + d.getFullYear() + '/' + (d.getMonth()+1) + '/' + d.getDate() + ' GMT');
2806 var ms = gmdate - gmd_1;
2807 var doy = parseInt(ms/60000/60/24, 10)+1;
2808 return xPad(doy, 0, 100);
2810 k: ['getHours', ' '],
2811 l: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, ' '); },
2812 m: function (d) { return xPad(d.getMonth()+1, 0); },
2813 M: ['getMinutes', '0'],
2814 p: function (d, l) { return l.p[d.getHours() >= 12 ? 1 : 0 ]; },
2815 P: function (d, l) { return l.P[d.getHours() >= 12 ? 1 : 0 ]; },
2816 s: function (d, l) { return parseInt(d.getTime()/1000, 10); },
2817 S: ['getSeconds', '0'],
2818 u: function (d) { var dow = d.getDay(); return dow===0?7:dow; },
2820 var doy = parseInt(Dt.formats.j(d), 10);
2821 var rdow = 6-d.getDay();
2822 var woy = parseInt((doy+rdow)/7, 10);
2823 return xPad(woy, 0);
2826 var woy = parseInt(Dt.formats.W(d), 10);
2827 var dow1_1 = (new Date('' + d.getFullYear() + '/1/1')).getDay();
2828 // First week is 01 and not 00 as in the case of %U and %W,
2829 // so we add 1 to the final result except if day 1 of the year
2830 // is a Monday (then %W returns 01).
2831 // We also need to subtract 1 if the day 1 of the year is
2832 // Friday-Sunday, so the resulting equation becomes:
2833 var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1);
2834 if(idow === 53 && (new Date('' + d.getFullYear() + '/12/31')).getDay() < 4)
2840 idow = Dt.formats.V(new Date('' + (d.getFullYear()-1) + '/12/31'));
2843 return xPad(idow, 0);
2847 var doy = parseInt(Dt.formats.j(d), 10);
2848 var rdow = 7-Dt.formats.u(d);
2849 var woy = parseInt((doy+rdow)/7, 10);
2850 return xPad(woy, 0, 10);
2852 y: function (d) { return xPad(d.getFullYear()%100, 0); },
2855 var o = d.getTimezoneOffset();
2856 var H = xPad(parseInt(Math.abs(o/60), 10), 0);
2857 var M = xPad(Math.abs(o%60), 0);
2858 return (o>0?'-':'+') + H + M;
2861 var tz = d.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/, '$2').replace(/[a-z ]/g, '');
2863 tz = Dt.formats.z(d);
2867 '%': function (d) { return '%'; }
2882 //'+': '%a %b %e %T %Z %Y'
2886 * Takes a native JavaScript Date and formats to string for display to user.
2889 * @param oDate {Date} Date.
2890 * @param oConfig {Object} (Optional) Object literal of configuration values:
2892 * <dt>format <String></dt>
2895 * Any strftime string is supported, such as "%I:%M:%S %p". strftime has several format specifiers defined by the Open group at
2896 * <a href="http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html">http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html</a>
2899 * PHP added a few of its own, defined at <a href="http://www.php.net/strftime">http://www.php.net/strftime</a>
2902 * This javascript implementation supports all the PHP specifiers and a few more. The full list is below:
2905 * <dt>%a</dt> <dd>abbreviated weekday name according to the current locale</dd>
2906 * <dt>%A</dt> <dd>full weekday name according to the current locale</dd>
2907 * <dt>%b</dt> <dd>abbreviated month name according to the current locale</dd>
2908 * <dt>%B</dt> <dd>full month name according to the current locale</dd>
2909 * <dt>%c</dt> <dd>preferred date and time representation for the current locale</dd>
2910 * <dt>%C</dt> <dd>century number (the year divided by 100 and truncated to an integer, range 00 to 99)</dd>
2911 * <dt>%d</dt> <dd>day of the month as a decimal number (range 01 to 31)</dd>
2912 * <dt>%D</dt> <dd>same as %m/%d/%y</dd>
2913 * <dt>%e</dt> <dd>day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')</dd>
2914 * <dt>%F</dt> <dd>same as %Y-%m-%d (ISO 8601 date format)</dd>
2915 * <dt>%g</dt> <dd>like %G, but without the century</dd>
2916 * <dt>%G</dt> <dd>The 4-digit year corresponding to the ISO week number</dd>
2917 * <dt>%h</dt> <dd>same as %b</dd>
2918 * <dt>%H</dt> <dd>hour as a decimal number using a 24-hour clock (range 00 to 23)</dd>
2919 * <dt>%I</dt> <dd>hour as a decimal number using a 12-hour clock (range 01 to 12)</dd>
2920 * <dt>%j</dt> <dd>day of the year as a decimal number (range 001 to 366)</dd>
2921 * <dt>%k</dt> <dd>hour as a decimal number using a 24-hour clock (range 0 to 23); single digits are preceded by a blank. (See also %H.)</dd>
2922 * <dt>%l</dt> <dd>hour as a decimal number using a 12-hour clock (range 1 to 12); single digits are preceded by a blank. (See also %I.) </dd>
2923 * <dt>%m</dt> <dd>month as a decimal number (range 01 to 12)</dd>
2924 * <dt>%M</dt> <dd>minute as a decimal number</dd>
2925 * <dt>%n</dt> <dd>newline character</dd>
2926 * <dt>%p</dt> <dd>either `AM' or `PM' according to the given time value, or the corresponding strings for the current locale</dd>
2927 * <dt>%P</dt> <dd>like %p, but lower case</dd>
2928 * <dt>%r</dt> <dd>time in a.m. and p.m. notation equal to %I:%M:%S %p</dd>
2929 * <dt>%R</dt> <dd>time in 24 hour notation equal to %H:%M</dd>
2930 * <dt>%s</dt> <dd>number of seconds since the Epoch, ie, since 1970-01-01 00:00:00 UTC</dd>
2931 * <dt>%S</dt> <dd>second as a decimal number</dd>
2932 * <dt>%t</dt> <dd>tab character</dd>
2933 * <dt>%T</dt> <dd>current time, equal to %H:%M:%S</dd>
2934 * <dt>%u</dt> <dd>weekday as a decimal number [1,7], with 1 representing Monday</dd>
2935 * <dt>%U</dt> <dd>week number of the current year as a decimal number, starting with the
2936 * first Sunday as the first day of the first week</dd>
2937 * <dt>%V</dt> <dd>The ISO 8601:1988 week number of the current year as a decimal number,
2938 * range 01 to 53, where week 1 is the first week that has at least 4 days
2939 * in the current year, and with Monday as the first day of the week.</dd>
2940 * <dt>%w</dt> <dd>day of the week as a decimal, Sunday being 0</dd>
2941 * <dt>%W</dt> <dd>week number of the current year as a decimal number, starting with the
2942 * first Monday as the first day of the first week</dd>
2943 * <dt>%x</dt> <dd>preferred date representation for the current locale without the time</dd>
2944 * <dt>%X</dt> <dd>preferred time representation for the current locale without the date</dd>
2945 * <dt>%y</dt> <dd>year as a decimal number without a century (range 00 to 99)</dd>
2946 * <dt>%Y</dt> <dd>year as a decimal number including the century</dd>
2947 * <dt>%z</dt> <dd>numerical time zone representation</dd>
2948 * <dt>%Z</dt> <dd>time zone name or abbreviation</dd>
2949 * <dt>%%</dt> <dd>a literal `%' character</dd>
2953 * @param sLocale {String} (Optional) The locale to use when displaying days of week,
2954 * months of the year, and other locale specific strings. The following locales are
2960 * <dd>US English</dd>
2962 * <dd>British English</dd>
2964 * <dd>Australian English (identical to British English)</dd>
2966 * More locales may be added by subclassing of YAHOO.util.DateLocale.
2967 * See YAHOO.util.DateLocale for more information.
2968 * @return {HTML} Formatted date for display. Non-date values are passed
2970 * @sa YAHOO.util.DateLocale
2972 format : function (oDate, oConfig, sLocale) {
2973 oConfig = oConfig || {};
2975 if(!(oDate instanceof Date)) {
2976 return YAHOO.lang.isValue(oDate) ? oDate : "";
2979 var format = oConfig.format || "%m/%d/%Y";
2981 // Be backwards compatible, support strings that are
2982 // exactly equal to YYYY/MM/DD, DD/MM/YYYY and MM/DD/YYYY
2983 if(format === 'YYYY/MM/DD') {
2984 format = '%Y/%m/%d';
2985 } else if(format === 'DD/MM/YYYY') {
2986 format = '%d/%m/%Y';
2987 } else if(format === 'MM/DD/YYYY') {
2988 format = '%m/%d/%Y';
2990 // end backwards compatibility block
2992 sLocale = sLocale || "en";
2994 // Make sure we have a definition for the requested locale, or default to en.
2995 if(!(sLocale in YAHOO.util.DateLocale)) {
2996 if(sLocale.replace(/-[a-zA-Z]+$/, '') in YAHOO.util.DateLocale) {
2997 sLocale = sLocale.replace(/-[a-zA-Z]+$/, '');
3003 var aLocale = YAHOO.util.DateLocale[sLocale];
3005 var replace_aggs = function (m0, m1) {
3006 var f = Dt.aggregates[m1];
3007 return (f === 'locale' ? aLocale[m1] : f);
3010 var replace_formats = function (m0, m1) {
3011 var f = Dt.formats[m1];
3012 if(typeof f === 'string') { // string => built in date function
3014 } else if(typeof f === 'function') { // function => our own function
3015 return f.call(oDate, oDate, aLocale);
3016 } else if(typeof f === 'object' && typeof f[0] === 'string') { // built in function with padding
3017 return xPad(oDate[f[0]](), f[1]);
3023 // First replace aggregates (run in a loop because an agg may be made up of other aggs)
3024 while(format.match(/%[cDFhnrRtTxX]/)) {
3025 format = format.replace(/%([cDFhnrRtTxX])/g, replace_aggs);
3028 // Now replace formats (do not run in a loop otherwise %%a will be replace with the value of %a)
3029 var str = format.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g, replace_formats);
3031 replace_aggs = replace_formats = undefined;
3037 YAHOO.namespace("YAHOO.util");
3038 YAHOO.util.Date = Dt;
3041 * The DateLocale class is a container and base class for all
3042 * localised date strings used by YAHOO.util.Date. It is used
3043 * internally, but may be extended to provide new date localisations.
3045 * To create your own DateLocale, follow these steps:
3047 * <li>Find an existing locale that matches closely with your needs</li>
3048 * <li>Use this as your base class. Use YAHOO.util.DateLocale if nothing
3050 * <li>Create your own class as an extension of the base class using
3051 * YAHOO.lang.merge, and add your own localisations where needed.</li>
3053 * See the YAHOO.util.DateLocale['en-US'] and YAHOO.util.DateLocale['en-GB']
3054 * classes which extend YAHOO.util.DateLocale['en'].
3056 * For example, to implement locales for French french and Canadian french,
3057 * we would do the following:
3059 * <li>For French french, we have no existing similar locale, so use
3060 * YAHOO.util.DateLocale as the base, and extend it:
3062 * YAHOO.util.DateLocale['fr'] = YAHOO.lang.merge(YAHOO.util.DateLocale, {
3063 * a: ['dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam'],
3064 * A: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
3065 * b: ['jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jui', 'aoû', 'sep', 'oct', 'nov', 'déc'],
3066 * B: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
3067 * c: '%a %d %b %Y %T %Z',
3075 * <li>For Canadian french, we start with French french and change the meaning of \%x:
3077 * YAHOO.util.DateLocale['fr-CA'] = YAHOO.lang.merge(YAHOO.util.DateLocale['fr'], {
3084 * With that, you can use your new locales:
3086 * var d = new Date("2008/04/22");
3087 * YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr");
3091 * mardi, 22 avril == 22.04.2008
3095 * YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr-CA");
3099 * mardi, 22 avril == 2008-04-22
3101 * @namespace YAHOO.util
3105 YAHOO.util.DateLocale = {
3106 a: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
3107 A: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
3108 b: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
3109 B: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
3110 c: '%a %d %b %Y %T %Z',
3118 YAHOO.util.DateLocale['en'] = YAHOO.lang.merge(YAHOO.util.DateLocale, {});
3120 YAHOO.util.DateLocale['en-US'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], {
3121 c: '%a %d %b %Y %I:%M:%S %p %Z',
3126 YAHOO.util.DateLocale['en-GB'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], {
3129 YAHOO.util.DateLocale['en-AU'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en']);
3133 YAHOO.register("datasource", YAHOO.util.DataSource, {version: "2.9.0", build: "2800"});