https://potatocongress.org/wp-content/plugins/bb-ultimate-addon/mo…/js/jquery.countdown.js?ver=7.1.2
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 || !inst.options) { 351 return; 352 } 353 // Code added By azhar - To resolve ajax loading error on 18 Sep 2016 354 if ( !inst.name ) { 355 elem = $( "#" + elem[0].id ).countdown('option', inst); 356 inst = this._getInst(elem); 357 } 358 //Ends here 359 360 elem.html(this._generateHTML(inst)).toggleClass(this._rtlClass, inst.options.isRTL); 361 if ($.isFunction(inst.options.onTick)) { 362 var periods = inst._hold != 'lap' ? inst._periods : 363 this._calculatePeriods(inst, inst._show, inst.options.significant, new Date()); 364 if (inst.options.tickInterval == 1 || 365 this.periodsToSeconds(periods) % inst.options.tickInterval == 0) {
366 inst.options.onTick.apply(elem[0], [periods]); 367 } 368 } 369 var expired = inst._hold != 'pause' && 370 (inst._since ? inst._now.getTime() < inst._since.getTime() : 371 inst._now.getTime() >= inst._until.getTime()); 372 if (expired && !inst._expiring) { 373 inst._expiring = true; 374 if (this._hasElem(elem[0]) || inst.options.alwaysExpire) { 375 this._removeElem(elem[0]); 376 if ($.isFunction(inst.options.onExpiry)) { 377 inst.options.onExpiry.apply(elem[0], []); 378 } 379 if (inst.options.expiryText) { 380 var layout = inst.options.layout; 381 inst.options.layout = inst.options.expiryText; 382 this._updateCountdown(elem[0], inst); 383 inst.options.layout = layout; 384 } 385 if (inst.options.expiryUrl) { 386 window.location = inst.options.expiryUrl; 387 } 388 } 389 inst._expiring = false; 390 } 391 else if (inst._hold == 'pause') { 392 this._removeElem(elem[0]); 393 } 394 }, 395 396 /** Reset any extra labelsn and compactLabelsn entries if changing labels. 397 @private 398 @param base {object} The options to be updated. 399 @param options {object} The new option values. */ 400 _resetExtraLabels: function(base, options) { 401 for (var n in options) { 402 if (n.match(/[Ll]abels[02-9]|compactLabels1/)) { 403 base[n] = options[n]; 404 } 405 } 406 for (var n in base) { // Remove custom numbered labels 407 if (n.match(/[Ll]abels[02-9]|compactLabels1/) && typeof options[n] === 'undefined') { 408 base[n] = null; 409 } 410 } 411 }, 412 413 /** Calculate internal settings for an instance. 414 @private 415 @param elem {jQuery} The containing division. 416 @param inst {object} The current settings for this instance. 417 @param recalc {boolean} True if until or since are set. */ 418 _adjustSettings: function(elem, inst, recalc) { 419 var serverEntry = null; 420 for (var i = 0; i < this._serverSyncs.length; i++) { 421 if (this._serverSyncs[i][0] == inst.options.serverSync) { 422 serverEntry = this._serverSyncs[i][1]; 423 break; 424 } 425 } 426 if (serverEntry != null) { 427 var serverOffset = (inst.options.serverSync ? serverEntry : 0); 428 var now = new Date(); 429 } 430 else { 431 var serverResult = ($.isFunction(inst.options.serverSync) ? 432 inst.options.serverSync.apply(elem[0], []) : null); 433 var now = new Date(); 434 var serverOffset = (serverResult ? now.getTime() - serverResult.getTime() : 0); 435 this._serverSyncs.push([inst.options.serverSync, serverOffset]); 436 } 437 var timezone = inst.options.timezone; 438 timezone = (timezone == null ? -now.getTimezoneOffset() : timezone); 439 if (recalc || (!recalc && inst._until == null && inst._since == null)) { 440 inst._since = inst.options.since; 441 if (inst._since != null) { 442 inst._since = this.UTCDate(timezone, this._determineTime(inst._since, null)); 443 if (inst._since && serverOffset) { 444 inst._since.setMilliseconds(inst._since.getMilliseconds() + serverOffset); 445 } 446 } 447 inst._until = this.UTCDate(timezone, this._determineTime(inst.options.until, now)); 448 if (serverOffset) { 449 inst._until.setMilliseconds(inst._until.getMilliseconds() + serverOffset); 450 } 451 } 452 inst._show = this._determineShow(inst); 453 }, 454 455 /** Remove the countdown widget from a div. 456 @param elem {jQuery} The containing division. 457 @param inst {object} The current instance object. */ 458 _preDestroy: function(elem, inst) { 459 this._removeElem(elem[0]); 460 elem.empty(); 461 }, 462 463 /** Pause a countdown widget at the current time. 464 Stop it running but remember and display the current time. 465 @param elem {Element} The containing division. 466 @example $(selector).countdown('pause') */ 467 pause: function(elem) { 468 this._hold(elem, 'pause'); 469 }, 470 471 /** Pause a countdown widget at the current time. 472 Stop the display but keep the countdown running. 473 @param elem {Element} The containing division. 474 @example $(selector).countdown('lap') */ 475 lap: function(elem) { 476 this._hold(elem, 'lap'); 477 }, 478 479 /** Resume a paused countdown widget. 480 @param elem {Element} The containing division. 481 @example $(selector).countdown('resume') */ 482 resume: function(elem) { 483 this._hold(elem, null); 484 }, 485 486 /** Toggle a paused countdown widget. 487 @param elem {Element} The containing division. 488 @example $(selector).countdown('toggle') */ 489 toggle: function(elem) { 490 var inst = $.data(elem, this.name) || {}; 491 this[!inst._hold ? 'pause' : 'resume'](elem); 492 }, 493 494 /** Toggle a lapped countdown widget. 495 @param elem {Element} The containing division. 496 @example $(selector).countdown('toggleLap') */ 497 toggleLap: function(elem) { 498 var inst = $.data(elem, this.name) || {}; 499 this[!inst._hold ? 'lap' : 'resume'](elem); 500 }, 501 502 /** Pause or resume a countdown widget. 503 @private 504 @param elem {Element} The containing division. 505 @param hold {string} The new hold setting. */ 506 _hold: function(elem, hold) { 507 var inst = $.data(elem, this.name); 508 if (inst) { 509 if (inst._hold == 'pause' && !hold) {
510 inst._periods = inst._savePeriods; 511 var sign = (inst._since ? '-' : '+'); 512 inst[inst._since ? '_since' : '_until'] = 513 this._determineTime(sign + inst._periods[0] + 'y' + 514 sign + inst._periods[1] + 'o' + sign + inst._periods[2] + 'w' + 515 sign + inst._periods[3] + 'd' + sign + inst._periods[4] + 'h' + 516 sign + inst._periods[5] + 'm' + sign + inst._periods[6] + 's'); 517 this._addElem(elem); 518 } 519 inst._hold = hold; 520 inst._savePeriods = (hold == 'pause' ? inst._periods : null); 521 $.data(elem, this.name, inst); 522 this._updateCountdown(elem, inst); 523 } 524 }, 525 526 /** Return the current time periods. 527 @param elem {Element} The containing division. 528 @return {number[]} The current periods for the countdown. 529 @example var periods = $(selector).countdown('getTimes') */ 530 getTimes: function(elem) { 531 var inst = $.data(elem, this.name); 532 return (!inst ? null : (inst._hold == 'pause' ? inst._savePeriods : (!inst._hold ? inst._periods : 533 this._calculatePeriods(inst, inst._show, inst.options.significant, new Date())))); 534 }, 535 536 /** A time may be specified as an exact value or a relative one. 537 @private 538 @param setting {string|number|Date} The date/time value as a relative or absolute value. 539 @param defaultTime {Date} The date/time to use if no other is supplied. 540 @return {Date} The corresponding date/time. */ 541 _determineTime: function(setting, defaultTime) { 542 var self = this; 543 var offsetNumeric = function(offset) { // e.g. +300, -2 544 var time = new Date(); 545 time.setTime(time.getTime() + offset * 1000); 546 return time; 547 }; 548 var offsetString = function(offset) { // e.g. '+2d', '-4w', '+3h +30m' 549 offset = offset.toLowerCase(); 550 var time = new Date(); 551 var year = time.getFullYear(); 552 var month = time.getMonth(); 553 var day = time.getDate(); 554 var hour = time.getHours(); 555 var minute = time.getMinutes(); 556 var second = time.getSeconds(); 557 var pattern = /([+-]?[0-9]+)\s*(s|m|h|d|w|o|y)?/g; 558 var matches = pattern.exec(offset); 559 while (matches) { 560 switch (matches[2] || 's') { 561 case 's': second += parseInt(matches[1], 10); break; 562 case 'm': minute += parseInt(matches[1], 10); break; 563 case 'h': hour += parseInt(matches[1], 10); break; 564 case 'd': day += parseInt(matches[1], 10); break; 565 case 'w': day += parseInt(matches[1], 10) * 7; break; 566 case 'o': 567 month += parseInt(matches[1], 10); 568 day = Math.min(day, self._getDaysInMonth(year, month)); 569 break; 570 case 'y': 571 year += parseInt(matches[1], 10); 572 day = Math.min(day, self._getDaysInMonth(year, month)); 573 break; 574 } 575 matches = pattern.exec(offset); 576 } 577 return new Date(year, month, day, hour, minute, second, 0); 578 }; 579 var time = (setting == null ? defaultTime : 580 (typeof setting == 'string' ? offsetString(setting) : 581 (typeof setting == 'number' ? offsetNumeric(setting) : setting))); 582 if (time) time.setMilliseconds(0); 583 return time; 584 }, 585 586 /** Determine the number of days in a month. 587 @private 588 @param year {number} The year. 589 @param month {number} The month. 590 @return {number} The days in that month. */ 591 _getDaysInMonth: function(year, month) { 592 return 32 - new Date(year, month, 32).getDate(); 593 }, 594 595 /** Default implementation to determine which set of labels should be used for an amount. 596 Use the <code>labels</code> attribute with the same numeric suffix (if it exists). 597 @private 598 @param num {number} The amount to be displayed. 599 @return {number} The set of labels to be used for this amount. */ 600 _normalLabels: function(num) { 601 return num; 602 }, 603 604 /** Generate the HTML to display the countdown widget. 605 @private 606 @param inst {object} The current settings for this instance. 607 @return {string} The new HTML for the countdown display. */ 608 _generateHTML: function(inst) { 609 var self = this; 610 // Determine what to show 611 inst._periods = (inst._hold ? inst._periods : 612 this._calculatePeriods(inst, inst._show, inst.options.significant, new Date())); 613 // Show all 'asNeeded' after first non-zero value 614 var shownNonZero = false; 615 var showCount = 0;
616 var sigCount = inst.options.significant; 617 var show = $.extend({}, inst._show); 618 for (var period = Y; period <= S; period++) { 619 shownNonZero |= (inst._show[period] == '?' && inst._periods[period] > 0); 620 show[period] = (inst._show[period] == '?' && !shownNonZero ? null : inst._show[period]); 621 showCount += (show[period] ? 1 : 0); 622 sigCount -= (inst._periods[period] > 0 ? 1 : 0); 623 } 624 var showSignificant = [false, false, false, false, false, false, false]; 625 for (var period = S; period >= Y; period--) { // Determine significant periods 626 if (inst._show[period]) { 627 if (inst._periods[period]) { 628 showSignificant[period] = true; 629 } 630 else { 631 showSignificant[period] = sigCount > 0; 632 sigCount--; 633 } 634 } 635 } 636 var labels = (inst.options.compact ? inst.options.compactLabels : inst.options.labels); 637 var whichLabels = inst.options.whichLabels || this._normalLabels; 638 var showCompact = function(period) { 639 var labelsNum = inst.options['compactLabels' + whichLabels(inst._periods[period])]; 640 return (show[period] ? self._translateDigits(inst, inst._periods[period]) + 641 (labelsNum ? labelsNum[period] : labels[period]) + ' ' : ''); 642 }; 643 var minDigits = (inst.options.padZeroes ? 2 : 1); 644 var showFull = function(period) { 645 var labelsNum = inst.options['labels' + whichLabels(inst._periods[period])]; 646 return ((!inst.options.significant && show[period]) || 647 (inst.options.significant && showSignificant[period]) ? 648 '<span class="' + self._sectionClass + '">' + 649 '<span class="' + self._amountClass + '">' + 650 self._minDigits(inst, inst._periods[period], minDigits) + '</span>' + 651 '<span class="' + self._periodClass + '">' + 652 (labelsNum ? labelsNum[period] : labels[period]) + '</span></span>' : ''); 653 }; 654 return (inst.options.layout ? this._buildLayout(inst, show, inst.options.layout, 655 inst.options.compact, inst.options.significant, showSignificant) : 656 ((inst.options.compact ? // Compact version 657 '<span class="' + this._rowClass + ' ' + this._amountClass + 658 (inst._hold ? ' ' + this._holdingClass : '') + '">' + 659 showCompact(Y) + showCompact(O) + showCompact(W) + showCompact(D) + 660 (show[H] ? this._minDigits(inst, inst._periods[H], 2) : '') + 661 (show[M] ? (show[H] ? inst.options.timeSeparator : '') + 662 this._minDigits(inst, inst._periods[M], 2) : '') + 663 (show[S] ? (show[H] || show[M] ? inst.options.timeSeparator : '') + 664 this._minDigits(inst, inst._periods[S], 2) : '') : 665 // Full version 666 '<span class="' + this._rowClass + ' ' + this._showClass + (inst.options.significant || showCount) + 667 (inst._hold ? ' ' + this._holdingClass : '') + '">' + 668 showFull(Y) + showFull(O) + showFull(W) + showFull(D) + 669 showFull(H) + showFull(M) + showFull(S)) + '</span>' + 670 (inst.options.description ? '<span class="' + this._rowClass + ' ' + this._descrClass + '">' + 671 inst.options.description + '</span>' : ''))); 672 }, 673 674 /** Construct a custom layout. 675 @private 676 @param inst {object} The current settings for this instance. 677 @param show {boolean[]} Flags indicating which periods are requested. 678 @param layout {string} The customised layout. 679 @param compact {boolean} True if using compact labels. 680 @param significant {number} The number of periods with values to show, zero for all. 681 @param showSignificant {boolean[]} Other periods to show for significance. 682 @return {string} The custom HTML. */ 683 _buildLayout: function(inst, show, layout, compact, significant, showSignificant) { 684 var labels = inst.options[compact ? 'compactLabels' : 'labels']; 685 var whichLabels = inst.options.whichLabels || this._normalLabels; 686 var labelFor = function(index) { 687 return (inst.options[(compact ? 'compactLabels' : 'labels') + 688 whichLabels(inst._periods[index])] || labels)[index]; 689 }; 690 var digit = function(value, position) { 691 return inst.options.digits[Math.floor(value / position) % 10]; 692 }; 693 var subs = {desc: inst.options.description, sep: inst.options.timeSeparator, 694 yl: labelFor(Y), yn: this._minDigits(inst, inst._periods[Y], 1),
695 ynn: this._minDigits(inst, inst._periods[Y], 2), 696 ynnn: this._minDigits(inst, inst._periods[Y], 3), y1: digit(inst._periods[Y], 1), 697 y10: digit(inst._periods[Y], 10), y100: digit(inst._periods[Y], 100), 698 y1000: digit(inst._periods[Y], 1000), 699 ol: labelFor(O), on: this._minDigits(inst, inst._periods[O], 1), 700 onn: this._minDigits(inst, inst._periods[O], 2), 701 onnn: this._minDigits(inst, inst._periods[O], 3), o1: digit(inst._periods[O], 1), 702 o10: digit(inst._periods[O], 10), o100: digit(inst._periods[O], 100), 703 o1000: digit(inst._periods[O], 1000), 704 wl: labelFor(W), wn: this._minDigits(inst, inst._periods[W], 1), 705 wnn: this._minDigits(inst, inst._periods[W], 2), 706 wnnn: this._minDigits(inst, inst._periods[W], 3), w1: digit(inst._periods[W], 1), 707 w10: digit(inst._periods[W], 10), w100: digit(inst._periods[W], 100), 708 w1000: digit(inst._periods[W], 1000), 709 dl: labelFor(D), dn: this._minDigits(inst, inst._periods[D], 1), 710 dnn: this._minDigits(inst, inst._periods[D], 2), 711 dnnn: this._minDigits(inst, inst._periods[D], 3), d1: digit(inst._periods[D], 1), 712 d10: digit(inst._periods[D], 10), d100: digit(inst._periods[D], 100), 713 d1000: digit(inst._periods[D], 1000), 714 hl: labelFor(H), hn: this._minDigits(inst, inst._periods[H], 1), 715 hnn: this._minDigits(inst, inst._periods[H], 2), 716 hnnn: this._minDigits(inst, inst._periods[H], 3), h1: digit(inst._periods[H], 1), 717 h10: digit(inst._periods[H], 10), h100: digit(inst._periods[H], 100), 718 h1000: digit(inst._periods[H], 1000), 719 ml: labelFor(M), mn: this._minDigits(inst, inst._periods[M], 1), 720 mnn: this._minDigits(inst, inst._periods[M], 2), 721 mnnn: this._minDigits(inst, inst._periods[M], 3), m1: digit(inst._periods[M], 1), 722 m10: digit(inst._periods[M], 10), m100: digit(inst._periods[M], 100), 723 m1000: digit(inst._periods[M], 1000), 724 sl: labelFor(S), sn: this._minDigits(inst, inst._periods[S], 1), 725 snn: this._minDigits(inst, inst._periods[S], 2), 726 snnn: this._minDigits(inst, inst._periods[S], 3), s1: digit(inst._periods[S], 1), 727 s10: digit(inst._periods[S], 10), s100: digit(inst._periods[S], 100), 728 s1000: digit(inst._periods[S], 1000)}; 729 var html = layout; 730 // Replace period containers: {p<}...{p>} 731 for (var i = Y; i <= S; i++) { 732 var period = 'yowdhms'.charAt(i); 733 var re = new RegExp('\\{' + period + '<\\}([\\s\\S]*)\\{' + period + '>\\}', 'g'); 734 html = html.replace(re, ((!significant && show[i]) || 735 (significant && showSignificant[i]) ? '$1' : '')); 736 } 737 // Replace period values: {pn} 738 $.each(subs, function(n, v) { 739 var re = new RegExp('\\{' + n + '\\}', 'g'); 740 html = html.replace(re, v); 741 }); 742 return html; 743 }, 744 745 /** Ensure a numeric value has at least n digits for display. 746 @private 747 @param inst {object} The current settings for this instance. 748 @param value {number} The value to display. 749 @param len {number} The minimum length. 750 @return {string} The display text. */ 751 _minDigits: function(inst, value, len) { 752 value = '' + value; 753 if (value.length >= len) { 754 return this._translateDigits(inst, value); 755 } 756 value = '0000000000' + value; 757 return this._translateDigits(inst, value.substr(value.length - len)); 758 }, 759 760 /** Translate digits into other representations. 761 @private 762 @param inst {object} The current settings for this instance. 763 @param value {string} The text to translate. 764 @return {string} The translated text. */ 765 _translateDigits: function(inst, value) { 766 return ('' + value).replace(/[0-9]/g, function(digit) { 767 return inst.options.digits[digit]; 768 }); 769 }, 770 771 /** Translate the format into flags for each period. 772 @private 773 @param inst {object} The current settings for this instance. 774 @return {string[]} Flags indicating which periods are requested (?) or 775 required (!) by year, month, week, day, hour, minute, second. */ 776 _determineShow: function(inst) { 777 var format = inst.options.format; 778 var show = []; 779 show[Y] = (format.match('y') ? '?' : (format.match('Y') ? '!' : null)); 780 show[O] = (format.match('o') ? '?' : (format.match('O') ? '!' : null)); 781 show[W] = (format.match('w') ? '?' : (format.match('W') ? '!' : null)); 782 show[D] = (format.match('d') ? '?' : (format.match('D') ? '!' : null)); 783 show[H] = (format.match('h') ? '?' : (format.match('H') ? '!' : null)); 784 show[M] = (format.match('m') ? '?' : (format.match('M') ? '!' : null)); 785 show[S] = (format.match('s') ? '?' : (format.match('S') ? '!' : null)); 786 return show; 787 }, 788 789 /** Calculate the requested periods between now and the target time. 790 @private 791 @param inst {object} The current settings for this instance. 792 @param show {string[]} Flags indicating which periods are requested/required. 793 @param significant {number} The number of periods with values to show, zero for all. 794 @param now {Date} The current date and time. 795 @return {number[]} The current time periods (always positive) 796 by year, month, week, day, hour, minute, second. */
797 _calculatePeriods: function(inst, show, significant, now) { 798 // Find endpoints 799 inst._now = now; 800 inst._now.setMilliseconds(0); 801 var until = new Date(inst._now.getTime()); 802 if (inst._since) { 803 if (now.getTime() < inst._since.getTime()) { 804 inst._now = now = until; 805 } 806 else { 807 now = inst._since; 808 } 809 } 810 else { 811 until.setTime(inst._until.getTime()); 812 if (now.getTime() > inst._until.getTime()) { 813 inst._now = now = until; 814 } 815 } 816 // Calculate differences by period 817 var periods = [0, 0, 0, 0, 0, 0, 0]; 818 if (show[Y] || show[O]) { 819 // Treat end of months as the same 820 var lastNow = this._getDaysInMonth(now.getFullYear(), now.getMonth()); 821 var lastUntil = this._getDaysInMonth(until.getFullYear(), until.getMonth()); 822 var sameDay = (until.getDate() == now.getDate() || 823 (until.getDate() >= Math.min(lastNow, lastUntil) && 824 now.getDate() >= Math.min(lastNow, lastUntil))); 825 var getSecs = function(date) { 826 return (date.getHours() * 60 + date.getMinutes()) * 60 + date.getSeconds(); 827 }; 828 var months = Math.max(0, 829 (until.getFullYear() - now.getFullYear()) * 12 + until.getMonth() - now.getMonth() + 830 ((until.getDate() < now.getDate() && !sameDay) || 831 (sameDay && getSecs(until) < getSecs(now)) ? -1 : 0)); 832 periods[Y] = (show[Y] ? Math.floor(months / 12) : 0); 833 periods[O] = (show[O] ? months - periods[Y] * 12 : 0); 834 // Adjust for months difference and end of month if necessary 835 now = new Date(now.getTime()); 836 var wasLastDay = (now.getDate() == lastNow); 837 var lastDay = this._getDaysInMonth(now.getFullYear() + periods[Y], 838 now.getMonth() + periods[O]); 839 if (now.getDate() > lastDay) { 840 now.setDate(lastDay); 841 } 842 now.setFullYear(now.getFullYear() + periods[Y]); 843 now.setMonth(now.getMonth() + periods[O]); 844 if (wasLastDay) { 845 now.setDate(lastDay); 846 } 847 } 848 var diff = Math.floor((until.getTime() - now.getTime()) / 1000); 849 var extractPeriod = function(period, numSecs) { 850 periods[period] = (show[period] ? Math.floor(diff / numSecs) : 0); 851 diff -= periods[period] * numSecs; 852 }; 853 extractPeriod(W, 604800); 854 extractPeriod(D, 86400); 855 extractPeriod(H, 3600); 856 extractPeriod(M, 60); 857 extractPeriod(S, 1); 858 if (diff > 0 && !inst._since) { // Round up if left overs 859 var multiplier = [1, 12, 4.3482, 7, 24, 60, 60]; 860 var lastShown = S; 861 var max = 1; 862 for (var period = S; period >= Y; period--) { 863 if (show[period]) { 864 if (periods[lastShown] >= max) { 865 periods[lastShown] = 0; 866 diff = 1; 867 } 868 if (diff > 0) { 869 periods[period]++; 870 diff = 0; 871 lastShown = period; 872 max = 1; 873 } 874 } 875 max *= multiplier[period]; 876 } 877 } 878 if (significant) { // Zero out insignificant periods 879 for (var period = Y; period <= S; period++) { 880 if (significant && periods[period]) { 881 significant--; 882 } 883 else if (!significant) { 884 periods[period] = 0; 885 } 886 } 887 } 888 return periods; 889 } 890 }); 891 892})(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.