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.callback {Object} The callback object.
142 * @param oArgs.caller {Object} (deprecated) Use callback.scope.
143 * @param oArgs.message {String} The error message.
145 this.createEvent("dataErrorEvent");
148 * Fired when the local cache is flushed.
150 * @event cacheFlushEvent
152 this.createEvent("cacheFlushEvent");
154 var DS = util.DataSourceBase;
155 this._sName = "DataSource instance" + DS._nIndex;
157 YAHOO.log("DataSource initialized", "info", this.toString());
160 var DS = util.DataSourceBase;
162 lang.augmentObject(DS, {
164 /////////////////////////////////////////////////////////////////////////////
166 // DataSourceBase public constants
168 /////////////////////////////////////////////////////////////////////////////
173 * @property TYPE_UNKNOWN
181 * Type is a JavaScript Array.
183 * @property TYPE_JSARRAY
191 * Type is a JavaScript Function.
193 * @property TYPE_JSFUNCTION
201 * Type is hosted on a server via an XHR connection.
213 * @property TYPE_JSON
231 * Type is plain text.
233 * @property TYPE_TEXT
241 * Type is an HTML TABLE element. Data is parsed out of TR elements from all TBODY elements.
243 * @property TYPE_HTMLTABLE
251 * Type is hosted on a server via a dynamic script node.
253 * @property TYPE_SCRIPTNODE
263 * @property TYPE_LOCAL
271 * Error message for invalid dataresponses.
273 * @property ERROR_DATAINVALID
276 * @default "Invalid data"
278 ERROR_DATAINVALID : "Invalid data",
281 * Error message for null data responses.
283 * @property ERROR_DATANULL
286 * @default "Null data"
288 ERROR_DATANULL : "Null data",
290 /////////////////////////////////////////////////////////////////////////////
292 // DataSourceBase private static properties
294 /////////////////////////////////////////////////////////////////////////////
297 * Internal class variable to index multiple DataSource instances.
299 * @property DataSourceBase._nIndex
307 * Internal class variable to assign unique transaction IDs.
309 * @property DataSourceBase._nTransactionId
316 /////////////////////////////////////////////////////////////////////////////
318 // DataSourceBase public static methods
320 /////////////////////////////////////////////////////////////////////////////
323 * Executes a configured callback. For object literal callbacks, the third
324 * param determines whether to execute the success handler or failure handler.
326 * @method issueCallback
327 * @param callback {Function|Object} the callback to execute
328 * @param params {Array} params to be passed to the callback method
329 * @param error {Boolean} whether an error occurred
330 * @param scope {Object} the scope from which to execute the callback
331 * (deprecated - use an object literal callback)
334 issueCallback : function (callback,params,error,scope) {
335 if (lang.isFunction(callback)) {
336 callback.apply(scope, params);
337 } else if (lang.isObject(callback)) {
338 scope = callback.scope || scope || window;
339 var callbackFunc = callback.success;
341 callbackFunc = callback.failure;
344 callbackFunc.apply(scope, params.concat([callback.argument]));
350 * Converts data to type String.
352 * @method DataSourceBase.parseString
353 * @param oData {String | Number | Boolean | Date | Array | Object} Data to parse.
354 * The special values null and undefined will return null.
355 * @return {String} A string, or null.
358 parseString : function(oData) {
359 // Special case null and undefined
360 if(!lang.isValue(oData)) {
365 var string = oData + "";
368 if(lang.isString(string)) {
372 YAHOO.log("Could not convert data " + lang.dump(oData) + " to type String", "warn", this.toString());
378 * Converts data to type Number.
380 * @method DataSourceBase.parseNumber
381 * @param oData {String | Number | Boolean} Data to convert. Note, the following
382 * values return as null: null, undefined, NaN, "".
383 * @return {Number} A number, or null.
386 parseNumber : function(oData) {
387 if(!lang.isValue(oData) || (oData === "")) {
392 var number = oData * 1;
395 if(lang.isNumber(number)) {
399 YAHOO.log("Could not convert data " + lang.dump(oData) + " to type Number", "warn", this.toString());
403 // Backward compatibility
404 convertNumber : function(oData) {
405 YAHOO.log("The method YAHOO.util.DataSourceBase.convertNumber() has been" +
406 " deprecated in favor of YAHOO.util.DataSourceBase.parseNumber()", "warn",
408 return DS.parseNumber(oData);
412 * Converts data to type Date.
414 * @method DataSourceBase.parseDate
415 * @param oData {Date | String | Number} Data to convert.
416 * @return {Date} A Date instance.
419 parseDate : function(oData) {
423 if(!(oData instanceof Date)) {
424 date = new Date(oData);
431 if(date instanceof Date) {
435 YAHOO.log("Could not convert data " + lang.dump(oData) + " to type Date", "warn", this.toString());
439 // Backward compatibility
440 convertDate : function(oData) {
441 YAHOO.log("The method YAHOO.util.DataSourceBase.convertDate() has been" +
442 " deprecated in favor of YAHOO.util.DataSourceBase.parseDate()", "warn",
444 return DS.parseDate(oData);
449 // Done in separate step so referenced functions are defined.
451 * Data parsing functions.
452 * @property DataSource.Parser
457 string : DS.parseString,
458 number : DS.parseNumber,
462 // Prototype properties and methods
465 /////////////////////////////////////////////////////////////////////////////
467 // DataSourceBase private properties
469 /////////////////////////////////////////////////////////////////////////////
472 * Name of DataSource instance.
481 * Local cache of data result object literals indexed chronologically.
490 * Local queue of request connections, enabled if queue needs to be managed.
499 * Array of polling interval IDs that have been enabled, needed to clear all intervals.
501 * @property _aIntervals
507 /////////////////////////////////////////////////////////////////////////////
509 // DataSourceBase public properties
511 /////////////////////////////////////////////////////////////////////////////
514 * Max size of the local cache. Set to 0 to turn off caching. Caching is
515 * useful to reduce the number of server connections. Recommended only for data
516 * sources that return comprehensive results for queries or when stale data is
519 * @property maxCacheEntries
526 * Pointer to live database.
534 * Where the live data is held:
537 * <dt>TYPE_UNKNOWN</dt>
538 * <dt>TYPE_LOCAL</dt>
540 * <dt>TYPE_SCRIPTNODE</dt>
541 * <dt>TYPE_JSFUNCTION</dt>
546 * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN
549 dataType : DS.TYPE_UNKNOWN,
552 * Format of response:
555 * <dt>TYPE_UNKNOWN</dt>
556 * <dt>TYPE_JSARRAY</dt>
560 * <dt>TYPE_HTMLTABLE</dt>
563 * @property responseType
565 * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN
567 responseType : DS.TYPE_UNKNOWN,
570 * Response schema object literal takes a combination of the following properties:
573 * <dt>resultsList</dt> <dd>Pointer to array of tabular data</dd>
574 * <dt>resultNode</dt> <dd>Pointer to node name of row data (XML data only)</dd>
575 * <dt>recordDelim</dt> <dd>Record delimiter (text data only)</dd>
576 * <dt>fieldDelim</dt> <dd>Field delimiter (text data only)</dd>
577 * <dt>fields</dt> <dd>Array of field names (aka keys), or array of object literals
578 * such as: {key:"fieldname",parser:YAHOO.util.DataSourceBase.parseDate}</dd>
579 * <dt>metaFields</dt> <dd>Object literal of keys to include in the oParsedResponse.meta collection</dd>
580 * <dt>metaNode</dt> <dd>Name of the node under which to search for meta information in XML response data</dd>
583 * @property responseSchema
586 responseSchema : null,
589 * Additional arguments passed to the JSON parse routine. The JSON string
590 * is the assumed first argument (where applicable). This property is not
591 * set by default, but the parse methods will use it if present.
593 * @property parseJSONArgs
594 * @type {MIXED|Array} If an Array, contents are used as individual arguments.
595 * Otherwise, value is used as an additional argument.
597 // property intentionally undefined
599 /////////////////////////////////////////////////////////////////////////////
601 // DataSourceBase public methods
603 /////////////////////////////////////////////////////////////////////////////
606 * Public accessor to the unique name of the DataSource instance.
609 * @return {String} Unique name of the DataSource instance.
611 toString : function() {
616 * Overridable method passes request to cache and returns cached response if any,
617 * refreshing the hit in the cache as the newest item. Returns null if there is
620 * @method getCachedResponse
621 * @param oRequest {Object} Request object.
622 * @param oCallback {Object} Callback object.
623 * @param oCaller {Object} (deprecated) Use callback object.
624 * @return {Object} Cached response object or null.
626 getCachedResponse : function(oRequest, oCallback, oCaller) {
627 var aCache = this._aCache;
629 // If cache is enabled...
630 if(this.maxCacheEntries > 0) {
631 // Initialize local cache
634 YAHOO.log("Cache initialized", "info", this.toString());
636 // Look in local cache
638 var nCacheLength = aCache.length;
639 if(nCacheLength > 0) {
640 var oResponse = null;
641 this.fireEvent("cacheRequestEvent", {request:oRequest,callback:oCallback,caller:oCaller});
643 // Loop through each cached element
644 for(var i = nCacheLength-1; i >= 0; i--) {
645 var oCacheElem = aCache[i];
647 // Defer cache hit logic to a public overridable method
648 if(this.isCacheHit(oRequest,oCacheElem.request)) {
649 // The cache returned a hit!
650 // Grab the cached response
651 oResponse = oCacheElem.response;
652 this.fireEvent("cacheResponseEvent", {request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});
654 // Refresh the position of the cache hit
655 if(i < nCacheLength-1) {
656 // Remove element from its original location
659 this.addToCache(oRequest, oResponse);
660 YAHOO.log("Refreshed cache position of the response for \"" + oRequest + "\"", "info", this.toString());
664 oResponse.cached = true;
668 YAHOO.log("The cached response for \"" + lang.dump(oRequest) +
669 "\" is " + lang.dump(oResponse), "info", this.toString());
676 YAHOO.log("Cache destroyed", "info", this.toString());
682 * Default overridable method matches given request to given cached request.
683 * Returns true if is a hit, returns false otherwise. Implementers should
684 * override this method to customize the cache-matching algorithm.
687 * @param oRequest {Object} Request object.
688 * @param oCachedRequest {Object} Cached request object.
689 * @return {Boolean} True if given request matches cached request, false otherwise.
691 isCacheHit : function(oRequest, oCachedRequest) {
692 return (oRequest === oCachedRequest);
696 * Adds a new item to the cache. If cache is full, evicts the stalest item
697 * before adding the new item.
700 * @param oRequest {Object} Request object.
701 * @param oResponse {Object} Response object to cache.
703 addToCache : function(oRequest, oResponse) {
704 var aCache = this._aCache;
709 // If the cache is full, make room by removing stalest element (index=0)
710 while(aCache.length >= this.maxCacheEntries) {
714 // Add to cache in the newest position, at the end of the array
715 var oCacheElem = {request:oRequest,response:oResponse};
716 aCache[aCache.length] = oCacheElem;
717 this.fireEvent("responseCacheEvent", {request:oRequest,response:oResponse});
718 YAHOO.log("Cached the response for \"" + oRequest + "\"", "info", this.toString());
726 flushCache : function() {
729 this.fireEvent("cacheFlushEvent");
730 YAHOO.log("Flushed the cache", "info", this.toString());
735 * Sets up a polling mechanism to send requests at set intervals and forward
736 * responses to given callback.
738 * @method setInterval
739 * @param nMsec {Number} Length of interval in milliseconds.
740 * @param oRequest {Object} Request object.
741 * @param oCallback {Function} Handler function to receive the response.
742 * @param oCaller {Object} (deprecated) Use oCallback.scope.
743 * @return {Number} Interval ID.
745 setInterval : function(nMsec, oRequest, oCallback, oCaller) {
746 if(lang.isNumber(nMsec) && (nMsec >= 0)) {
747 YAHOO.log("Enabling polling to live data for \"" + oRequest + "\" at interval " + nMsec, "info", this.toString());
749 var nId = setInterval(function() {
750 oSelf.makeConnection(oRequest, oCallback, oCaller);
752 this._aIntervals.push(nId);
756 YAHOO.log("Could not enable polling to live data for \"" + oRequest + "\" at interval " + nMsec, "info", this.toString());
761 * Disables polling mechanism associated with the given interval ID.
763 * @method clearInterval
764 * @param nId {Number} Interval ID.
766 clearInterval : function(nId) {
767 // Remove from tracker if there
768 var tracker = this._aIntervals || [];
769 for(var i=tracker.length-1; i>-1; i--) {
770 if(tracker[i] === nId) {
778 * Disables all known polling intervals.
780 * @method clearAllIntervals
782 clearAllIntervals : function() {
783 var tracker = this._aIntervals || [];
784 for(var i=tracker.length-1; i>-1; i--) {
785 clearInterval(tracker[i]);
791 * First looks for cached response, then sends request to live data. The
792 * following arguments are passed to the callback function:
794 * <dt><code>oRequest</code></dt>
795 * <dd>The same value that was passed in as the first argument to sendRequest.</dd>
796 * <dt><code>oParsedResponse</code></dt>
797 * <dd>An object literal containing the following properties:
799 * <dt><code>tId</code></dt>
800 * <dd>Unique transaction ID number.</dd>
801 * <dt><code>results</code></dt>
802 * <dd>Schema-parsed data results.</dd>
803 * <dt><code>error</code></dt>
804 * <dd>True in cases of data error.</dd>
805 * <dt><code>cached</code></dt>
806 * <dd>True when response is returned from DataSource cache.</dd>
807 * <dt><code>meta</code></dt>
808 * <dd>Schema-parsed meta data.</dd>
810 * <dt><code>oPayload</code></dt>
811 * <dd>The same value as was passed in as <code>argument</code> in the oCallback object literal.</dd>
814 * @method sendRequest
815 * @param oRequest {Object} Request object.
816 * @param oCallback {Object} An object literal with the following properties:
818 * <dt><code>success</code></dt>
819 * <dd>The function to call when the data is ready.</dd>
820 * <dt><code>failure</code></dt>
821 * <dd>The function to call upon a response failure condition.</dd>
822 * <dt><code>scope</code></dt>
823 * <dd>The object to serve as the scope for the success and failure handlers.</dd>
824 * <dt><code>argument</code></dt>
825 * <dd>Arbitrary data that will be passed back to the success and failure handlers.</dd>
827 * @param oCaller {Object} (deprecated) Use oCallback.scope.
828 * @return {Number} Transaction ID, or null if response found in cache.
830 sendRequest : function(oRequest, oCallback, oCaller) {
831 // First look in cache
832 var oCachedResponse = this.getCachedResponse(oRequest, oCallback, oCaller);
833 if(oCachedResponse) {
834 DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller);
839 // Not in cache, so forward request to live data
840 YAHOO.log("Making connection to live data for \"" + oRequest + "\"", "info", this.toString());
841 return this.makeConnection(oRequest, oCallback, oCaller);
845 * Overridable default method generates a unique transaction ID and passes
846 * the live data reference directly to the handleResponse function. This
847 * method should be implemented by subclasses to achieve more complex behavior
848 * or to access remote data.
850 * @method makeConnection
851 * @param oRequest {Object} Request object.
852 * @param oCallback {Object} Callback object literal.
853 * @param oCaller {Object} (deprecated) Use oCallback.scope.
854 * @return {Number} Transaction ID.
856 makeConnection : function(oRequest, oCallback, oCaller) {
857 var tId = DS._nTransactionId++;
858 this.fireEvent("requestEvent", {tId:tId, request:oRequest,callback:oCallback,caller:oCaller});
860 /* accounts for the following cases:
861 YAHOO.util.DataSourceBase.TYPE_UNKNOWN
862 YAHOO.util.DataSourceBase.TYPE_JSARRAY
863 YAHOO.util.DataSourceBase.TYPE_JSON
864 YAHOO.util.DataSourceBase.TYPE_HTMLTABLE
865 YAHOO.util.DataSourceBase.TYPE_XML
866 YAHOO.util.DataSourceBase.TYPE_TEXT
868 var oRawResponse = this.liveData;
870 this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
875 * Receives raw data response and type converts to XML, JSON, etc as necessary.
876 * Forwards oFullResponse to appropriate parsing function to get turned into
877 * oParsedResponse. Calls doBeforeCallback() and adds oParsedResponse to
878 * the cache when appropriate before calling issueCallback().
880 * The oParsedResponse object literal has the following properties:
882 * <dd><dt>tId {Number}</dt> Unique transaction ID</dd>
883 * <dd><dt>results {Array}</dt> Array of parsed data results</dd>
884 * <dd><dt>meta {Object}</dt> Object literal of meta values</dd>
885 * <dd><dt>error {Boolean}</dt> (optional) True if there was an error</dd>
886 * <dd><dt>cached {Boolean}</dt> (optional) True if response was cached</dd>
889 * @method handleResponse
890 * @param oRequest {Object} Request object
891 * @param oRawResponse {Object} The raw response from the live database.
892 * @param oCallback {Object} Callback object literal.
893 * @param oCaller {Object} (deprecated) Use oCallback.scope.
894 * @param tId {Number} Transaction ID.
896 handleResponse : function(oRequest, oRawResponse, oCallback, oCaller, tId) {
897 this.fireEvent("responseEvent", {tId:tId, request:oRequest, response:oRawResponse,
898 callback:oCallback, caller:oCaller});
899 YAHOO.log("Received live data response for \"" + oRequest + "\"", "info", this.toString());
900 var xhr = (this.dataType == DS.TYPE_XHR) ? true : false;
901 var oParsedResponse = null;
902 var oFullResponse = oRawResponse;
904 // Try to sniff data type if it has not been defined
905 if(this.responseType === DS.TYPE_UNKNOWN) {
906 var ctype = (oRawResponse && oRawResponse.getResponseHeader) ? oRawResponse.getResponseHeader["Content-Type"] : null;
909 if(ctype.indexOf("text/xml") > -1) {
910 this.responseType = DS.TYPE_XML;
912 else if(ctype.indexOf("application/json") > -1) { // json
913 this.responseType = DS.TYPE_JSON;
915 else if(ctype.indexOf("text/plain") > -1) { // text
916 this.responseType = DS.TYPE_TEXT;
920 if(YAHOO.lang.isArray(oRawResponse)) { // array
921 this.responseType = DS.TYPE_JSARRAY;
924 else if(oRawResponse && oRawResponse.nodeType && oRawResponse.nodeType == 9) {
925 this.responseType = DS.TYPE_XML;
927 else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
928 this.responseType = DS.TYPE_HTMLTABLE;
930 else if(YAHOO.lang.isObject(oRawResponse)) { // json
931 this.responseType = DS.TYPE_JSON;
933 else if(YAHOO.lang.isString(oRawResponse)) { // text
934 this.responseType = DS.TYPE_TEXT;
939 switch(this.responseType) {
940 case DS.TYPE_JSARRAY:
941 if(xhr && oRawResponse && oRawResponse.responseText) {
942 oFullResponse = oRawResponse.responseText;
945 // Convert to JS array if it's a string
946 if(lang.isString(oFullResponse)) {
947 var parseArgs = [oFullResponse].concat(this.parseJSONArgs);
948 // Check for YUI JSON Util
950 oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs);
952 // Look for JSON parsers using an API similar to json2.js
953 else if(window.JSON && JSON.parse) {
954 oFullResponse = JSON.parse.apply(JSON,parseArgs);
956 // Look for JSON parsers using an API similar to json.js
957 else if(oFullResponse.parseJSON) {
958 oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1));
960 // No JSON lib found so parse the string
962 // Trim leading spaces
963 while (oFullResponse.length > 0 &&
964 (oFullResponse.charAt(0) != "{") &&
965 (oFullResponse.charAt(0) != "[")) {
966 oFullResponse = oFullResponse.substring(1, oFullResponse.length);
969 if(oFullResponse.length > 0) {
970 // Strip extraneous stuff at the end
972 Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));
973 oFullResponse = oFullResponse.substring(0,arrayEnd+1);
975 // Turn the string into an object literal...
976 // ...eval is necessary here
977 oFullResponse = eval("(" + oFullResponse + ")");
985 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
986 oParsedResponse = this.parseArrayData(oRequest, oFullResponse);
989 if(xhr && oRawResponse && oRawResponse.responseText) {
990 oFullResponse = oRawResponse.responseText;
993 // Convert to JSON object if it's a string
994 if(lang.isString(oFullResponse)) {
995 var parseArgs = [oFullResponse].concat(this.parseJSONArgs);
996 // Check for YUI JSON Util
998 oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs);
1000 // Look for JSON parsers using an API similar to json2.js
1001 else if(window.JSON && JSON.parse) {
1002 oFullResponse = JSON.parse.apply(JSON,parseArgs);
1004 // Look for JSON parsers using an API similar to json.js
1005 else if(oFullResponse.parseJSON) {
1006 oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1));
1008 // No JSON lib found so parse the string
1010 // Trim leading spaces
1011 while (oFullResponse.length > 0 &&
1012 (oFullResponse.charAt(0) != "{") &&
1013 (oFullResponse.charAt(0) != "[")) {
1014 oFullResponse = oFullResponse.substring(1, oFullResponse.length);
1017 if(oFullResponse.length > 0) {
1018 // Strip extraneous stuff at the end
1019 var objEnd = Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));
1020 oFullResponse = oFullResponse.substring(0,objEnd+1);
1022 // Turn the string into an object literal...
1023 // ...eval is necessary here
1024 oFullResponse = eval("(" + oFullResponse + ")");
1033 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1034 oParsedResponse = this.parseJSONData(oRequest, oFullResponse);
1036 case DS.TYPE_HTMLTABLE:
1037 if(xhr && oRawResponse.responseText) {
1038 var el = document.createElement('div');
1039 el.innerHTML = oRawResponse.responseText;
1040 oFullResponse = el.getElementsByTagName('table')[0];
1042 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1043 oParsedResponse = this.parseHTMLTableData(oRequest, oFullResponse);
1046 if(xhr && oRawResponse.responseXML) {
1047 oFullResponse = oRawResponse.responseXML;
1049 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1050 oParsedResponse = this.parseXMLData(oRequest, oFullResponse);
1053 if(xhr && lang.isString(oRawResponse.responseText)) {
1054 oFullResponse = oRawResponse.responseText;
1056 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1057 oParsedResponse = this.parseTextData(oRequest, oFullResponse);
1060 oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
1061 oParsedResponse = this.parseData(oRequest, oFullResponse);
1066 // Clean up for consistent signature
1067 oParsedResponse = oParsedResponse || {};
1068 if(!oParsedResponse.results) {
1069 oParsedResponse.results = [];
1071 if(!oParsedResponse.meta) {
1072 oParsedResponse.meta = {};
1076 if(oParsedResponse && !oParsedResponse.error) {
1077 // Last chance to touch the raw response or the parsed response
1078 oParsedResponse = this.doBeforeCallback(oRequest, oFullResponse, oParsedResponse, oCallback);
1079 this.fireEvent("responseParseEvent", {request:oRequest,
1080 response:oParsedResponse, callback:oCallback, caller:oCaller});
1081 // Cache the response
1082 this.addToCache(oRequest, oParsedResponse);
1086 // Be sure the error flag is on
1087 oParsedResponse.error = true;
1088 this.fireEvent("dataErrorEvent", {request:oRequest, response: oRawResponse, callback:oCallback,
1089 caller:oCaller, message:DS.ERROR_DATANULL});
1090 YAHOO.log(DS.ERROR_DATANULL, "error", this.toString());
1093 // Send the response back to the caller
1094 oParsedResponse.tId = tId;
1095 DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller);
1099 * Overridable method gives implementers access to the original full response
1100 * before the data gets parsed. Implementers should take care not to return an
1101 * unparsable or otherwise invalid response.
1103 * @method doBeforeParseData
1104 * @param oRequest {Object} Request object.
1105 * @param oFullResponse {Object} The full response from the live database.
1106 * @param oCallback {Object} The callback object.
1107 * @return {Object} Full response for parsing.
1110 doBeforeParseData : function(oRequest, oFullResponse, oCallback) {
1111 return oFullResponse;
1115 * Overridable method gives implementers access to the original full response and
1116 * the parsed response (parsed against the given schema) before the data
1117 * is added to the cache (if applicable) and then sent back to callback function.
1118 * This is your chance to access the raw response and/or populate the parsed
1119 * response with any custom data.
1121 * @method doBeforeCallback
1122 * @param oRequest {Object} Request object.
1123 * @param oFullResponse {Object} The full response from the live database.
1124 * @param oParsedResponse {Object} The parsed response to return to calling object.
1125 * @param oCallback {Object} The callback object.
1126 * @return {Object} Parsed response object.
1128 doBeforeCallback : function(oRequest, oFullResponse, oParsedResponse, oCallback) {
1129 return oParsedResponse;
1133 * Overridable method parses data of generic RESPONSE_TYPE into a response object.
1136 * @param oRequest {Object} Request object.
1137 * @param oFullResponse {Object} The full Array from the live database.
1138 * @return {Object} Parsed response object with the following properties:<br>
1139 * - results {Array} Array of parsed data results<br>
1140 * - meta {Object} Object literal of meta values<br>
1141 * - error {Boolean} (optional) True if there was an error<br>
1143 parseData : function(oRequest, oFullResponse) {
1144 if(lang.isValue(oFullResponse)) {
1145 var oParsedResponse = {results:oFullResponse,meta:{}};
1146 YAHOO.log("Parsed generic data is " +
1147 lang.dump(oParsedResponse), "info", this.toString());
1148 return oParsedResponse;
1151 YAHOO.log("Generic data could not be parsed: " + lang.dump(oFullResponse),
1152 "error", this.toString());
1157 * Overridable method parses Array data into a response object.
1159 * @method parseArrayData
1160 * @param oRequest {Object} Request object.
1161 * @param oFullResponse {Object} The full Array from the live database.
1162 * @return {Object} Parsed response object with the following properties:<br>
1163 * - results (Array) Array of parsed data results<br>
1164 * - error (Boolean) True if there was an error
1166 parseArrayData : function(oRequest, oFullResponse) {
1167 if(lang.isArray(oFullResponse)) {
1173 if(lang.isArray(this.responseSchema.fields)) {
1174 var fields = this.responseSchema.fields;
1175 for (i = fields.length - 1; i >= 0; --i) {
1176 if (typeof fields[i] !== 'object') {
1177 fields[i] = { key : fields[i] };
1181 var parsers = {}, p;
1182 for (i = fields.length - 1; i >= 0; --i) {
1183 p = (typeof fields[i].parser === 'function' ?
1185 DS.Parser[fields[i].parser+'']) || fields[i].converter;
1187 parsers[fields[i].key] = p;
1191 var arrType = lang.isArray(oFullResponse[0]);
1192 for(i=oFullResponse.length-1; i>-1; i--) {
1194 rec = oFullResponse[i];
1195 if (typeof rec === 'object') {
1196 for(j=fields.length-1; j>-1; j--) {
1198 data = arrType ? rec[j] : rec[field.key];
1200 if (parsers[field.key]) {
1201 data = parsers[field.key].call(this,data);
1205 if(data === undefined) {
1209 oResult[field.key] = data;
1212 else if (lang.isString(rec)) {
1213 for(j=fields.length-1; j>-1; j--) {
1217 if (parsers[field.key]) {
1218 data = parsers[field.key].call(this,data);
1222 if(data === undefined) {
1226 oResult[field.key] = data;
1229 results[i] = oResult;
1232 // Return entire data set
1234 results = oFullResponse;
1236 var oParsedResponse = {results:results};
1237 YAHOO.log("Parsed array data is " +
1238 lang.dump(oParsedResponse), "info", this.toString());
1239 return oParsedResponse;
1242 YAHOO.log("Array data could not be parsed: " + lang.dump(oFullResponse),
1243 "error", this.toString());
1248 * Overridable method parses plain text data into a response object.
1250 * @method parseTextData
1251 * @param oRequest {Object} Request object.
1252 * @param oFullResponse {Object} The full text response from the live database.
1253 * @return {Object} Parsed response object with the following properties:<br>
1254 * - results (Array) Array of parsed data results<br>
1255 * - error (Boolean) True if there was an error
1257 parseTextData : function(oRequest, oFullResponse) {
1258 if(lang.isString(oFullResponse)) {
1259 if(lang.isString(this.responseSchema.recordDelim) &&
1260 lang.isString(this.responseSchema.fieldDelim)) {
1261 var oParsedResponse = {results:[]};
1262 var recDelim = this.responseSchema.recordDelim;
1263 var fieldDelim = this.responseSchema.fieldDelim;
1264 if(oFullResponse.length > 0) {
1265 // Delete the last line delimiter at the end of the data if it exists
1266 var newLength = oFullResponse.length-recDelim.length;
1267 if(oFullResponse.substr(newLength) == recDelim) {
1268 oFullResponse = oFullResponse.substr(0, newLength);
1270 if(oFullResponse.length > 0) {
1271 // Split along record delimiter to get an array of strings
1272 var recordsarray = oFullResponse.split(recDelim);
1273 // Cycle through each record
1274 for(var i = 0, len = recordsarray.length, recIdx = 0; i < len; ++i) {
1276 sRecord = recordsarray[i];
1277 if (lang.isString(sRecord) && (sRecord.length > 0)) {
1278 // Split each record along field delimiter to get data
1279 var fielddataarray = recordsarray[i].split(fieldDelim);
1282 // Filter for fields data
1283 if(lang.isArray(this.responseSchema.fields)) {
1284 var fields = this.responseSchema.fields;
1285 for(var j=fields.length-1; j>-1; j--) {
1287 // Remove quotation marks from edges, if applicable
1288 var data = fielddataarray[j];
1289 if (lang.isString(data)) {
1290 if(data.charAt(0) == "\"") {
1291 data = data.substr(1);
1293 if(data.charAt(data.length-1) == "\"") {
1294 data = data.substr(0,data.length-1);
1296 var field = fields[j];
1297 var key = (lang.isValue(field.key)) ? field.key : field;
1298 // Backward compatibility
1299 if(!field.parser && field.converter) {
1300 field.parser = field.converter;
1301 YAHOO.log("The field property converter has been deprecated" +
1302 " in favor of parser", "warn", this.toString());
1304 var parser = (typeof field.parser === 'function') ?
1306 DS.Parser[field.parser+''];
1308 data = parser.call(this, data);
1311 if(data === undefined) {
1314 oResult[key] = data;
1325 // No fields defined so pass along all data as an array
1327 oResult = fielddataarray;
1330 oParsedResponse.results[recIdx++] = oResult;
1336 YAHOO.log("Parsed text data is " +
1337 lang.dump(oParsedResponse), "info", this.toString());
1338 return oParsedResponse;
1341 YAHOO.log("Text data could not be parsed: " + lang.dump(oFullResponse),
1342 "error", this.toString());
1349 * Overridable method parses XML data for one result into an object literal.
1351 * @method parseXMLResult
1352 * @param result {XML} XML for one result.
1353 * @return {Object} Object literal of data for one result.
1355 parseXMLResult : function(result) {
1357 schema = this.responseSchema;
1360 // Loop through each data field in each result using the schema
1361 for(var m = schema.fields.length-1; m >= 0 ; m--) {
1362 var field = schema.fields[m];
1363 var key = (lang.isValue(field.key)) ? field.key : field;
1365 // Values may be held in an attribute...
1366 var xmlAttr = result.attributes.getNamedItem(key);
1368 data = xmlAttr.value;
1372 var xmlNode = result.getElementsByTagName(key);
1373 if(xmlNode && xmlNode.item(0)) {
1374 var item = xmlNode.item(0);
1375 // For IE, then DOM...
1376 data = (item) ? ((item.text) ? item.text : (item.textContent) ? item.textContent : null) : null;
1377 // ...then fallback, but check for multiple child nodes
1379 var datapieces = [];
1380 for(var j=0, len=item.childNodes.length; j<len; j++) {
1381 if(item.childNodes[j].nodeValue) {
1382 datapieces[datapieces.length] = item.childNodes[j].nodeValue;
1385 if(datapieces.length > 0) {
1386 data = datapieces.join("");
1395 // Backward compatibility
1396 if(!field.parser && field.converter) {
1397 field.parser = field.converter;
1398 YAHOO.log("The field property converter has been deprecated" +
1399 " in favor of parser", "warn", this.toString());
1401 var parser = (typeof field.parser === 'function') ?
1403 DS.Parser[field.parser+''];
1405 data = parser.call(this, data);
1408 if(data === undefined) {
1411 oResult[key] = data;
1415 YAHOO.log("Error while parsing XML result: " + e.message);
1424 * Overridable method parses XML data into a response object.
1426 * @method parseXMLData
1427 * @param oRequest {Object} Request object.
1428 * @param oFullResponse {Object} The full XML response from the live database.
1429 * @return {Object} Parsed response object with the following properties<br>
1430 * - results (Array) Array of parsed data results<br>
1431 * - error (Boolean) True if there was an error
1433 parseXMLData : function(oRequest, oFullResponse) {
1435 schema = this.responseSchema,
1436 oParsedResponse = {meta:{}},
1438 metaNode = schema.metaNode,
1439 metaLocators = schema.metaFields || {},
1442 // In case oFullResponse is something funky
1444 xmlList = (schema.resultNode) ?
1445 oFullResponse.getElementsByTagName(schema.resultNode) :
1448 // Pull any meta identified
1449 metaNode = metaNode ? oFullResponse.getElementsByTagName(metaNode)[0] :
1453 for (k in metaLocators) {
1454 if (lang.hasOwnProperty(metaLocators, k)) {
1455 loc = metaLocators[k];
1457 v = metaNode.getElementsByTagName(loc)[0];
1460 v = v.firstChild.nodeValue;
1462 // Look for an attribute
1463 v = metaNode.attributes.getNamedItem(loc);
1469 if (lang.isValue(v)) {
1470 oParsedResponse.meta[k] = v;
1478 YAHOO.log("Error while parsing XML data: " + e.message);
1480 if(!xmlList || !lang.isArray(schema.fields)) {
1483 // Loop through each result
1485 oParsedResponse.results = [];
1486 for(i = xmlList.length-1; i >= 0 ; --i) {
1487 var oResult = this.parseXMLResult(xmlList.item(i));
1488 // Capture each array of values into an array of results
1489 oParsedResponse.results[i] = oResult;
1493 YAHOO.log("XML data could not be parsed: " +
1494 lang.dump(oFullResponse), "error", this.toString());
1495 oParsedResponse.error = true;
1498 YAHOO.log("Parsed XML data is " +
1499 lang.dump(oParsedResponse), "info", this.toString());
1501 return oParsedResponse;
1505 * Overridable method parses JSON data into a response object.
1507 * @method parseJSONData
1508 * @param oRequest {Object} Request object.
1509 * @param oFullResponse {Object} The full JSON from the live database.
1510 * @return {Object} Parsed response object with the following properties<br>
1511 * - results (Array) Array of parsed data results<br>
1512 * - error (Boolean) True if there was an error
1514 parseJSONData : function(oRequest, oFullResponse) {
1515 var oParsedResponse = {results:[],meta:{}};
1517 if(lang.isObject(oFullResponse) && this.responseSchema.resultsList) {
1518 var schema = this.responseSchema,
1519 fields = schema.fields,
1520 resultsList = oFullResponse,
1522 metaFields = schema.metaFields || {},
1527 i,len,j,v,key,parser,path;
1529 // Function to convert the schema's fields into walk paths
1530 var buildPath = function (needle) {
1531 var path = null, keys = [], i = 0;
1533 // Strip the ["string keys"] and [1] array indexes
1535 replace(/\[(['"])(.*?)\1\]/g,
1536 function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}).
1537 replace(/\[(\d+)\]/g,
1538 function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}).
1539 replace(/^\./,''); // remove leading dot
1541 // If the cleaned needle contains invalid characters, the
1543 if (!/[^\w\.\$@]/.test(needle)) {
1544 path = needle.split('.');
1545 for (i=path.length-1; i >= 0; --i) {
1546 if (path[i].charAt(0) === '@') {
1547 path[i] = keys[parseInt(path[i].substr(1),10)];
1552 YAHOO.log("Invalid locator: " + needle, "error", this.toString());
1559 // Function to walk a path and return the pot of gold
1560 var walkPath = function (path, origin) {
1561 var v=origin,i=0,len=path.length;
1562 for (;i<len && v;++i) {
1568 // Parse the response
1569 // Step 1. Pull the resultsList from oFullResponse (default assumes
1570 // oFullResponse IS the resultsList)
1571 path = buildPath(schema.resultsList);
1573 resultsList = walkPath(path, oFullResponse);
1574 if (resultsList === undefined) {
1585 if (!lang.isArray(resultsList)) {
1586 resultsList = [resultsList];
1590 // Step 2. Parse out field data if identified
1593 // Build the field parser map and location paths
1594 for (i=0, len=fields.length; i<len; i++) {
1596 key = field.key || field;
1597 parser = ((typeof field.parser === 'function') ?
1599 DS.Parser[field.parser+'']) || field.converter;
1600 path = buildPath(key);
1603 fieldParsers[fieldParsers.length] = {key:key,parser:parser};
1607 if (path.length > 1) {
1608 fieldPaths[fieldPaths.length] = {key:key,path:path};
1610 simpleFields[simpleFields.length] = {key:key,path:path[0]};
1613 YAHOO.log("Invalid key syntax: " + key,"warn",this.toString());
1617 // Process the results, flattening the records and/or applying parsers if needed
1618 for (i = resultsList.length - 1; i >= 0; --i) {
1619 var r = resultsList[i], rec = {};
1621 for (j = simpleFields.length - 1; j >= 0; --j) {
1622 // Bug 1777850: data might be held in an array
1623 rec[simpleFields[j].key] =
1624 (r[simpleFields[j].path] !== undefined) ?
1625 r[simpleFields[j].path] : r[j];
1628 for (j = fieldPaths.length - 1; j >= 0; --j) {
1629 rec[fieldPaths[j].key] = walkPath(fieldPaths[j].path,r);
1632 for (j = fieldParsers.length - 1; j >= 0; --j) {
1633 var p = fieldParsers[j].key;
1634 rec[p] = fieldParsers[j].parser(rec[p]);
1635 if (rec[p] === undefined) {
1644 results = resultsList;
1647 for (key in metaFields) {
1648 if (lang.hasOwnProperty(metaFields,key)) {
1649 path = buildPath(metaFields[key]);
1651 v = walkPath(path, oFullResponse);
1652 oParsedResponse.meta[key] = v;
1658 YAHOO.log("JSON data could not be parsed due to invalid responseSchema.resultsList or invalid response: " +
1659 lang.dump(oFullResponse), "error", this.toString());
1661 oParsedResponse.error = true;
1664 oParsedResponse.results = results;
1667 YAHOO.log("JSON data could not be parsed: " +
1668 lang.dump(oFullResponse), "error", this.toString());
1669 oParsedResponse.error = true;
1672 return oParsedResponse;
1676 * Overridable method parses an HTML TABLE element reference into a response object.
1677 * Data is parsed out of TR elements from all TBODY elements.
1679 * @method parseHTMLTableData
1680 * @param oRequest {Object} Request object.
1681 * @param oFullResponse {Object} The full HTML element reference from the live database.
1682 * @return {Object} Parsed response object with the following properties<br>
1683 * - results (Array) Array of parsed data results<br>
1684 * - error (Boolean) True if there was an error
1686 parseHTMLTableData : function(oRequest, oFullResponse) {
1688 var elTable = oFullResponse;
1689 var fields = this.responseSchema.fields;
1690 var oParsedResponse = {results:[]};
1692 if(lang.isArray(fields)) {
1693 // Iterate through each TBODY
1694 for(var i=0; i<elTable.tBodies.length; i++) {
1695 var elTbody = elTable.tBodies[i];
1697 // Iterate through each TR
1698 for(var j=elTbody.rows.length-1; j>-1; j--) {
1699 var elRow = elTbody.rows[j];
1702 for(var k=fields.length-1; k>-1; k--) {
1703 var field = fields[k];
1704 var key = (lang.isValue(field.key)) ? field.key : field;
1705 var data = elRow.cells[k].innerHTML;
1707 // Backward compatibility
1708 if(!field.parser && field.converter) {
1709 field.parser = field.converter;
1710 YAHOO.log("The field property converter has been deprecated" +
1711 " in favor of parser", "warn", this.toString());
1713 var parser = (typeof field.parser === 'function') ?
1715 DS.Parser[field.parser+''];
1717 data = parser.call(this, data);
1720 if(data === undefined) {
1723 oResult[key] = data;
1725 oParsedResponse.results[j] = oResult;
1731 YAHOO.log("Invalid responseSchema.fields", "error", this.toString());
1735 YAHOO.log("HTML TABLE data could not be parsed: " +
1736 lang.dump(oFullResponse), "error", this.toString());
1737 oParsedResponse.error = true;
1740 YAHOO.log("Parsed HTML TABLE data is " +
1741 lang.dump(oParsedResponse), "info", this.toString());
1743 return oParsedResponse;
1748 // DataSourceBase uses EventProvider
1749 lang.augmentProto(DS, util.EventProvider);
1753 /****************************************************************************/
1754 /****************************************************************************/
1755 /****************************************************************************/
1758 * LocalDataSource class for in-memory data structs including JavaScript arrays,
1759 * JavaScript object literals (JSON), XML documents, and HTML tables.
1761 * @namespace YAHOO.util
1762 * @class YAHOO.util.LocalDataSource
1763 * @extends YAHOO.util.DataSourceBase
1765 * @param oLiveData {HTMLElement} Pointer to live data.
1766 * @param oConfigs {object} (optional) Object literal of configuration values.
1768 util.LocalDataSource = function(oLiveData, oConfigs) {
1769 this.dataType = DS.TYPE_LOCAL;
1772 if(YAHOO.lang.isArray(oLiveData)) { // array
1773 this.responseType = DS.TYPE_JSARRAY;
1776 else if(oLiveData.nodeType && oLiveData.nodeType == 9) {
1777 this.responseType = DS.TYPE_XML;
1779 else if(oLiveData.nodeName && (oLiveData.nodeName.toLowerCase() == "table")) { // table
1780 this.responseType = DS.TYPE_HTMLTABLE;
1781 oLiveData = oLiveData.cloneNode(true);
1783 else if(YAHOO.lang.isString(oLiveData)) { // text
1784 this.responseType = DS.TYPE_TEXT;
1786 else if(YAHOO.lang.isObject(oLiveData)) { // json
1787 this.responseType = DS.TYPE_JSON;
1792 this.responseType = DS.TYPE_JSARRAY;
1795 util.LocalDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
1798 // LocalDataSource extends DataSourceBase
1799 lang.extend(util.LocalDataSource, DS);
1801 // Copy static members to LocalDataSource class
1802 lang.augmentObject(util.LocalDataSource, DS);
1816 /****************************************************************************/
1817 /****************************************************************************/
1818 /****************************************************************************/
1821 * FunctionDataSource class for JavaScript functions.
1823 * @namespace YAHOO.util
1824 * @class YAHOO.util.FunctionDataSource
1825 * @extends YAHOO.util.DataSourceBase
1827 * @param oLiveData {HTMLElement} Pointer to live data.
1828 * @param oConfigs {object} (optional) Object literal of configuration values.
1830 util.FunctionDataSource = function(oLiveData, oConfigs) {
1831 this.dataType = DS.TYPE_JSFUNCTION;
1832 oLiveData = oLiveData || function() {};
1834 util.FunctionDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
1837 // FunctionDataSource extends DataSourceBase
1838 lang.extend(util.FunctionDataSource, DS, {
1840 /////////////////////////////////////////////////////////////////////////////
1842 // FunctionDataSource public properties
1844 /////////////////////////////////////////////////////////////////////////////
1847 * Context in which to execute the function. By default, is the DataSource
1848 * instance itself. If set, the function will receive the DataSource instance
1849 * as an additional argument.
1858 /////////////////////////////////////////////////////////////////////////////
1860 // FunctionDataSource public methods
1862 /////////////////////////////////////////////////////////////////////////////
1865 * Overriding method passes query to a function. The returned response is then
1866 * forwarded to the handleResponse function.
1868 * @method makeConnection
1869 * @param oRequest {Object} Request object.
1870 * @param oCallback {Object} Callback object literal.
1871 * @param oCaller {Object} (deprecated) Use oCallback.scope.
1872 * @return {Number} Transaction ID.
1874 makeConnection : function(oRequest, oCallback, oCaller) {
1875 var tId = DS._nTransactionId++;
1876 this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
1878 // Pass the request in as a parameter and
1879 // forward the return value to the handler
1882 var oRawResponse = (this.scope) ? this.liveData.call(this.scope, oRequest, this) : this.liveData(oRequest);
1884 // Try to sniff data type if it has not been defined
1885 if(this.responseType === DS.TYPE_UNKNOWN) {
1886 if(YAHOO.lang.isArray(oRawResponse)) { // array
1887 this.responseType = DS.TYPE_JSARRAY;
1890 else if(oRawResponse && oRawResponse.nodeType && oRawResponse.nodeType == 9) {
1891 this.responseType = DS.TYPE_XML;
1893 else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
1894 this.responseType = DS.TYPE_HTMLTABLE;
1896 else if(YAHOO.lang.isObject(oRawResponse)) { // json
1897 this.responseType = DS.TYPE_JSON;
1899 else if(YAHOO.lang.isString(oRawResponse)) { // text
1900 this.responseType = DS.TYPE_TEXT;
1904 this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
1910 // Copy static members to FunctionDataSource class
1911 lang.augmentObject(util.FunctionDataSource, DS);
1925 /****************************************************************************/
1926 /****************************************************************************/
1927 /****************************************************************************/
1930 * ScriptNodeDataSource class for accessing remote data via the YUI Get Utility.
1932 * @namespace YAHOO.util
1933 * @class YAHOO.util.ScriptNodeDataSource
1934 * @extends YAHOO.util.DataSourceBase
1936 * @param oLiveData {HTMLElement} Pointer to live data.
1937 * @param oConfigs {object} (optional) Object literal of configuration values.
1939 util.ScriptNodeDataSource = function(oLiveData, oConfigs) {
1940 this.dataType = DS.TYPE_SCRIPTNODE;
1941 oLiveData = oLiveData || "";
1943 util.ScriptNodeDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
1946 // ScriptNodeDataSource extends DataSourceBase
1947 lang.extend(util.ScriptNodeDataSource, DS, {
1949 /////////////////////////////////////////////////////////////////////////////
1951 // ScriptNodeDataSource public properties
1953 /////////////////////////////////////////////////////////////////////////////
1956 * Alias to YUI Get Utility, to allow implementers to use a custom class.
1958 * @property getUtility
1960 * @default YAHOO.util.Get
1962 getUtility : util.Get,
1965 * Defines request/response management in the following manner:
1967 * <!--<dt>queueRequests</dt>
1968 * <dd>If a request is already in progress, wait until response is returned before sending the next request.</dd>
1969 * <dt>cancelStaleRequests</dt>
1970 * <dd>If a request is already in progress, cancel it before sending the next request.</dd>-->
1971 * <dt>ignoreStaleResponses</dt>
1972 * <dd>Send all requests, but handle only the response for the most recently sent request.</dd>
1974 * <dd>Send all requests and handle all responses.</dd>
1977 * @property asyncMode
1979 * @default "allowAll"
1981 asyncMode : "allowAll",
1984 * Callback string parameter name sent to the remote script. By default,
1985 * requests are sent to
1986 * <URI>?<scriptCallbackParam>=callbackFunction
1988 * @property scriptCallbackParam
1990 * @default "callback"
1992 scriptCallbackParam : "callback",
1995 /////////////////////////////////////////////////////////////////////////////
1997 // ScriptNodeDataSource public methods
1999 /////////////////////////////////////////////////////////////////////////////
2002 * Creates a request callback that gets appended to the script URI. Implementers
2003 * can customize this string to match their server's query syntax.
2005 * @method generateRequestCallback
2006 * @return {String} String fragment that gets appended to script URI that
2007 * specifies the callback function
2009 generateRequestCallback : function(id) {
2010 return "&" + this.scriptCallbackParam + "=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]" ;
2014 * Overridable method gives implementers access to modify the URI before the dynamic
2015 * script node gets inserted. Implementers should take care not to return an
2018 * @method doBeforeGetScriptNode
2019 * @param {String} URI to the script
2020 * @return {String} URI to the script
2022 doBeforeGetScriptNode : function(sUri) {
2027 * Overriding method passes query to Get Utility. The returned
2028 * response is then forwarded to the handleResponse function.
2030 * @method makeConnection
2031 * @param oRequest {Object} Request object.
2032 * @param oCallback {Object} Callback object literal.
2033 * @param oCaller {Object} (deprecated) Use oCallback.scope.
2034 * @return {Number} Transaction ID.
2036 makeConnection : function(oRequest, oCallback, oCaller) {
2037 var tId = DS._nTransactionId++;
2038 this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
2040 // If there are no global pending requests, it is safe to purge global callback stack and global counter
2041 if(util.ScriptNodeDataSource._nPending === 0) {
2042 util.ScriptNodeDataSource.callbacks = [];
2043 util.ScriptNodeDataSource._nId = 0;
2046 // ID for this request
2047 var id = util.ScriptNodeDataSource._nId;
2048 util.ScriptNodeDataSource._nId++;
2050 // Dynamically add handler function with a closure to the callback stack
2052 util.ScriptNodeDataSource.callbacks[id] = function(oRawResponse) {
2053 if((oSelf.asyncMode !== "ignoreStaleResponses")||
2054 (id === util.ScriptNodeDataSource.callbacks.length-1)) { // Must ignore stale responses
2056 // Try to sniff data type if it has not been defined
2057 if(oSelf.responseType === DS.TYPE_UNKNOWN) {
2058 if(YAHOO.lang.isArray(oRawResponse)) { // array
2059 oSelf.responseType = DS.TYPE_JSARRAY;
2062 else if(oRawResponse.nodeType && oRawResponse.nodeType == 9) {
2063 oSelf.responseType = DS.TYPE_XML;
2065 else if(oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
2066 oSelf.responseType = DS.TYPE_HTMLTABLE;
2068 else if(YAHOO.lang.isObject(oRawResponse)) { // json
2069 oSelf.responseType = DS.TYPE_JSON;
2071 else if(YAHOO.lang.isString(oRawResponse)) { // text
2072 oSelf.responseType = DS.TYPE_TEXT;
2076 oSelf.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
2079 YAHOO.log("DataSource ignored stale response for tId " + tId + "(" + oRequest + ")", "info", oSelf.toString());
2082 delete util.ScriptNodeDataSource.callbacks[id];
2085 // We are now creating a request
2086 util.ScriptNodeDataSource._nPending++;
2087 var sUri = this.liveData + oRequest + this.generateRequestCallback(id);
2088 sUri = this.doBeforeGetScriptNode(sUri);
2089 YAHOO.log("DataSource is querying URL " + sUri, "info", this.toString());
2090 this.getUtility.script(sUri,
2092 onsuccess: util.ScriptNodeDataSource._bumpPendingDown,
2093 onfail: util.ScriptNodeDataSource._bumpPendingDown});
2100 // Copy static members to ScriptNodeDataSource class
2101 lang.augmentObject(util.ScriptNodeDataSource, DS);
2103 // Copy static members to ScriptNodeDataSource class
2104 lang.augmentObject(util.ScriptNodeDataSource, {
2106 /////////////////////////////////////////////////////////////////////////////
2108 // ScriptNodeDataSource private static properties
2110 /////////////////////////////////////////////////////////////////////////////
2113 * Unique ID to track requests.
2123 * Counter for pending requests. When this is 0, it is safe to purge callbacks
2126 * @property _nPending
2134 * Global array of callback functions, one for each request sent.
2136 * @property callbacks
2157 /****************************************************************************/
2158 /****************************************************************************/
2159 /****************************************************************************/
2162 * XHRDataSource class for accessing remote data via the YUI Connection Manager
2165 * @namespace YAHOO.util
2166 * @class YAHOO.util.XHRDataSource
2167 * @extends YAHOO.util.DataSourceBase
2169 * @param oLiveData {HTMLElement} Pointer to live data.
2170 * @param oConfigs {object} (optional) Object literal of configuration values.
2172 util.XHRDataSource = function(oLiveData, oConfigs) {
2173 this.dataType = DS.TYPE_XHR;
2174 this.connMgr = this.connMgr || util.Connect;
2175 oLiveData = oLiveData || "";
2177 util.XHRDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
2180 // XHRDataSource extends DataSourceBase
2181 lang.extend(util.XHRDataSource, DS, {
2183 /////////////////////////////////////////////////////////////////////////////
2185 // XHRDataSource public properties
2187 /////////////////////////////////////////////////////////////////////////////
2190 * Alias to YUI Connection Manager, to allow implementers to use a custom class.
2194 * @default YAHOO.util.Connect
2199 * Defines request/response management in the following manner:
2201 * <dt>queueRequests</dt>
2202 * <dd>If a request is already in progress, wait until response is returned
2203 * before sending the next request.</dd>
2205 * <dt>cancelStaleRequests</dt>
2206 * <dd>If a request is already in progress, cancel it before sending the next
2209 * <dt>ignoreStaleResponses</dt>
2210 * <dd>Send all requests, but handle only the response for the most recently
2211 * sent request.</dd>
2214 * <dd>Send all requests and handle all responses.</dd>
2218 * @property connXhrMode
2220 * @default "allowAll"
2222 connXhrMode: "allowAll",
2225 * True if data is to be sent via POST. By default, data will be sent via GET.
2227 * @property connMethodPost
2231 connMethodPost: false,
2234 * The connection timeout defines how many milliseconds the XHR connection will
2235 * wait for a server response. Any non-zero value will enable the Connection Manager's
2236 * Auto-Abort feature.
2238 * @property connTimeout
2244 /////////////////////////////////////////////////////////////////////////////
2246 // XHRDataSource public methods
2248 /////////////////////////////////////////////////////////////////////////////
2251 * Overriding method passes query to Connection Manager. The returned
2252 * response is then forwarded to the handleResponse function.
2254 * @method makeConnection
2255 * @param oRequest {Object} Request object.
2256 * @param oCallback {Object} Callback object literal.
2257 * @param oCaller {Object} (deprecated) Use oCallback.scope.
2258 * @return {Number} Transaction ID.
2260 makeConnection : function(oRequest, oCallback, oCaller) {
2262 var oRawResponse = null;
2263 var tId = DS._nTransactionId++;
2264 this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
2266 // Set up the callback object and
2267 // pass the request in as a URL query and
2268 // forward the response to the handler
2270 var oConnMgr = this.connMgr;
2271 var oQueue = this._oQueue;
2274 * Define Connection Manager success handler
2276 * @method _xhrSuccess
2277 * @param oResponse {Object} HTTPXMLRequest object
2280 var _xhrSuccess = function(oResponse) {
2281 // If response ID does not match last made request ID,
2282 // silently fail and wait for the next response
2283 if(oResponse && (this.connXhrMode == "ignoreStaleResponses") &&
2284 (oResponse.tId != oQueue.conn.tId)) {
2285 YAHOO.log("Ignored stale response", "warn", this.toString());
2288 // Error if no response
2289 else if(!oResponse) {
2290 this.fireEvent("dataErrorEvent", {request:oRequest,
2291 callback:oCallback, caller:oCaller,
2292 message:DS.ERROR_DATANULL});
2293 YAHOO.log(DS.ERROR_DATANULL, "error", this.toString());
2295 // Send error response back to the caller with the error flag on
2296 DS.issueCallback(oCallback,[oRequest, {error:true}], true, oCaller);
2300 // Forward to handler
2302 // Try to sniff data type if it has not been defined
2303 if(this.responseType === DS.TYPE_UNKNOWN) {
2304 var ctype = (oResponse.getResponseHeader) ? oResponse.getResponseHeader["Content-Type"] : null;
2307 if(ctype.indexOf("text/xml") > -1) {
2308 this.responseType = DS.TYPE_XML;
2310 else if(ctype.indexOf("application/json") > -1) { // json
2311 this.responseType = DS.TYPE_JSON;
2313 else if(ctype.indexOf("text/plain") > -1) { // text
2314 this.responseType = DS.TYPE_TEXT;
2318 this.handleResponse(oRequest, oResponse, oCallback, oCaller, tId);
2323 * Define Connection Manager failure handler
2325 * @method _xhrFailure
2326 * @param oResponse {Object} HTTPXMLRequest object
2329 var _xhrFailure = function(oResponse) {
2330 this.fireEvent("dataErrorEvent", {request:oRequest,
2331 callback:oCallback, caller:oCaller,
2332 message:DS.ERROR_DATAINVALID});
2333 YAHOO.log(DS.ERROR_DATAINVALID + ": " +
2334 oResponse.statusText, "error", this.toString());
2336 // Backward compatibility
2337 if(lang.isString(this.liveData) && lang.isString(oRequest) &&
2338 (this.liveData.lastIndexOf("?") !== this.liveData.length-1) &&
2339 (oRequest.indexOf("?") !== 0)){
2340 YAHOO.log("DataSources using XHR no longer automatically supply " +
2341 "a \"?\" between the host and query parameters" +
2342 " -- please check that the request URL is correct", "warn", this.toString());
2345 // Send failure response back to the caller with the error flag on
2346 oResponse = oResponse || {};
2347 oResponse.error = true;
2348 DS.issueCallback(oCallback,[oRequest,oResponse],true, oCaller);
2354 * Define Connection Manager callback object
2356 * @property _xhrCallback
2357 * @param oResponse {Object} HTTPXMLRequest object
2360 var _xhrCallback = {
2361 success:_xhrSuccess,
2362 failure:_xhrFailure,
2366 // Apply Connection Manager timeout
2367 if(lang.isNumber(this.connTimeout)) {
2368 _xhrCallback.timeout = this.connTimeout;
2371 // Cancel stale requests
2372 if(this.connXhrMode == "cancelStaleRequests") {
2373 // Look in queue for stale requests
2375 if(oConnMgr.abort) {
2376 oConnMgr.abort(oQueue.conn);
2378 YAHOO.log("Canceled stale request", "warn", this.toString());
2381 YAHOO.log("Could not find Connection Manager abort() function", "error", this.toString());
2386 // Get ready to send the request URL
2387 if(oConnMgr && oConnMgr.asyncRequest) {
2388 var sLiveData = this.liveData;
2389 var isPost = this.connMethodPost;
2390 var sMethod = (isPost) ? "POST" : "GET";
2392 var sUri = (isPost || !lang.isValue(oRequest)) ? sLiveData : sLiveData+oRequest;
2393 var sRequest = (isPost) ? oRequest : null;
2395 // Send the request right away
2396 if(this.connXhrMode != "queueRequests") {
2397 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest);
2399 // Queue up then send the request
2401 // Found a request already in progress
2403 var allRequests = oQueue.requests;
2404 // Add request to queue
2405 allRequests.push({request:oRequest, callback:_xhrCallback});
2407 // Interval needs to be started
2408 if(!oQueue.interval) {
2409 oQueue.interval = setInterval(function() {
2410 // Connection is in progress
2411 if(oConnMgr.isCallInProgress(oQueue.conn)) {
2415 // Send next request
2416 if(allRequests.length > 0) {
2418 sUri = (isPost || !lang.isValue(allRequests[0].request)) ? sLiveData : sLiveData+allRequests[0].request;
2419 sRequest = (isPost) ? allRequests[0].request : null;
2420 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, allRequests[0].callback, sRequest);
2422 // Remove request from queue
2423 allRequests.shift();
2427 clearInterval(oQueue.interval);
2428 oQueue.interval = null;
2434 // Nothing is in progress
2436 oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest);
2441 YAHOO.log("Could not find Connection Manager asyncRequest() function", "error", this.toString());
2442 // Send null response back to the caller with the error flag on
2443 DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller);
2451 // Copy static members to XHRDataSource class
2452 lang.augmentObject(util.XHRDataSource, DS);
2466 /****************************************************************************/
2467 /****************************************************************************/
2468 /****************************************************************************/
2471 * Factory class for creating a BaseDataSource subclass instance. The sublcass is
2472 * determined by oLiveData's type, unless the dataType config is explicitly passed in.
2474 * @namespace YAHOO.util
2475 * @class YAHOO.util.DataSource
2477 * @param oLiveData {HTMLElement} Pointer to live data.
2478 * @param oConfigs {object} (optional) Object literal of configuration values.
2480 util.DataSource = function(oLiveData, oConfigs) {
2481 oConfigs = oConfigs || {};
2483 // Point to one of the subclasses, first by dataType if given, then by sniffing oLiveData type.
2484 var dataType = oConfigs.dataType;
2486 if(dataType == DS.TYPE_LOCAL) {
2487 lang.augmentObject(util.DataSource, util.LocalDataSource);
2488 return new util.LocalDataSource(oLiveData, oConfigs);
2490 else if(dataType == DS.TYPE_XHR) {
2491 lang.augmentObject(util.DataSource, util.XHRDataSource);
2492 return new util.XHRDataSource(oLiveData, oConfigs);
2494 else if(dataType == DS.TYPE_SCRIPTNODE) {
2495 lang.augmentObject(util.DataSource, util.ScriptNodeDataSource);
2496 return new util.ScriptNodeDataSource(oLiveData, oConfigs);
2498 else if(dataType == DS.TYPE_JSFUNCTION) {
2499 lang.augmentObject(util.DataSource, util.FunctionDataSource);
2500 return new util.FunctionDataSource(oLiveData, oConfigs);
2504 if(YAHOO.lang.isString(oLiveData)) { // strings default to xhr
2505 lang.augmentObject(util.DataSource, util.XHRDataSource);
2506 return new util.XHRDataSource(oLiveData, oConfigs);
2508 else if(YAHOO.lang.isFunction(oLiveData)) {
2509 lang.augmentObject(util.DataSource, util.FunctionDataSource);
2510 return new util.FunctionDataSource(oLiveData, oConfigs);
2512 else { // ultimate default is local
2513 lang.augmentObject(util.DataSource, util.LocalDataSource);
2514 return new util.LocalDataSource(oLiveData, oConfigs);
2518 // Copy static members to DataSource class
2519 lang.augmentObject(util.DataSource, DS);
2523 /****************************************************************************/
2524 /****************************************************************************/
2525 /****************************************************************************/
2528 * The static Number class provides helper functions to deal with data of type
2531 * @namespace YAHOO.util
2536 YAHOO.util.Number = {
2539 * Takes a native JavaScript Number and formats to string for display to user.
2542 * @param nData {Number} Number.
2543 * @param oConfig {Object} (Optional) Optional configuration values:
2545 * <dt>prefix {String}</dd>
2546 * <dd>String prepended before each number, like a currency designator "$"</dd>
2547 * <dt>decimalPlaces {Number}</dd>
2548 * <dd>Number of decimal places to round.</dd>
2549 * <dt>decimalSeparator {String}</dd>
2550 * <dd>Decimal separator</dd>
2551 * <dt>thousandsSeparator {String}</dd>
2552 * <dd>Thousands separator</dd>
2553 * <dt>suffix {String}</dd>
2554 * <dd>String appended after each number, like " items" (note the space)</dd>
2556 * @return {String} Formatted number for display. Note, the following values
2557 * return as "": null, undefined, NaN, "".
2559 format : function(nData, oConfig) {
2560 var lang = YAHOO.lang;
2561 if(!lang.isValue(nData) || (nData === "")) {
2565 oConfig = oConfig || {};
2567 if(!lang.isNumber(nData)) {
2571 if(lang.isNumber(nData)) {
2572 var bNegative = (nData < 0);
2573 var sOutput = nData + "";
2574 var sDecimalSeparator = (oConfig.decimalSeparator) ? oConfig.decimalSeparator : ".";
2578 if(lang.isNumber(oConfig.decimalPlaces)) {
2579 // Round to the correct decimal place
2580 var nDecimalPlaces = oConfig.decimalPlaces;
2581 var nDecimal = Math.pow(10, nDecimalPlaces);
2582 sOutput = Math.round(nData*nDecimal)/nDecimal + "";
2583 nDotIndex = sOutput.lastIndexOf(".");
2585 if(nDecimalPlaces > 0) {
2586 // Add the decimal separator
2588 sOutput += sDecimalSeparator;
2589 nDotIndex = sOutput.length-1;
2592 else if(sDecimalSeparator !== "."){
2593 sOutput = sOutput.replace(".",sDecimalSeparator);
2595 // Add missing zeros
2596 while((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) {
2602 // Add the thousands separator
2603 if(oConfig.thousandsSeparator) {
2604 var sThousandsSeparator = oConfig.thousandsSeparator;
2605 nDotIndex = sOutput.lastIndexOf(sDecimalSeparator);
2606 nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length;
2607 var sNewOutput = sOutput.substring(nDotIndex);
2609 for (var i=nDotIndex; i>0; i--) {
2611 if ((nCount%3 === 0) && (i !== nDotIndex) && (!bNegative || (i > 1))) {
2612 sNewOutput = sThousandsSeparator + sNewOutput;
2614 sNewOutput = sOutput.charAt(i-1) + sNewOutput;
2616 sOutput = sNewOutput;
2620 sOutput = (oConfig.prefix) ? oConfig.prefix + sOutput : sOutput;
2623 sOutput = (oConfig.suffix) ? sOutput + oConfig.suffix : sOutput;
2627 // Still not a Number, just return unaltered
2636 /****************************************************************************/
2637 /****************************************************************************/
2638 /****************************************************************************/
2642 var xPad=function (x, pad, r)
2644 if(typeof r === 'undefined')
2648 for( ; parseInt(x, 10)<r && r>1; r/=10) {
2649 x = pad.toString() + x;
2651 return x.toString();
2656 * The static Date class provides helper functions to deal with data of type Date.
2658 * @namespace YAHOO.util
2665 a: function (d, l) { return l.a[d.getDay()]; },
2666 A: function (d, l) { return l.A[d.getDay()]; },
2667 b: function (d, l) { return l.b[d.getMonth()]; },
2668 B: function (d, l) { return l.B[d.getMonth()]; },
2669 C: function (d) { return xPad(parseInt(d.getFullYear()/100, 10), 0); },
2670 d: ['getDate', '0'],
2671 e: ['getDate', ' '],
2672 g: function (d) { return xPad(parseInt(Dt.formats.G(d)%100, 10), 0); },
2674 var y = d.getFullYear();
2675 var V = parseInt(Dt.formats.V(d), 10);
2676 var W = parseInt(Dt.formats.W(d), 10);
2680 } else if(W===0 && V>=52) {
2686 H: ['getHours', '0'],
2687 I: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, 0); },
2689 var gmd_1 = new Date('' + d.getFullYear() + '/1/1 GMT');
2690 var gmdate = new Date('' + d.getFullYear() + '/' + (d.getMonth()+1) + '/' + d.getDate() + ' GMT');
2691 var ms = gmdate - gmd_1;
2692 var doy = parseInt(ms/60000/60/24, 10)+1;
2693 return xPad(doy, 0, 100);
2695 k: ['getHours', ' '],
2696 l: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, ' '); },
2697 m: function (d) { return xPad(d.getMonth()+1, 0); },
2698 M: ['getMinutes', '0'],
2699 p: function (d, l) { return l.p[d.getHours() >= 12 ? 1 : 0 ]; },
2700 P: function (d, l) { return l.P[d.getHours() >= 12 ? 1 : 0 ]; },
2701 s: function (d, l) { return parseInt(d.getTime()/1000, 10); },
2702 S: ['getSeconds', '0'],
2703 u: function (d) { var dow = d.getDay(); return dow===0?7:dow; },
2705 var doy = parseInt(Dt.formats.j(d), 10);
2706 var rdow = 6-d.getDay();
2707 var woy = parseInt((doy+rdow)/7, 10);
2708 return xPad(woy, 0);
2711 var woy = parseInt(Dt.formats.W(d), 10);
2712 var dow1_1 = (new Date('' + d.getFullYear() + '/1/1')).getDay();
2713 // First week is 01 and not 00 as in the case of %U and %W,
2714 // so we add 1 to the final result except if day 1 of the year
2715 // is a Monday (then %W returns 01).
2716 // We also need to subtract 1 if the day 1 of the year is
2717 // Friday-Sunday, so the resulting equation becomes:
2718 var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1);
2719 if(idow === 53 && (new Date('' + d.getFullYear() + '/12/31')).getDay() < 4)
2725 idow = Dt.formats.V(new Date('' + (d.getFullYear()-1) + '/12/31'));
2728 return xPad(idow, 0);
2732 var doy = parseInt(Dt.formats.j(d), 10);
2733 var rdow = 7-Dt.formats.u(d);
2734 var woy = parseInt((doy+rdow)/7, 10);
2735 return xPad(woy, 0, 10);
2737 y: function (d) { return xPad(d.getFullYear()%100, 0); },
2740 var o = d.getTimezoneOffset();
2741 var H = xPad(parseInt(Math.abs(o/60), 10), 0);
2742 var M = xPad(Math.abs(o%60), 0);
2743 return (o>0?'-':'+') + H + M;
2746 var tz = d.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/, '$2').replace(/[a-z ]/g, '');
2748 tz = Dt.formats.z(d);
2752 '%': function (d) { return '%'; }
2767 //'+': '%a %b %e %T %Z %Y'
2771 * Takes a native JavaScript Date and formats to string for display to user.
2774 * @param oDate {Date} Date.
2775 * @param oConfig {Object} (Optional) Object literal of configuration values:
2777 * <dt>format <String></dt>
2780 * Any strftime string is supported, such as "%I:%M:%S %p". strftime has several format specifiers defined by the Open group at
2781 * <a href="http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html">http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html</a>
2784 * PHP added a few of its own, defined at <a href="http://www.php.net/strftime">http://www.php.net/strftime</a>
2787 * This javascript implementation supports all the PHP specifiers and a few more. The full list is below:
2790 * <dt>%a</dt> <dd>abbreviated weekday name according to the current locale</dd>
2791 * <dt>%A</dt> <dd>full weekday name according to the current locale</dd>
2792 * <dt>%b</dt> <dd>abbreviated month name according to the current locale</dd>
2793 * <dt>%B</dt> <dd>full month name according to the current locale</dd>
2794 * <dt>%c</dt> <dd>preferred date and time representation for the current locale</dd>
2795 * <dt>%C</dt> <dd>century number (the year divided by 100 and truncated to an integer, range 00 to 99)</dd>
2796 * <dt>%d</dt> <dd>day of the month as a decimal number (range 01 to 31)</dd>
2797 * <dt>%D</dt> <dd>same as %m/%d/%y</dd>
2798 * <dt>%e</dt> <dd>day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')</dd>
2799 * <dt>%F</dt> <dd>same as %Y-%m-%d (ISO 8601 date format)</dd>
2800 * <dt>%g</dt> <dd>like %G, but without the century</dd>
2801 * <dt>%G</dt> <dd>The 4-digit year corresponding to the ISO week number</dd>
2802 * <dt>%h</dt> <dd>same as %b</dd>
2803 * <dt>%H</dt> <dd>hour as a decimal number using a 24-hour clock (range 00 to 23)</dd>
2804 * <dt>%I</dt> <dd>hour as a decimal number using a 12-hour clock (range 01 to 12)</dd>
2805 * <dt>%j</dt> <dd>day of the year as a decimal number (range 001 to 366)</dd>
2806 * <dt>%k</dt> <dd>hour as a decimal number using a 24-hour clock (range 0 to 23); single digits are preceded by a blank. (See also %H.)</dd>
2807 * <dt>%l</dt> <dd>hour as a decimal number using a 12-hour clock (range 1 to 12); single digits are preceded by a blank. (See also %I.) </dd>
2808 * <dt>%m</dt> <dd>month as a decimal number (range 01 to 12)</dd>
2809 * <dt>%M</dt> <dd>minute as a decimal number</dd>
2810 * <dt>%n</dt> <dd>newline character</dd>
2811 * <dt>%p</dt> <dd>either `AM' or `PM' according to the given time value, or the corresponding strings for the current locale</dd>
2812 * <dt>%P</dt> <dd>like %p, but lower case</dd>
2813 * <dt>%r</dt> <dd>time in a.m. and p.m. notation equal to %I:%M:%S %p</dd>
2814 * <dt>%R</dt> <dd>time in 24 hour notation equal to %H:%M</dd>
2815 * <dt>%s</dt> <dd>number of seconds since the Epoch, ie, since 1970-01-01 00:00:00 UTC</dd>
2816 * <dt>%S</dt> <dd>second as a decimal number</dd>
2817 * <dt>%t</dt> <dd>tab character</dd>
2818 * <dt>%T</dt> <dd>current time, equal to %H:%M:%S</dd>
2819 * <dt>%u</dt> <dd>weekday as a decimal number [1,7], with 1 representing Monday</dd>
2820 * <dt>%U</dt> <dd>week number of the current year as a decimal number, starting with the
2821 * first Sunday as the first day of the first week</dd>
2822 * <dt>%V</dt> <dd>The ISO 8601:1988 week number of the current year as a decimal number,
2823 * range 01 to 53, where week 1 is the first week that has at least 4 days
2824 * in the current year, and with Monday as the first day of the week.</dd>
2825 * <dt>%w</dt> <dd>day of the week as a decimal, Sunday being 0</dd>
2826 * <dt>%W</dt> <dd>week number of the current year as a decimal number, starting with the
2827 * first Monday as the first day of the first week</dd>
2828 * <dt>%x</dt> <dd>preferred date representation for the current locale without the time</dd>
2829 * <dt>%X</dt> <dd>preferred time representation for the current locale without the date</dd>
2830 * <dt>%y</dt> <dd>year as a decimal number without a century (range 00 to 99)</dd>
2831 * <dt>%Y</dt> <dd>year as a decimal number including the century</dd>
2832 * <dt>%z</dt> <dd>numerical time zone representation</dd>
2833 * <dt>%Z</dt> <dd>time zone name or abbreviation</dd>
2834 * <dt>%%</dt> <dd>a literal `%' character</dd>
2838 * @param sLocale {String} (Optional) The locale to use when displaying days of week,
2839 * months of the year, and other locale specific strings. The following locales are
2845 * <dd>US English</dd>
2847 * <dd>British English</dd>
2849 * <dd>Australian English (identical to British English)</dd>
2851 * More locales may be added by subclassing of YAHOO.util.DateLocale.
2852 * See YAHOO.util.DateLocale for more information.
2853 * @return {String} Formatted date for display.
2854 * @sa YAHOO.util.DateLocale
2856 format : function (oDate, oConfig, sLocale) {
2857 oConfig = oConfig || {};
2859 if(!(oDate instanceof Date)) {
2860 return YAHOO.lang.isValue(oDate) ? oDate : "";
2863 var format = oConfig.format || "%m/%d/%Y";
2865 // Be backwards compatible, support strings that are
2866 // exactly equal to YYYY/MM/DD, DD/MM/YYYY and MM/DD/YYYY
2867 if(format === 'YYYY/MM/DD') {
2868 format = '%Y/%m/%d';
2869 } else if(format === 'DD/MM/YYYY') {
2870 format = '%d/%m/%Y';
2871 } else if(format === 'MM/DD/YYYY') {
2872 format = '%m/%d/%Y';
2874 // end backwards compatibility block
2876 sLocale = sLocale || "en";
2878 // Make sure we have a definition for the requested locale, or default to en.
2879 if(!(sLocale in YAHOO.util.DateLocale)) {
2880 if(sLocale.replace(/-[a-zA-Z]+$/, '') in YAHOO.util.DateLocale) {
2881 sLocale = sLocale.replace(/-[a-zA-Z]+$/, '');
2887 var aLocale = YAHOO.util.DateLocale[sLocale];
2889 var replace_aggs = function (m0, m1) {
2890 var f = Dt.aggregates[m1];
2891 return (f === 'locale' ? aLocale[m1] : f);
2894 var replace_formats = function (m0, m1) {
2895 var f = Dt.formats[m1];
2896 if(typeof f === 'string') { // string => built in date function
2898 } else if(typeof f === 'function') { // function => our own function
2899 return f.call(oDate, oDate, aLocale);
2900 } else if(typeof f === 'object' && typeof f[0] === 'string') { // built in function with padding
2901 return xPad(oDate[f[0]](), f[1]);
2907 // First replace aggregates (run in a loop because an agg may be made up of other aggs)
2908 while(format.match(/%[cDFhnrRtTxX]/)) {
2909 format = format.replace(/%([cDFhnrRtTxX])/g, replace_aggs);
2912 // Now replace formats (do not run in a loop otherwise %%a will be replace with the value of %a)
2913 var str = format.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g, replace_formats);
2915 replace_aggs = replace_formats = undefined;
2921 YAHOO.namespace("YAHOO.util");
2922 YAHOO.util.Date = Dt;
2925 * The DateLocale class is a container and base class for all
2926 * localised date strings used by YAHOO.util.Date. It is used
2927 * internally, but may be extended to provide new date localisations.
2929 * To create your own DateLocale, follow these steps:
2931 * <li>Find an existing locale that matches closely with your needs</li>
2932 * <li>Use this as your base class. Use YAHOO.util.DateLocale if nothing
2934 * <li>Create your own class as an extension of the base class using
2935 * YAHOO.lang.merge, and add your own localisations where needed.</li>
2937 * See the YAHOO.util.DateLocale['en-US'] and YAHOO.util.DateLocale['en-GB']
2938 * classes which extend YAHOO.util.DateLocale['en'].
2940 * For example, to implement locales for French french and Canadian french,
2941 * we would do the following:
2943 * <li>For French french, we have no existing similar locale, so use
2944 * YAHOO.util.DateLocale as the base, and extend it:
2946 * YAHOO.util.DateLocale['fr'] = YAHOO.lang.merge(YAHOO.util.DateLocale, {
2947 * a: ['dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam'],
2948 * A: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
2949 * b: ['jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jui', 'aoû', 'sep', 'oct', 'nov', 'déc'],
2950 * B: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
2951 * c: '%a %d %b %Y %T %Z',
2959 * <li>For Canadian french, we start with French french and change the meaning of \%x:
2961 * YAHOO.util.DateLocale['fr-CA'] = YAHOO.lang.merge(YAHOO.util.DateLocale['fr'], {
2968 * With that, you can use your new locales:
2970 * var d = new Date("2008/04/22");
2971 * YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr");
2975 * mardi, 22 avril == 22.04.2008
2979 * YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr-CA");
2983 * mardi, 22 avril == 2008-04-22
2985 * @namespace YAHOO.util
2989 YAHOO.util.DateLocale = {
2990 a: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
2991 A: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
2992 b: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
2993 B: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
2994 c: '%a %d %b %Y %T %Z',
3002 YAHOO.util.DateLocale['en'] = YAHOO.lang.merge(YAHOO.util.DateLocale, {});
3004 YAHOO.util.DateLocale['en-US'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], {
3005 c: '%a %d %b %Y %I:%M:%S %p %Z',
3010 YAHOO.util.DateLocale['en-GB'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], {
3013 YAHOO.util.DateLocale['en-AU'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en']);
3017 YAHOO.register("datasource", YAHOO.util.DataSource, {version: "2.7.0", build: "1799"});