Guest User

jquery.countdown.js

a guest
Oct 24th, 2012
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 32.20 KB | None | 0 0
  1. /* http://keith-wood.name/countdown.html
  2. Countdown for jQuery v1.6.0.
  3. Written by Keith Wood (kbwood{at}iinet.com.au) January 2008.
  4. Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and
  5. MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses.
  6. Please attribute the author if you use it. */
  7.  
  8. /* Display a countdown timer.
  9. Attach it with options like:
  10. $('div selector').countdown(
  11. {until: new Date(2009, 1 - 1, 1, 0, 0, 0), onExpiry: happyNewYear}); */
  12.  
  13. (function($) { // Hide scope, no $ conflict
  14.  
  15. /* Countdown manager. */
  16. function Countdown() {
  17. this.regional = []; // Available regional settings, indexed by language code
  18. this.regional[''] = { // Default regional settings
  19. // The display texts for the counters
  20. labels: ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'],
  21. // The display texts for the counters if only one
  22. labels1: ['Year', 'Month', 'Week', 'Day', 'Hour', 'Minute', 'Second'],
  23. compactLabels: ['y', 'm', 'w', 'd'], // The compact texts for the counters
  24. whichLabels: null, // Function to determine which labels to use
  25. digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], // The digits to display
  26. timeSeparator: ':', // Separator for time periods
  27. isRTL: false // True for right-to-left languages, false for left-to-right
  28. };
  29. this._defaults = {
  30. until: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count down to
  31. // or numeric for seconds offset, or string for unit offset(s):
  32. // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
  33. since: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count up from
  34. // or numeric for seconds offset, or string for unit offset(s):
  35. // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
  36. timezone: null, // The timezone (hours or minutes from GMT) for the target times,
  37. // or null for client local
  38. serverSync: null, // A function to retrieve the current server time for synchronisation
  39. format: 'dHMS', // Format for display - upper case for always, lower case only if non-zero,
  40. // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
  41. layout: '', // Build your own layout for the countdown
  42. compact: false, // True to display in a compact format, false for an expanded one
  43. significant: 0, // The number of periods with values to show, zero for all
  44. description: '', // The description displayed for the countdown
  45. expiryUrl: '', // A URL to load upon expiry, replacing the current page
  46. expiryText: '', // Text to display upon expiry, replacing the countdown
  47. alwaysExpire: false, // True to trigger onExpiry even if never counted down
  48. onExpiry: null, // Callback when the countdown expires -
  49. // receives no parameters and 'this' is the containing division
  50. onTick: null, // Callback when the countdown is updated -
  51. // receives int[7] being the breakdown by period (based on format)
  52. // and 'this' is the containing division
  53. tickInterval: 1 // Interval (seconds) between onTick callbacks
  54. };
  55. $.extend(this._defaults, this.regional['']);
  56. this._serverSyncs = [];
  57. // Shared timer for all countdowns
  58. function timerCallBack(timestamp) {
  59. var drawStart = (timestamp || new Date().getTime());
  60. if (drawStart - animationStartTime >= 1000) {
  61. plugin._updateTargets();
  62. animationStartTime = drawStart;
  63. }
  64. requestAnimationFrame(timerCallBack);
  65. }
  66. var requestAnimationFrame = window.requestAnimationFrame ||
  67. window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame ||
  68. window.oRequestAnimationFrame || window.msRequestAnimationFrame || null;
  69. // This is when we expect a fall-back to setInterval as it's much more fluid
  70. var animationStartTime = 0;
  71. if (!requestAnimationFrame || $.noRequestAnimationFrame) {
  72. $.noRequestAnimationFrame = null;
  73. setInterval(function() { plugin._updateTargets(); }, 980); // Fall back to good old setInterval
  74. }
  75. else {
  76. animationStartTime = window.mozAnimationStartTime || new Date().getTime();
  77. requestAnimationFrame(timerCallBack);
  78. }
  79. }
  80.  
  81. var Y = 0; // Years
  82. var O = 1; // Months
  83. var W = 2; // Weeks
  84. var D = 3; // Days
  85. var H = 4; // Hours
  86. var M = 5; // Minutes
  87. var S = 6; // Seconds
  88.  
  89. $.extend(Countdown.prototype, {
  90. /* Class name added to elements to indicate already configured with countdown. */
  91. markerClassName: 'hasCountdown',
  92. /* Name of the data property for instance settings. */
  93. propertyName: 'countdown',
  94.  
  95. /* Class name for the right-to-left marker. */
  96. _rtlClass: 'countdown_rtl',
  97. /* Class name for the countdown section marker. */
  98. _sectionClass: 'countdown_section',
  99. /* Class name for the period amount marker. */
  100. _amountClass: 'countdown_amount',
  101. /* Class name for the countdown row marker. */
  102. _rowClass: 'countdown_row',
  103. /* Class name for the holding countdown marker. */
  104. _holdingClass: 'countdown_holding',
  105. /* Class name for the showing countdown marker. */
  106. _showClass: 'countdown_show',
  107. /* Class name for the description marker. */
  108. _descrClass: 'countdown_descr',
  109.  
  110. /* List of currently active countdown targets. */
  111. _timerTargets: [],
  112.  
  113. /* Override the default settings for all instances of the countdown widget.
  114. @param options (object) the new settings to use as defaults */
  115. setDefaults: function(options) {
  116. this._resetExtraLabels(this._defaults, options);
  117. $.extend(this._defaults, options || {});
  118. },
  119.  
  120. /* Convert a date/time to UTC.
  121. @param tz (number) the hour or minute offset from GMT, e.g. +9, -360
  122. @param year (Date) the date/time in that timezone or
  123. (number) the year in that timezone
  124. @param month (number, optional) the month (0 - 11) (omit if year is a Date)
  125. @param day (number, optional) the day (omit if year is a Date)
  126. @param hours (number, optional) the hour (omit if year is a Date)
  127. @param mins (number, optional) the minute (omit if year is a Date)
  128. @param secs (number, optional) the second (omit if year is a Date)
  129. @param ms (number, optional) the millisecond (omit if year is a Date)
  130. @return (Date) the equivalent UTC date/time */
  131. UTCDate: function(tz, year, month, day, hours, mins, secs, ms) {
  132. if (typeof year == 'object' && year.constructor == Date) {
  133. ms = year.getMilliseconds();
  134. secs = year.getSeconds();
  135. mins = year.getMinutes();
  136. hours = year.getHours();
  137. day = year.getDate();
  138. month = year.getMonth();
  139. year = year.getFullYear();
  140. }
  141. var d = new Date();
  142. d.setUTCFullYear(year);
  143. d.setUTCDate(1);
  144. d.setUTCMonth(month || 0);
  145. d.setUTCDate(day || 1);
  146. d.setUTCHours(hours || 0);
  147. d.setUTCMinutes((mins || 0) - (Math.abs(tz) < 30 ? tz * 60 : tz));
  148. d.setUTCSeconds(secs || 0);
  149. d.setUTCMilliseconds(ms || 0);
  150. return d;
  151. },
  152.  
  153. /* Convert a set of periods into seconds.
  154. Averaged for months and years.
  155. @param periods (number[7]) the periods per year/month/week/day/hour/minute/second
  156. @return (number) the corresponding number of seconds */
  157. periodsToSeconds: function(periods) {
  158. return periods[0] * 31557600 + periods[1] * 2629800 + periods[2] * 604800 +
  159. periods[3] * 86400 + periods[4] * 3600 + periods[5] * 60 + periods[6];
  160. },
  161.  
  162. /* Attach the countdown widget to a div.
  163. @param target (element) the containing division
  164. @param options (object) the initial settings for the countdown */
  165. _attachPlugin: function(target, options) {
  166. target = $(target);
  167. if (target.hasClass(this.markerClassName)) {
  168. return;
  169. }
  170. var inst = {options: $.extend({}, this._defaults), _periods: [0, 0, 0, 0, 0, 0, 0]};
  171. target.addClass(this.markerClassName).data(this.propertyName, inst);
  172. this._optionPlugin(target, options);
  173. },
  174.  
  175. /* Add a target to the list of active ones.
  176. @param target (element) the countdown target */
  177. _addTarget: function(target) {
  178. if (!this._hasTarget(target)) {
  179. this._timerTargets.push(target);
  180. }
  181. },
  182.  
  183. /* See if a target is in the list of active ones.
  184. @param target (element) the countdown target
  185. @return (boolean) true if present, false if not */
  186. _hasTarget: function(target) {
  187. return ($.inArray(target, this._timerTargets) > -1);
  188. },
  189.  
  190. /* Remove a target from the list of active ones.
  191. @param target (element) the countdown target */
  192. _removeTarget: function(target) {
  193. this._timerTargets = $.map(this._timerTargets,
  194. function(value) { return (value == target ? null : value); }); // delete entry
  195. },
  196.  
  197. /* Update each active timer target. */
  198. _updateTargets: function() {
  199. for (var i = this._timerTargets.length - 1; i >= 0; i--) {
  200. this._updateCountdown(this._timerTargets[i]);
  201. }
  202. },
  203.  
  204. /* Reconfigure the settings for a countdown div.
  205. @param target (element) the control to affect
  206. @param options (object) the new options for this instance or
  207. (string) an individual property name
  208. @param value (any) the individual property value (omit if options
  209. is an object or to retrieve the value of a setting)
  210. @return (any) if retrieving a value */
  211. _optionPlugin: function(target, options, value) {
  212. target = $(target);
  213. var inst = target.data(this.propertyName);
  214. if (!options || (typeof options == 'string' && value == null)) { // Get option
  215. var name = options;
  216. options = (inst || {}).options;
  217. return (options && name ? options[name] : options);
  218. }
  219.  
  220. if (!target.hasClass(this.markerClassName)) {
  221. return;
  222. }
  223. options = options || {};
  224. if (typeof options == 'string') {
  225. var name = options;
  226. options = {};
  227. options[name] = value;
  228. }
  229. this._resetExtraLabels(inst.options, options);
  230. $.extend(inst.options, options);
  231. this._adjustSettings(target, inst);
  232. var now = new Date();
  233. if ((inst._since && inst._since < now) || (inst._until && inst._until > now)) {
  234. this._addTarget(target);
  235. }
  236. this._updateCountdown(target, inst);
  237. },
  238.  
  239. /* Redisplay the countdown with an updated display.
  240. @param target (jQuery) the containing division
  241. @param inst (object) the current settings for this instance */
  242. _updateCountdown: function(target, inst) {
  243. var $target = $(target);
  244. inst = inst || $target.data(this.propertyName);
  245. if (!inst) {
  246. return;
  247. }
  248. $target.html(this._generateHTML(inst)).toggleClass(this._rtlClass, inst.options.isRTL);
  249. if ($.isFunction(inst.options.onTick)) {
  250. var periods = inst._hold != 'lap' ? inst._periods :
  251. this._calculatePeriods(inst, inst._show, inst.options.significant, new Date());
  252. if (inst.options.tickInterval == 1 ||
  253. this.periodsToSeconds(periods) % inst.options.tickInterval == 0) {
  254. inst.options.onTick.apply(target, [periods]);
  255. }
  256. }
  257. var expired = inst._hold != 'pause' &&
  258. (inst._since ? inst._now.getTime() < inst._since.getTime() :
  259. inst._now.getTime() >= inst._until.getTime());
  260. if (expired && !inst._expiring) {
  261. inst._expiring = true;
  262. if (this._hasTarget(target) || inst.options.alwaysExpire) {
  263. this._removeTarget(target);
  264. if ($.isFunction(inst.options.onExpiry)) {
  265. inst.options.onExpiry.apply(target, []);
  266. }
  267. if (inst.options.expiryText) {
  268. var layout = inst.options.layout;
  269. inst.options.layout = inst.options.expiryText;
  270. this._updateCountdown(target, inst);
  271. inst.options.layout = layout;
  272. }
  273. if (inst.options.expiryUrl) {
  274. window.location = inst.options.expiryUrl;
  275. }
  276. }
  277. inst._expiring = false;
  278. }
  279. else if (inst._hold == 'pause') {
  280. this._removeTarget(target);
  281. }
  282. $target.data(this.propertyName, inst);
  283. },
  284.  
  285. /* Reset any extra labelsn and compactLabelsn entries if changing labels.
  286. @param base (object) the options to be updated
  287. @param options (object) the new option values */
  288. _resetExtraLabels: function(base, options) {
  289. var changingLabels = false;
  290. for (var n in options) {
  291. if (n != 'whichLabels' && n.match(/[Ll]abels/)) {
  292. changingLabels = true;
  293. break;
  294. }
  295. }
  296. if (changingLabels) {
  297. for (var n in base) { // Remove custom numbered labels
  298. if (n.match(/[Ll]abels[02-9]/)) {
  299. base[n] = null;
  300. }
  301. }
  302. }
  303. },
  304.  
  305. /* Calculate interal settings for an instance.
  306. @param target (element) the containing division
  307. @param inst (object) the current settings for this instance */
  308. _adjustSettings: function(target, inst) {
  309. var now;
  310. var serverOffset = 0;
  311. var serverEntry = null;
  312. for (var i = 0; i < this._serverSyncs.length; i++) {
  313. if (this._serverSyncs[i][0] == inst.options.serverSync) {
  314. serverEntry = this._serverSyncs[i][1];
  315. break;
  316. }
  317. }
  318. if (serverEntry != null) {
  319. serverOffset = (inst.options.serverSync ? serverEntry : 0);
  320. now = new Date();
  321. }
  322. else {
  323. var serverResult = ($.isFunction(inst.options.serverSync) ?
  324. inst.options.serverSync.apply(target, []) : null);
  325. now = new Date();
  326. serverOffset = (serverResult ? now.getTime() - serverResult.getTime() : 0);
  327. this._serverSyncs.push([inst.options.serverSync, serverOffset]);
  328. }
  329. var timezone = inst.options.timezone;
  330. timezone = (timezone == null ? -now.getTimezoneOffset() : timezone);
  331. inst._since = inst.options.since;
  332. if (inst._since != null) {
  333. inst._since = this.UTCDate(timezone, this._determineTime(inst._since, null));
  334. if (inst._since && serverOffset) {
  335. inst._since.setMilliseconds(inst._since.getMilliseconds() + serverOffset);
  336. }
  337. }
  338. inst._until = this.UTCDate(timezone, this._determineTime(inst.options.until, now));
  339. if (serverOffset) {
  340. inst._until.setMilliseconds(inst._until.getMilliseconds() + serverOffset);
  341. }
  342. inst._show = this._determineShow(inst);
  343. },
  344.  
  345. /* Remove the countdown widget from a div.
  346. @param target (element) the containing division */
  347. _destroyPlugin: function(target) {
  348. target = $(target);
  349. if (!target.hasClass(this.markerClassName)) {
  350. return;
  351. }
  352. this._removeTarget(target[0]);
  353. target.removeClass(this.markerClassName).empty().removeData(this.propertyName);
  354. },
  355.  
  356. /* Pause a countdown widget at the current time.
  357. Stop it running but remember and display the current time.
  358. @param target (element) the containing division */
  359. _pausePlugin: function(target) {
  360. this._hold(target, 'pause');
  361. },
  362.  
  363. /* Pause a countdown widget at the current time.
  364. Stop the display but keep the countdown running.
  365. @param target (element) the containing division */
  366. _lapPlugin: function(target) {
  367. this._hold(target, 'lap');
  368. },
  369.  
  370. /* Resume a paused countdown widget.
  371. @param target (element) the containing division */
  372. _resumePlugin: function(target) {
  373. this._hold(target, null);
  374. },
  375.  
  376. /* Pause or resume a countdown widget.
  377. @param target (element) the containing division
  378. @param hold (string) the new hold setting */
  379. _hold: function(target, hold) {
  380. var inst = $.data(target, this.propertyName);
  381. if (inst) {
  382. if (inst._hold == 'pause' && !hold) {
  383. inst._periods = inst._savePeriods;
  384. var sign = (inst._since ? '-' : '+');
  385. inst[inst._since ? '_since' : '_until'] =
  386. this._determineTime(sign + inst._periods[0] + 'y' +
  387. sign + inst._periods[1] + 'o' + sign + inst._periods[2] + 'w' +
  388. sign + inst._periods[3] + 'd' + sign + inst._periods[4] + 'h' +
  389. sign + inst._periods[5] + 'm' + sign + inst._periods[6] + 's');
  390. this._addTarget(target);
  391. }
  392. inst._hold = hold;
  393. inst._savePeriods = (hold == 'pause' ? inst._periods : null);
  394. $.data(target, this.propertyName, inst);
  395. this._updateCountdown(target, inst);
  396. }
  397. },
  398.  
  399. /* Return the current time periods.
  400. @param target (element) the containing division
  401. @return (number[7]) the current periods for the countdown */
  402. _getTimesPlugin: function(target) {
  403. var inst = $.data(target, this.propertyName);
  404. return (!inst ? null : (!inst._hold ? inst._periods :
  405. this._calculatePeriods(inst, inst._show, inst.options.significant, new Date())));
  406. },
  407.  
  408. /* A time may be specified as an exact value or a relative one.
  409. @param setting (string or number or Date) - the date/time value
  410. as a relative or absolute value
  411. @param defaultTime (Date) the date/time to use if no other is supplied
  412. @return (Date) the corresponding date/time */
  413. _determineTime: function(setting, defaultTime) {
  414. var offsetNumeric = function(offset) { // e.g. +300, -2
  415. var time = new Date();
  416. time.setTime(time.getTime() + offset * 1000);
  417. return time;
  418. };
  419. var offsetString = function(offset) { // e.g. '+2d', '-4w', '+3h +30m'
  420. offset = offset.toLowerCase();
  421. var time = new Date();
  422. var year = time.getFullYear();
  423. var month = time.getMonth();
  424. var day = time.getDate();
  425. var hour = time.getHours();
  426. var minute = time.getMinutes();
  427. var second = time.getSeconds();
  428. var pattern = /([+-]?[0-9]+)\s*(s|m|h|d|w|o|y)?/g;
  429. var matches = pattern.exec(offset);
  430. while (matches) {
  431. switch (matches[2] || 's') {
  432. case 's': second += parseInt(matches[1], 10); break;
  433. case 'm': minute += parseInt(matches[1], 10); break;
  434. case 'h': hour += parseInt(matches[1], 10); break;
  435. case 'd': day += parseInt(matches[1], 10); break;
  436. case 'w': day += parseInt(matches[1], 10) * 7; break;
  437. case 'o':
  438. month += parseInt(matches[1], 10);
  439. day = Math.min(day, plugin._getDaysInMonth(year, month));
  440. break;
  441. case 'y':
  442. year += parseInt(matches[1], 10);
  443. day = Math.min(day, plugin._getDaysInMonth(year, month));
  444. break;
  445. }
  446. matches = pattern.exec(offset);
  447. }
  448. return new Date(year, month, day, hour, minute, second, 0);
  449. };
  450. var time = (setting == null ? defaultTime :
  451. (typeof setting == 'string' ? offsetString(setting) :
  452. (typeof setting == 'number' ? offsetNumeric(setting) : setting)));
  453. if (time) time.setMilliseconds(0);
  454. return time;
  455. },
  456.  
  457. /* Determine the number of days in a month.
  458. @param year (number) the year
  459. @param month (number) the month
  460. @return (number) the days in that month */
  461. _getDaysInMonth: function(year, month) {
  462. return 32 - new Date(year, month, 32).getDate();
  463. },
  464.  
  465. /* Determine which set of labels should be used for an amount.
  466. @param num (number) the amount to be displayed
  467. @return (number) the set of labels to be used for this amount */
  468. _normalLabels: function(num) {
  469. return num;
  470. },
  471.  
  472. /* Generate the HTML to display the countdown widget.
  473. @param inst (object) the current settings for this instance
  474. @return (string) the new HTML for the countdown display */
  475. _generateHTML: function(inst) {
  476. var self = this;
  477. // Determine what to show
  478. inst._periods = (inst._hold ? inst._periods :
  479. this._calculatePeriods(inst, inst._show, inst.options.significant, new Date()));
  480. // Show all 'asNeeded' after first non-zero value
  481. var shownNonZero = false;
  482. var showCount = 0;
  483. var sigCount = inst.options.significant;
  484. var show = $.extend({}, inst._show);
  485. for (var period = Y; period <= S; period++) {
  486. shownNonZero |= (inst._show[period] == '?' && inst._periods[period] > 0);
  487. show[period] = (inst._show[period] == '?' && !shownNonZero ? null : inst._show[period]);
  488. showCount += (show[period] ? 1 : 0);
  489. sigCount -= (inst._periods[period] > 0 ? 1 : 0);
  490. }
  491. var showSignificant = [false, false, false, false, false, false, false];
  492. for (var period = S; period >= Y; period--) { // Determine significant periods
  493. if (inst._show[period]) {
  494. if (inst._periods[period]) {
  495. showSignificant[period] = true;
  496. }
  497. else {
  498. showSignificant[period] = sigCount > 0;
  499. sigCount--;
  500. }
  501. }
  502. }
  503. var labels = (inst.options.compact ? inst.options.compactLabels : inst.options.labels);
  504. var whichLabels = inst.options.whichLabels || this._normalLabels;
  505. var showCompact = function(period) {
  506. var labelsNum = inst.options['compactLabels' + whichLabels(inst._periods[period])];
  507. return (show[period] ? self._translateDigits(inst, inst._periods[period]) +
  508. (labelsNum ? labelsNum[period] : labels[period]) + ' ' : '');
  509. };
  510. var showFull = function(period) {
  511. var labelsNum = inst.options['labels' + whichLabels(inst._periods[period])];
  512. return ((!inst.options.significant && show[period]) ||
  513. (inst.options.significant && showSignificant[period]) ?
  514. '<span class="' + plugin._sectionClass + '">' +
  515. '<span class="' + plugin._amountClass + '">' +
  516. self._translateDigits(inst, inst._periods[period]) + '</span><br/>' +
  517. (labelsNum ? labelsNum[period] : labels[period]) + '</span>' : '');
  518. };
  519. return (inst.options.layout ? this._buildLayout(inst, show, inst.options.layout,
  520. inst.options.compact, inst.options.significant, showSignificant) :
  521. ((inst.options.compact ? // Compact version
  522. '<span class="' + this._rowClass + ' ' + this._amountClass +
  523. (inst._hold ? ' ' + this._holdingClass : '') + '">' +
  524. showCompact(Y) + showCompact(O) + showCompact(W) + showCompact(D) +
  525. (show[H] ? this._minDigits(inst, inst._periods[H], 2) : '') +
  526. (show[M] ? (show[H] ? inst.options.timeSeparator : '') +
  527. this._minDigits(inst, inst._periods[M], 2) : '') +
  528. (show[S] ? (show[H] || show[M] ? inst.options.timeSeparator : '') +
  529. this._minDigits(inst, inst._periods[S], 2) : '') :
  530. // Full version
  531. '<span class="' + this._rowClass + ' ' + this._showClass + (inst.options.significant || showCount) +
  532. (inst._hold ? ' ' + this._holdingClass : '') + '">' +
  533. showFull(Y) + showFull(O) + showFull(W) + showFull(D) +
  534. showFull(H) + showFull(M) + showFull(S)) + '</span>' +
  535. (inst.options.description ? '<span class="' + this._rowClass + ' ' + this._descrClass + '">' +
  536. inst.options.description + '</span>' : '')));
  537. },
  538.  
  539. /* Construct a custom layout.
  540. @param inst (object) the current settings for this instance
  541. @param show (string[7]) flags indicating which periods are requested
  542. @param layout (string) the customised layout
  543. @param compact (boolean) true if using compact labels
  544. @param significant (number) the number of periods with values to show, zero for all
  545. @param showSignificant (boolean[7]) other periods to show for significance
  546. @return (string) the custom HTML */
  547. _buildLayout: function(inst, show, layout, compact, significant, showSignificant) {
  548. var labels = inst.options[compact ? 'compactLabels' : 'labels'];
  549. var whichLabels = inst.options.whichLabels || this._normalLabels;
  550. var labelFor = function(index) {
  551. return (inst.options[(compact ? 'compactLabels' : 'labels') +
  552. whichLabels(inst._periods[index])] || labels)[index];
  553. };
  554. var digit = function(value, position) {
  555. return inst.options.digits[Math.floor(value / position) % 10];
  556. };
  557. var subs = {desc: inst.options.description, sep: inst.options.timeSeparator,
  558. yl: labelFor(Y), yn: this._minDigits(inst, inst._periods[Y], 1),
  559. ynn: this._minDigits(inst, inst._periods[Y], 2),
  560. ynnn: this._minDigits(inst, inst._periods[Y], 3), y1: digit(inst._periods[Y], 1),
  561. y10: digit(inst._periods[Y], 10), y100: digit(inst._periods[Y], 100),
  562. y1000: digit(inst._periods[Y], 1000),
  563. ol: labelFor(O), on: this._minDigits(inst, inst._periods[O], 1),
  564. onn: this._minDigits(inst, inst._periods[O], 2),
  565. onnn: this._minDigits(inst, inst._periods[O], 3), o1: digit(inst._periods[O], 1),
  566. o10: digit(inst._periods[O], 10), o100: digit(inst._periods[O], 100),
  567. o1000: digit(inst._periods[O], 1000),
  568. wl: labelFor(W), wn: this._minDigits(inst, inst._periods[W], 1),
  569. wnn: this._minDigits(inst, inst._periods[W], 2),
  570. wnnn: this._minDigits(inst, inst._periods[W], 3), w1: digit(inst._periods[W], 1),
  571. w10: digit(inst._periods[W], 10), w100: digit(inst._periods[W], 100),
  572. w1000: digit(inst._periods[W], 1000),
  573. dl: labelFor(D), dn: this._minDigits(inst, inst._periods[D], 1),
  574. dnn: this._minDigits(inst, inst._periods[D], 2),
  575. dnnn: this._minDigits(inst, inst._periods[D], 3), d1: digit(inst._periods[D], 1),
  576. d10: digit(inst._periods[D], 10), d100: digit(inst._periods[D], 100),
  577. d1000: digit(inst._periods[D], 1000),
  578. hl: labelFor(H), hn: this._minDigits(inst, inst._periods[H], 1),
  579. hnn: this._minDigits(inst, inst._periods[H], 2),
  580. hnnn: this._minDigits(inst, inst._periods[H], 3), h1: digit(inst._periods[H], 1),
  581. h10: digit(inst._periods[H], 10), h100: digit(inst._periods[H], 100),
  582. h1000: digit(inst._periods[H], 1000),
  583. ml: labelFor(M), mn: this._minDigits(inst, inst._periods[M], 1),
  584. mnn: this._minDigits(inst, inst._periods[M], 2),
  585. mnnn: this._minDigits(inst, inst._periods[M], 3), m1: digit(inst._periods[M], 1),
  586. m10: digit(inst._periods[M], 10), m100: digit(inst._periods[M], 100),
  587. m1000: digit(inst._periods[M], 1000),
  588. sl: labelFor(S), sn: this._minDigits(inst, inst._periods[S], 1),
  589. snn: this._minDigits(inst, inst._periods[S], 2),
  590. snnn: this._minDigits(inst, inst._periods[S], 3), s1: digit(inst._periods[S], 1),
  591. s10: digit(inst._periods[S], 10), s100: digit(inst._periods[S], 100),
  592. s1000: digit(inst._periods[S], 1000)};
  593. var html = layout;
  594. // Replace period containers: {p<}...{p>}
  595. for (var i = Y; i <= S; i++) {
  596. var period = 'yowdhms'.charAt(i);
  597. var re = new RegExp('\\{' + period + '<\\}(.*)\\{' + period + '>\\}', 'g');
  598. html = html.replace(re, ((!significant && show[i]) ||
  599. (significant && showSignificant[i]) ? '$1' : ''));
  600. }
  601. // Replace period values: {pn}
  602. $.each(subs, function(n, v) {
  603. var re = new RegExp('\\{' + n + '\\}', 'g');
  604. html = html.replace(re, v);
  605. });
  606. return html;
  607. },
  608.  
  609. /* Ensure a numeric value has at least n digits for display.
  610. @param inst (object) the current settings for this instance
  611. @param value (number) the value to display
  612. @param len (number) the minimum length
  613. @return (string) the display text */
  614. _minDigits: function(inst, value, len) {
  615. value = '' + value;
  616. if (value.length >= len) {
  617. return this._translateDigits(inst, value);
  618. }
  619. value = '0000000000' + value;
  620. return this._translateDigits(inst, value.substr(value.length - len));
  621. },
  622.  
  623. /* Translate digits into other representations.
  624. @param inst (object) the current settings for this instance
  625. @param value (string) the text to translate
  626. @return (string) the translated text */
  627. _translateDigits: function(inst, value) {
  628. return ('' + value).replace(/[0-9]/g, function(digit) {
  629. return inst.options.digits[digit];
  630. });
  631. },
  632.  
  633. /* Translate the format into flags for each period.
  634. @param inst (object) the current settings for this instance
  635. @return (string[7]) flags indicating which periods are requested (?) or
  636. required (!) by year, month, week, day, hour, minute, second */
  637. _determineShow: function(inst) {
  638. var format = inst.options.format;
  639. var show = [];
  640. show[Y] = (format.match('y') ? '?' : (format.match('Y') ? '!' : null));
  641. show[O] = (format.match('o') ? '?' : (format.match('O') ? '!' : null));
  642. show[W] = (format.match('w') ? '?' : (format.match('W') ? '!' : null));
  643. show[D] = (format.match('d') ? '?' : (format.match('D') ? '!' : null));
  644. show[H] = (format.match('h') ? '?' : (format.match('H') ? '!' : null));
  645. show[M] = (format.match('m') ? '?' : (format.match('M') ? '!' : null));
  646. show[S] = (format.match('s') ? '?' : (format.match('S') ? '!' : null));
  647. return show;
  648. },
  649.  
  650. /* Calculate the requested periods between now and the target time.
  651. @param inst (object) the current settings for this instance
  652. @param show (string[7]) flags indicating which periods are requested/required
  653. @param significant (number) the number of periods with values to show, zero for all
  654. @param now (Date) the current date and time
  655. @return (number[7]) the current time periods (always positive)
  656. by year, month, week, day, hour, minute, second */
  657. _calculatePeriods: function(inst, show, significant, now) {
  658. // Find endpoints
  659. inst._now = now;
  660. inst._now.setMilliseconds(0);
  661. var until = new Date(inst._now.getTime());
  662. if (inst._since) {
  663. if (now.getTime() < inst._since.getTime()) {
  664. inst._now = now = until;
  665. }
  666. else {
  667. now = inst._since;
  668. }
  669. }
  670. else {
  671. until.setTime(inst._until.getTime());
  672. if (now.getTime() > inst._until.getTime()) {
  673. inst._now = now = until;
  674. }
  675. }
  676. // Calculate differences by period
  677. var periods = [0, 0, 0, 0, 0, 0, 0];
  678. if (show[Y] || show[O]) {
  679. // Treat end of months as the same
  680. var lastNow = plugin._getDaysInMonth(now.getFullYear(), now.getMonth());
  681. var lastUntil = plugin._getDaysInMonth(until.getFullYear(), until.getMonth());
  682. var sameDay = (until.getDate() == now.getDate() ||
  683. (until.getDate() >= Math.min(lastNow, lastUntil) &&
  684. now.getDate() >= Math.min(lastNow, lastUntil)));
  685. var getSecs = function(date) {
  686. return (date.getHours() * 60 + date.getMinutes()) * 60 + date.getSeconds();
  687. };
  688. var months = Math.max(0,
  689. (until.getFullYear() - now.getFullYear()) * 12 + until.getMonth() - now.getMonth() +
  690. ((until.getDate() < now.getDate() && !sameDay) ||
  691. (sameDay && getSecs(until) < getSecs(now)) ? -1 : 0));
  692. periods[Y] = (show[Y] ? Math.floor(months / 12) : 0);
  693. periods[O] = (show[O] ? months - periods[Y] * 12 : 0);
  694. // Adjust for months difference and end of month if necessary
  695. now = new Date(now.getTime());
  696. var wasLastDay = (now.getDate() == lastNow);
  697. var lastDay = plugin._getDaysInMonth(now.getFullYear() + periods[Y],
  698. now.getMonth() + periods[O]);
  699. if (now.getDate() > lastDay) {
  700. now.setDate(lastDay);
  701. }
  702. now.setFullYear(now.getFullYear() + periods[Y]);
  703. now.setMonth(now.getMonth() + periods[O]);
  704. if (wasLastDay) {
  705. now.setDate(lastDay);
  706. }
  707. }
  708. var diff = Math.floor((until.getTime() - now.getTime()) / 1000);
  709. var extractPeriod = function(period, numSecs) {
  710. periods[period] = (show[period] ? Math.floor(diff / numSecs) : 0);
  711. diff -= periods[period] * numSecs;
  712. };
  713. extractPeriod(W, 604800);
  714. extractPeriod(D, 86400);
  715. extractPeriod(H, 3600);
  716. extractPeriod(M, 60);
  717. extractPeriod(S, 1);
  718. if (diff > 0 && !inst._since) { // Round up if left overs
  719. var multiplier = [1, 12, 4.3482, 7, 24, 60, 60];
  720. var lastShown = S;
  721. var max = 1;
  722. for (var period = S; period >= Y; period--) {
  723. if (show[period]) {
  724. if (periods[lastShown] >= max) {
  725. periods[lastShown] = 0;
  726. diff = 1;
  727. }
  728. if (diff > 0) {
  729. periods[period]++;
  730. diff = 0;
  731. lastShown = period;
  732. max = 1;
  733. }
  734. }
  735. max *= multiplier[period];
  736. }
  737. }
  738. if (significant) { // Zero out insignificant periods
  739. for (var period = Y; period <= S; period++) {
  740. if (significant && periods[period]) {
  741. significant--;
  742. }
  743. else if (!significant) {
  744. periods[period] = 0;
  745. }
  746. }
  747. }
  748. return periods;
  749. }
  750. });
  751.  
  752. // The list of commands that return values and don't permit chaining
  753. var getters = ['getTimes'];
  754.  
  755. /* Determine whether a command is a getter and doesn't permit chaining.
  756. @param command (string, optional) the command to run
  757. @param otherArgs ([], optional) any other arguments for the command
  758. @return true if the command is a getter, false if not */
  759. function isNotChained(command, otherArgs) {
  760. if (command == 'option' && (otherArgs.length == 0 ||
  761. (otherArgs.length == 1 && typeof otherArgs[0] == 'string'))) {
  762. return true;
  763. }
  764. return $.inArray(command, getters) > -1;
  765. }
  766.  
  767. /* Process the countdown functionality for a jQuery selection.
  768. @param options (object) the new settings to use for these instances (optional) or
  769. (string) the command to run (optional)
  770. @return (jQuery) for chaining further calls or
  771. (any) getter value */
  772. $.fn.countdown = function(options) {
  773. var otherArgs = Array.prototype.slice.call(arguments, 1);
  774. if (isNotChained(options, otherArgs)) {
  775. return plugin['_' + options + 'Plugin'].
  776. apply(plugin, [this[0]].concat(otherArgs));
  777. }
  778. return this.each(function() {
  779. if (typeof options == 'string') {
  780. if (!plugin['_' + options + 'Plugin']) {
  781. throw 'Unknown command: ' + options;
  782. }
  783. plugin['_' + options + 'Plugin'].
  784. apply(plugin, [this].concat(otherArgs));
  785. }
  786. else {
  787. plugin._attachPlugin(this, options || {});
  788. }
  789. });
  790. };
  791.  
  792. /* Initialise the countdown functionality. */
  793. var plugin = $.countdown = new Countdown(); // Singleton instance
  794.  
  795. })(jQuery);
Advertisement
Add Comment
Please, Sign In to add comment