Advertisement
Guest User

Untitled

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