jquery.countdown.js 33 KB

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