1/* http://keith-wood.name/countdown.html 2 Countdown for jQuery v2.0.2. 3 Written by Keith Wood (kbwood{at}iinet.com.au) January 2008. 4 Available under the MIT (http://keith-wood.name/licence.html) license. 5 Please attribute the author if you use it. */ 6 7(function($) { // Hide scope, no $ conflict 8 9 var pluginName = 'countdown'; 10 11 var Y = 0; // Years 12 var O = 1; // Months 13 var W = 2; // Weeks 14 var D = 3; // Days 15 var H = 4; // Hours 16 var M = 5; // Minutes 17 var S = 6; // Seconds 18 19 /** Create the countdown plugin. 20 <p>Sets an element to show the time remaining until a given instant.</p> 21 <p>Expects HTML like:</p> 22 <pre><div></div></pre> 23 <p>Provide inline configuration like:</p> 24 <pre><div data-countdown="name: 'value'"></div></pre> 25 @module Countdown 26 @augments JQPlugin 27 @example $(selector).countdown({until: +300}) */ 28 $.JQPlugin.createPlugin({ 29 30 /** The name of the plugin. */ 31 name: pluginName, 32 33 /** Countdown expiry callback. 34 Triggered when the countdown expires. 35 @callback expiryCallback */ 36 37 /** Countdown server synchronisation callback. 38 Triggered when the countdown is initialised. 39 @callback serverSyncCallback 40 @return {Date} The current date/time on the server as expressed in the local timezone. */ 41 42 /** Countdown tick callback. 43 Triggered on every <code>tickInterval</code> ticks of the countdown. 44 @callback tickCallback 45 @param periods {number[]} The breakdown by period (years, months, weeks, days, 46 hours, minutes, seconds) of the time remaining/passed. */ 47 48 /** Countdown which labels callback. 49 Triggered when the countdown is being display to determine which set of labels 50 (<code>labels</code>, <code>labels1</code>, ...) are to be used for the current period value. 51 @callback whichLabelsCallback 52 @param num {number} The current period value. 53 @return {number} The suffix for the label set to use. */ 54 55 /** Default settings for the plugin. 56 @property until {Date|number|string} The date/time to count down to, or number of seconds 57 offset from now, or string of amounts and units for offset(s) from now: 58 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds. 59 @example until: new Date(2013, 12-1, 25, 13, 30) 60 until: +300 61 until: '+1O -2D' 62 @property [since] {Date|number|string} The date/time to count up from, or 63 number of seconds offset from now, or string for unit offset(s): 64 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds. 65 @example since: new Date(2013, 1-1, 1) 66 since: -300 67 since: '-1O +2D' 68 @property [timezone=null] {number} The timezone (hours or minutes from GMT) for the target times, 69 or null for client local timezone. 70 @example timezone: +10 71 timezone: -60 72 @property [serverSync=null] {serverSyncCallback} A function to retrieve the current server time 73 for synchronisation. 74 @property [format='dHMS'] {string} The format for display - upper case for always, lower case only if non-zero, 75 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds. 76 @property [layout=''] {string} Build your own layout for the countdown. 77 @example layout: '{d<}{dn} {dl}{d>} {hnn}:{mnn}:{snn}' 78 @property [compact=false] {boolean} True to display in a compact format, false for an expanded one. 79 @property [padZeroes=false] {boolean} True to add leading zeroes 80 @property [significant=0] {number} The number of periods with non-zero values to show, zero for all. 81 @property [description=''] {string} The description displayed for the countdown. 82 @property [expiryUrl=''] {string} A URL to load upon expiry, replacing the current page. 83 @property [expiryText=''] {string} Text to display upon expiry, replacing the countdown. This may be HTML. 84 @property [alwaysExpire=false] {boolean} True to trigger <code>onExpiry</code> even if target time has passed. 85 @property [onExpiry=null] {expiryCallback} Callback when the countdown expires - 86 receives no parameters and <code>this</code> is the containing division. 87 @example onExpiry: function() { 88 ... 89 } 90 @property [onTick=null] {tickCallback} Callback when the countdown is updated - 91 receives <code>number[7]</code> being the breakdown by period 92 (years, months, weeks, days, hours, minutes, seconds - based on 93 <code>format</code>) and <code>this</code> is the containing division. 94 @example onTick: function(periods) { 95 var secs = $.countdown.periodsToSeconds(periods); 96 if (secs < 300) { // Last five minutes 97 ... 98 } 99 } 100 @property [tickInterval=1] {number} The interval (seconds) between <code>onTick</code> callbacks. */ 101 defaultOptions: { 102 until: null, 103 since: null, 104 timezone: null, 105 serverSync: null, 106 format: 'dHMS', 107 layout: '', 108 compact: false, 109 padZeroes: false, 110 significant: 0, 111 description: '', 112 expiryUrl: '', 113 expiryText: '', 114 alwaysExpire: false, 115 onExpiry: null, 116 onTick: null, 117 tickInterval: 1 118 }, 119 120 /** Localisations for the plugin. 121 Entries are objects indexed by the language code ('' being the default US/English). 122 Each object has the following attributes. 123 @property [labels=['Years','Months','Weeks','Days','Hours','Minutes','Seconds']] {string[]} 124 The display texts for the counter periods. 125 @property [labels1=['Year','Month','Week','Day','Hour','Minute','Second']] {string[]} 126 The display texts for the counter periods if they have a value of 1. 127 Add other <code>labels<em>n</em></code> attributes as necessary to 128 cater for other numeric idiosyncrasies of the localisation. 129 @property [compactLabels=['y','m','w','d']] {string[]} The compact texts for the counter periods. 130 @property [whichLabels=null] {whichLabelsCallback} A function to determine which 131 <code>labels<em>n</em></code> to use. 132 @example whichLabels: function(num) { 133 return (num > 1 ? 0 : 1); 134 } 135 @property [digits=['0','1',...,'9']] {number[]} The digits to display (0-9). 136 @property [timeSeparator=':'] {string} Separator for time periods in the compact layout. 137 @property [isRTL=false] {boolean} True for right-to-left languages, false for left-to-right. */ 138 regionalOptions: { // Available regional settings, indexed by language/country code 139 '': { // Default regional settings - English/US 140 labels: ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'], 141 labels1: ['Year', 'Month', 'Week', 'Day', 'Hour', 'Minute', 'Second'], 142 compactLabels: ['y', 'm', 'w', 'd'], 143 whichLabels: null, 144 digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 145 timeSeparator: ':', 146 isRTL: false 147 } 148 }, 149 150 /** Names of getter methods - those that can't be chained. */ 151 _getters: ['getTimes'], 152 153 /* Class name for the right-to-left marker. */ 154 _rtlClass: pluginName + '-rtl', 155 /* Class name for the countdown section marker. */ 156 _sectionClass: pluginName + '-section',
157 /* Class name for the period amount marker. */ 158 _amountClass: pluginName + '-amount', 159 /* Class name for the period name marker. */ 160 _periodClass: pluginName + '-period', 161 /* Class name for the countdown row marker. */ 162 _rowClass: pluginName + '-row', 163 /* Class name for the holding countdown marker. */ 164 _holdingClass: pluginName + '-holding', 165 /* Class name for the showing countdown marker. */ 166 _showClass: pluginName + '-show', 167 /* Class name for the description marker. */ 168 _descrClass: pluginName + '-descr', 169 170 /* List of currently active countdown elements. */ 171 _timerElems: [], 172 173 /** Additional setup for the countdown. 174 Apply default localisations. 175 Create the timer. */ 176 _init: function() { 177 var self = this; 178 this._super(); 179 this._serverSyncs = []; 180 var now = (typeof Date.now == 'function' ? Date.now : 181 function() { return new Date().getTime(); }); 182 var perfAvail = (window.performance && typeof window.performance.now == 'function'); 183 // Shared timer for all countdowns 184 function timerCallBack(timestamp) { 185 var drawStart = (timestamp < 1e12 ? // New HTML5 high resolution timer 186 (perfAvail ? (performance.now() + performance.timing.navigationStart) : now()) : 187 // Integer milliseconds since unix epoch 188 timestamp || now()); 189 if (drawStart - animationStartTime >= 1000) { 190 self._updateElems(); 191 animationStartTime = drawStart; 192 } 193 requestAnimationFrame(timerCallBack); 194 } 195 var requestAnimationFrame = window.requestAnimationFrame || 196 window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || 197 window.oRequestAnimationFrame || window.msRequestAnimationFrame || null; 198 // This is when we expect a fall-back to setInterval as it's much more fluid 199 var animationStartTime = 0; 200 if (!requestAnimationFrame || $.noRequestAnimationFrame) { 201 $.noRequestAnimationFrame = null; 202 setInterval(function() { self._updateElems(); }, 980); // Fall back to good old setInterval 203 } 204 else { 205 animationStartTime = window.animationStartTime || 206 window.webkitAnimationStartTime || window.mozAnimationStartTime || 207 window.oAnimationStartTime || window.msAnimationStartTime || now(); 208 requestAnimationFrame(timerCallBack); 209 } 210 }, 211 212 /** Convert a date/time to UTC. 213 @param tz {number} The hour or minute offset from GMT, e.g. +9, -360. 214 @param year {Date|number} the date/time in that timezone or the year in that timezone. 215 @param [month] {number} The month (0 - 11) (omit if <code>year</code> is a <code>Date</code>). 216 @param [day] {number} The day (omit if <code>year</code> is a <code>Date</code>). 217 @param [hours] {number} The hour (omit if <code>year</code> is a <code>Date</code>). 218 @param [mins] {number} The minute (omit if <code>year</code> is a <code>Date</code>). 219 @param [secs] {number} The second (omit if <code>year</code> is a <code>Date</code>). 220 @param [ms] {number} The millisecond (omit if <code>year</code> is a <code>Date</code>). 221 @return {Date} The equivalent UTC date/time. 222 @example $.countdown.UTCDate(+10, 2013, 12-1, 25, 12, 0) 223 $.countdown.UTCDate(-7, new Date(2013, 12-1, 25, 12, 0)) */ 224 UTCDate: function(tz, year, month, day, hours, mins, secs, ms) { 225 if (typeof year == 'object' && year.constructor == Date) { 226 ms = year.getMilliseconds(); 227 secs = year.getSeconds(); 228 mins = year.getMinutes(); 229 hours = year.getHours(); 230 day = year.getDate(); 231 month = year.getMonth(); 232 year = year.getFullYear(); 233 } 234 var d = new Date(); 235 d.setUTCFullYear(year); 236 d.setUTCDate(1); 237 d.setUTCMonth(month || 0); 238 d.setUTCDate(day || 1); 239 d.setUTCHours(hours || 0); 240 d.setUTCMinutes((mins || 0) - (Math.abs(tz) < 30 ? tz * 60 : tz)); 241 d.setUTCSeconds(secs || 0); 242 d.setUTCMilliseconds(ms || 0); 243 return d; 244 }, 245 246 /** Convert a set of periods into seconds. 247 Averaged for months and years. 248 @param periods {number[]} The periods per year/month/week/day/hour/minute/second. 249 @return {number} The corresponding number of seconds. 250 @example var secs = $.countdown.periodsToSeconds(periods) */
251 periodsToSeconds: function(periods) { 252 return periods[0] * 31557600 + periods[1] * 2629800 + periods[2] * 604800 + 253 periods[3] * 86400 + periods[4] * 3600 + periods[5] * 60 + periods[6]; 254 }, 255 256 /** Resynchronise the countdowns with the server. 257 @example $.countdown.resync() */ 258 resync: function() { 259 var self = this; 260 $('.' + this._getMarker()).each(function() { // Each countdown 261 var inst = $.data(this, self.name); 262 if (inst.options.serverSync) { // If synced 263 var serverSync = null; 264 for (var i = 0; i < self._serverSyncs.length; i++) { 265 if (self._serverSyncs[i][0] == inst.options.serverSync) { // Find sync details 266 serverSync = self._serverSyncs[i]; 267 break; 268 } 269 } 270 if (serverSync[2] == null) { // Recalculate if missing 271 var serverResult = ($.isFunction(inst.options.serverSync) ? 272 inst.options.serverSync.apply(this, []) : null); 273 serverSync[2] = 274 (serverResult ? new Date().getTime() - serverResult.getTime() : 0) - serverSync[1]; 275 } 276 if (inst._since) { // Apply difference 277 inst._since.setMilliseconds(inst._since.getMilliseconds() + serverSync[2]); 278 } 279 inst._until.setMilliseconds(inst._until.getMilliseconds() + serverSync[2]); 280 } 281 }); 282 for (var i = 0; i < self._serverSyncs.length; i++) { // Update sync details 283 if (self._serverSyncs[i][2] != null) { 284 self._serverSyncs[i][1] += self._serverSyncs[i][2]; 285 delete self._serverSyncs[i][2]; 286 } 287 } 288 }, 289 290 _instSettings: function(elem, options) { 291 return {_periods: [0, 0, 0, 0, 0, 0, 0]}; 292 }, 293 294 /** Add an element to the list of active ones. 295 @private 296 @param elem {Element} The countdown element. */ 297 _addElem: function(elem) { 298 if (!this._hasElem(elem)) { 299 this._timerElems.push(elem); 300 } 301 }, 302 303 /** See if an element is in the list of active ones. 304 @private 305 @param elem {Element} The countdown element. 306 @return {boolean} True if present, false if not. */ 307 _hasElem: function(elem) { 308 return ($.inArray(elem, this._timerElems) > -1); 309 }, 310 311 /** Remove an element from the list of active ones. 312 @private 313 @param elem {Element} The countdown element. */ 314 _removeElem: function(elem) { 315 this._timerElems = $.map(this._timerElems, 316 function(value) { return (value == elem ? null : value); }); // delete entry 317 }, 318 319 /** Update each active timer element. 320 @private */ 321 _updateElems: function() { 322 for (var i = this._timerElems.length - 1; i >= 0; i--) { 323 this._updateCountdown(this._timerElems[i]); 324 } 325 }, 326 327 _optionsChanged: function(elem, inst, options) { 328 if (options.layout) { 329 options.layout = options.layout.replace(/</g, '<').replace(/>/g, '>'); 330 } 331 this._resetExtraLabels(inst.options, options); 332 var timezoneChanged = (inst.options.timezone != options.timezone); 333 $.extend(inst.options, options); 334 this._adjustSettings(elem, inst, 335 options.until != null || options.since != null || timezoneChanged); 336 var now = new Date(); 337 if ((inst._since && inst._since < now) || (inst._until && inst._until > now)) { 338 this._addElem(elem[0]); 339 } 340 this._updateCountdown(elem, inst); 341 }, 342 343 /** Redisplay the countdown with an updated display. 344 @private 345 @param elem {Element|jQuery} The containing division. 346 @param inst {object} The current settings for this instance. */ 347 _updateCountdown: function(elem, inst) { 348 elem = elem.jquery ? elem : $(elem); 349 inst = inst || this._getInst(elem); 350 if (!inst) { 351 return; 352 } 353 elem.html(this._generateHTML(inst)).toggleClass(this._rtlClass, inst.options.isRTL); 354 if ($.isFunction(inst.options.onTick)) { 355 var periods = inst._hold != 'lap' ? inst._periods : 356 this._calculatePeriods(inst, inst._show, inst.options.significant, new Date()); 357 if (inst.options.tickInterval == 1 || 358 this.periodsToSeconds(periods) % inst.options.tickInterval == 0) { 359 inst.options.onTick.apply(elem[0], [periods]); 360 } 361 } 362 var expired = inst._hold != 'pause' && 363 (inst._since ? inst._now.getTime() < inst._since.getTime() : 364 inst._now.getTime() >= inst._until.getTime()); 365 if (expired && !inst._expiring) { 366 inst._expiring = true; 367 if (this._hasElem(elem[0]) || inst.options.alwaysExpire) { 368 this._removeElem(elem[0]); 369 if ($.isFunction(inst.options.onExpiry)) { 370 inst.options.onExpiry.apply(elem[0], []); 371 } 372 if (inst.options.expiryText) { 373 var layout = inst.options.layout; 374 inst.options.layout = inst.options.expiryText; 375 this._updateCountdown(elem[0], inst); 376 inst.options.layout = layout; 377 } 378 if (inst.options.expiryUrl) { 379 window.location = inst.options.expiryUrl; 380 } 381 } 382 inst._expiring = false;
383 } 384 else if (inst._hold == 'pause') { 385 this._removeElem(elem[0]); 386 } 387 }, 388 389 /** Reset any extra labelsn and compactLabelsn entries if changing labels. 390 @private 391 @param base {object} The options to be updated. 392 @param options {object} The new option values. */ 393 _resetExtraLabels: function(base, options) { 394 for (var n in options) { 395 if (n.match(/[Ll]abels[02-9]|compactLabels1/)) { 396 base[n] = options[n]; 397 } 398 } 399 for (var n in base) { // Remove custom numbered labels 400 if (n.match(/[Ll]abels[02-9]|compactLabels1/) && typeof options[n] === 'undefined') { 401 base[n] = null; 402 } 403 } 404 }, 405 406 /** Calculate internal settings for an instance. 407 @private 408 @param elem {jQuery} The containing division. 409 @param inst {object} The current settings for this instance. 410 @param recalc {boolean} True if until or since are set. */ 411 _adjustSettings: function(elem, inst, recalc) { 412 var serverEntry = null; 413 for (var i = 0; i < this._serverSyncs.length; i++) { 414 if (this._serverSyncs[i][0] == inst.options.serverSync) { 415 serverEntry = this._serverSyncs[i][1]; 416 break; 417 } 418 } 419 if (serverEntry != null) { 420 var serverOffset = (inst.options.serverSync ? serverEntry : 0); 421 var now = new Date(); 422 } 423 else { 424 var serverResult = ($.isFunction(inst.options.serverSync) ? 425 inst.options.serverSync.apply(elem[0], []) : null); 426 var now = new Date(); 427 var serverOffset = (serverResult ? now.getTime() - serverResult.getTime() : 0); 428 this._serverSyncs.push([inst.options.serverSync, serverOffset]); 429 } 430 var timezone = inst.options.timezone; 431 timezone = (timezone == null ? -now.getTimezoneOffset() : timezone); 432 if (recalc || (!recalc && inst._until == null && inst._since == null)) { 433 inst._since = inst.options.since; 434 if (inst._since != null) { 435 inst._since = this.UTCDate(timezone, this._determineTime(inst._since, null)); 436 if (inst._since && serverOffset) { 437 inst._since.setMilliseconds(inst._since.getMilliseconds() + serverOffset); 438 } 439 } 440 inst._until = this.UTCDate(timezone, this._determineTime(inst.options.until, now)); 441 if (serverOffset) { 442 inst._until.setMilliseconds(inst._until.getMilliseconds() + serverOffset); 443 } 444 } 445 inst._show = this._determineShow(inst); 446 }, 447 448 /** Remove the countdown widget from a div. 449 @param elem {jQuery} The containing division. 450 @param inst {object} The current instance object. */ 451 _preDestroy: function(elem, inst) { 452 this._removeElem(elem[0]); 453 elem.empty(); 454 }, 455 456 /** Pause a countdown widget at the current time. 457 Stop it running but remember and display the current time. 458 @param elem {Element} The containing division. 459 @example $(selector).countdown('pause') */ 460 pause: function(elem) { 461 this._hold(elem, 'pause'); 462 }, 463 464 /** Pause a countdown widget at the current time. 465 Stop the display but keep the countdown running. 466 @param elem {Element} The containing division. 467 @example $(selector).countdown('lap') */ 468 lap: function(elem) { 469 this._hold(elem, 'lap'); 470 }, 471 472 /** Resume a paused countdown widget. 473 @param elem {Element} The containing division. 474 @example $(selector).countdown('resume') */ 475 resume: function(elem) { 476 this._hold(elem, null); 477 }, 478 479 /** Toggle a paused countdown widget. 480 @param elem {Element} The containing division. 481 @example $(selector).countdown('toggle') */ 482 toggle: function(elem) { 483 var inst = $.data(elem, this.name) || {}; 484 this[!inst._hold ? 'pause' : 'resume'](elem); 485 }, 486 487 /** Toggle a lapped countdown widget. 488 @param elem {Element} The containing division. 489 @example $(selector).countdown('toggleLap') */ 490 toggleLap: function(elem) { 491 var inst = $.data(elem, this.name) || {}; 492 this[!inst._hold ? 'lap' : 'resume'](elem); 493 }, 494 495 /** Pause or resume a countdown widget. 496 @private 497 @param elem {Element} The containing division. 498 @param hold {string} The new hold setting. */ 499 _hold: function(elem, hold) { 500 var inst = $.data(elem, this.name); 501 if (inst) { 502 if (inst._hold == 'pause' && !hold) { 503 inst._periods = inst._savePeriods; 504 var sign = (inst._since ? '-' : '+'); 505 inst[inst._since ? '_since' : '_until'] =
506 this._determineTime(sign + inst._periods[0] + 'y' + 507 sign + inst._periods[1] + 'o' + sign + inst._periods[2] + 'w' + 508 sign + inst._periods[3] + 'd' + sign + inst._periods[4] + 'h' + 509 sign + inst._periods[5] + 'm' + sign + inst._periods[6] + 's'); 510 this._addElem(elem); 511 } 512 inst._hold = hold; 513 inst._savePeriods = (hold == 'pause' ? inst._periods : null); 514 $.data(elem, this.name, inst); 515 this._updateCountdown(elem, inst); 516 } 517 }, 518 519 /** Return the current time periods. 520 @param elem {Element} The containing division. 521 @return {number[]} The current periods for the countdown. 522 @example var periods = $(selector).countdown('getTimes') */ 523 getTimes: function(elem) { 524 var inst = $.data(elem, this.name); 525 return (!inst ? null : (inst._hold == 'pause' ? inst._savePeriods : (!inst._hold ? inst._periods : 526 this._calculatePeriods(inst, inst._show, inst.options.significant, new Date())))); 527 }, 528 529 /** A time may be specified as an exact value or a relative one. 530 @private 531 @param setting {string|number|Date} The date/time value as a relative or absolute value. 532 @param defaultTime {Date} The date/time to use if no other is supplied. 533 @return {Date} The corresponding date/time. */ 534 _determineTime: function(setting, defaultTime) { 535 var self = this; 536 var offsetNumeric = function(offset) { // e.g. +300, -2 537 var time = new Date(); 538 time.setTime(time.getTime() + offset * 1000); 539 return time; 540 }; 541 var offsetString = function(offset) { // e.g. '+2d', '-4w', '+3h +30m' 542 offset = offset.toLowerCase(); 543 var time = new Date(); 544 var year = time.getFullYear(); 545 var month = time.getMonth(); 546 var day = time.getDate(); 547 var hour = time.getHours(); 548 var minute = time.getMinutes(); 549 var second = time.getSeconds(); 550 var pattern = /([+-]?[0-9]+)\s*(s|m|h|d|w|o|y)?/g; 551 var matches = pattern.exec(offset); 552 while (matches) { 553 switch (matches[2] || 's') { 554 case 's': second += parseInt(matches[1], 10); break; 555 case 'm': minute += parseInt(matches[1], 10); break; 556 case 'h': hour += parseInt(matches[1], 10); break; 557 case 'd': day += parseInt(matches[1], 10); break; 558 case 'w': day += parseInt(matches[1], 10) * 7; break; 559 case 'o': 560 month += parseInt(matches[1], 10); 561 day = Math.min(day, self._getDaysInMonth(year, month)); 562 break; 563 case 'y': 564 year += parseInt(matches[1], 10); 565 day = Math.min(day, self._getDaysInMonth(year, month)); 566 break; 567 } 568 matches = pattern.exec(offset); 569 } 570 return new Date(year, month, day, hour, minute, second, 0); 571 }; 572 var time = (setting == null ? defaultTime : 573 (typeof setting == 'string' ? offsetString(setting) : 574 (typeof setting == 'number' ? offsetNumeric(setting) : setting))); 575 if (time) time.setMilliseconds(0); 576 return time; 577 }, 578 579 /** Determine the number of days in a month. 580 @private 581 @param year {number} The year. 582 @param month {number} The month. 583 @return {number} The days in that month. */ 584 _getDaysInMonth: function(year, month) { 585 return 32 - new Date(year, month, 32).getDate(); 586 }, 587 588 /** Default implementation to determine which set of labels should be used for an amount. 589 Use the <code>labels</code> attribute with the same numeric suffix (if it exists). 590 @private 591 @param num {number} The amount to be displayed. 592 @return {number} The set of labels to be used for this amount. */ 593 _normalLabels: function(num) { 594 return num; 595 }, 596 597 /** Generate the HTML to display the countdown widget. 598 @private 599 @param inst {object} The current settings for this instance. 600 @return {string} The new HTML for the countdown display. */ 601 _generateHTML: function(inst) { 602 var self = this; 603 // Determine what to show 604 inst._periods = (inst._hold ? inst._periods : 605 this._calculatePeriods(inst, inst._show, inst.options.significant, new Date())); 606 // Show all 'asNeeded' after first non-zero value 607 var shownNonZero = false; 608 var showCount = 0; 609 var sigCount = inst.options.significant; 610 var show = $.extend({}, inst._show); 611 for (var period = Y; period <= S; period++) {
612 shownNonZero |= (inst._show[period] == '?' && inst._periods[period] > 0); 613 show[period] = (inst._show[period] == '?' && !shownNonZero ? null : inst._show[period]); 614 showCount += (show[period] ? 1 : 0); 615 sigCount -= (inst._periods[period] > 0 ? 1 : 0); 616 } 617 var showSignificant = [false, false, false, false, false, false, false]; 618 for (var period = S; period >= Y; period--) { // Determine significant periods 619 if (inst._show[period]) { 620 if (inst._periods[period]) { 621 showSignificant[period] = true; 622 } 623 else { 624 showSignificant[period] = sigCount > 0; 625 sigCount--; 626 } 627 } 628 } 629 var labels = (inst.options.compact ? inst.options.compactLabels : inst.options.labels); 630 var whichLabels = inst.options.whichLabels || this._normalLabels; 631 var showCompact = function(period) { 632 var labelsNum = inst.options['compactLabels' + whichLabels(inst._periods[period])]; 633 return (show[period] ? self._translateDigits(inst, inst._periods[period]) + 634 (labelsNum ? labelsNum[period] : labels[period]) + ' ' : ''); 635 }; 636 var minDigits = (inst.options.padZeroes ? 2 : 1); 637 var showFull = function(period) { 638 var labelsNum = inst.options['labels' + whichLabels(inst._periods[period])]; 639 return ((!inst.options.significant && show[period]) || 640 (inst.options.significant && showSignificant[period]) ? 641 '<span class="' + self._sectionClass + '">' + 642 '<span class="' + self._amountClass + '">' + 643 self._minDigits(inst, inst._periods[period], minDigits) + '</span>' + 644 '<span class="' + self._periodClass + '">' + 645 (labelsNum ? labelsNum[period] : labels[period]) + '</span></span>' : ''); 646 }; 647 return (inst.options.layout ? this._buildLayout(inst, show, inst.options.layout, 648 inst.options.compact, inst.options.significant, showSignificant) : 649 ((inst.options.compact ? // Compact version 650 '<span class="' + this._rowClass + ' ' + this._amountClass + 651 (inst._hold ? ' ' + this._holdingClass : '') + '">' + 652 showCompact(Y) + showCompact(O) + showCompact(W) + showCompact(D) + 653 (show[H] ? this._minDigits(inst, inst._periods[H], 2) : '') + 654 (show[M] ? (show[H] ? inst.options.timeSeparator : '') + 655 this._minDigits(inst, inst._periods[M], 2) : '') + 656 (show[S] ? (show[H] || show[M] ? inst.options.timeSeparator : '') + 657 this._minDigits(inst, inst._periods[S], 2) : '') : 658 // Full version 659 '<span class="' + this._rowClass + ' ' + this._showClass + (inst.options.significant || showCount) + 660 (inst._hold ? ' ' + this._holdingClass : '') + '">' + 661 showFull(Y) + showFull(O) + showFull(W) + showFull(D) + 662 showFull(H) + showFull(M) + showFull(S)) + '</span>' + 663 (inst.options.description ? '<span class="' + this._rowClass + ' ' + this._descrClass + '">' + 664 inst.options.description + '</span>' : ''))); 665 }, 666 667 /** Construct a custom layout. 668 @private 669 @param inst {object} The current settings for this instance. 670 @param show {boolean[]} Flags indicating which periods are requested. 671 @param layout {string} The customised layout. 672 @param compact {boolean} True if using compact labels. 673 @param significant {number} The number of periods with values to show, zero for all. 674 @param showSignificant {boolean[]} Other periods to show for significance. 675 @return {string} The custom HTML. */ 676 _buildLayout: function(inst, show, layout, compact, significant, showSignificant) { 677 var labels = inst.options[compact ? 'compactLabels' : 'labels']; 678 var whichLabels = inst.options.whichLabels || this._normalLabels; 679 var labelFor = function(index) { 680 return (inst.options[(compact ? 'compactLabels' : 'labels') + 681 whichLabels(inst._periods[index])] || labels)[index]; 682 }; 683 var digit = function(value, position) { 684 return inst.options.digits[Math.floor(value / position) % 10]; 685 }; 686 var subs = {desc: inst.options.description, sep: inst.options.timeSeparator, 687 yl: labelFor(Y), yn: this._minDigits(inst, inst._periods[Y], 1), 688 ynn: this._minDigits(inst, inst._periods[Y], 2), 689 ynnn: this._minDigits(inst, inst._periods[Y], 3), y1: digit(inst._periods[Y], 1),
690 y10: digit(inst._periods[Y], 10), y100: digit(inst._periods[Y], 100), 691 y1000: digit(inst._periods[Y], 1000), 692 ol: labelFor(O), on: this._minDigits(inst, inst._periods[O], 1), 693 onn: this._minDigits(inst, inst._periods[O], 2), 694 onnn: this._minDigits(inst, inst._periods[O], 3), o1: digit(inst._periods[O], 1), 695 o10: digit(inst._periods[O], 10), o100: digit(inst._periods[O], 100), 696 o1000: digit(inst._periods[O], 1000), 697 wl: labelFor(W), wn: this._minDigits(inst, inst._periods[W], 1), 698 wnn: this._minDigits(inst, inst._periods[W], 2), 699 wnnn: this._minDigits(inst, inst._periods[W], 3), w1: digit(inst._periods[W], 1), 700 w10: digit(inst._periods[W], 10), w100: digit(inst._periods[W], 100), 701 w1000: digit(inst._periods[W], 1000), 702 dl: labelFor(D), dn: this._minDigits(inst, inst._periods[D], 1), 703 dnn: this._minDigits(inst, inst._periods[D], 2), 704 dnnn: this._minDigits(inst, inst._periods[D], 3), d1: digit(inst._periods[D], 1), 705 d10: digit(inst._periods[D], 10), d100: digit(inst._periods[D], 100), 706 d1000: digit(inst._periods[D], 1000), 707 hl: labelFor(H), hn: this._minDigits(inst, inst._periods[H], 1), 708 hnn: this._minDigits(inst, inst._periods[H], 2), 709 hnnn: this._minDigits(inst, inst._periods[H], 3), h1: digit(inst._periods[H], 1), 710 h10: digit(inst._periods[H], 10), h100: digit(inst._periods[H], 100), 711 h1000: digit(inst._periods[H], 1000), 712 ml: labelFor(M), mn: this._minDigits(inst, inst._periods[M], 1), 713 mnn: this._minDigits(inst, inst._periods[M], 2), 714 mnnn: this._minDigits(inst, inst._periods[M], 3), m1: digit(inst._periods[M], 1), 715 m10: digit(inst._periods[M], 10), m100: digit(inst._periods[M], 100), 716 m1000: digit(inst._periods[M], 1000), 717 sl: labelFor(S), sn: this._minDigits(inst, inst._periods[S], 1), 718 snn: this._minDigits(inst, inst._periods[S], 2), 719 snnn: this._minDigits(inst, inst._periods[S], 3), s1: digit(inst._periods[S], 1), 720 s10: digit(inst._periods[S], 10), s100: digit(inst._periods[S], 100), 721 s1000: digit(inst._periods[S], 1000)}; 722 var html = layout; 723 // Replace period containers: {p<}...{p>} 724 for (var i = Y; i <= S; i++) { 725 var period = 'yowdhms'.charAt(i); 726 var re = new RegExp('\\{' + period + '<\\}([\\s\\S]*)\\{' + period + '>\\}', 'g'); 727 html = html.replace(re, ((!significant && show[i]) || 728 (significant && showSignificant[i]) ? '$1' : '')); 729 } 730 // Replace period values: {pn} 731 $.each(subs, function(n, v) { 732 var re = new RegExp('\\{' + n + '\\}', 'g'); 733 html = html.replace(re, v); 734 }); 735 return html; 736 }, 737 738 /** Ensure a numeric value has at least n digits for display. 739 @private 740 @param inst {object} The current settings for this instance. 741 @param value {number} The value to display. 742 @param len {number} The minimum length. 743 @return {string} The display text. */ 744 _minDigits: function(inst, value, len) { 745 value = '' + value; 746 if (value.length >= len) { 747 return this._translateDigits(inst, value); 748 } 749 value = '0000000000' + value; 750 return this._translateDigits(inst, value.substr(value.length - len)); 751 }, 752 753 /** Translate digits into other representations. 754 @private 755 @param inst {object} The current settings for this instance. 756 @param value {string} The text to translate. 757 @return {string} The translated text. */ 758 _translateDigits: function(inst, value) { 759 return ('' + value).replace(/[0-9]/g, function(digit) { 760 return inst.options.digits[digit]; 761 }); 762 }, 763 764 /** Translate the format into flags for each period. 765 @private 766 @param inst {object} The current settings for this instance. 767 @return {string[]} Flags indicating which periods are requested (?) or 768 required (!) by year, month, week, day, hour, minute, second. */ 769 _determineShow: function(inst) { 770 var format = inst.options.format; 771 var show = []; 772 show[Y] = (format.match('y') ? '?' : (format.match('Y') ? '!' : null)); 773 show[O] = (format.match('o') ? '?' : (format.match('O') ? '!' : null)); 774 show[W] = (format.match('w') ? '?' : (format.match('W') ? '!' : null)); 775 show[D] = (format.match('d') ? '?' : (format.match('D') ? '!' : null)); 776 show[H] = (format.match('h') ? '?' : (format.match('H') ? '!' : null)); 777 show[M] = (format.match('m') ? '?' : (format.match('M') ? '!' : null)); 778 show[S] = (format.match('s') ? '?' : (format.match('S') ? '!' : null)); 779 return show; 780 }, 781 782 /** Calculate the requested periods between now and the target time. 783 @private 784 @param inst {object} The current settings for this instance. 785 @param show {string[]} Flags indicating which periods are requested/required. 786 @param significant {number} The number of periods with values to show, zero for all. 787 @param now {Date} The current date and time. 788 @return {number[]} The current time periods (always positive) 789 by year, month, week, day, hour, minute, second. */
790 _calculatePeriods: function(inst, show, significant, now) { 791 // Find endpoints 792 inst._now = now; 793 inst._now.setMilliseconds(0); 794 var until = new Date(inst._now.getTime()); 795 if (inst._since) { 796 if (now.getTime() < inst._since.getTime()) { 797 inst._now = now = until; 798 } 799 else { 800 now = inst._since; 801 } 802 } 803 else { 804 until.setTime(inst._until.getTime()); 805 if (now.getTime() > inst._until.getTime()) { 806 inst._now = now = until; 807 } 808 } 809 // Calculate differences by period 810 var periods = [0, 0, 0, 0, 0, 0, 0]; 811 if (show[Y] || show[O]) { 812 // Treat end of months as the same 813 var lastNow = this._getDaysInMonth(now.getFullYear(), now.getMonth()); 814 var lastUntil = this._getDaysInMonth(until.getFullYear(), until.getMonth()); 815 var sameDay = (until.getDate() == now.getDate() || 816 (until.getDate() >= Math.min(lastNow, lastUntil) && 817 now.getDate() >= Math.min(lastNow, lastUntil))); 818 var getSecs = function(date) { 819 return (date.getHours() * 60 + date.getMinutes()) * 60 + date.getSeconds(); 820 }; 821 var months = Math.max(0, 822 (until.getFullYear() - now.getFullYear()) * 12 + until.getMonth() - now.getMonth() + 823 ((until.getDate() < now.getDate() && !sameDay) || 824 (sameDay && getSecs(until) < getSecs(now)) ? -1 : 0)); 825 periods[Y] = (show[Y] ? Math.floor(months / 12) : 0); 826 periods[O] = (show[O] ? months - periods[Y] * 12 : 0); 827 // Adjust for months difference and end of month if necessary 828 now = new Date(now.getTime()); 829 var wasLastDay = (now.getDate() == lastNow); 830 var lastDay = this._getDaysInMonth(now.getFullYear() + periods[Y], 831 now.getMonth() + periods[O]); 832 if (now.getDate() > lastDay) { 833 now.setDate(lastDay); 834 } 835 now.setFullYear(now.getFullYear() + periods[Y]); 836 now.setMonth(now.getMonth() + periods[O]); 837 if (wasLastDay) { 838 now.setDate(lastDay); 839 } 840 } 841 var diff = Math.floor((until.getTime() - now.getTime()) / 1000); 842 var extractPeriod = function(period, numSecs) { 843 periods[period] = (show[period] ? Math.floor(diff / numSecs) : 0); 844 diff -= periods[period] * numSecs; 845 }; 846 extractPeriod(W, 604800); 847 extractPeriod(D, 86400); 848 extractPeriod(H, 3600); 849 extractPeriod(M, 60); 850 extractPeriod(S, 1); 851 if (diff > 0 && !inst._since) { // Round up if left overs 852 var multiplier = [1, 12, 4.3482, 7, 24, 60, 60]; 853 var lastShown = S; 854 var max = 1; 855 for (var period = S; period >= Y; period--) { 856 if (show[period]) { 857 if (periods[lastShown] >= max) { 858 periods[lastShown] = 0; 859 diff = 1; 860 } 861 if (diff > 0) { 862 periods[period]++; 863 diff = 0; 864 lastShown = period; 865 max = 1; 866 } 867 } 868 max *= multiplier[period]; 869 } 870 } 871 if (significant) { // Zero out insignificant periods 872 for (var period = Y; period <= S; period++) { 873 if (significant && periods[period]) { 874 significant--; 875 } 876 else if (!significant) { 877 periods[period] = 0; 878 } 879 } 880 } 881 return periods; 882 } 883 }); 884 885})(jQuery);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.