Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

811 wiersze
32 KiB

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