PageRenderTime 59ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/src/main/resources/org/apache/struts2/static/datasource/datasource-debug.js

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