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',
208 /* Class name for the period amount marker. */ 209 _amountClass: pluginName + '-amount', 210 /* Class name for the period name marker. */ 211 _periodClass: pluginName + '-period', 212 /* Class name for the countdown row marker. */ 213 _rowClass: pluginName + '-row', 214 /* Class name for the holding countdown marker. */ 215 _holdingClass: pluginName + '-holding', 216 /* Class name for the showing countdown marker. */ 217 _showClass: pluginName + '-show', 218 /* Class name for the description marker. */ 219 _descrClass: pluginName + '-descr', 220 221 /* List of currently active countdown elements. */ 222 _timerElems: [], 223 224 /** Additional setup for the countdown. 225 Apply default localisations. 226 Create the timer. 227 @private */ 228 _init: function() { 229 var self = this; 230 this._super(); 231 this._serverSyncs = []; 232 var now = (typeof Date.now === 'function' ? Date.now : function() { return new Date().getTime(); }); 233 var perfAvail = (window.performance && typeof window.performance.now === 'function'); 234 // Shared timer for all countdowns 235 function timerCallBack(timestamp) { 236 var drawStart = (timestamp < 1e12 ? // New HTML5 high resolution timer 237 (perfAvail ? (window.performance.now() + window.performance.timing.navigationStart) : now()) : 238 // Integer milliseconds since unix epoch 239 timestamp || now()); 240 if (drawStart - animationStartTime >= 1000) { 241 self._updateElems(); 242 animationStartTime = drawStart; 243 } 244 requestAnimationFrame(timerCallBack); 245 } 246 var requestAnimationFrame = window.requestAnimationFrame || 247 window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || 248 window.oRequestAnimationFrame || window.msRequestAnimationFrame || null; 249 // This is when we expect a fall-back to setInterval as it's much more fluid 250 var animationStartTime = 0; 251 if (!requestAnimationFrame || $.noRequestAnimationFrame) { 252 $.noRequestAnimationFrame = null; 253 // Fall back to good old setInterval 254 $.countdown._timer = setInterval(function() { self._updateElems(); }, 1000); 255 } 256 else { 257 animationStartTime = window.animationStartTime || 258 window.webkitAnimationStartTime || window.mozAnimationStartTime || 259 window.oAnimationStartTime || window.msAnimationStartTime || now(); 260 requestAnimationFrame(timerCallBack); 261 } 262 }, 263 264 /** Convert a date/time to UTC. 265 @param {number} tz The hour or minute offset from GMT, e.g. +9, -360. 266 @param {Date|number} year the date/time in that timezone or the year in that timezone. 267 @param {number} [month] The month (0 - 11) (omit if <code>year</code> is a <code>Date</code>). 268 @param {number} [day] The day (omit if <code>year</code> is a <code>Date</code>). 269 @param {number} [hours] The hour (omit if <code>year</code> is a <code>Date</code>). 270 @param {number} [mins] The minute (omit if <code>year</code> is a <code>Date</code>). 271 @param {number} [secs] The second (omit if <code>year</code> is a <code>Date</code>). 272 @param {number} [ms] The millisecond (omit if <code>year</code> is a <code>Date</code>). 273 @return {Date} The equivalent UTC date/time. 274 @example $.countdown.UTCDate(+10, 2013, 12-1, 25, 12, 0) 275$.countdown.UTCDate(-7, new Date(2013, 12-1, 25, 12, 0)) */ 276 UTCDate: function(tz, year, month, day, hours, mins, secs, ms) { 277 if (typeof year === 'object' && year instanceof Date) { 278 ms = year.getMilliseconds(); 279 secs = year.getSeconds(); 280 mins = year.getMinutes(); 281 hours = year.getHours(); 282 day = year.getDate(); 283 month = year.getMonth(); 284 year = year.getFullYear(); 285 } 286 var d = new Date(); 287 d.setUTCFullYear(year); 288 d.setUTCDate(1); 289 d.setUTCMonth(month || 0); 290 d.setUTCDate(day || 1); 291 d.setUTCHours(hours || 0); 292 d.setUTCMinutes((mins || 0) - (Math.abs(tz) < 30 ? tz * 60 : tz)); 293 d.setUTCSeconds(secs || 0); 294 d.setUTCMilliseconds(ms || 0); 295 return d; 296 }, 297 298 /** Convert a set of periods into seconds. 299 Averaged for months and years. 300 @param {number[]} periods The periods per year/month/week/day/hour/minute/second. 301 @return {number} The corresponding number of seconds. 302 @example var secs = $.countdown.periodsToSeconds(periods) */
303 periodsToSeconds: function(periods) { 304 return periods[0] * 31557600 + periods[1] * 2629800 + periods[2] * 604800 + 305 periods[3] * 86400 + periods[4] * 3600 + periods[5] * 60 + periods[6]; 306 }, 307 308 /** Resynchronise the countdowns with the server. 309 @example $.countdown.resync() */ 310 resync: function() { 311 var self = this; 312 $('.' + this._getMarker()).each(function() { // Each countdown 313 var inst = $.data(this, self.name); 314 if (inst.options.serverSync) { // If synced 315 var serverSync = null; 316 for (var i = 0; i < self._serverSyncs.length; i++) { 317 if (self._serverSyncs[i][0] === inst.options.serverSync) { // Find sync details 318 serverSync = self._serverSyncs[i]; 319 break; 320 } 321 } 322 if (self._eqNull(serverSync[2])) { // Recalculate if missing 323 var serverResult = ($.isFunction(inst.options.serverSync) ? 324 inst.options.serverSync.apply(this, []) : null); 325 serverSync[2] = 326 (serverResult ? new Date().getTime() - serverResult.getTime() : 0) - serverSync[1]; 327 } 328 if (inst._since) { // Apply difference 329 inst._since.setMilliseconds(inst._since.getMilliseconds() + serverSync[2]); 330 } 331 inst._until.setMilliseconds(inst._until.getMilliseconds() + serverSync[2]); 332 } 333 }); 334 for (var i = 0; i < self._serverSyncs.length; i++) { // Update sync details 335 if (!self._eqNull(self._serverSyncs[i][2])) { 336 self._serverSyncs[i][1] += self._serverSyncs[i][2]; 337 delete self._serverSyncs[i][2]; 338 } 339 } 340 }, 341 342 _instSettings: function(elem, options) { // jshint unused:false 343 return {_periods: [0, 0, 0, 0, 0, 0, 0]}; 344 }, 345 346 /** Add an element to the list of active ones. 347 @private 348 @param {Element} elem The countdown element. */ 349 _addElem: function(elem) { 350 if (!this._hasElem(elem)) { 351 this._timerElems.push(elem); 352 } 353 }, 354 355 /** See if an element is in the list of active ones. 356 @private 357 @param {Element} elem The countdown element. 358 @return {boolean} <code>true</code> if present, <code>false</code> if not. */ 359 _hasElem: function(elem) { 360 return ($.inArray(elem, this._timerElems) > -1); 361 }, 362 363 /** Remove an element from the list of active ones. 364 @private 365 @param {Element} elem The countdown element. */ 366 _removeElem: function(elem) { 367 this._timerElems = $.map(this._timerElems, 368 function(value) { return (value === elem ? null : value); }); // delete entry 369 }, 370 371 /** Update each active timer element. 372 @private */ 373 _updateElems: function() { 374 for (var i = this._timerElems.length - 1; i >= 0; i--) { 375 this._updateCountdown(this._timerElems[i]); 376 } 377 }, 378 379 _optionsChanged: function(elem, inst, options) { 380 if (options.layout) { 381 options.layout = options.layout.replace(/</g, '<').replace(/>/g, '>'); 382 } 383 this._resetExtraLabels(inst.options, options); 384 var timezoneChanged = (inst.options.timezone !== options.timezone); 385 $.extend(inst.options, options); 386 this._adjustSettings(elem, inst, 387 !this._eqNull(options.until) || !this._eqNull(options.since) || timezoneChanged); 388 var now = new Date(); 389 if ((inst._since && inst._since < now) || (inst._until && inst._until > now)) { 390 this._addElem(elem[0]); 391 } 392 this._updateCountdown(elem, inst); 393 }, 394 395 /** Redisplay the countdown with an updated display. 396 @private 397 @param {Element|jQuery} elem The containing element. 398 @param {object} inst The current settings for this instance. */ 399 _updateCountdown: function(elem, inst) { 400 elem = elem.jquery ? elem : $(elem); 401 inst = inst || this._getInst(elem); 402 if (!inst) { 403 return; 404 } 405 elem.html(this._generateHTML(inst)).toggleClass(this._rtlClass, inst.options.isRTL); 406 if (inst._hold !== 'pause' && $.isFunction(inst.options.onTick)) { 407 var periods = inst._hold !== 'lap' ? inst._periods : 408 this._calculatePeriods(inst, inst._show, inst.options.significant, new Date()); 409 if (inst.options.tickInterval === 1 || 410 this.periodsToSeconds(periods) % inst.options.tickInterval === 0) { 411 inst.options.onTick.apply(elem[0], [periods]); 412 } 413 } 414 var expired = inst._hold !== 'pause' && 415 (inst._since ? inst._now.getTime() < inst._since.getTime() : 416 inst._now.getTime() >= inst._until.getTime()); 417 if (expired && !inst._expiring) { 418 inst._expiring = true; 419 if (this._hasElem(elem[0]) || inst.options.alwaysExpire) { 420 this._removeElem(elem[0]); 421 if ($.isFunction(inst.options.onExpiry)) { 422 inst.options.onExpiry.apply(elem[0], []); 423 } 424 if (inst.options.expiryText) { 425 var layout = inst.options.layout; 426 inst.options.layout = inst.options.expiryText; 427 this._updateCountdown(elem[0], inst); 428 inst.options.layout = layout; 429 } 430 if (inst.options.expiryUrl) { 431 window.location = inst.options.expiryUrl; 432 } 433 } 434 inst._expiring = false;
435 } 436 else if (inst._hold === 'pause') { 437 this._removeElem(elem[0]); 438 } 439 }, 440 441 /** Reset any extra labelsn and compactLabelsn entries if changing labels. 442 @private 443 @param {object} base The options to be updated. 444 @param {object} options The new option values. */ 445 _resetExtraLabels: function(base, options) { 446 var n = null; 447 for (n in options) { 448 if (n.match(/[Ll]abels[02-9]|compactLabels1/)) { 449 base[n] = options[n]; 450 } 451 } 452 for (n in base) { // Remove custom numbered labels 453 if (n.match(/[Ll]abels[02-9]|compactLabels1/) && typeof options[n] === 'undefined') { 454 base[n] = null; 455 } 456 } 457 }, 458 459 /** Determine whether or not a value is equivalent to <code>null</code>. 460 @private 461 @param {object} value The value to test. 462 @return {boolean} <code>true</code> if equivalent to <code>null</code>, <code>false</code> if not. */ 463 _eqNull: function(value) { 464 return typeof value === 'undefined' || value === null; 465 }, 466 467 468 /** Calculate internal settings for an instance. 469 @private 470 @param {jQuery} elem The containing element. 471 @param {object} inst The current settings for this instance. 472 @param {boolean} recalc <code>true</code> if until or since are set. */ 473 _adjustSettings: function(elem, inst, recalc) { 474 var serverEntry = null; 475 for (var i = 0; i < this._serverSyncs.length; i++) { 476 if (this._serverSyncs[i][0] === inst.options.serverSync) { 477 serverEntry = this._serverSyncs[i][1]; 478 break; 479 } 480 } 481 var now = null; 482 var serverOffset = null; 483 if (!this._eqNull(serverEntry)) { 484 now = new Date(); 485 serverOffset = (inst.options.serverSync ? serverEntry : 0); 486 } 487 else { 488 var serverResult = ($.isFunction(inst.options.serverSync) ? 489 inst.options.serverSync.apply(elem[0], []) : null); 490 now = new Date(); 491 serverOffset = (serverResult ? now.getTime() - serverResult.getTime() : 0); 492 this._serverSyncs.push([inst.options.serverSync, serverOffset]); 493 } 494 var timezone = inst.options.timezone; 495 timezone = (this._eqNull(timezone) ? -now.getTimezoneOffset() : timezone); 496 if (recalc || (!recalc && this._eqNull(inst._until) && this._eqNull(inst._since))) { 497 inst._since = inst.options.since; 498 if (!this._eqNull(inst._since)) { 499 inst._since = this.UTCDate(timezone, this._determineTime(inst._since, null)); 500 if (inst._since && serverOffset) { 501 inst._since.setMilliseconds(inst._since.getMilliseconds() + serverOffset); 502 } 503 } 504 inst._until = this.UTCDate(timezone, this._determineTime(inst.options.until, now)); 505 if (serverOffset) { 506 inst._until.setMilliseconds(inst._until.getMilliseconds() + serverOffset); 507 } 508 } 509 inst._show = this._determineShow(inst); 510 }, 511 512 /** Remove the countdown widget from an element. 513 @private 514 @param {jQuery} elem The containing element. 515 @param {object} inst The current instance object. */ 516 _preDestroy: function(elem, inst) { // jshint unused:false 517 this._removeElem(elem[0]); 518 elem.empty(); 519 }, 520 521 /** Pause a countdown widget at the current time. 522 Stop it running but remember and display the current time. 523 @param {Element} elem The containing element. 524 @example $(selector).countdown('pause') */ 525 pause: function(elem) { 526 this._hold(elem, 'pause'); 527 }, 528 529 /** Pause a countdown widget at the current time. 530 Stop the display but keep the countdown running. 531 @param {Element} elem The containing element. 532 @example $(selector).countdown('lap') */ 533 lap: function(elem) { 534 this._hold(elem, 'lap'); 535 }, 536 537 /** Resume a paused countdown widget. 538 @param {Element} elem The containing element. 539 @example $(selector).countdown('resume') */ 540 resume: function(elem) { 541 this._hold(elem, null); 542 }, 543 544 /** Toggle a paused countdown widget. 545 @param {Element} elem The containing element. 546 @example $(selector).countdown('toggle') */ 547 toggle: function(elem) { 548 var inst = $.data(elem, this.name) || {}; 549 this[!inst._hold ? 'pause' : 'resume'](elem); 550 }, 551 552 /** Toggle a lapped countdown widget. 553 @param {Element} elem The containing element. 554 @example $(selector).countdown('toggleLap') */ 555 toggleLap: function(elem) { 556 var inst = $.data(elem, this.name) || {}; 557 this[!inst._hold ? 'lap' : 'resume'](elem); 558 }, 559 560 /** Pause or resume a countdown widget. 561 @private 562 @param {Element} elem The containing element. 563 @param {string} hold The new hold setting. */ 564 _hold: function(elem, hold) { 565 var inst = $.data(elem, this.name); 566 if (inst) { 567 if (inst._hold === 'pause' && !hold) {
568 inst._periods = inst._savePeriods; 569 var sign = (inst._since ? '-' : '+'); 570 inst[inst._since ? '_since' : '_until'] = 571 this._determineTime(sign + inst._periods[0] + 'y' + 572 sign + inst._periods[1] + 'o' + sign + inst._periods[2] + 'w' + 573 sign + inst._periods[3] + 'd' + sign + inst._periods[4] + 'h' + 574 sign + inst._periods[5] + 'm' + sign + inst._periods[6] + 's'); 575 this._addElem(elem); 576 } 577 inst._hold = hold; 578 inst._savePeriods = (hold === 'pause' ? inst._periods : null); 579 $.data(elem, this.name, inst); 580 this._updateCountdown(elem, inst); 581 } 582 }, 583 584 /** Return the current time periods, broken down by years, months, weeks, days, hours, minutes, and seconds. 585 @param {Element} elem The containing element. 586 @return {number[]} The current periods for the countdown. 587 @example var periods = $(selector).countdown('getTimes') */ 588 getTimes: function(elem) { 589 var inst = $.data(elem, this.name); 590 return (!inst ? null : (inst._hold === 'pause' ? inst._savePeriods : (!inst._hold ? inst._periods : 591 this._calculatePeriods(inst, inst._show, inst.options.significant, new Date())))); 592 }, 593 594 /** A time may be specified as an exact value or a relative one. 595 @private 596 @param {string|number|Date} setting The date/time value as a relative or absolute value. 597 @param {Date} defaultTime The date/time to use if no other is supplied. 598 @return {Date} The corresponding date/time. */ 599 _determineTime: function(setting, defaultTime) { 600 var self = this; 601 var offsetNumeric = function(offset) { // e.g. +300, -2 602 var time = new Date(); 603 time.setTime(time.getTime() + offset * 1000); 604 return time; 605 }; 606 var offsetString = function(offset) { // e.g. '+2d', '-4w', '+3h +30m' 607 offset = offset.toLowerCase(); 608 var time = new Date(); 609 var year = time.getFullYear(); 610 var month = time.getMonth(); 611 var day = time.getDate(); 612 var hour = time.getHours(); 613 var minute = time.getMinutes(); 614 var second = time.getSeconds(); 615 var pattern = /([+-]?[0-9]+)\s*(s|m|h|d|w|o|y)?/g; 616 var matches = pattern.exec(offset); 617 while (matches) { 618 switch (matches[2] || 's') { 619 case 's': 620 second += parseInt(matches[1], 10); 621 break; 622 case 'm': 623 minute += parseInt(matches[1], 10); 624 break; 625 case 'h': 626 hour += parseInt(matches[1], 10); 627 break; 628 case 'd': 629 day += parseInt(matches[1], 10); 630 break; 631 case 'w': 632 day += parseInt(matches[1], 10) * 7; 633 break; 634 case 'o': 635 month += parseInt(matches[1], 10); 636 day = Math.min(day, self._getDaysInMonth(year, month)); 637 break; 638 case 'y': 639 year += parseInt(matches[1], 10); 640 day = Math.min(day, self._getDaysInMonth(year, month)); 641 break; 642 } 643 matches = pattern.exec(offset); 644 } 645 return new Date(year, month, day, hour, minute, second, 0); 646 }; 647 var time = (this._eqNull(setting) ? defaultTime : 648 (typeof setting === 'string' ? offsetString(setting) : 649 (typeof setting === 'number' ? offsetNumeric(setting) : setting))); 650 if (time) { 651 time.setMilliseconds(0); 652 } 653 return time; 654 }, 655 656 /** Determine the number of days in a month. 657 @private 658 @param {number} year The year. 659 @param {number} month The month. 660 @return {number} The days in that month. */ 661 _getDaysInMonth: function(year, month) { 662 return 32 - new Date(year, month, 32).getDate(); 663 }, 664 665 /** Default implementation to determine which set of labels should be used for an amount. 666 Use the <code>labels</code> attribute with the same numeric suffix (if it exists). 667 @private 668 @param {number} num The amount to be displayed. 669 @return {number} The set of labels to be used for this amount. */ 670 _normalLabels: function(num) { 671 return num; 672 }, 673 674 /** Generate the HTML to display the countdown widget. 675 @private 676 @param {object} inst The current settings for this instance. 677 @return {string} The new HTML for the countdown display. */ 678 _generateHTML: function(inst) { 679 var self = this; 680 // Determine what to show
681 inst._periods = (inst._hold ? inst._periods : 682 this._calculatePeriods(inst, inst._show, inst.options.significant, new Date())); 683 // Show all 'asNeeded' after first non-zero value 684 var shownNonZero = false; 685 var showCount = 0; 686 var sigCount = inst.options.significant; 687 var show = $.extend({}, inst._show); 688 var period = null; 689 for (period = Y; period <= S; period++) { 690 shownNonZero = shownNonZero || (inst._show[period] === '?' && inst._periods[period] > 0); 691 show[period] = (inst._show[period] === '?' && !shownNonZero ? null : inst._show[period]); 692 showCount += (show[period] ? 1 : 0); 693 sigCount -= (inst._periods[period] > 0 ? 1 : 0); 694 } 695 var showSignificant = [false, false, false, false, false, false, false]; 696 for (period = S; period >= Y; period--) { // Determine significant periods 697 if (inst._show[period]) { 698 if (inst._periods[period]) { 699 showSignificant[period] = true; 700 } 701 else { 702 showSignificant[period] = sigCount > 0; 703 sigCount--; 704 } 705 } 706 } 707 var labels = (inst.options.compact ? inst.options.compactLabels : inst.options.labels); 708 var whichLabels = inst.options.whichLabels || this._normalLabels; 709 var showCompact = function(period) { 710 var labelsNum = inst.options['compactLabels' + whichLabels(inst._periods[period])]; 711 return (show[period] ? self._translateDigits(inst, inst._periods[period]) + 712 (labelsNum ? labelsNum[period] : labels[period]) + ' ' : ''); 713 }; 714 var minDigits = (inst.options.padZeroes ? 2 : 1); 715 var showFull = function(period) { 716 var labelsNum = inst.options['labels' + whichLabels(inst._periods[period])]; 717 return ((!inst.options.significant && show[period]) || 718 (inst.options.significant && showSignificant[period]) ? 719 '<span class="' + self._sectionClass + '">' + 720 '<span class="' + self._amountClass + '">' + 721 self._minDigits(inst, inst._periods[period], minDigits) + '</span>' + 722 '<span class="' + self._periodClass + '">' + 723 (labelsNum ? labelsNum[period] : labels[period]) + '</span></span>' : ''); 724 }; 725 return (inst.options.layout ? this._buildLayout(inst, show, inst.options.layout, 726 inst.options.compact, inst.options.significant, showSignificant) : 727 ((inst.options.compact ? // Compact version 728 '<span class="' + this._rowClass + ' ' + this._amountClass + 729 (inst._hold ? ' ' + this._holdingClass : '') + '">' + 730 showCompact(Y) + showCompact(O) + showCompact(W) + showCompact(D) + 731 (show[H] ? this._minDigits(inst, inst._periods[H], 2) : '') + 732 (show[M] ? (show[H] ? inst.options.timeSeparator : '') + 733 this._minDigits(inst, inst._periods[M], 2) : '') + 734 (show[S] ? (show[H] || show[M] ? inst.options.timeSeparator : '') + 735 this._minDigits(inst, inst._periods[S], 2) : '') : 736 // Full version 737 '<span class="' + this._rowClass + ' ' + this._showClass + (inst.options.significant || showCount) + 738 (inst._hold ? ' ' + this._holdingClass : '') + '">' + 739 showFull(Y) + showFull(O) + showFull(W) + showFull(D) + 740 showFull(H) + showFull(M) + showFull(S)) + '</span>' + 741 (inst.options.description ? '<span class="' + this._rowClass + ' ' + this._descrClass + '">' + 742 inst.options.description + '</span>' : ''))); 743 }, 744 745 /** Construct a custom layout. 746 @private 747 @param {object} inst The current settings for this instance. 748 @param {boolean[]} show Flags indicating which periods are requested. 749 @param {string} layout The customised layout. 750 @param {boolean} compact <code>true</code> if using compact labels. 751 @param {number} significant The number of periods with values to show, zero for all. 752 @param {boolean[]} showSignificant Other periods to show for significance. 753 @return {string} The custom HTML. */ 754 _buildLayout: function(inst, show, layout, compact, significant, showSignificant) { 755 var labels = inst.options[compact ? 'compactLabels' : 'labels']; 756 var whichLabels = inst.options.whichLabels || this._normalLabels; 757 var labelFor = function(index) { 758 return (inst.options[(compact ? 'compactLabels' : 'labels') +
759 whichLabels(inst._periods[index])] || labels)[index]; 760 }; 761 var digit = function(value, position) { 762 return inst.options.digits[Math.floor(value / position) % 10]; 763 }; 764 var subs = {desc: inst.options.description, sep: inst.options.timeSeparator, 765 yl: labelFor(Y), yn: this._minDigits(inst, inst._periods[Y], 1), 766 ynn: this._minDigits(inst, inst._periods[Y], 2), 767 ynnn: this._minDigits(inst, inst._periods[Y], 3), y1: digit(inst._periods[Y], 1), 768 y10: digit(inst._periods[Y], 10), y100: digit(inst._periods[Y], 100), 769 y1000: digit(inst._periods[Y], 1000), 770 ol: labelFor(O), on: this._minDigits(inst, inst._periods[O], 1), 771 onn: this._minDigits(inst, inst._periods[O], 2), 772 onnn: this._minDigits(inst, inst._periods[O], 3), o1: digit(inst._periods[O], 1), 773 o10: digit(inst._periods[O], 10), o100: digit(inst._periods[O], 100), 774 o1000: digit(inst._periods[O], 1000), 775 wl: labelFor(W), wn: this._minDigits(inst, inst._periods[W], 1), 776 wnn: this._minDigits(inst, inst._periods[W], 2), 777 wnnn: this._minDigits(inst, inst._periods[W], 3), w1: digit(inst._periods[W], 1), 778 w10: digit(inst._periods[W], 10), w100: digit(inst._periods[W], 100), 779 w1000: digit(inst._periods[W], 1000), 780 dl: labelFor(D), dn: this._minDigits(inst, inst._periods[D], 1), 781 dnn: this._minDigits(inst, inst._periods[D], 2), 782 dnnn: this._minDigits(inst, inst._periods[D], 3), d1: digit(inst._periods[D], 1), 783 d10: digit(inst._periods[D], 10), d100: digit(inst._periods[D], 100), 784 d1000: digit(inst._periods[D], 1000), 785 hl: labelFor(H), hn: this._minDigits(inst, inst._periods[H], 1), 786 hnn: this._minDigits(inst, inst._periods[H], 2), 787 hnnn: this._minDigits(inst, inst._periods[H], 3), h1: digit(inst._periods[H], 1), 788 h10: digit(inst._periods[H], 10), h100: digit(inst._periods[H], 100), 789 h1000: digit(inst._periods[H], 1000), 790 ml: labelFor(M), mn: this._minDigits(inst, inst._periods[M], 1), 791 mnn: this._minDigits(inst, inst._periods[M], 2), 792 mnnn: this._minDigits(inst, inst._periods[M], 3), m1: digit(inst._periods[M], 1), 793 m10: digit(inst._periods[M], 10), m100: digit(inst._periods[M], 100), 794 m1000: digit(inst._periods[M], 1000), 795 sl: labelFor(S), sn: this._minDigits(inst, inst._periods[S], 1), 796 snn: this._minDigits(inst, inst._periods[S], 2), 797 snnn: this._minDigits(inst, inst._periods[S], 3), s1: digit(inst._periods[S], 1), 798 s10: digit(inst._periods[S], 10), s100: digit(inst._periods[S], 100), 799 s1000: digit(inst._periods[S], 1000)}; 800 var html = layout; 801 // Replace period containers: {p<}...{p>} 802 for (var i = Y; i <= S; i++) { 803 var period = 'yowdhms'.charAt(i); 804 var re = new RegExp('\\{' + period + '<\\}([\\s\\S]*)\\{' + period + '>\\}', 'g'); 805 html = html.replace(re, ((!significant && show[i]) || 806 (significant && showSignificant[i]) ? '$1' : '')); 807 } 808 // Replace period values: {pn} 809 $.each(subs, function(n, v) { 810 var re = new RegExp('\\{' + n + '\\}', 'g'); 811 html = html.replace(re, v); 812 }); 813 return html; 814 }, 815 816 /** Ensure a numeric value has at least n digits for display. 817 @private 818 @param {object} inst The current settings for this instance. 819 @param {number} value The value to display. 820 @param {number} len The minimum length. 821 @return {string} The display text. */ 822 _minDigits: function(inst, value, len) { 823 value = '' + value; 824 if (value.length >= len) { 825 return this._translateDigits(inst, value); 826 } 827 value = '0000000000' + value; 828 return this._translateDigits(inst, value.substr(value.length - len)); 829 }, 830 831 /** Translate digits into other representations. 832 @private 833 @param {object} inst The current settings for this instance. 834 @param {string} value The text to translate. 835 @return {string} The translated text. */ 836 _translateDigits: function(inst, value) { 837 return ('' + value).replace(/[0-9]/g, function(digit) { 838 return inst.options.digits[digit]; 839 }); 840 }, 841 842 /** Translate the format into flags for each period. 843 @private 844 @param {object} inst The current settings for this instance. 845 @return {string[]} Flags indicating which periods are requested (?) or 846 required (!) by year, month, week, day, hour, minute, second. */ 847 _determineShow: function(inst) { 848 var format = inst.options.format; 849 var show = []; 850 show[Y] = (format.match('y') ? '?' : (format.match('Y') ? '!' : null)); 851 show[O] = (format.match('o') ? '?' : (format.match('O') ? '!' : null)); 852 show[W] = (format.match('w') ? '?' : (format.match('W') ? '!' : null)); 853 show[D] = (format.match('d') ? '?' : (format.match('D') ? '!' : null)); 854 show[H] = (format.match('h') ? '?' : (format.match('H') ? '!' : null)); 855 show[M] = (format.match('m') ? '?' : (format.match('M') ? '!' : null)); 856 show[S] = (format.match('s') ? '?' : (format.match('S') ? '!' : null)); 857 return show; 858 }, 859 860 /** Calculate the requested periods between now and the target time. 861 @private 862 @param {object} inst The current settings for this instance. 863 @param {string[]} show Flags indicating which periods are requested/required. 864 @param {number} significant The number of periods with values to show, zero for all. 865 @param {Date} now The current date and time. 866 @return {number[]} The current time periods (always positive) 867 by year, month, week, day, hour, minute, second. */
868 _calculatePeriods: function(inst, show, significant, now) { 869 // Find endpoints 870 inst._now = now; 871 inst._now.setMilliseconds(0); 872 var until = new Date(inst._now.getTime()); 873 if (inst._since) { 874 if (now.getTime() < inst._since.getTime()) { 875 inst._now = now = until; 876 } 877 else { 878 now = inst._since; 879 } 880 } 881 else { 882 until.setTime(inst._until.getTime()); 883 if (now.getTime() > inst._until.getTime()) { 884 inst._now = now = until; 885 } 886 } 887 // Calculate differences by period 888 var periods = [0, 0, 0, 0, 0, 0, 0]; 889 if (show[Y] || show[O]) { 890 // Treat end of months as the same 891 var lastNow = this._getDaysInMonth(now.getFullYear(), now.getMonth()); 892 var lastUntil = this._getDaysInMonth(until.getFullYear(), until.getMonth()); 893 var sameDay = (until.getDate() === now.getDate() || 894 (until.getDate() >= Math.min(lastNow, lastUntil) && 895 now.getDate() >= Math.min(lastNow, lastUntil))); 896 var getSecs = function(date) { 897 return (date.getHours() * 60 + date.getMinutes()) * 60 + date.getSeconds(); 898 }; 899 var months = Math.max(0, 900 (until.getFullYear() - now.getFullYear()) * 12 + until.getMonth() - now.getMonth() + 901 ((until.getDate() < now.getDate() && !sameDay) || 902 (sameDay && getSecs(until) < getSecs(now)) ? -1 : 0)); 903 periods[Y] = (show[Y] ? Math.floor(months / 12) : 0); 904 periods[O] = (show[O] ? months - periods[Y] * 12 : 0); 905 // Adjust for months difference and end of month if necessary 906 now = new Date(now.getTime()); 907 var wasLastDay = (now.getDate() === lastNow); 908 var lastDay = this._getDaysInMonth(now.getFullYear() + periods[Y], 909 now.getMonth() + periods[O]); 910 if (now.getDate() > lastDay) { 911 now.setDate(lastDay); 912 } 913 now.setFullYear(now.getFullYear() + periods[Y]); 914 now.setMonth(now.getMonth() + periods[O]); 915 if (wasLastDay) { 916 now.setDate(lastDay); 917 } 918 } 919 var diff = Math.floor((until.getTime() - now.getTime()) / 1000); 920 var period = null; 921 var extractPeriod = function(period, numSecs) { 922 periods[period] = (show[period] ? Math.floor(diff / numSecs) : 0); 923 diff -= periods[period] * numSecs; 924 }; 925 extractPeriod(W, 604800); 926 extractPeriod(D, 86400); 927 extractPeriod(H, 3600); 928 extractPeriod(M, 60); 929 extractPeriod(S, 1); 930 if (diff > 0 && !inst._since) { // Round up if left overs 931 var multiplier = [1, 12, 4.3482, 7, 24, 60, 60]; 932 var lastShown = S; 933 var max = 1; 934 for (period = S; period >= Y; period--) { 935 if (show[period]) { 936 if (periods[lastShown] >= max) { 937 periods[lastShown] = 0; 938 diff = 1; 939 } 940 if (diff > 0) { 941 periods[period]++; 942 diff = 0; 943 lastShown = period; 944 max = 1; 945 } 946 } 947 max *= multiplier[period]; 948 } 949 } 950 if (significant) { // Zero out insignificant periods 951 for (period = Y; period <= S; period++) { 952 if (significant && periods[period]) { 953 significant--; 954 } 955 else if (!significant) { 956 periods[period] = 0; 957 } 958 } 959 } 960 return periods; 961 } 962 }); 963 964})(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.