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 which = $.countdown._get(inst, 'which');
 
 476                 var labelsNum = $.countdown._get(inst, 'compactLabels' + which(periods[period]));
 
 478                         return (show[period] ? periods[period] +
 
 479                                 (labelsNum ? labelsNum[period] : labels[period]) + ' ' : '');
 
 481                 var showFull = function(period) {
 
 482                         var which = $.countdown._get(inst, 'which');
 
 484                                 var labelsNum = $.countdown._get(inst, 'labels' + which(periods[period]));
 
 486                         return (show[period] ?
 
 487                                 '<span class="countdown_section"><span class="countdown_amount">' +
 
 488                                 periods[period] + '</span><br/>' +
 
 489                                 (labelsNum ? labelsNum[period] : labels[period]) + '</span>' : '');
 
 491                 return (layout ? this._buildLayout(inst, show, layout, compact) :
 
 492                         ((compact ? // Compact version
 
 493                         '<span class="countdown_row countdown_amount' +
 
 494                         (inst._hold ? ' countdown_holding' : '') + '">' + 
 
 495                         showCompact(Y) + showCompact(O) + showCompact(W) + showCompact(D) + 
 
 496                         (show[H] ? this._minDigits(periods[H], 2) : '') +
 
 497                         (show[M] ? (show[H] ? timeSeparator : '') +
 
 498                         this._minDigits(periods[M], 2) : '') +
 
 499                         (show[S] ? (show[H] || show[M] ? timeSeparator : '') +
 
 500                         this._minDigits(periods[S], 2) : '') :
 
 502                         '<span class="countdown_row countdown_show' + showCount +
 
 503                         (inst._hold ? ' countdown_holding' : '') + '">' +
 
 504                         showFull(Y) + showFull(O) + showFull(W) + showFull(D) +
 
 505                         showFull(H) + showFull(M) + showFull(S)) + '</span>' +
 
 506                         (description ? '<span class="countdown_row countdown_descr">' + description + '</span>' : '')));
 
 509         /* Construct a custom layout.
 
 510            @param  inst     (object) the current settings for this instance
 
 511            @param  show     (string[7]) flags indicating which periods are requested
 
 512            @param  layout   (string) the customised layout
 
 513            @param  compact  (boolean) true if using compact labels
 
 514            @return  (string) the custom HTML */
 
 515         _buildLayout: function(inst, show, layout, compact) {
 
 516                 var labels = this._get(inst, (compact ? 'compactLabels' : 'labels'));
 
 517                 var labelFor = function(index) {
 
 518                         return ($.countdown._get(inst,
 
 519                                 (compact ? 'compactLabels' : 'labels') + inst._periods[index]) ||
 
 522                 var digit = function(value, position) {
 
 523                         return Math.floor(value / position) % 10;
 
 525                 var subs = {desc: this._get(inst, 'description'), sep: this._get(inst, 'timeSeparator'),
 
 526                         yl: labelFor(Y), yn: inst._periods[Y], ynn: this._minDigits(inst._periods[Y], 2),
 
 527                         ynnn: this._minDigits(inst._periods[Y], 3), y1: digit(inst._periods[Y], 1),
 
 528                         y10: digit(inst._periods[Y], 10), y100: digit(inst._periods[Y], 100),
 
 529                         y1000: digit(inst._periods[Y], 1000),
 
 530                         ol: labelFor(O), on: inst._periods[O], onn: this._minDigits(inst._periods[O], 2),
 
 531                         onnn: this._minDigits(inst._periods[O], 3), o1: digit(inst._periods[O], 1),
 
 532                         o10: digit(inst._periods[O], 10), o100: digit(inst._periods[O], 100),
 
 533                         o1000: digit(inst._periods[O], 1000),
 
 534                         wl: labelFor(W), wn: inst._periods[W], wnn: this._minDigits(inst._periods[W], 2),
 
 535                         wnnn: this._minDigits(inst._periods[W], 3), w1: digit(inst._periods[W], 1),
 
 536                         w10: digit(inst._periods[W], 10), w100: digit(inst._periods[W], 100),
 
 537                         w1000: digit(inst._periods[W], 1000),
 
 538                         dl: labelFor(D), dn: inst._periods[D], dnn: this._minDigits(inst._periods[D], 2),
 
 539                         dnnn: this._minDigits(inst._periods[D], 3), d1: digit(inst._periods[D], 1),
 
 540                         d10: digit(inst._periods[D], 10), d100: digit(inst._periods[D], 100),
 
 541                         d1000: digit(inst._periods[D], 1000),
 
 542                         hl: labelFor(H), hn: inst._periods[H], hnn: this._minDigits(inst._periods[H], 2),
 
 543                         hnnn: this._minDigits(inst._periods[H], 3), h1: digit(inst._periods[H], 1),
 
 544                         h10: digit(inst._periods[H], 10), h100: digit(inst._periods[H], 100),
 
 545                         h1000: digit(inst._periods[H], 1000),
 
 546                         ml: labelFor(M), mn: inst._periods[M], mnn: this._minDigits(inst._periods[M], 2),
 
 547                         mnnn: this._minDigits(inst._periods[M], 3), m1: digit(inst._periods[M], 1),
 
 548                         m10: digit(inst._periods[M], 10), m100: digit(inst._periods[M], 100),
 
 549                         m1000: digit(inst._periods[M], 1000),
 
 550                         sl: labelFor(S), sn: inst._periods[S], snn: this._minDigits(inst._periods[S], 2),
 
 551                         snnn: this._minDigits(inst._periods[S], 3), s1: digit(inst._periods[S], 1),
 
 552                         s10: digit(inst._periods[S], 10), s100: digit(inst._periods[S], 100),
 
 553                         s1000: digit(inst._periods[S], 1000)};
 
 555                 // Replace period containers: {p<}...{p>}
 
 556                 for (var i = 0; i < 7; i++) {
 
 557                         var period = 'yowdhms'.charAt(i);
 
 558                         var re = new RegExp('\\{' + period + '<\\}(.*)\\{' + period + '>\\}', 'g');
 
 559                         html = html.replace(re, (show[i] ? '$1' : ''));
 
 561                 // Replace period values: {pn}
 
 562                 $.each(subs, function(n, v) {
 
 563                         var re = new RegExp('\\{' + n + '\\}', 'g');
 
 564                         html = html.replace(re, v);
 
 569         /* Ensure a numeric value has at least n digits for display.
 
 570            @param  value  (number) the value to display
 
 571            @param  len    (number) the minimum length
 
 572            @return  (string) the display text */
 
 573         _minDigits: function(value, len) {
 
 575                 if (value.length >= len) {
 
 578                 value = '0000000000' + value;
 
 579                 return value.substr(value.length - len);
 
 582         /* Translate the format into flags for each period.
 
 583            @param  inst  (object) the current settings for this instance
 
 584            @return  (string[7]) flags indicating which periods are requested (?) or
 
 585                     required (!) by year, month, week, day, hour, minute, second */
 
 586         _determineShow: function(inst) {
 
 587                 var format = this._get(inst, 'format');
 
 589                 show[Y] = (format.match('y') ? '?' : (format.match('Y') ? '!' : null));
 
 590                 show[O] = (format.match('o') ? '?' : (format.match('O') ? '!' : null));
 
 591                 show[W] = (format.match('w') ? '?' : (format.match('W') ? '!' : null));
 
 592                 show[D] = (format.match('d') ? '?' : (format.match('D') ? '!' : null));
 
 593                 show[H] = (format.match('h') ? '?' : (format.match('H') ? '!' : null));
 
 594                 show[M] = (format.match('m') ? '?' : (format.match('M') ? '!' : null));
 
 595                 show[S] = (format.match('s') ? '?' : (format.match('S') ? '!' : null));
 
 599         /* Calculate the requested periods between now and the target time.
 
 600            @param  inst  (object) the current settings for this instance
 
 601            @param  show  (string[7]) flags indicating which periods are requested/required
 
 602            @param  now   (Date) the current date and time
 
 603            @return  (number[7]) the current time periods (always positive)
 
 604                     by year, month, week, day, hour, minute, second */
 
 605         _calculatePeriods: function(inst, show, now) {
 
 608                 inst._now.setMilliseconds(0);
 
 609                 var until = new Date(inst._now.getTime());
 
 611                         if (now.getTime() < inst._since.getTime()) {
 
 612                                 inst._now = now = until;
 
 619                         until.setTime(inst._until.getTime());
 
 620                         if (now.getTime() > inst._until.getTime()) {
 
 621                                 inst._now = now = until;
 
 624                 // Calculate differences by period
 
 625                 var periods = [0, 0, 0, 0, 0, 0, 0];
 
 626                 if (show[Y] || show[O]) {
 
 627                         // Treat end of months as the same
 
 628                         var lastNow = $.countdown._getDaysInMonth(now.getFullYear(), now.getMonth());
 
 629                         var lastUntil = $.countdown._getDaysInMonth(until.getFullYear(), until.getMonth());
 
 630                         var sameDay = (until.getDate() == now.getDate() ||
 
 631                                 (until.getDate() >= Math.min(lastNow, lastUntil) &&
 
 632                                 now.getDate() >= Math.min(lastNow, lastUntil)));
 
 633                         var getSecs = function(date) {
 
 634                                 return (date.getHours() * 60 + date.getMinutes()) * 60 + date.getSeconds();
 
 636                         var months = Math.max(0,
 
 637                                 (until.getFullYear() - now.getFullYear()) * 12 + until.getMonth() - now.getMonth() +
 
 638                                 ((until.getDate() < now.getDate() && !sameDay) ||
 
 639                                 (sameDay && getSecs(until) < getSecs(now)) ? -1 : 0));
 
 640                         periods[Y] = (show[Y] ? Math.floor(months / 12) : 0);
 
 641                         periods[O] = (show[O] ? months - periods[Y] * 12 : 0);
 
 642                         // Adjust for months difference and end of month if necessary
 
 643                         var adjustDate = function(date, offset, last) {
 
 644                                 var wasLastDay = (date.getDate() == last);
 
 645                                 var lastDay = $.countdown._getDaysInMonth(date.getFullYear() + offset * periods[Y],
 
 646                                         date.getMonth() + offset * periods[O]);
 
 647                                 if (date.getDate() > lastDay) {
 
 648                                         date.setDate(lastDay);
 
 650                                 date.setFullYear(date.getFullYear() + offset * periods[Y]);
 
 651                                 date.setMonth(date.getMonth() + offset * periods[O]);
 
 653                                         date.setDate(lastDay);
 
 658                                 until = adjustDate(until, -1, lastUntil);
 
 661                                 now = adjustDate(new Date(now.getTime()), +1, lastNow);
 
 664                 var diff = Math.floor((until.getTime() - now.getTime()) / 1000);
 
 665                 var extractPeriod = function(period, numSecs) {
 
 666                         periods[period] = (show[period] ? Math.floor(diff / numSecs) : 0);
 
 667                         diff -= periods[period] * numSecs;
 
 669                 extractPeriod(W, 604800);
 
 670                 extractPeriod(D, 86400);
 
 671                 extractPeriod(H, 3600);
 
 672                 extractPeriod(M, 60);
 
 674                 if (diff > 0 && !inst._since) { // Round up if left overs
 
 675                         var multiplier = [1, 12, 4.3482, 7, 24, 60, 60];
 
 678                         for (var period = S; period >= Y; period--) {
 
 680                                         if (periods[lastShown] >= max) {
 
 681                                                 periods[lastShown] = 0;
 
 691                                 max *= multiplier[period];
 
 698 /* jQuery extend now ignores nulls!
 
 699    @param  target  (object) the object to update
 
 700    @param  props   (object) the new settings
 
 701    @return  (object) the updated object */
 
 702 function extendRemove(target, props) {
 
 703         $.extend(target, props);
 
 704         for (var name in props) {
 
 705                 if (props[name] == null) {
 
 712 /* Process the countdown functionality for a jQuery selection.
 
 713    @param  command  (string) the command to run (optional, default 'attach')
 
 714    @param  options  (object) the new settings to use for these countdown instances
 
 715    @return  (jQuery) for chaining further calls */
 
 716 $.fn.countdown = function(options) {
 
 717         var otherArgs = Array.prototype.slice.call(arguments, 1);
 
 718         if (options == 'getTimes' || options == 'settings') {
 
 719                 return $.countdown['_' + options + 'Countdown'].
 
 720                         apply($.countdown, [this[0]].concat(otherArgs));
 
 722         return this.each(function() {
 
 723                 if (typeof options == 'string') {
 
 724                         $.countdown['_' + options + 'Countdown'].apply($.countdown, [this].concat(otherArgs));
 
 727                         $.countdown._attachCountdown(this, options);
 
 732 /* Initialise the countdown functionality. */
 
 733 $.countdown = new Countdown(); // singleton instance