1 /* http://keith-wood.name/countdown.html
2 Countdown for jQuery v1.5.8.
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. */
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}); */
13 (function($) { // Hide scope, no $ conflict
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 timeSeparator: ':', // Separator for time periods
26 isRTL: false // True for right-to-left languages, false for left-to-right
29 until: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count down to
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 since: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count up from
33 // or numeric for seconds offset, or string for unit offset(s):
34 // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
35 timezone: null, // The timezone (hours or minutes from GMT) for the target times,
36 // or null for client local
37 serverSync: null, // A function to retrieve the current server time for synchronisation
38 format: 'dHMS', // Format for display - upper case for always, lower case only if non-zero,
39 // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
40 layout: '', // Build your own layout for the countdown
41 compact: false, // True to display in a compact format, false for an expanded one
42 significant: 0, // The number of periods with values to show, zero for all
43 description: '', // The description displayed for the countdown
44 expiryUrl: '', // A URL to load upon expiry, replacing the current page
45 expiryText: '', // Text to display upon expiry, replacing the countdown
46 alwaysExpire: false, // True to trigger onExpiry even if never counted down
47 onExpiry: null, // Callback when the countdown expires -
48 // receives no parameters and 'this' is the containing division
49 onTick: null, // Callback when the countdown is updated -
50 // receives int[7] being the breakdown by period (based on format)
51 // and 'this' is the containing division
52 tickInterval: 1 // Interval (seconds) between onTick callbacks
54 $.extend(this._defaults, this.regional['']);
55 this._serverSyncs = [];
58 var PROP_NAME = 'countdown';
68 $.extend(Countdown.prototype, {
69 /* Class name added to elements to indicate already configured with countdown. */
70 markerClassName: 'hasCountdown',
72 /* Shared timer for all countdowns. */
73 _timer: setInterval(function() { $.countdown._updateTargets(); }, 980),
74 /* List of currently active countdown targets. */
77 /* Override the default settings for all instances of the countdown widget.
78 @param options (object) the new settings to use as defaults */
79 setDefaults: function(options) {
80 this._resetExtraLabels(this._defaults, options);
81 extendRemove(this._defaults, options || {});
84 /* Convert a date/time to UTC.
85 @param tz (number) the hour or minute offset from GMT, e.g. +9, -360
86 @param year (Date) the date/time in that timezone or
87 (number) the year in that timezone
88 @param month (number, optional) the month (0 - 11) (omit if year is a Date)
89 @param day (number, optional) the day (omit if year is a Date)
90 @param hours (number, optional) the hour (omit if year is a Date)
91 @param mins (number, optional) the minute (omit if year is a Date)
92 @param secs (number, optional) the second (omit if year is a Date)
93 @param ms (number, optional) the millisecond (omit if year is a Date)
94 @return (Date) the equivalent UTC date/time */
95 UTCDate: function(tz, year, month, day, hours, mins, secs, ms) {
96 if (typeof year == 'object' && year.constructor == Date) {
97 ms = year.getMilliseconds();
98 secs = year.getSeconds();
99 mins = year.getMinutes();
100 hours = year.getHours();
101 day = year.getDate();
102 month = year.getMonth();
103 year = year.getFullYear();
106 d.setUTCFullYear(year);
108 d.setUTCMonth(month || 0);
109 d.setUTCDate(day || 1);
110 d.setUTCHours(hours || 0);
111 d.setUTCMinutes((mins || 0) - (Math.abs(tz) < 30 ? tz * 60 : tz));
112 d.setUTCSeconds(secs || 0);
113 d.setUTCMilliseconds(ms || 0);
117 /* Convert a set of periods into seconds.
118 Averaged for months and years.
119 @param periods (number[7]) the periods per year/month/week/day/hour/minute/second
120 @return (number) the corresponding number of seconds */
121 periodsToSeconds: function(periods) {
122 return periods[0] * 31557600 + periods[1] * 2629800 + periods[2] * 604800 +
123 periods[3] * 86400 + periods[4] * 3600 + periods[5] * 60 + periods[6];
126 /* Retrieve one or more settings values.
127 @param name (string, optional) the name of the setting to retrieve
128 or 'all' for all instance settings or omit for all default settings
129 @return (any) the requested setting(s) */
130 _settingsCountdown: function(target, name) {
132 return $.countdown._defaults;
134 var inst = $.data(target, PROP_NAME);
135 return (name == 'all' ? inst.options : inst.options[name]);
138 /* Attach the countdown widget to a div.
139 @param target (element) the containing division
140 @param options (object) the initial settings for the countdown */
141 _attachCountdown: function(target, options) {
142 var $target = $(target);
143 if ($target.hasClass(this.markerClassName)) {
146 $target.addClass(this.markerClassName);
147 var inst = {options: $.extend({}, options),
148 _periods: [0, 0, 0, 0, 0, 0, 0]};
149 $.data(target, PROP_NAME, inst);
150 this._changeCountdown(target);
153 /* Add a target to the list of active ones.
154 @param target (element) the countdown target */
155 _addTarget: function(target) {
156 if (!this._hasTarget(target)) {
157 this._timerTargets.push(target);
161 /* See if a target is in the list of active ones.
162 @param target (element) the countdown target
163 @return (boolean) true if present, false if not */
164 _hasTarget: function(target) {
165 return ($.inArray(target, this._timerTargets) > -1);
168 /* Remove a target from the list of active ones.
169 @param target (element) the countdown target */
170 _removeTarget: function(target) {
171 this._timerTargets = $.map(this._timerTargets,
172 function(value) { return (value == target ? null : value); }); // delete entry
175 /* Update each active timer target. */
176 _updateTargets: function() {
177 for (var i = this._timerTargets.length - 1; i >= 0; i--) {
178 this._updateCountdown(this._timerTargets[i]);
182 /* Redisplay the countdown with an updated display.
183 @param target (jQuery) the containing division
184 @param inst (object) the current settings for this instance */
185 _updateCountdown: function(target, inst) {
186 var $target = $(target);
187 inst = inst || $.data(target, PROP_NAME);
191 $target.html(this._generateHTML(inst));
192 $target[(this._get(inst, 'isRTL') ? 'add' : 'remove') + 'Class']('countdown_rtl');
193 var onTick = this._get(inst, 'onTick');
195 var periods = inst._hold != 'lap' ? inst._periods :
196 this._calculatePeriods(inst, inst._show, this._get(inst, 'significant'), new Date());
197 var tickInterval = this._get(inst, 'tickInterval');
198 if (tickInterval == 1 || this.periodsToSeconds(periods) % tickInterval == 0) {
199 onTick.apply(target, [periods]);
202 var expired = inst._hold != 'pause' &&
203 (inst._since ? inst._now.getTime() < inst._since.getTime() :
204 inst._now.getTime() >= inst._until.getTime());
205 if (expired && !inst._expiring) {
206 inst._expiring = true;
207 if (this._hasTarget(target) || this._get(inst, 'alwaysExpire')) {
208 this._removeTarget(target);
209 var onExpiry = this._get(inst, 'onExpiry');
211 onExpiry.apply(target, []);
213 var expiryText = this._get(inst, 'expiryText');
215 var layout = this._get(inst, 'layout');
216 inst.options.layout = expiryText;
217 this._updateCountdown(target, inst);
218 inst.options.layout = layout;
220 var expiryUrl = this._get(inst, 'expiryUrl');
222 window.location = expiryUrl;
225 inst._expiring = false;
227 else if (inst._hold == 'pause') {
228 this._removeTarget(target);
230 $.data(target, PROP_NAME, inst);
233 /* Reconfigure the settings for a countdown div.
234 @param target (element) the containing division
235 @param options (object) the new settings for the countdown or
236 (string) an individual property name
237 @param value (any) the individual property value
238 (omit if options is an object) */
239 _changeCountdown: function(target, options, value) {
240 options = options || {};
241 if (typeof options == 'string') {
244 options[name] = value;
246 var inst = $.data(target, PROP_NAME);
248 this._resetExtraLabels(inst.options, options);
249 extendRemove(inst.options, options);
250 this._adjustSettings(target, inst);
251 $.data(target, PROP_NAME, inst);
252 var now = new Date();
253 if ((inst._since && inst._since < now) ||
254 (inst._until && inst._until > now)) {
255 this._addTarget(target);
257 this._updateCountdown(target, inst);
261 /* Reset any extra labelsn and compactLabelsn entries if changing labels.
262 @param base (object) the options to be updated
263 @param options (object) the new option values */
264 _resetExtraLabels: function(base, options) {
265 var changingLabels = false;
266 for (var n in options) {
267 if (n != 'whichLabels' && n.match(/[Ll]abels/)) {
268 changingLabels = true;
272 if (changingLabels) {
273 for (var n in base) { // Remove custom numbered labels
274 if (n.match(/[Ll]abels[0-9]/)) {
281 /* Calculate interal settings for an instance.
282 @param target (element) the containing division
283 @param inst (object) the current settings for this instance */
284 _adjustSettings: function(target, inst) {
286 var serverSync = this._get(inst, 'serverSync');
287 var serverOffset = 0;
288 var serverEntry = null;
289 for (var i = 0; i < this._serverSyncs.length; i++) {
290 if (this._serverSyncs[i][0] == serverSync) {
291 serverEntry = this._serverSyncs[i][1];
295 if (serverEntry != null) {
296 serverOffset = (serverSync ? serverEntry : 0);
300 var serverResult = (serverSync ? serverSync.apply(target, []) : null);
302 serverOffset = (serverResult ? now.getTime() - serverResult.getTime() : 0);
303 this._serverSyncs.push([serverSync, serverOffset]);
305 var timezone = this._get(inst, 'timezone');
306 timezone = (timezone == null ? -now.getTimezoneOffset() : timezone);
307 inst._since = this._get(inst, 'since');
308 if (inst._since != null) {
309 inst._since = this.UTCDate(timezone, this._determineTime(inst._since, null));
310 if (inst._since && serverOffset) {
311 inst._since.setMilliseconds(inst._since.getMilliseconds() + serverOffset);
314 inst._until = this.UTCDate(timezone, this._determineTime(this._get(inst, 'until'), now));
316 inst._until.setMilliseconds(inst._until.getMilliseconds() + serverOffset);
318 inst._show = this._determineShow(inst);
321 /* Remove the countdown widget from a div.
322 @param target (element) the containing division */
323 _destroyCountdown: function(target) {
324 var $target = $(target);
325 if (!$target.hasClass(this.markerClassName)) {
328 this._removeTarget(target);
329 $target.removeClass(this.markerClassName).empty();
330 $.removeData(target, PROP_NAME);
333 /* Pause a countdown widget at the current time.
334 Stop it running but remember and display the current time.
335 @param target (element) the containing division */
336 _pauseCountdown: function(target) {
337 this._hold(target, 'pause');
340 /* Pause a countdown widget at the current time.
341 Stop the display but keep the countdown running.
342 @param target (element) the containing division */
343 _lapCountdown: function(target) {
344 this._hold(target, 'lap');
347 /* Resume a paused countdown widget.
348 @param target (element) the containing division */
349 _resumeCountdown: function(target) {
350 this._hold(target, null);
353 /* Pause or resume a countdown widget.
354 @param target (element) the containing division
355 @param hold (string) the new hold setting */
356 _hold: function(target, hold) {
357 var inst = $.data(target, PROP_NAME);
359 if (inst._hold == 'pause' && !hold) {
360 inst._periods = inst._savePeriods;
361 var sign = (inst._since ? '-' : '+');
362 inst[inst._since ? '_since' : '_until'] =
363 this._determineTime(sign + inst._periods[0] + 'y' +
364 sign + inst._periods[1] + 'o' + sign + inst._periods[2] + 'w' +
365 sign + inst._periods[3] + 'd' + sign + inst._periods[4] + 'h' +
366 sign + inst._periods[5] + 'm' + sign + inst._periods[6] + 's');
367 this._addTarget(target);
370 inst._savePeriods = (hold == 'pause' ? inst._periods : null);
371 $.data(target, PROP_NAME, inst);
372 this._updateCountdown(target, inst);
376 /* Return the current time periods.
377 @param target (element) the containing division
378 @return (number[7]) the current periods for the countdown */
379 _getTimesCountdown: function(target) {
380 var inst = $.data(target, PROP_NAME);
381 return (!inst ? null : (!inst._hold ? inst._periods :
382 this._calculatePeriods(inst, inst._show, this._get(inst, 'significant'), new Date())));
385 /* Get a setting value, defaulting if necessary.
386 @param inst (object) the current settings for this instance
387 @param name (string) the name of the required setting
388 @return (any) the setting's value or a default if not overridden */
389 _get: function(inst, name) {
390 return (inst.options[name] != null ?
391 inst.options[name] : $.countdown._defaults[name]);
394 /* A time may be specified as an exact value or a relative one.
395 @param setting (string or number or Date) - the date/time value
396 as a relative or absolute value
397 @param defaultTime (Date) the date/time to use if no other is supplied
398 @return (Date) the corresponding date/time */
399 _determineTime: function(setting, defaultTime) {
400 var offsetNumeric = function(offset) { // e.g. +300, -2
401 var time = new Date();
402 time.setTime(time.getTime() + offset * 1000);
405 var offsetString = function(offset) { // e.g. '+2d', '-4w', '+3h +30m'
406 offset = offset.toLowerCase();
407 var time = new Date();
408 var year = time.getFullYear();
409 var month = time.getMonth();
410 var day = time.getDate();
411 var hour = time.getHours();
412 var minute = time.getMinutes();
413 var second = time.getSeconds();
414 var pattern = /([+-]?[0-9]+)\s*(s|m|h|d|w|o|y)?/g;
415 var matches = pattern.exec(offset);
417 switch (matches[2] || 's') {
418 case 's': second += parseInt(matches[1], 10); break;
419 case 'm': minute += parseInt(matches[1], 10); break;
420 case 'h': hour += parseInt(matches[1], 10); break;
421 case 'd': day += parseInt(matches[1], 10); break;
422 case 'w': day += parseInt(matches[1], 10) * 7; break;
424 month += parseInt(matches[1], 10);
425 day = Math.min(day, $.countdown._getDaysInMonth(year, month));
428 year += parseInt(matches[1], 10);
429 day = Math.min(day, $.countdown._getDaysInMonth(year, month));
432 matches = pattern.exec(offset);
434 return new Date(year, month, day, hour, minute, second, 0);
436 var time = (setting == null ? defaultTime :
437 (typeof setting == 'string' ? offsetString(setting) :
438 (typeof setting == 'number' ? offsetNumeric(setting) : setting)));
439 if (time) time.setMilliseconds(0);
443 /* Determine the number of days in a month.
444 @param year (number) the year
445 @param month (number) the month
446 @return (number) the days in that month */
447 _getDaysInMonth: function(year, month) {
448 return 32 - new Date(year, month, 32).getDate();
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) {
458 /* Generate the HTML to display the countdown widget.
459 @param inst (object) the current settings for this instance
460 @return (string) the new HTML for the countdown display */
461 _generateHTML: function(inst) {
462 // Determine what to show
463 var significant = this._get(inst, 'significant');
464 inst._periods = (inst._hold ? inst._periods :
465 this._calculatePeriods(inst, inst._show, significant, new Date()));
466 // Show all 'asNeeded' after first non-zero value
467 var shownNonZero = false;
469 var sigCount = significant;
470 var show = $.extend({}, inst._show);
471 for (var period = Y; period <= S; period++) {
472 shownNonZero |= (inst._show[period] == '?' && inst._periods[period] > 0);
473 show[period] = (inst._show[period] == '?' && !shownNonZero ? null : inst._show[period]);
474 showCount += (show[period] ? 1 : 0);
475 sigCount -= (inst._periods[period] > 0 ? 1 : 0);
477 var showSignificant = [false, false, false, false, false, false, false];
478 for (var period = S; period >= Y; period--) { // Determine significant periods
479 if (inst._show[period]) {
480 if (inst._periods[period]) {
481 showSignificant[period] = true;
484 showSignificant[period] = sigCount > 0;
489 var compact = this._get(inst, 'compact');
490 var layout = this._get(inst, 'layout');
491 var labels = (compact ? this._get(inst, 'compactLabels') : this._get(inst, 'labels'));
492 var whichLabels = this._get(inst, 'whichLabels') || this._normalLabels;
493 var timeSeparator = this._get(inst, 'timeSeparator');
494 var description = this._get(inst, 'description') || '';
495 var showCompact = function(period) {
496 var labelsNum = $.countdown._get(inst,
497 'compactLabels' + whichLabels(inst._periods[period]));
498 return (show[period] ? inst._periods[period] +
499 (labelsNum ? labelsNum[period] : labels[period]) + ' ' : '');
501 var showFull = function(period) {
502 var labelsNum = $.countdown._get(inst, 'labels' + whichLabels(inst._periods[period]));
503 return ((!significant && show[period]) || (significant && showSignificant[period]) ?
504 '<span class="countdown_section"><span class="countdown_amount">' +
505 inst._periods[period] + '</span><br/>' +
506 (labelsNum ? labelsNum[period] : labels[period]) + '</span>' : '');
508 return (layout ? this._buildLayout(inst, show, layout, compact, significant, showSignificant) :
509 ((compact ? // Compact version
510 '<span class="countdown_row countdown_amount' +
511 (inst._hold ? ' countdown_holding' : '') + '">' +
512 showCompact(Y) + showCompact(O) + showCompact(W) + showCompact(D) +
513 (show[H] ? this._minDigits(inst._periods[H], 2) : '') +
514 (show[M] ? (show[H] ? timeSeparator : '') +
515 this._minDigits(inst._periods[M], 2) : '') +
516 (show[S] ? (show[H] || show[M] ? timeSeparator : '') +
517 this._minDigits(inst._periods[S], 2) : '') :
519 '<span class="countdown_row countdown_show' + (significant || showCount) +
520 (inst._hold ? ' countdown_holding' : '') + '">' +
521 showFull(Y) + showFull(O) + showFull(W) + showFull(D) +
522 showFull(H) + showFull(M) + showFull(S)) + '</span>' +
523 (description ? '<span class="countdown_row countdown_descr">' + description + '</span>' : '')));
526 /* Construct a custom layout.
527 @param inst (object) the current settings for this instance
528 @param show (string[7]) flags indicating which periods are requested
529 @param layout (string) the customised layout
530 @param compact (boolean) true if using compact labels
531 @param significant (number) the number of periods with values to show, zero for all
532 @param showSignificant (boolean[7]) other periods to show for significance
533 @return (string) the custom HTML */
534 _buildLayout: function(inst, show, layout, compact, significant, showSignificant) {
535 var labels = this._get(inst, (compact ? 'compactLabels' : 'labels'));
536 var whichLabels = this._get(inst, 'whichLabels') || this._normalLabels;
537 var labelFor = function(index) {
538 return ($.countdown._get(inst,
539 (compact ? 'compactLabels' : 'labels') + whichLabels(inst._periods[index])) ||
542 var digit = function(value, position) {
543 return Math.floor(value / position) % 10;
545 var subs = {desc: this._get(inst, 'description'), sep: this._get(inst, 'timeSeparator'),
546 yl: labelFor(Y), yn: inst._periods[Y], ynn: this._minDigits(inst._periods[Y], 2),
547 ynnn: this._minDigits(inst._periods[Y], 3), y1: digit(inst._periods[Y], 1),
548 y10: digit(inst._periods[Y], 10), y100: digit(inst._periods[Y], 100),
549 y1000: digit(inst._periods[Y], 1000),
550 ol: labelFor(O), on: inst._periods[O], onn: this._minDigits(inst._periods[O], 2),
551 onnn: this._minDigits(inst._periods[O], 3), o1: digit(inst._periods[O], 1),
552 o10: digit(inst._periods[O], 10), o100: digit(inst._periods[O], 100),
553 o1000: digit(inst._periods[O], 1000),
554 wl: labelFor(W), wn: inst._periods[W], wnn: this._minDigits(inst._periods[W], 2),
555 wnnn: this._minDigits(inst._periods[W], 3), w1: digit(inst._periods[W], 1),
556 w10: digit(inst._periods[W], 10), w100: digit(inst._periods[W], 100),
557 w1000: digit(inst._periods[W], 1000),
558 dl: labelFor(D), dn: inst._periods[D], dnn: this._minDigits(inst._periods[D], 2),
559 dnnn: this._minDigits(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: inst._periods[H], hnn: this._minDigits(inst._periods[H], 2),
563 hnnn: this._minDigits(inst._periods[H], 3), h1: digit(inst._periods[H], 1),
564 h10: digit(inst._periods[H], 10), h100: digit(inst._periods[H], 100),
565 h1000: digit(inst._periods[H], 1000),
566 ml: labelFor(M), mn: inst._periods[M], mnn: this._minDigits(inst._periods[M], 2),
567 mnnn: this._minDigits(inst._periods[M], 3), m1: digit(inst._periods[M], 1),
568 m10: digit(inst._periods[M], 10), m100: digit(inst._periods[M], 100),
569 m1000: digit(inst._periods[M], 1000),
570 sl: labelFor(S), sn: inst._periods[S], snn: this._minDigits(inst._periods[S], 2),
571 snnn: this._minDigits(inst._periods[S], 3), s1: digit(inst._periods[S], 1),
572 s10: digit(inst._periods[S], 10), s100: digit(inst._periods[S], 100),
573 s1000: digit(inst._periods[S], 1000)};
575 // Replace period containers: {p<}...{p>}
576 for (var i = Y; i <= S; i++) {
577 var period = 'yowdhms'.charAt(i);
578 var re = new RegExp('\\{' + period + '<\\}(.*)\\{' + period + '>\\}', 'g');
579 html = html.replace(re, ((!significant && show[i]) ||
580 (significant && showSignificant[i]) ? '$1' : ''));
582 // Replace period values: {pn}
583 $.each(subs, function(n, v) {
584 var re = new RegExp('\\{' + n + '\\}', 'g');
585 html = html.replace(re, v);
590 /* Ensure a numeric value has at least n digits for display.
591 @param value (number) the value to display
592 @param len (number) the minimum length
593 @return (string) the display text */
594 _minDigits: function(value, len) {
596 if (value.length >= len) {
599 value = '0000000000' + value;
600 return value.substr(value.length - len);
603 /* Translate the format into flags for each period.
604 @param inst (object) the current settings for this instance
605 @return (string[7]) flags indicating which periods are requested (?) or
606 required (!) by year, month, week, day, hour, minute, second */
607 _determineShow: function(inst) {
608 var format = this._get(inst, 'format');
610 show[Y] = (format.match('y') ? '?' : (format.match('Y') ? '!' : null));
611 show[O] = (format.match('o') ? '?' : (format.match('O') ? '!' : null));
612 show[W] = (format.match('w') ? '?' : (format.match('W') ? '!' : null));
613 show[D] = (format.match('d') ? '?' : (format.match('D') ? '!' : null));
614 show[H] = (format.match('h') ? '?' : (format.match('H') ? '!' : null));
615 show[M] = (format.match('m') ? '?' : (format.match('M') ? '!' : null));
616 show[S] = (format.match('s') ? '?' : (format.match('S') ? '!' : null));
620 /* Calculate the requested periods between now and the target time.
621 @param inst (object) the current settings for this instance
622 @param show (string[7]) flags indicating which periods are requested/required
623 @param significant (number) the number of periods with values to show, zero for all
624 @param now (Date) the current date and time
625 @return (number[7]) the current time periods (always positive)
626 by year, month, week, day, hour, minute, second */
627 _calculatePeriods: function(inst, show, significant, now) {
630 inst._now.setMilliseconds(0);
631 var until = new Date(inst._now.getTime());
633 if (now.getTime() < inst._since.getTime()) {
634 inst._now = now = until;
641 until.setTime(inst._until.getTime());
642 if (now.getTime() > inst._until.getTime()) {
643 inst._now = now = until;
646 // Calculate differences by period
647 var periods = [0, 0, 0, 0, 0, 0, 0];
648 if (show[Y] || show[O]) {
649 // Treat end of months as the same
650 var lastNow = $.countdown._getDaysInMonth(now.getFullYear(), now.getMonth());
651 var lastUntil = $.countdown._getDaysInMonth(until.getFullYear(), until.getMonth());
652 var sameDay = (until.getDate() == now.getDate() ||
653 (until.getDate() >= Math.min(lastNow, lastUntil) &&
654 now.getDate() >= Math.min(lastNow, lastUntil)));
655 var getSecs = function(date) {
656 return (date.getHours() * 60 + date.getMinutes()) * 60 + date.getSeconds();
658 var months = Math.max(0,
659 (until.getFullYear() - now.getFullYear()) * 12 + until.getMonth() - now.getMonth() +
660 ((until.getDate() < now.getDate() && !sameDay) ||
661 (sameDay && getSecs(until) < getSecs(now)) ? -1 : 0));
662 periods[Y] = (show[Y] ? Math.floor(months / 12) : 0);
663 periods[O] = (show[O] ? months - periods[Y] * 12 : 0);
664 // Adjust for months difference and end of month if necessary
665 now = new Date(now.getTime());
666 var wasLastDay = (now.getDate() == lastNow);
667 var lastDay = $.countdown._getDaysInMonth(now.getFullYear() + periods[Y],
668 now.getMonth() + periods[O]);
669 if (now.getDate() > lastDay) {
670 now.setDate(lastDay);
672 now.setFullYear(now.getFullYear() + periods[Y]);
673 now.setMonth(now.getMonth() + periods[O]);
675 now.setDate(lastDay);
678 var diff = Math.floor((until.getTime() - now.getTime()) / 1000);
679 var extractPeriod = function(period, numSecs) {
680 periods[period] = (show[period] ? Math.floor(diff / numSecs) : 0);
681 diff -= periods[period] * numSecs;
683 extractPeriod(W, 604800);
684 extractPeriod(D, 86400);
685 extractPeriod(H, 3600);
686 extractPeriod(M, 60);
688 if (diff > 0 && !inst._since) { // Round up if left overs
689 var multiplier = [1, 12, 4.3482, 7, 24, 60, 60];
692 for (var period = S; period >= Y; period--) {
694 if (periods[lastShown] >= max) {
695 periods[lastShown] = 0;
705 max *= multiplier[period];
708 if (significant) { // Zero out insignificant periods
709 for (var period = Y; period <= S; period++) {
710 if (significant && periods[period]) {
713 else if (!significant) {
722 /* jQuery extend now ignores nulls!
723 @param target (object) the object to update
724 @param props (object) the new settings
725 @return (object) the updated object */
726 function extendRemove(target, props) {
727 $.extend(target, props);
728 for (var name in props) {
729 if (props[name] == null) {
736 /* Process the countdown functionality for a jQuery selection.
737 @param command (string) the command to run (optional, default 'attach')
738 @param options (object) the new settings to use for these countdown instances
739 @return (jQuery) for chaining further calls */
740 $.fn.countdown = function(options) {
741 var otherArgs = Array.prototype.slice.call(arguments, 1);
742 if (options == 'getTimes' || options == 'settings') {
743 return $.countdown['_' + options + 'Countdown'].
744 apply($.countdown, [this[0]].concat(otherArgs));
746 return this.each(function() {
747 if (typeof options == 'string') {
748 $.countdown['_' + options + 'Countdown'].apply($.countdown, [this].concat(otherArgs));
751 $.countdown._attachCountdown(this, options);
756 /* Initialise the countdown functionality. */
757 $.countdown = new Countdown(); // singleton instance