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