1 /* http://keith-wood.name/countdown.html
2 Countdown for jQuery v1.5.7.
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 /* Modified by Radek Czajka, Fundacja Nowoczesna Polska (radoslaw.czajka(at)nowoczesnapolska.org.pl) */
10 /* Display a countdown timer.
11 Attach it with options like:
12 $('div selector').countdown(
13 {until: new Date(2009, 1 - 1, 1, 0, 0, 0), onExpiry: happyNewYear}); */
15 (function($) { // Hide scope, no $ conflict
17 /* Countdown manager. */
18 function Countdown() {
19 this.regional = []; // Available regional settings, indexed by language code
20 this.regional[''] = { // Default regional settings
21 // The display texts for the counters
22 labels: ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'],
23 // The display texts for the counters if only one
24 labels1: ['Year', 'Month', 'Week', 'Day', 'Hour', 'Minute', 'Second'],
25 compactLabels: ['y', 'm', 'w', 'd'], // The compact texts for the counters
26 timeSeparator: ':', // Separator for time periods
27 isRTL: false, // True for right-to-left languages, false for left-to-right
28 which: function(n) {return n}
31 until: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count down to
32 // or numeric for seconds offset, or string for unit offset(s):
33 // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
34 since: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count up from
35 // or numeric for seconds offset, or string for unit offset(s):
36 // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
37 timezone: null, // The timezone (hours or minutes from GMT) for the target times,
38 // or null for client local
39 serverSync: null, // A function to retrieve the current server time for synchronisation
40 format: 'dHMS', // Format for display - upper case for always, lower case only if non-zero,
41 // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
42 layout: '', // Build your own layout for the countdown
43 compact: false, // True to display in a compact format, false for an expanded one
44 description: '', // The description displayed for the countdown
45 expiryUrl: '', // A URL to load upon expiry, replacing the current page
46 expiryText: '', // Text to display upon expiry, replacing the countdown
47 alwaysExpire: false, // True to trigger onExpiry even if never counted down
48 onExpiry: null, // Callback when the countdown expires -
49 // receives no parameters and 'this' is the containing division
50 onTick: null, // Callback when the countdown is updated -
51 // receives int[7] being the breakdown by period (based on format)
52 // and 'this' is the containing division
53 tickInterval: 1 // Interval (seconds) between onTick callbacks
55 $.extend(this._defaults, this.regional['']);
56 this._serverSyncs = [];
59 var PROP_NAME = 'countdown';
69 $.extend(Countdown.prototype, {
70 /* Class name added to elements to indicate already configured with countdown. */
71 markerClassName: 'hasCountdown',
73 /* Shared timer for all countdowns. */
74 _timer: setInterval(function() { $.countdown._updateTargets(); }, 980),
75 /* List of currently active countdown targets. */
78 /* Override the default settings for all instances of the countdown widget.
79 @param options (object) the new settings to use as defaults */
80 setDefaults: function(options) {
81 this._resetExtraLabels(this._defaults, options);
82 extendRemove(this._defaults, options || {});
85 /* Convert a date/time to UTC.
86 @param tz (number) the hour or minute offset from GMT, e.g. +9, -360
87 @param year (Date) the date/time in that timezone or
88 (number) the year in that timezone
89 @param month (number, optional) the month (0 - 11) (omit if year is a Date)
90 @param day (number, optional) the day (omit if year is a Date)
91 @param hours (number, optional) the hour (omit if year is a Date)
92 @param mins (number, optional) the minute (omit if year is a Date)
93 @param secs (number, optional) the second (omit if year is a Date)
94 @param ms (number, optional) the millisecond (omit if year is a Date)
95 @return (Date) the equivalent UTC date/time */
96 UTCDate: function(tz, year, month, day, hours, mins, secs, ms) {
97 if (typeof year == 'object' && year.constructor == Date) {
98 ms = year.getMilliseconds();
99 secs = year.getSeconds();
100 mins = year.getMinutes();
101 hours = year.getHours();
102 day = year.getDate();
103 month = year.getMonth();
104 year = year.getFullYear();
107 d.setUTCFullYear(year);
109 d.setUTCMonth(month || 0);
110 d.setUTCDate(day || 1);
111 d.setUTCHours(hours || 0);
112 d.setUTCMinutes((mins || 0) - (Math.abs(tz) < 30 ? tz * 60 : tz));
113 d.setUTCSeconds(secs || 0);
114 d.setUTCMilliseconds(ms || 0);
118 /* Convert a set of periods into seconds.
119 Averaged for months and years.
120 @param periods (number[7]) the periods per year/month/week/day/hour/minute/second
121 @return (number) the corresponding number of seconds */
122 periodsToSeconds: function(periods) {
123 return periods[0] * 31557600 + periods[1] * 2629800 + periods[2] * 604800 +
124 periods[3] * 86400 + periods[4] * 3600 + periods[5] * 60 + periods[6];
127 /* Retrieve one or more settings values.
128 @param name (string, optional) the name of the setting to retrieve
129 or 'all' for all instance settings or omit for all default settings
130 @return (any) the requested setting(s) */
131 _settingsCountdown: function(target, name) {
133 return $.countdown._defaults;
135 var inst = $.data(target, PROP_NAME);
136 return (name == 'all' ? inst.options : inst.options[name]);
139 /* Attach the countdown widget to a div.
140 @param target (element) the containing division
141 @param options (object) the initial settings for the countdown */
142 _attachCountdown: function(target, options) {
143 var $target = $(target);
144 if ($target.hasClass(this.markerClassName)) {
147 $target.addClass(this.markerClassName);
148 var inst = {options: $.extend({}, options),
149 _periods: [0, 0, 0, 0, 0, 0, 0]};
150 $.data(target, PROP_NAME, inst);
151 this._changeCountdown(target);
154 /* Add a target to the list of active ones.
155 @param target (element) the countdown target */
156 _addTarget: function(target) {
157 if (!this._hasTarget(target)) {
158 this._timerTargets.push(target);
162 /* See if a target is in the list of active ones.
163 @param target (element) the countdown target
164 @return (boolean) true if present, false if not */
165 _hasTarget: function(target) {
166 return ($.inArray(target, this._timerTargets) > -1);
169 /* Remove a target from the list of active ones.
170 @param target (element) the countdown target */
171 _removeTarget: function(target) {
172 this._timerTargets = $.map(this._timerTargets,
173 function(value) { return (value == target ? null : value); }); // delete entry
176 /* Update each active timer target. */
177 _updateTargets: function() {
178 for (var i = this._timerTargets.length - 1; i >= 0; i--) {
179 this._updateCountdown(this._timerTargets[i]);
183 /* Redisplay the countdown with an updated display.
184 @param target (jQuery) the containing division
185 @param inst (object) the current settings for this instance */
186 _updateCountdown: function(target, inst) {
187 var $target = $(target);
188 inst = inst || $.data(target, PROP_NAME);
192 $target.html(this._generateHTML(inst));
193 $target[(this._get(inst, 'isRTL') ? 'add' : 'remove') + 'Class']('countdown_rtl');
194 var onTick = this._get(inst, 'onTick');
196 var periods = inst._hold != 'lap' ? inst._periods :
197 this._calculatePeriods(inst, inst._show, new Date());
198 var tickInterval = this._get(inst, 'tickInterval');
199 if (tickInterval == 1 || this.periodsToSeconds(periods) % tickInterval == 0) {
200 onTick.apply(target, [periods]);
203 var expired = inst._hold != 'pause' &&
204 (inst._since ? inst._now.getTime() < inst._since.getTime() :
205 inst._now.getTime() >= inst._until.getTime());
206 if (expired && !inst._expiring) {
207 inst._expiring = true;
208 if (this._hasTarget(target) || this._get(inst, 'alwaysExpire')) {
209 this._removeTarget(target);
210 var onExpiry = this._get(inst, 'onExpiry');
212 onExpiry.apply(target, []);
214 var expiryText = this._get(inst, 'expiryText');
216 var layout = this._get(inst, 'layout');
217 inst.options.layout = expiryText;
218 this._updateCountdown(target, inst);
219 inst.options.layout = layout;
221 var expiryUrl = this._get(inst, 'expiryUrl');
223 window.location = expiryUrl;
226 inst._expiring = false;
228 else if (inst._hold == 'pause') {
229 this._removeTarget(target);
231 $.data(target, PROP_NAME, inst);
234 /* Reconfigure the settings for a countdown div.
235 @param target (element) the containing division
236 @param options (object) the new settings for the countdown or
237 (string) an individual property name
238 @param value (any) the individual property value
239 (omit if options is an object) */
240 _changeCountdown: function(target, options, value) {
241 options = options || {};
242 if (typeof options == 'string') {
245 options[name] = value;
247 var inst = $.data(target, PROP_NAME);
249 this._resetExtraLabels(inst.options, options);
250 extendRemove(inst.options, options);
251 this._adjustSettings(target, inst);
252 $.data(target, PROP_NAME, inst);
253 var now = new Date();
254 if ((inst._since && inst._since < now) ||
255 (inst._until && inst._until > now)) {
256 this._addTarget(target);
258 this._updateCountdown(target, inst);
262 /* Reset any extra labelsn and compactLabelsn entries if changing labels.
263 @param base (object) the options to be updated
264 @param options (object) the new option values */
265 _resetExtraLabels: function(base, options) {
266 var changingLabels = false;
267 for (var n in options) {
268 if (n.match(/[Ll]abels/)) {
269 changingLabels = true;
273 if (changingLabels) {
274 for (var n in base) { // Remove custom numbered labels
275 if (n.match(/[Ll]abels[0-9]/)) {
282 /* Calculate interal settings for an instance.
283 @param target (element) the containing division
284 @param inst (object) the current settings for this instance */
285 _adjustSettings: function(target, inst) {
287 var serverSync = this._get(inst, 'serverSync');
288 var serverOffset = 0;
289 var serverEntry = null;
290 for (var i = 0; i < this._serverSyncs.length; i++) {
291 if (this._serverSyncs[i][0] == serverSync) {
292 serverEntry = this._serverSyncs[i][1];
296 if (serverEntry != null) {
297 serverOffset = (serverSync ? serverEntry : 0);
301 var serverResult = (serverSync ? serverSync.apply(target, []) : null);
303 serverOffset = (serverResult ? now.getTime() - serverResult.getTime() : 0);
304 this._serverSyncs.push([serverSync, serverOffset]);
306 var timezone = this._get(inst, 'timezone');
307 timezone = (timezone == null ? -now.getTimezoneOffset() : timezone);
308 inst._since = this._get(inst, 'since');
309 if (inst._since != null) {
310 inst._since = this.UTCDate(timezone, this._determineTime(inst._since, null));
311 if (inst._since && serverOffset) {
312 inst._since.setMilliseconds(inst._since.getMilliseconds() + serverOffset);
315 inst._until = this.UTCDate(timezone, this._determineTime(this._get(inst, 'until'), now));
317 inst._until.setMilliseconds(inst._until.getMilliseconds() + serverOffset);
319 inst._show = this._determineShow(inst);
322 /* Remove the countdown widget from a div.
323 @param target (element) the containing division */
324 _destroyCountdown: function(target) {
325 var $target = $(target);
326 if (!$target.hasClass(this.markerClassName)) {
329 this._removeTarget(target);
330 $target.removeClass(this.markerClassName).empty();
331 $.removeData(target, PROP_NAME);
334 /* Pause a countdown widget at the current time.
335 Stop it running but remember and display the current time.
336 @param target (element) the containing division */
337 _pauseCountdown: function(target) {
338 this._hold(target, 'pause');
341 /* Pause a countdown widget at the current time.
342 Stop the display but keep the countdown running.
343 @param target (element) the containing division */
344 _lapCountdown: function(target) {
345 this._hold(target, 'lap');
348 /* Resume a paused countdown widget.
349 @param target (element) the containing division */
350 _resumeCountdown: function(target) {
351 this._hold(target, null);
354 /* Pause or resume a countdown widget.
355 @param target (element) the containing division
356 @param hold (string) the new hold setting */
357 _hold: function(target, hold) {
358 var inst = $.data(target, PROP_NAME);
360 if (inst._hold == 'pause' && !hold) {
361 inst._periods = inst._savePeriods;
362 var sign = (inst._since ? '-' : '+');
363 inst[inst._since ? '_since' : '_until'] =
364 this._determineTime(sign + inst._periods[0] + 'y' +
365 sign + inst._periods[1] + 'o' + sign + inst._periods[2] + 'w' +
366 sign + inst._periods[3] + 'd' + sign + inst._periods[4] + 'h' +
367 sign + inst._periods[5] + 'm' + sign + inst._periods[6] + 's');
368 this._addTarget(target);
371 inst._savePeriods = (hold == 'pause' ? inst._periods : null);
372 $.data(target, PROP_NAME, inst);
373 this._updateCountdown(target, inst);
377 /* Return the current time periods.
378 @param target (element) the containing division
379 @return (number[7]) the current periods for the countdown */
380 _getTimesCountdown: function(target) {
381 var inst = $.data(target, PROP_NAME);
382 return (!inst ? null : (!inst._hold ? inst._periods :
383 this._calculatePeriods(inst, inst._show, new Date())));
386 /* Get a setting value, defaulting if necessary.
387 @param inst (object) the current settings for this instance
388 @param name (string) the name of the required setting
389 @return (any) the setting's value or a default if not overridden */
390 _get: function(inst, name) {
391 return (inst.options[name] != null ?
392 inst.options[name] : $.countdown._defaults[name]);
395 /* A time may be specified as an exact value or a relative one.
396 @param setting (string or number or Date) - the date/time value
397 as a relative or absolute value
398 @param defaultTime (Date) the date/time to use if no other is supplied
399 @return (Date) the corresponding date/time */
400 _determineTime: function(setting, defaultTime) {
401 var offsetNumeric = function(offset) { // e.g. +300, -2
402 var time = new Date();
403 time.setTime(time.getTime() + offset * 1000);
406 var offsetString = function(offset) { // e.g. '+2d', '-4w', '+3h +30m'
407 offset = offset.toLowerCase();
408 var time = new Date();
409 var year = time.getFullYear();
410 var month = time.getMonth();
411 var day = time.getDate();
412 var hour = time.getHours();
413 var minute = time.getMinutes();
414 var second = time.getSeconds();
415 var pattern = /([+-]?[0-9]+)\s*(s|m|h|d|w|o|y)?/g;
416 var matches = pattern.exec(offset);
418 switch (matches[2] || 's') {
419 case 's': second += parseInt(matches[1], 10); break;
420 case 'm': minute += parseInt(matches[1], 10); break;
421 case 'h': hour += parseInt(matches[1], 10); break;
422 case 'd': day += parseInt(matches[1], 10); break;
423 case 'w': day += parseInt(matches[1], 10) * 7; break;
425 month += parseInt(matches[1], 10);
426 day = Math.min(day, $.countdown._getDaysInMonth(year, month));
429 year += parseInt(matches[1], 10);
430 day = Math.min(day, $.countdown._getDaysInMonth(year, month));
433 matches = pattern.exec(offset);
435 return new Date(year, month, day, hour, minute, second, 0);
437 var time = (setting == null ? defaultTime :
438 (typeof setting == 'string' ? offsetString(setting) :
439 (typeof setting == 'number' ? offsetNumeric(setting) : setting)));
440 if (time) time.setMilliseconds(0);
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();
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 // Determine what to show
457 inst._periods = periods = (inst._hold ? inst._periods :
458 this._calculatePeriods(inst, inst._show, new Date()));
459 // Show all 'asNeeded' after first non-zero value
460 var shownNonZero = false;
462 var show = $.extend({}, inst._show);
463 for (var period = 0; period < inst._show.length; period++) {
464 shownNonZero |= (inst._show[period] == '?' && periods[period] > 0);
465 show[period] = (inst._show[period] == '?' && !shownNonZero ? null : inst._show[period]);
466 showCount += (show[period] ? 1 : 0);
468 var compact = this._get(inst, 'compact');
469 var layout = this._get(inst, 'layout');
470 var labels = (compact ? this._get(inst, 'compactLabels') : this._get(inst, 'labels'));
471 var timeSeparator = this._get(inst, 'timeSeparator');
472 var description = this._get(inst, 'description') || '';
473 var showCompact = function(period) {
474 var labelsNum = $.countdown._get(inst, 'compactLabels' + periods[period]);
475 return (show[period] ? periods[period] +
476 (labelsNum ? labelsNum[period] : labels[period]) + ' ' : '');
478 var showFull = function(period) {
479 var which = $.countdown._get(inst, 'which');
481 var labelsNum = $.countdown._get(inst, 'labels' + which(periods[period]));
483 return (show[period] ?
484 '<span class="countdown_section"><span class="countdown_amount">' +
485 periods[period] + '</span><br/>' +
486 (labelsNum ? labelsNum[period] : labels[period]) + '</span>' : '');
488 return (layout ? this._buildLayout(inst, show, layout, compact) :
489 ((compact ? // Compact version
490 '<span class="countdown_row countdown_amount' +
491 (inst._hold ? ' countdown_holding' : '') + '">' +
492 showCompact(Y) + showCompact(O) + showCompact(W) + showCompact(D) +
493 (show[H] ? this._minDigits(periods[H], 2) : '') +
494 (show[M] ? (show[H] ? timeSeparator : '') +
495 this._minDigits(periods[M], 2) : '') +
496 (show[S] ? (show[H] || show[M] ? timeSeparator : '') +
497 this._minDigits(periods[S], 2) : '') :
499 '<span class="countdown_row countdown_show' + showCount +
500 (inst._hold ? ' countdown_holding' : '') + '">' +
501 showFull(Y) + showFull(O) + showFull(W) + showFull(D) +
502 showFull(H) + showFull(M) + showFull(S)) + '</span>' +
503 (description ? '<span class="countdown_row countdown_descr">' + description + '</span>' : '')));
506 /* Construct a custom layout.
507 @param inst (object) the current settings for this instance
508 @param show (string[7]) flags indicating which periods are requested
509 @param layout (string) the customised layout
510 @param compact (boolean) true if using compact labels
511 @return (string) the custom HTML */
512 _buildLayout: function(inst, show, layout, compact) {
513 var labels = this._get(inst, (compact ? 'compactLabels' : 'labels'));
514 var labelFor = function(index) {
515 return ($.countdown._get(inst,
516 (compact ? 'compactLabels' : 'labels') + inst._periods[index]) ||
519 var digit = function(value, position) {
520 return Math.floor(value / position) % 10;
522 var subs = {desc: this._get(inst, 'description'), sep: this._get(inst, 'timeSeparator'),
523 yl: labelFor(Y), yn: inst._periods[Y], ynn: this._minDigits(inst._periods[Y], 2),
524 ynnn: this._minDigits(inst._periods[Y], 3), y1: digit(inst._periods[Y], 1),
525 y10: digit(inst._periods[Y], 10), y100: digit(inst._periods[Y], 100),
526 y1000: digit(inst._periods[Y], 1000),
527 ol: labelFor(O), on: inst._periods[O], onn: this._minDigits(inst._periods[O], 2),
528 onnn: this._minDigits(inst._periods[O], 3), o1: digit(inst._periods[O], 1),
529 o10: digit(inst._periods[O], 10), o100: digit(inst._periods[O], 100),
530 o1000: digit(inst._periods[O], 1000),
531 wl: labelFor(W), wn: inst._periods[W], wnn: this._minDigits(inst._periods[W], 2),
532 wnnn: this._minDigits(inst._periods[W], 3), w1: digit(inst._periods[W], 1),
533 w10: digit(inst._periods[W], 10), w100: digit(inst._periods[W], 100),
534 w1000: digit(inst._periods[W], 1000),
535 dl: labelFor(D), dn: inst._periods[D], dnn: this._minDigits(inst._periods[D], 2),
536 dnnn: this._minDigits(inst._periods[D], 3), d1: digit(inst._periods[D], 1),
537 d10: digit(inst._periods[D], 10), d100: digit(inst._periods[D], 100),
538 d1000: digit(inst._periods[D], 1000),
539 hl: labelFor(H), hn: inst._periods[H], hnn: this._minDigits(inst._periods[H], 2),
540 hnnn: this._minDigits(inst._periods[H], 3), h1: digit(inst._periods[H], 1),
541 h10: digit(inst._periods[H], 10), h100: digit(inst._periods[H], 100),
542 h1000: digit(inst._periods[H], 1000),
543 ml: labelFor(M), mn: inst._periods[M], mnn: this._minDigits(inst._periods[M], 2),
544 mnnn: this._minDigits(inst._periods[M], 3), m1: digit(inst._periods[M], 1),
545 m10: digit(inst._periods[M], 10), m100: digit(inst._periods[M], 100),
546 m1000: digit(inst._periods[M], 1000),
547 sl: labelFor(S), sn: inst._periods[S], snn: this._minDigits(inst._periods[S], 2),
548 snnn: this._minDigits(inst._periods[S], 3), s1: digit(inst._periods[S], 1),
549 s10: digit(inst._periods[S], 10), s100: digit(inst._periods[S], 100),
550 s1000: digit(inst._periods[S], 1000)};
552 // Replace period containers: {p<}...{p>}
553 for (var i = 0; i < 7; i++) {
554 var period = 'yowdhms'.charAt(i);
555 var re = new RegExp('\\{' + period + '<\\}(.*)\\{' + period + '>\\}', 'g');
556 html = html.replace(re, (show[i] ? '$1' : ''));
558 // Replace period values: {pn}
559 $.each(subs, function(n, v) {
560 var re = new RegExp('\\{' + n + '\\}', 'g');
561 html = html.replace(re, v);
566 /* Ensure a numeric value has at least n digits for display.
567 @param value (number) the value to display
568 @param len (number) the minimum length
569 @return (string) the display text */
570 _minDigits: function(value, len) {
572 if (value.length >= len) {
575 value = '0000000000' + value;
576 return value.substr(value.length - len);
579 /* Translate the format into flags for each period.
580 @param inst (object) the current settings for this instance
581 @return (string[7]) flags indicating which periods are requested (?) or
582 required (!) by year, month, week, day, hour, minute, second */
583 _determineShow: function(inst) {
584 var format = this._get(inst, 'format');
586 show[Y] = (format.match('y') ? '?' : (format.match('Y') ? '!' : null));
587 show[O] = (format.match('o') ? '?' : (format.match('O') ? '!' : null));
588 show[W] = (format.match('w') ? '?' : (format.match('W') ? '!' : null));
589 show[D] = (format.match('d') ? '?' : (format.match('D') ? '!' : null));
590 show[H] = (format.match('h') ? '?' : (format.match('H') ? '!' : null));
591 show[M] = (format.match('m') ? '?' : (format.match('M') ? '!' : null));
592 show[S] = (format.match('s') ? '?' : (format.match('S') ? '!' : null));
596 /* Calculate the requested periods between now and the target time.
597 @param inst (object) the current settings for this instance
598 @param show (string[7]) flags indicating which periods are requested/required
599 @param now (Date) the current date and time
600 @return (number[7]) the current time periods (always positive)
601 by year, month, week, day, hour, minute, second */
602 _calculatePeriods: function(inst, show, now) {
605 inst._now.setMilliseconds(0);
606 var until = new Date(inst._now.getTime());
608 if (now.getTime() < inst._since.getTime()) {
609 inst._now = now = until;
616 until.setTime(inst._until.getTime());
617 if (now.getTime() > inst._until.getTime()) {
618 inst._now = now = until;
621 // Calculate differences by period
622 var periods = [0, 0, 0, 0, 0, 0, 0];
623 if (show[Y] || show[O]) {
624 // Treat end of months as the same
625 var lastNow = $.countdown._getDaysInMonth(now.getFullYear(), now.getMonth());
626 var lastUntil = $.countdown._getDaysInMonth(until.getFullYear(), until.getMonth());
627 var sameDay = (until.getDate() == now.getDate() ||
628 (until.getDate() >= Math.min(lastNow, lastUntil) &&
629 now.getDate() >= Math.min(lastNow, lastUntil)));
630 var getSecs = function(date) {
631 return (date.getHours() * 60 + date.getMinutes()) * 60 + date.getSeconds();
633 var months = Math.max(0,
634 (until.getFullYear() - now.getFullYear()) * 12 + until.getMonth() - now.getMonth() +
635 ((until.getDate() < now.getDate() && !sameDay) ||
636 (sameDay && getSecs(until) < getSecs(now)) ? -1 : 0));
637 periods[Y] = (show[Y] ? Math.floor(months / 12) : 0);
638 periods[O] = (show[O] ? months - periods[Y] * 12 : 0);
639 // Adjust for months difference and end of month if necessary
640 var adjustDate = function(date, offset, last) {
641 var wasLastDay = (date.getDate() == last);
642 var lastDay = $.countdown._getDaysInMonth(date.getFullYear() + offset * periods[Y],
643 date.getMonth() + offset * periods[O]);
644 if (date.getDate() > lastDay) {
645 date.setDate(lastDay);
647 date.setFullYear(date.getFullYear() + offset * periods[Y]);
648 date.setMonth(date.getMonth() + offset * periods[O]);
650 date.setDate(lastDay);
655 until = adjustDate(until, -1, lastUntil);
658 now = adjustDate(new Date(now.getTime()), +1, lastNow);
661 var diff = Math.floor((until.getTime() - now.getTime()) / 1000);
662 var extractPeriod = function(period, numSecs) {
663 periods[period] = (show[period] ? Math.floor(diff / numSecs) : 0);
664 diff -= periods[period] * numSecs;
666 extractPeriod(W, 604800);
667 extractPeriod(D, 86400);
668 extractPeriod(H, 3600);
669 extractPeriod(M, 60);
671 if (diff > 0 && !inst._since) { // Round up if left overs
672 var multiplier = [1, 12, 4.3482, 7, 24, 60, 60];
675 for (var period = S; period >= Y; period--) {
677 if (periods[lastShown] >= max) {
678 periods[lastShown] = 0;
688 max *= multiplier[period];
695 /* jQuery extend now ignores nulls!
696 @param target (object) the object to update
697 @param props (object) the new settings
698 @return (object) the updated object */
699 function extendRemove(target, props) {
700 $.extend(target, props);
701 for (var name in props) {
702 if (props[name] == null) {
709 /* Process the countdown functionality for a jQuery selection.
710 @param command (string) the command to run (optional, default 'attach')
711 @param options (object) the new settings to use for these countdown instances
712 @return (jQuery) for chaining further calls */
713 $.fn.countdown = function(options) {
714 var otherArgs = Array.prototype.slice.call(arguments, 1);
715 if (options == 'getTimes' || options == 'settings') {
716 return $.countdown['_' + options + 'Countdown'].
717 apply($.countdown, [this[0]].concat(otherArgs));
719 return this.each(function() {
720 if (typeof options == 'string') {
721 $.countdown['_' + options + 'Countdown'].apply($.countdown, [this].concat(otherArgs));
724 $.countdown._attachCountdown(this, options);
729 /* Initialise the countdown functionality. */
730 $.countdown = new Countdown(); // singleton instance