a93638151159dee92d9593518f15044d5c92642e
[qcg-portal.git] / qcg / static / qcg / daterangepicker / moment.js
1 //! moment.js
2 //! version : 2.8.1
3 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
4 //! license : MIT
5 //! momentjs.com
6
7 (function (undefined) {
8     /************************************
9         Constants
10     ************************************/
11
12     var moment,
13         VERSION = '2.8.1',
14         // the global-scope this is NOT the global object in Node.js
15         globalScope = typeof global !== 'undefined' ? global : this,
16         oldGlobalMoment,
17         round = Math.round,
18         i,
19
20         YEAR = 0,
21         MONTH = 1,
22         DATE = 2,
23         HOUR = 3,
24         MINUTE = 4,
25         SECOND = 5,
26         MILLISECOND = 6,
27
28         // internal storage for locale config files
29         locales = {},
30
31         // extra moment internal properties (plugins register props here)
32         momentProperties = [],
33
34         // check for nodeJS
35         hasModule = (typeof module !== 'undefined' && module.exports),
36
37         // ASP.NET json date format regex
38         aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
39         aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
40
41         // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
42         // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
43         isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
44
45         // format tokens
46         formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,
47         localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
48
49         // parsing token regexes
50         parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
51         parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
52         parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
53         parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
54         parseTokenDigits = /\d+/, // nonzero number of digits
55         parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic.
56         parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
57         parseTokenT = /T/i, // T (ISO separator)
58         parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
59         parseTokenOrdinal = /\d{1,2}/,
60
61         //strict parsing regexes
62         parseTokenOneDigit = /\d/, // 0 - 9
63         parseTokenTwoDigits = /\d\d/, // 00 - 99
64         parseTokenThreeDigits = /\d{3}/, // 000 - 999
65         parseTokenFourDigits = /\d{4}/, // 0000 - 9999
66         parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
67         parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
68
69         // iso 8601 regex
70         // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
71         isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
72
73         isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
74
75         isoDates = [
76             ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
77             ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
78             ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
79             ['GGGG-[W]WW', /\d{4}-W\d{2}/],
80             ['YYYY-DDD', /\d{4}-\d{3}/]
81         ],
82
83         // iso time formats and regexes
84         isoTimes = [
85             ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/],
86             ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
87             ['HH:mm', /(T| )\d\d:\d\d/],
88             ['HH', /(T| )\d\d/]
89         ],
90
91         // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
92         parseTimezoneChunker = /([\+\-]|\d\d)/gi,
93
94         // getter and setter names
95         proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
96         unitMillisecondFactors = {
97             'Milliseconds' : 1,
98             'Seconds' : 1e3,
99             'Minutes' : 6e4,
100             'Hours' : 36e5,
101             'Days' : 864e5,
102             'Months' : 2592e6,
103             'Years' : 31536e6
104         },
105
106         unitAliases = {
107             ms : 'millisecond',
108             s : 'second',
109             m : 'minute',
110             h : 'hour',
111             d : 'day',
112             D : 'date',
113             w : 'week',
114             W : 'isoWeek',
115             M : 'month',
116             Q : 'quarter',
117             y : 'year',
118             DDD : 'dayOfYear',
119             e : 'weekday',
120             E : 'isoWeekday',
121             gg: 'weekYear',
122             GG: 'isoWeekYear'
123         },
124
125         camelFunctions = {
126             dayofyear : 'dayOfYear',
127             isoweekday : 'isoWeekday',
128             isoweek : 'isoWeek',
129             weekyear : 'weekYear',
130             isoweekyear : 'isoWeekYear'
131         },
132
133         // format function strings
134         formatFunctions = {},
135
136         // default relative time thresholds
137         relativeTimeThresholds = {
138             s: 45,  // seconds to minute
139             m: 45,  // minutes to hour
140             h: 22,  // hours to day
141             d: 26,  // days to month
142             M: 11   // months to year
143         },
144
145         // tokens to ordinalize and pad
146         ordinalizeTokens = 'DDD w W M D d'.split(' '),
147         paddedTokens = 'M D H h m s w W'.split(' '),
148
149         formatTokenFunctions = {
150             M    : function () {
151                 return this.month() + 1;
152             },
153             MMM  : function (format) {
154                 return this.localeData().monthsShort(this, format);
155             },
156             MMMM : function (format) {
157                 return this.localeData().months(this, format);
158             },
159             D    : function () {
160                 return this.date();
161             },
162             DDD  : function () {
163                 return this.dayOfYear();
164             },
165             d    : function () {
166                 return this.day();
167             },
168             dd   : function (format) {
169                 return this.localeData().weekdaysMin(this, format);
170             },
171             ddd  : function (format) {
172                 return this.localeData().weekdaysShort(this, format);
173             },
174             dddd : function (format) {
175                 return this.localeData().weekdays(this, format);
176             },
177             w    : function () {
178                 return this.week();
179             },
180             W    : function () {
181                 return this.isoWeek();
182             },
183             YY   : function () {
184                 return leftZeroFill(this.year() % 100, 2);
185             },
186             YYYY : function () {
187                 return leftZeroFill(this.year(), 4);
188             },
189             YYYYY : function () {
190                 return leftZeroFill(this.year(), 5);
191             },
192             YYYYYY : function () {
193                 var y = this.year(), sign = y >= 0 ? '+' : '-';
194                 return sign + leftZeroFill(Math.abs(y), 6);
195             },
196             gg   : function () {
197                 return leftZeroFill(this.weekYear() % 100, 2);
198             },
199             gggg : function () {
200                 return leftZeroFill(this.weekYear(), 4);
201             },
202             ggggg : function () {
203                 return leftZeroFill(this.weekYear(), 5);
204             },
205             GG   : function () {
206                 return leftZeroFill(this.isoWeekYear() % 100, 2);
207             },
208             GGGG : function () {
209                 return leftZeroFill(this.isoWeekYear(), 4);
210             },
211             GGGGG : function () {
212                 return leftZeroFill(this.isoWeekYear(), 5);
213             },
214             e : function () {
215                 return this.weekday();
216             },
217             E : function () {
218                 return this.isoWeekday();
219             },
220             a    : function () {
221                 return this.localeData().meridiem(this.hours(), this.minutes(), true);
222             },
223             A    : function () {
224                 return this.localeData().meridiem(this.hours(), this.minutes(), false);
225             },
226             H    : function () {
227                 return this.hours();
228             },
229             h    : function () {
230                 return this.hours() % 12 || 12;
231             },
232             m    : function () {
233                 return this.minutes();
234             },
235             s    : function () {
236                 return this.seconds();
237             },
238             S    : function () {
239                 return toInt(this.milliseconds() / 100);
240             },
241             SS   : function () {
242                 return leftZeroFill(toInt(this.milliseconds() / 10), 2);
243             },
244             SSS  : function () {
245                 return leftZeroFill(this.milliseconds(), 3);
246             },
247             SSSS : function () {
248                 return leftZeroFill(this.milliseconds(), 3);
249             },
250             Z    : function () {
251                 var a = -this.zone(),
252                     b = '+';
253                 if (a < 0) {
254                     a = -a;
255                     b = '-';
256                 }
257                 return b + leftZeroFill(toInt(a / 60), 2) + ':' + leftZeroFill(toInt(a) % 60, 2);
258             },
259             ZZ   : function () {
260                 var a = -this.zone(),
261                     b = '+';
262                 if (a < 0) {
263                     a = -a;
264                     b = '-';
265                 }
266                 return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
267             },
268             z : function () {
269                 return this.zoneAbbr();
270             },
271             zz : function () {
272                 return this.zoneName();
273             },
274             X    : function () {
275                 return this.unix();
276             },
277             Q : function () {
278                 return this.quarter();
279             }
280         },
281
282         deprecations = {},
283
284         lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
285
286     // Pick the first defined of two or three arguments. dfl comes from
287     // default.
288     function dfl(a, b, c) {
289         switch (arguments.length) {
290             case 2: return a != null ? a : b;
291             case 3: return a != null ? a : b != null ? b : c;
292             default: throw new Error('Implement me');
293         }
294     }
295
296     function defaultParsingFlags() {
297         // We need to deep clone this object, and es5 standard is not very
298         // helpful.
299         return {
300             empty : false,
301             unusedTokens : [],
302             unusedInput : [],
303             overflow : -2,
304             charsLeftOver : 0,
305             nullInput : false,
306             invalidMonth : null,
307             invalidFormat : false,
308             userInvalidated : false,
309             iso: false
310         };
311     }
312
313     function printMsg(msg) {
314         if (moment.suppressDeprecationWarnings === false &&
315                 typeof console !== 'undefined' && console.warn) {
316             console.warn("Deprecation warning: " + msg);
317         }
318     }
319
320     function deprecate(msg, fn) {
321         var firstTime = true;
322         return extend(function () {
323             if (firstTime) {
324                 printMsg(msg);
325                 firstTime = false;
326             }
327             return fn.apply(this, arguments);
328         }, fn);
329     }
330
331     function deprecateSimple(name, msg) {
332         if (!deprecations[name]) {
333             printMsg(msg);
334             deprecations[name] = true;
335         }
336     }
337
338     function padToken(func, count) {
339         return function (a) {
340             return leftZeroFill(func.call(this, a), count);
341         };
342     }
343     function ordinalizeToken(func, period) {
344         return function (a) {
345             return this.localeData().ordinal(func.call(this, a), period);
346         };
347     }
348
349     while (ordinalizeTokens.length) {
350         i = ordinalizeTokens.pop();
351         formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
352     }
353     while (paddedTokens.length) {
354         i = paddedTokens.pop();
355         formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
356     }
357     formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
358
359
360     /************************************
361         Constructors
362     ************************************/
363
364     function Locale() {
365     }
366
367     // Moment prototype object
368     function Moment(config, skipOverflow) {
369         if (skipOverflow !== false) {
370             checkOverflow(config);
371         }
372         copyConfig(this, config);
373         this._d = new Date(+config._d);
374     }
375
376     // Duration Constructor
377     function Duration(duration) {
378         var normalizedInput = normalizeObjectUnits(duration),
379             years = normalizedInput.year || 0,
380             quarters = normalizedInput.quarter || 0,
381             months = normalizedInput.month || 0,
382             weeks = normalizedInput.week || 0,
383             days = normalizedInput.day || 0,
384             hours = normalizedInput.hour || 0,
385             minutes = normalizedInput.minute || 0,
386             seconds = normalizedInput.second || 0,
387             milliseconds = normalizedInput.millisecond || 0;
388
389         // representation for dateAddRemove
390         this._milliseconds = +milliseconds +
391             seconds * 1e3 + // 1000
392             minutes * 6e4 + // 1000 * 60
393             hours * 36e5; // 1000 * 60 * 60
394         // Because of dateAddRemove treats 24 hours as different from a
395         // day when working around DST, we need to store them separately
396         this._days = +days +
397             weeks * 7;
398         // It is impossible translate months into days without knowing
399         // which months you are are talking about, so we have to store
400         // it separately.
401         this._months = +months +
402             quarters * 3 +
403             years * 12;
404
405         this._data = {};
406
407         this._locale = moment.localeData();
408
409         this._bubble();
410     }
411
412     /************************************
413         Helpers
414     ************************************/
415
416
417     function extend(a, b) {
418         for (var i in b) {
419             if (b.hasOwnProperty(i)) {
420                 a[i] = b[i];
421             }
422         }
423
424         if (b.hasOwnProperty('toString')) {
425             a.toString = b.toString;
426         }
427
428         if (b.hasOwnProperty('valueOf')) {
429             a.valueOf = b.valueOf;
430         }
431
432         return a;
433     }
434
435     function copyConfig(to, from) {
436         var i, prop, val;
437
438         if (typeof from._isAMomentObject !== 'undefined') {
439             to._isAMomentObject = from._isAMomentObject;
440         }
441         if (typeof from._i !== 'undefined') {
442             to._i = from._i;
443         }
444         if (typeof from._f !== 'undefined') {
445             to._f = from._f;
446         }
447         if (typeof from._l !== 'undefined') {
448             to._l = from._l;
449         }
450         if (typeof from._strict !== 'undefined') {
451             to._strict = from._strict;
452         }
453         if (typeof from._tzm !== 'undefined') {
454             to._tzm = from._tzm;
455         }
456         if (typeof from._isUTC !== 'undefined') {
457             to._isUTC = from._isUTC;
458         }
459         if (typeof from._offset !== 'undefined') {
460             to._offset = from._offset;
461         }
462         if (typeof from._pf !== 'undefined') {
463             to._pf = from._pf;
464         }
465         if (typeof from._locale !== 'undefined') {
466             to._locale = from._locale;
467         }
468
469         if (momentProperties.length > 0) {
470             for (i in momentProperties) {
471                 prop = momentProperties[i];
472                 val = from[prop];
473                 if (typeof val !== 'undefined') {
474                     to[prop] = val;
475                 }
476             }
477         }
478
479         return to;
480     }
481
482     function absRound(number) {
483         if (number < 0) {
484             return Math.ceil(number);
485         } else {
486             return Math.floor(number);
487         }
488     }
489
490     // left zero fill a number
491     // see http://jsperf.com/left-zero-filling for performance comparison
492     function leftZeroFill(number, targetLength, forceSign) {
493         var output = '' + Math.abs(number),
494             sign = number >= 0;
495
496         while (output.length < targetLength) {
497             output = '0' + output;
498         }
499         return (sign ? (forceSign ? '+' : '') : '-') + output;
500     }
501
502     function positiveMomentsDifference(base, other) {
503         var res = {milliseconds: 0, months: 0};
504
505         res.months = other.month() - base.month() +
506             (other.year() - base.year()) * 12;
507         if (base.clone().add(res.months, 'M').isAfter(other)) {
508             --res.months;
509         }
510
511         res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
512
513         return res;
514     }
515
516     function momentsDifference(base, other) {
517         var res;
518         other = makeAs(other, base);
519         if (base.isBefore(other)) {
520             res = positiveMomentsDifference(base, other);
521         } else {
522             res = positiveMomentsDifference(other, base);
523             res.milliseconds = -res.milliseconds;
524             res.months = -res.months;
525         }
526
527         return res;
528     }
529
530     // TODO: remove 'name' arg after deprecation is removed
531     function createAdder(direction, name) {
532         return function (val, period) {
533             var dur, tmp;
534             //invert the arguments, but complain about it
535             if (period !== null && !isNaN(+period)) {
536                 deprecateSimple(name, "moment()." + name  + "(period, number) is deprecated. Please use moment()." + name + "(number, period).");
537                 tmp = val; val = period; period = tmp;
538             }
539
540             val = typeof val === 'string' ? +val : val;
541             dur = moment.duration(val, period);
542             addOrSubtractDurationFromMoment(this, dur, direction);
543             return this;
544         };
545     }
546
547     function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) {
548         var milliseconds = duration._milliseconds,
549             days = duration._days,
550             months = duration._months;
551         updateOffset = updateOffset == null ? true : updateOffset;
552
553         if (milliseconds) {
554             mom._d.setTime(+mom._d + milliseconds * isAdding);
555         }
556         if (days) {
557             rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding);
558         }
559         if (months) {
560             rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding);
561         }
562         if (updateOffset) {
563             moment.updateOffset(mom, days || months);
564         }
565     }
566
567     // check if is an array
568     function isArray(input) {
569         return Object.prototype.toString.call(input) === '[object Array]';
570     }
571
572     function isDate(input) {
573         return Object.prototype.toString.call(input) === '[object Date]' ||
574             input instanceof Date;
575     }
576
577     // compare two arrays, return the number of differences
578     function compareArrays(array1, array2, dontConvert) {
579         var len = Math.min(array1.length, array2.length),
580             lengthDiff = Math.abs(array1.length - array2.length),
581             diffs = 0,
582             i;
583         for (i = 0; i < len; i++) {
584             if ((dontConvert && array1[i] !== array2[i]) ||
585                 (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
586                 diffs++;
587             }
588         }
589         return diffs + lengthDiff;
590     }
591
592     function normalizeUnits(units) {
593         if (units) {
594             var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
595             units = unitAliases[units] || camelFunctions[lowered] || lowered;
596         }
597         return units;
598     }
599
600     function normalizeObjectUnits(inputObject) {
601         var normalizedInput = {},
602             normalizedProp,
603             prop;
604
605         for (prop in inputObject) {
606             if (inputObject.hasOwnProperty(prop)) {
607                 normalizedProp = normalizeUnits(prop);
608                 if (normalizedProp) {
609                     normalizedInput[normalizedProp] = inputObject[prop];
610                 }
611             }
612         }
613
614         return normalizedInput;
615     }
616
617     function makeList(field) {
618         var count, setter;
619
620         if (field.indexOf('week') === 0) {
621             count = 7;
622             setter = 'day';
623         }
624         else if (field.indexOf('month') === 0) {
625             count = 12;
626             setter = 'month';
627         }
628         else {
629             return;
630         }
631
632         moment[field] = function (format, index) {
633             var i, getter,
634                 method = moment._locale[field],
635                 results = [];
636
637             if (typeof format === 'number') {
638                 index = format;
639                 format = undefined;
640             }
641
642             getter = function (i) {
643                 var m = moment().utc().set(setter, i);
644                 return method.call(moment._locale, m, format || '');
645             };
646
647             if (index != null) {
648                 return getter(index);
649             }
650             else {
651                 for (i = 0; i < count; i++) {
652                     results.push(getter(i));
653                 }
654                 return results;
655             }
656         };
657     }
658
659     function toInt(argumentForCoercion) {
660         var coercedNumber = +argumentForCoercion,
661             value = 0;
662
663         if (coercedNumber !== 0 && isFinite(coercedNumber)) {
664             if (coercedNumber >= 0) {
665                 value = Math.floor(coercedNumber);
666             } else {
667                 value = Math.ceil(coercedNumber);
668             }
669         }
670
671         return value;
672     }
673
674     function daysInMonth(year, month) {
675         return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
676     }
677
678     function weeksInYear(year, dow, doy) {
679         return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week;
680     }
681
682     function daysInYear(year) {
683         return isLeapYear(year) ? 366 : 365;
684     }
685
686     function isLeapYear(year) {
687         return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
688     }
689
690     function checkOverflow(m) {
691         var overflow;
692         if (m._a && m._pf.overflow === -2) {
693             overflow =
694                 m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
695                 m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
696                 m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
697                 m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
698                 m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
699                 m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
700                 -1;
701
702             if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
703                 overflow = DATE;
704             }
705
706             m._pf.overflow = overflow;
707         }
708     }
709
710     function isValid(m) {
711         if (m._isValid == null) {
712             m._isValid = !isNaN(m._d.getTime()) &&
713                 m._pf.overflow < 0 &&
714                 !m._pf.empty &&
715                 !m._pf.invalidMonth &&
716                 !m._pf.nullInput &&
717                 !m._pf.invalidFormat &&
718                 !m._pf.userInvalidated;
719
720             if (m._strict) {
721                 m._isValid = m._isValid &&
722                     m._pf.charsLeftOver === 0 &&
723                     m._pf.unusedTokens.length === 0;
724             }
725         }
726         return m._isValid;
727     }
728
729     function normalizeLocale(key) {
730         return key ? key.toLowerCase().replace('_', '-') : key;
731     }
732
733     // pick the locale from the array
734     // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
735     // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
736     function chooseLocale(names) {
737         var i = 0, j, next, locale, split;
738
739         while (i < names.length) {
740             split = normalizeLocale(names[i]).split('-');
741             j = split.length;
742             next = normalizeLocale(names[i + 1]);
743             next = next ? next.split('-') : null;
744             while (j > 0) {
745                 locale = loadLocale(split.slice(0, j).join('-'));
746                 if (locale) {
747                     return locale;
748                 }
749                 if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
750                     //the next array item is better than a shallower substring of this one
751                     break;
752                 }
753                 j--;
754             }
755             i++;
756         }
757         return null;
758     }
759
760     function loadLocale(name) {
761         var oldLocale = null;
762         if (!locales[name] && hasModule) {
763             try {
764                 oldLocale = moment.locale();
765                 require('./locale/' + name);
766                 // because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales
767                 moment.locale(oldLocale);
768             } catch (e) { }
769         }
770         return locales[name];
771     }
772
773     // Return a moment from input, that is local/utc/zone equivalent to model.
774     function makeAs(input, model) {
775         return model._isUTC ? moment(input).zone(model._offset || 0) :
776             moment(input).local();
777     }
778
779     /************************************
780         Locale
781     ************************************/
782
783
784     extend(Locale.prototype, {
785
786         set : function (config) {
787             var prop, i;
788             for (i in config) {
789                 prop = config[i];
790                 if (typeof prop === 'function') {
791                     this[i] = prop;
792                 } else {
793                     this['_' + i] = prop;
794                 }
795             }
796         },
797
798         _months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
799         months : function (m) {
800             return this._months[m.month()];
801         },
802
803         _monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
804         monthsShort : function (m) {
805             return this._monthsShort[m.month()];
806         },
807
808         monthsParse : function (monthName) {
809             var i, mom, regex;
810
811             if (!this._monthsParse) {
812                 this._monthsParse = [];
813             }
814
815             for (i = 0; i < 12; i++) {
816                 // make the regex if we don't have it already
817                 if (!this._monthsParse[i]) {
818                     mom = moment.utc([2000, i]);
819                     regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
820                     this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
821                 }
822                 // test the regex
823                 if (this._monthsParse[i].test(monthName)) {
824                     return i;
825                 }
826             }
827         },
828
829         _weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
830         weekdays : function (m) {
831             return this._weekdays[m.day()];
832         },
833
834         _weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
835         weekdaysShort : function (m) {
836             return this._weekdaysShort[m.day()];
837         },
838
839         _weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
840         weekdaysMin : function (m) {
841             return this._weekdaysMin[m.day()];
842         },
843
844         weekdaysParse : function (weekdayName) {
845             var i, mom, regex;
846
847             if (!this._weekdaysParse) {
848                 this._weekdaysParse = [];
849             }
850
851             for (i = 0; i < 7; i++) {
852                 // make the regex if we don't have it already
853                 if (!this._weekdaysParse[i]) {
854                     mom = moment([2000, 1]).day(i);
855                     regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
856                     this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
857                 }
858                 // test the regex
859                 if (this._weekdaysParse[i].test(weekdayName)) {
860                     return i;
861                 }
862             }
863         },
864
865         _longDateFormat : {
866             LT : 'h:mm A',
867             L : 'MM/DD/YYYY',
868             LL : 'MMMM D, YYYY',
869             LLL : 'MMMM D, YYYY LT',
870             LLLL : 'dddd, MMMM D, YYYY LT'
871         },
872         longDateFormat : function (key) {
873             var output = this._longDateFormat[key];
874             if (!output && this._longDateFormat[key.toUpperCase()]) {
875                 output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
876                     return val.slice(1);
877                 });
878                 this._longDateFormat[key] = output;
879             }
880             return output;
881         },
882
883         isPM : function (input) {
884             // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
885             // Using charAt should be more compatible.
886             return ((input + '').toLowerCase().charAt(0) === 'p');
887         },
888
889         _meridiemParse : /[ap]\.?m?\.?/i,
890         meridiem : function (hours, minutes, isLower) {
891             if (hours > 11) {
892                 return isLower ? 'pm' : 'PM';
893             } else {
894                 return isLower ? 'am' : 'AM';
895             }
896         },
897
898         _calendar : {
899             sameDay : '[Today at] LT',
900             nextDay : '[Tomorrow at] LT',
901             nextWeek : 'dddd [at] LT',
902             lastDay : '[Yesterday at] LT',
903             lastWeek : '[Last] dddd [at] LT',
904             sameElse : 'L'
905         },
906         calendar : function (key, mom) {
907             var output = this._calendar[key];
908             return typeof output === 'function' ? output.apply(mom) : output;
909         },
910
911         _relativeTime : {
912             future : 'in %s',
913             past : '%s ago',
914             s : 'a few seconds',
915             m : 'a minute',
916             mm : '%d minutes',
917             h : 'an hour',
918             hh : '%d hours',
919             d : 'a day',
920             dd : '%d days',
921             M : 'a month',
922             MM : '%d months',
923             y : 'a year',
924             yy : '%d years'
925         },
926
927         relativeTime : function (number, withoutSuffix, string, isFuture) {
928             var output = this._relativeTime[string];
929             return (typeof output === 'function') ?
930                 output(number, withoutSuffix, string, isFuture) :
931                 output.replace(/%d/i, number);
932         },
933
934         pastFuture : function (diff, output) {
935             var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
936             return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
937         },
938
939         ordinal : function (number) {
940             return this._ordinal.replace('%d', number);
941         },
942         _ordinal : '%d',
943
944         preparse : function (string) {
945             return string;
946         },
947
948         postformat : function (string) {
949             return string;
950         },
951
952         week : function (mom) {
953             return weekOfYear(mom, this._week.dow, this._week.doy).week;
954         },
955
956         _week : {
957             dow : 0, // Sunday is the first day of the week.
958             doy : 6  // The week that contains Jan 1st is the first week of the year.
959         },
960
961         _invalidDate: 'Invalid date',
962         invalidDate: function () {
963             return this._invalidDate;
964         }
965     });
966
967     /************************************
968         Formatting
969     ************************************/
970
971
972     function removeFormattingTokens(input) {
973         if (input.match(/\[[\s\S]/)) {
974             return input.replace(/^\[|\]$/g, '');
975         }
976         return input.replace(/\\/g, '');
977     }
978
979     function makeFormatFunction(format) {
980         var array = format.match(formattingTokens), i, length;
981
982         for (i = 0, length = array.length; i < length; i++) {
983             if (formatTokenFunctions[array[i]]) {
984                 array[i] = formatTokenFunctions[array[i]];
985             } else {
986                 array[i] = removeFormattingTokens(array[i]);
987             }
988         }
989
990         return function (mom) {
991             var output = '';
992             for (i = 0; i < length; i++) {
993                 output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
994             }
995             return output;
996         };
997     }
998
999     // format date using native date object
1000     function formatMoment(m, format) {
1001         if (!m.isValid()) {
1002             return m.localeData().invalidDate();
1003         }
1004
1005         format = expandFormat(format, m.localeData());
1006
1007         if (!formatFunctions[format]) {
1008             formatFunctions[format] = makeFormatFunction(format);
1009         }
1010
1011         return formatFunctions[format](m);
1012     }
1013
1014     function expandFormat(format, locale) {
1015         var i = 5;
1016
1017         function replaceLongDateFormatTokens(input) {
1018             return locale.longDateFormat(input) || input;
1019         }
1020
1021         localFormattingTokens.lastIndex = 0;
1022         while (i >= 0 && localFormattingTokens.test(format)) {
1023             format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
1024             localFormattingTokens.lastIndex = 0;
1025             i -= 1;
1026         }
1027
1028         return format;
1029     }
1030
1031
1032     /************************************
1033         Parsing
1034     ************************************/
1035
1036
1037     // get the regex to find the next token
1038     function getParseRegexForToken(token, config) {
1039         var a, strict = config._strict;
1040         switch (token) {
1041         case 'Q':
1042             return parseTokenOneDigit;
1043         case 'DDDD':
1044             return parseTokenThreeDigits;
1045         case 'YYYY':
1046         case 'GGGG':
1047         case 'gggg':
1048             return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
1049         case 'Y':
1050         case 'G':
1051         case 'g':
1052             return parseTokenSignedNumber;
1053         case 'YYYYYY':
1054         case 'YYYYY':
1055         case 'GGGGG':
1056         case 'ggggg':
1057             return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
1058         case 'S':
1059             if (strict) {
1060                 return parseTokenOneDigit;
1061             }
1062             /* falls through */
1063         case 'SS':
1064             if (strict) {
1065                 return parseTokenTwoDigits;
1066             }
1067             /* falls through */
1068         case 'SSS':
1069             if (strict) {
1070                 return parseTokenThreeDigits;
1071             }
1072             /* falls through */
1073         case 'DDD':
1074             return parseTokenOneToThreeDigits;
1075         case 'MMM':
1076         case 'MMMM':
1077         case 'dd':
1078         case 'ddd':
1079         case 'dddd':
1080             return parseTokenWord;
1081         case 'a':
1082         case 'A':
1083             return config._locale._meridiemParse;
1084         case 'X':
1085             return parseTokenTimestampMs;
1086         case 'Z':
1087         case 'ZZ':
1088             return parseTokenTimezone;
1089         case 'T':
1090             return parseTokenT;
1091         case 'SSSS':
1092             return parseTokenDigits;
1093         case 'MM':
1094         case 'DD':
1095         case 'YY':
1096         case 'GG':
1097         case 'gg':
1098         case 'HH':
1099         case 'hh':
1100         case 'mm':
1101         case 'ss':
1102         case 'ww':
1103         case 'WW':
1104             return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
1105         case 'M':
1106         case 'D':
1107         case 'd':
1108         case 'H':
1109         case 'h':
1110         case 'm':
1111         case 's':
1112         case 'w':
1113         case 'W':
1114         case 'e':
1115         case 'E':
1116             return parseTokenOneOrTwoDigits;
1117         case 'Do':
1118             return parseTokenOrdinal;
1119         default :
1120             a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i'));
1121             return a;
1122         }
1123     }
1124
1125     function timezoneMinutesFromString(string) {
1126         string = string || '';
1127         var possibleTzMatches = (string.match(parseTokenTimezone) || []),
1128             tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
1129             parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
1130             minutes = +(parts[1] * 60) + toInt(parts[2]);
1131
1132         return parts[0] === '+' ? -minutes : minutes;
1133     }
1134
1135     // function to convert string input to date
1136     function addTimeToArrayFromToken(token, input, config) {
1137         var a, datePartArray = config._a;
1138
1139         switch (token) {
1140         // QUARTER
1141         case 'Q':
1142             if (input != null) {
1143                 datePartArray[MONTH] = (toInt(input) - 1) * 3;
1144             }
1145             break;
1146         // MONTH
1147         case 'M' : // fall through to MM
1148         case 'MM' :
1149             if (input != null) {
1150                 datePartArray[MONTH] = toInt(input) - 1;
1151             }
1152             break;
1153         case 'MMM' : // fall through to MMMM
1154         case 'MMMM' :
1155             a = config._locale.monthsParse(input);
1156             // if we didn't find a month name, mark the date as invalid.
1157             if (a != null) {
1158                 datePartArray[MONTH] = a;
1159             } else {
1160                 config._pf.invalidMonth = input;
1161             }
1162             break;
1163         // DAY OF MONTH
1164         case 'D' : // fall through to DD
1165         case 'DD' :
1166             if (input != null) {
1167                 datePartArray[DATE] = toInt(input);
1168             }
1169             break;
1170         case 'Do' :
1171             if (input != null) {
1172                 datePartArray[DATE] = toInt(parseInt(input, 10));
1173             }
1174             break;
1175         // DAY OF YEAR
1176         case 'DDD' : // fall through to DDDD
1177         case 'DDDD' :
1178             if (input != null) {
1179                 config._dayOfYear = toInt(input);
1180             }
1181
1182             break;
1183         // YEAR
1184         case 'YY' :
1185             datePartArray[YEAR] = moment.parseTwoDigitYear(input);
1186             break;
1187         case 'YYYY' :
1188         case 'YYYYY' :
1189         case 'YYYYYY' :
1190             datePartArray[YEAR] = toInt(input);
1191             break;
1192         // AM / PM
1193         case 'a' : // fall through to A
1194         case 'A' :
1195             config._isPm = config._locale.isPM(input);
1196             break;
1197         // 24 HOUR
1198         case 'H' : // fall through to hh
1199         case 'HH' : // fall through to hh
1200         case 'h' : // fall through to hh
1201         case 'hh' :
1202             datePartArray[HOUR] = toInt(input);
1203             break;
1204         // MINUTE
1205         case 'm' : // fall through to mm
1206         case 'mm' :
1207             datePartArray[MINUTE] = toInt(input);
1208             break;
1209         // SECOND
1210         case 's' : // fall through to ss
1211         case 'ss' :
1212             datePartArray[SECOND] = toInt(input);
1213             break;
1214         // MILLISECOND
1215         case 'S' :
1216         case 'SS' :
1217         case 'SSS' :
1218         case 'SSSS' :
1219             datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
1220             break;
1221         // UNIX TIMESTAMP WITH MS
1222         case 'X':
1223             config._d = new Date(parseFloat(input) * 1000);
1224             break;
1225         // TIMEZONE
1226         case 'Z' : // fall through to ZZ
1227         case 'ZZ' :
1228             config._useUTC = true;
1229             config._tzm = timezoneMinutesFromString(input);
1230             break;
1231         // WEEKDAY - human
1232         case 'dd':
1233         case 'ddd':
1234         case 'dddd':
1235             a = config._locale.weekdaysParse(input);
1236             // if we didn't get a weekday name, mark the date as invalid
1237             if (a != null) {
1238                 config._w = config._w || {};
1239                 config._w['d'] = a;
1240             } else {
1241                 config._pf.invalidWeekday = input;
1242             }
1243             break;
1244         // WEEK, WEEK DAY - numeric
1245         case 'w':
1246         case 'ww':
1247         case 'W':
1248         case 'WW':
1249         case 'd':
1250         case 'e':
1251         case 'E':
1252             token = token.substr(0, 1);
1253             /* falls through */
1254         case 'gggg':
1255         case 'GGGG':
1256         case 'GGGGG':
1257             token = token.substr(0, 2);
1258             if (input) {
1259                 config._w = config._w || {};
1260                 config._w[token] = toInt(input);
1261             }
1262             break;
1263         case 'gg':
1264         case 'GG':
1265             config._w = config._w || {};
1266             config._w[token] = moment.parseTwoDigitYear(input);
1267         }
1268     }
1269
1270     function dayOfYearFromWeekInfo(config) {
1271         var w, weekYear, week, weekday, dow, doy, temp;
1272
1273         w = config._w;
1274         if (w.GG != null || w.W != null || w.E != null) {
1275             dow = 1;
1276             doy = 4;
1277
1278             // TODO: We need to take the current isoWeekYear, but that depends on
1279             // how we interpret now (local, utc, fixed offset). So create
1280             // a now version of current config (take local/utc/offset flags, and
1281             // create now).
1282             weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year);
1283             week = dfl(w.W, 1);
1284             weekday = dfl(w.E, 1);
1285         } else {
1286             dow = config._locale._week.dow;
1287             doy = config._locale._week.doy;
1288
1289             weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year);
1290             week = dfl(w.w, 1);
1291
1292             if (w.d != null) {
1293                 // weekday -- low day numbers are considered next week
1294                 weekday = w.d;
1295                 if (weekday < dow) {
1296                     ++week;
1297                 }
1298             } else if (w.e != null) {
1299                 // local weekday -- counting starts from begining of week
1300                 weekday = w.e + dow;
1301             } else {
1302                 // default to begining of week
1303                 weekday = dow;
1304             }
1305         }
1306         temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow);
1307
1308         config._a[YEAR] = temp.year;
1309         config._dayOfYear = temp.dayOfYear;
1310     }
1311
1312     // convert an array to a date.
1313     // the array should mirror the parameters below
1314     // note: all values past the year are optional and will default to the lowest possible value.
1315     // [year, month, day , hour, minute, second, millisecond]
1316     function dateFromConfig(config) {
1317         var i, date, input = [], currentDate, yearToUse;
1318
1319         if (config._d) {
1320             return;
1321         }
1322
1323         currentDate = currentDateArray(config);
1324
1325         //compute day of the year from weeks and weekdays
1326         if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
1327             dayOfYearFromWeekInfo(config);
1328         }
1329
1330         //if the day of the year is set, figure out what it is
1331         if (config._dayOfYear) {
1332             yearToUse = dfl(config._a[YEAR], currentDate[YEAR]);
1333
1334             if (config._dayOfYear > daysInYear(yearToUse)) {
1335                 config._pf._overflowDayOfYear = true;
1336             }
1337
1338             date = makeUTCDate(yearToUse, 0, config._dayOfYear);
1339             config._a[MONTH] = date.getUTCMonth();
1340             config._a[DATE] = date.getUTCDate();
1341         }
1342
1343         // Default to current date.
1344         // * if no year, month, day of month are given, default to today
1345         // * if day of month is given, default month and year
1346         // * if month is given, default only year
1347         // * if year is given, don't default anything
1348         for (i = 0; i < 3 && config._a[i] == null; ++i) {
1349             config._a[i] = input[i] = currentDate[i];
1350         }
1351
1352         // Zero out whatever was not defaulted, including time
1353         for (; i < 7; i++) {
1354             config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
1355         }
1356
1357         config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
1358         // Apply timezone offset from input. The actual zone can be changed
1359         // with parseZone.
1360         if (config._tzm != null) {
1361             config._d.setUTCMinutes(config._d.getUTCMinutes() + config._tzm);
1362         }
1363     }
1364
1365     function dateFromObject(config) {
1366         var normalizedInput;
1367
1368         if (config._d) {
1369             return;
1370         }
1371
1372         normalizedInput = normalizeObjectUnits(config._i);
1373         config._a = [
1374             normalizedInput.year,
1375             normalizedInput.month,
1376             normalizedInput.day,
1377             normalizedInput.hour,
1378             normalizedInput.minute,
1379             normalizedInput.second,
1380             normalizedInput.millisecond
1381         ];
1382
1383         dateFromConfig(config);
1384     }
1385
1386     function currentDateArray(config) {
1387         var now = new Date();
1388         if (config._useUTC) {
1389             return [
1390                 now.getUTCFullYear(),
1391                 now.getUTCMonth(),
1392                 now.getUTCDate()
1393             ];
1394         } else {
1395             return [now.getFullYear(), now.getMonth(), now.getDate()];
1396         }
1397     }
1398
1399     // date from string and format string
1400     function makeDateFromStringAndFormat(config) {
1401         if (config._f === moment.ISO_8601) {
1402             parseISO(config);
1403             return;
1404         }
1405
1406         config._a = [];
1407         config._pf.empty = true;
1408
1409         // This array is used to make a Date, either with `new Date` or `Date.UTC`
1410         var string = '' + config._i,
1411             i, parsedInput, tokens, token, skipped,
1412             stringLength = string.length,
1413             totalParsedInputLength = 0;
1414
1415         tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
1416
1417         for (i = 0; i < tokens.length; i++) {
1418             token = tokens[i];
1419             parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
1420             if (parsedInput) {
1421                 skipped = string.substr(0, string.indexOf(parsedInput));
1422                 if (skipped.length > 0) {
1423                     config._pf.unusedInput.push(skipped);
1424                 }
1425                 string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
1426                 totalParsedInputLength += parsedInput.length;
1427             }
1428             // don't parse if it's not a known token
1429             if (formatTokenFunctions[token]) {
1430                 if (parsedInput) {
1431                     config._pf.empty = false;
1432                 }
1433                 else {
1434                     config._pf.unusedTokens.push(token);
1435                 }
1436                 addTimeToArrayFromToken(token, parsedInput, config);
1437             }
1438             else if (config._strict && !parsedInput) {
1439                 config._pf.unusedTokens.push(token);
1440             }
1441         }
1442
1443         // add remaining unparsed input length to the string
1444         config._pf.charsLeftOver = stringLength - totalParsedInputLength;
1445         if (string.length > 0) {
1446             config._pf.unusedInput.push(string);
1447         }
1448
1449         // handle am pm
1450         if (config._isPm && config._a[HOUR] < 12) {
1451             config._a[HOUR] += 12;
1452         }
1453         // if is 12 am, change hours to 0
1454         if (config._isPm === false && config._a[HOUR] === 12) {
1455             config._a[HOUR] = 0;
1456         }
1457
1458         dateFromConfig(config);
1459         checkOverflow(config);
1460     }
1461
1462     function unescapeFormat(s) {
1463         return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
1464             return p1 || p2 || p3 || p4;
1465         });
1466     }
1467
1468     // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
1469     function regexpEscape(s) {
1470         return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
1471     }
1472
1473     // date from string and array of format strings
1474     function makeDateFromStringAndArray(config) {
1475         var tempConfig,
1476             bestMoment,
1477
1478             scoreToBeat,
1479             i,
1480             currentScore;
1481
1482         if (config._f.length === 0) {
1483             config._pf.invalidFormat = true;
1484             config._d = new Date(NaN);
1485             return;
1486         }
1487
1488         for (i = 0; i < config._f.length; i++) {
1489             currentScore = 0;
1490             tempConfig = copyConfig({}, config);
1491             tempConfig._pf = defaultParsingFlags();
1492             tempConfig._f = config._f[i];
1493             makeDateFromStringAndFormat(tempConfig);
1494
1495             if (!isValid(tempConfig)) {
1496                 continue;
1497             }
1498
1499             // if there is any input that was not parsed add a penalty for that format
1500             currentScore += tempConfig._pf.charsLeftOver;
1501
1502             //or tokens
1503             currentScore += tempConfig._pf.unusedTokens.length * 10;
1504
1505             tempConfig._pf.score = currentScore;
1506
1507             if (scoreToBeat == null || currentScore < scoreToBeat) {
1508                 scoreToBeat = currentScore;
1509                 bestMoment = tempConfig;
1510             }
1511         }
1512
1513         extend(config, bestMoment || tempConfig);
1514     }
1515
1516     // date from iso format
1517     function parseISO(config) {
1518         var i, l,
1519             string = config._i,
1520             match = isoRegex.exec(string);
1521
1522         if (match) {
1523             config._pf.iso = true;
1524             for (i = 0, l = isoDates.length; i < l; i++) {
1525                 if (isoDates[i][1].exec(string)) {
1526                     // match[5] should be "T" or undefined
1527                     config._f = isoDates[i][0] + (match[6] || ' ');
1528                     break;
1529                 }
1530             }
1531             for (i = 0, l = isoTimes.length; i < l; i++) {
1532                 if (isoTimes[i][1].exec(string)) {
1533                     config._f += isoTimes[i][0];
1534                     break;
1535                 }
1536             }
1537             if (string.match(parseTokenTimezone)) {
1538                 config._f += 'Z';
1539             }
1540             makeDateFromStringAndFormat(config);
1541         } else {
1542             config._isValid = false;
1543         }
1544     }
1545
1546     // date from iso format or fallback
1547     function makeDateFromString(config) {
1548         parseISO(config);
1549         if (config._isValid === false) {
1550             delete config._isValid;
1551             moment.createFromInputFallback(config);
1552         }
1553     }
1554
1555     function makeDateFromInput(config) {
1556         var input = config._i, matched;
1557         if (input === undefined) {
1558             config._d = new Date();
1559         } else if (isDate(input)) {
1560             config._d = new Date(+input);
1561         } else if ((matched = aspNetJsonRegex.exec(input)) !== null) {
1562             config._d = new Date(+matched[1]);
1563         } else if (typeof input === 'string') {
1564             makeDateFromString(config);
1565         } else if (isArray(input)) {
1566             config._a = input.slice(0);
1567             dateFromConfig(config);
1568         } else if (typeof(input) === 'object') {
1569             dateFromObject(config);
1570         } else if (typeof(input) === 'number') {
1571             // from milliseconds
1572             config._d = new Date(input);
1573         } else {
1574             moment.createFromInputFallback(config);
1575         }
1576     }
1577
1578     function makeDate(y, m, d, h, M, s, ms) {
1579         //can't just apply() to create a date:
1580         //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
1581         var date = new Date(y, m, d, h, M, s, ms);
1582
1583         //the date constructor doesn't accept years < 1970
1584         if (y < 1970) {
1585             date.setFullYear(y);
1586         }
1587         return date;
1588     }
1589
1590     function makeUTCDate(y) {
1591         var date = new Date(Date.UTC.apply(null, arguments));
1592         if (y < 1970) {
1593             date.setUTCFullYear(y);
1594         }
1595         return date;
1596     }
1597
1598     function parseWeekday(input, locale) {
1599         if (typeof input === 'string') {
1600             if (!isNaN(input)) {
1601                 input = parseInt(input, 10);
1602             }
1603             else {
1604                 input = locale.weekdaysParse(input);
1605                 if (typeof input !== 'number') {
1606                     return null;
1607                 }
1608             }
1609         }
1610         return input;
1611     }
1612
1613     /************************************
1614         Relative Time
1615     ************************************/
1616
1617
1618     // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
1619     function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
1620         return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
1621     }
1622
1623     function relativeTime(posNegDuration, withoutSuffix, locale) {
1624         var duration = moment.duration(posNegDuration).abs(),
1625             seconds = round(duration.as('s')),
1626             minutes = round(duration.as('m')),
1627             hours = round(duration.as('h')),
1628             days = round(duration.as('d')),
1629             months = round(duration.as('M')),
1630             years = round(duration.as('y')),
1631
1632             args = seconds < relativeTimeThresholds.s && ['s', seconds] ||
1633                 minutes === 1 && ['m'] ||
1634                 minutes < relativeTimeThresholds.m && ['mm', minutes] ||
1635                 hours === 1 && ['h'] ||
1636                 hours < relativeTimeThresholds.h && ['hh', hours] ||
1637                 days === 1 && ['d'] ||
1638                 days < relativeTimeThresholds.d && ['dd', days] ||
1639                 months === 1 && ['M'] ||
1640                 months < relativeTimeThresholds.M && ['MM', months] ||
1641                 years === 1 && ['y'] || ['yy', years];
1642
1643         args[2] = withoutSuffix;
1644         args[3] = +posNegDuration > 0;
1645         args[4] = locale;
1646         return substituteTimeAgo.apply({}, args);
1647     }
1648
1649
1650     /************************************
1651         Week of Year
1652     ************************************/
1653
1654
1655     // firstDayOfWeek       0 = sun, 6 = sat
1656     //                      the day of the week that starts the week
1657     //                      (usually sunday or monday)
1658     // firstDayOfWeekOfYear 0 = sun, 6 = sat
1659     //                      the first week is the week that contains the first
1660     //                      of this day of the week
1661     //                      (eg. ISO weeks use thursday (4))
1662     function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
1663         var end = firstDayOfWeekOfYear - firstDayOfWeek,
1664             daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
1665             adjustedMoment;
1666
1667
1668         if (daysToDayOfWeek > end) {
1669             daysToDayOfWeek -= 7;
1670         }
1671
1672         if (daysToDayOfWeek < end - 7) {
1673             daysToDayOfWeek += 7;
1674         }
1675
1676         adjustedMoment = moment(mom).add(daysToDayOfWeek, 'd');
1677         return {
1678             week: Math.ceil(adjustedMoment.dayOfYear() / 7),
1679             year: adjustedMoment.year()
1680         };
1681     }
1682
1683     //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
1684     function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
1685         var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
1686
1687         d = d === 0 ? 7 : d;
1688         weekday = weekday != null ? weekday : firstDayOfWeek;
1689         daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
1690         dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
1691
1692         return {
1693             year: dayOfYear > 0 ? year : year - 1,
1694             dayOfYear: dayOfYear > 0 ?  dayOfYear : daysInYear(year - 1) + dayOfYear
1695         };
1696     }
1697
1698     /************************************
1699         Top Level Functions
1700     ************************************/
1701
1702     function makeMoment(config) {
1703         var input = config._i,
1704             format = config._f;
1705
1706         config._locale = config._locale || moment.localeData(config._l);
1707
1708         if (input === null || (format === undefined && input === '')) {
1709             return moment.invalid({nullInput: true});
1710         }
1711
1712         if (typeof input === 'string') {
1713             config._i = input = config._locale.preparse(input);
1714         }
1715
1716         if (moment.isMoment(input)) {
1717             return new Moment(input, true);
1718         } else if (format) {
1719             if (isArray(format)) {
1720                 makeDateFromStringAndArray(config);
1721             } else {
1722                 makeDateFromStringAndFormat(config);
1723             }
1724         } else {
1725             makeDateFromInput(config);
1726         }
1727
1728         return new Moment(config);
1729     }
1730
1731     moment = function (input, format, locale, strict) {
1732         var c;
1733
1734         if (typeof(locale) === "boolean") {
1735             strict = locale;
1736             locale = undefined;
1737         }
1738         // object construction must be done this way.
1739         // https://github.com/moment/moment/issues/1423
1740         c = {};
1741         c._isAMomentObject = true;
1742         c._i = input;
1743         c._f = format;
1744         c._l = locale;
1745         c._strict = strict;
1746         c._isUTC = false;
1747         c._pf = defaultParsingFlags();
1748
1749         return makeMoment(c);
1750     };
1751
1752     moment.suppressDeprecationWarnings = false;
1753
1754     moment.createFromInputFallback = deprecate(
1755         'moment construction falls back to js Date. This is ' +
1756         'discouraged and will be removed in upcoming major ' +
1757         'release. Please refer to ' +
1758         'https://github.com/moment/moment/issues/1407 for more info.',
1759         function (config) {
1760             config._d = new Date(config._i);
1761         }
1762     );
1763
1764     // Pick a moment m from moments so that m[fn](other) is true for all
1765     // other. This relies on the function fn to be transitive.
1766     //
1767     // moments should either be an array of moment objects or an array, whose
1768     // first element is an array of moment objects.
1769     function pickBy(fn, moments) {
1770         var res, i;
1771         if (moments.length === 1 && isArray(moments[0])) {
1772             moments = moments[0];
1773         }
1774         if (!moments.length) {
1775             return moment();
1776         }
1777         res = moments[0];
1778         for (i = 1; i < moments.length; ++i) {
1779             if (moments[i][fn](res)) {
1780                 res = moments[i];
1781             }
1782         }
1783         return res;
1784     }
1785
1786     moment.min = function () {
1787         var args = [].slice.call(arguments, 0);
1788
1789         return pickBy('isBefore', args);
1790     };
1791
1792     moment.max = function () {
1793         var args = [].slice.call(arguments, 0);
1794
1795         return pickBy('isAfter', args);
1796     };
1797
1798     // creating with utc
1799     moment.utc = function (input, format, locale, strict) {
1800         var c;
1801
1802         if (typeof(locale) === "boolean") {
1803             strict = locale;
1804             locale = undefined;
1805         }
1806         // object construction must be done this way.
1807         // https://github.com/moment/moment/issues/1423
1808         c = {};
1809         c._isAMomentObject = true;
1810         c._useUTC = true;
1811         c._isUTC = true;
1812         c._l = locale;
1813         c._i = input;
1814         c._f = format;
1815         c._strict = strict;
1816         c._pf = defaultParsingFlags();
1817
1818         return makeMoment(c).utc();
1819     };
1820
1821     // creating with unix timestamp (in seconds)
1822     moment.unix = function (input) {
1823         return moment(input * 1000);
1824     };
1825
1826     // duration
1827     moment.duration = function (input, key) {
1828         var duration = input,
1829             // matching against regexp is expensive, do it on demand
1830             match = null,
1831             sign,
1832             ret,
1833             parseIso,
1834             diffRes;
1835
1836         if (moment.isDuration(input)) {
1837             duration = {
1838                 ms: input._milliseconds,
1839                 d: input._days,
1840                 M: input._months
1841             };
1842         } else if (typeof input === 'number') {
1843             duration = {};
1844             if (key) {
1845                 duration[key] = input;
1846             } else {
1847                 duration.milliseconds = input;
1848             }
1849         } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
1850             sign = (match[1] === '-') ? -1 : 1;
1851             duration = {
1852                 y: 0,
1853                 d: toInt(match[DATE]) * sign,
1854                 h: toInt(match[HOUR]) * sign,
1855                 m: toInt(match[MINUTE]) * sign,
1856                 s: toInt(match[SECOND]) * sign,
1857                 ms: toInt(match[MILLISECOND]) * sign
1858             };
1859         } else if (!!(match = isoDurationRegex.exec(input))) {
1860             sign = (match[1] === '-') ? -1 : 1;
1861             parseIso = function (inp) {
1862                 // We'd normally use ~~inp for this, but unfortunately it also
1863                 // converts floats to ints.
1864                 // inp may be undefined, so careful calling replace on it.
1865                 var res = inp && parseFloat(inp.replace(',', '.'));
1866                 // apply sign while we're at it
1867                 return (isNaN(res) ? 0 : res) * sign;
1868             };
1869             duration = {
1870                 y: parseIso(match[2]),
1871                 M: parseIso(match[3]),
1872                 d: parseIso(match[4]),
1873                 h: parseIso(match[5]),
1874                 m: parseIso(match[6]),
1875                 s: parseIso(match[7]),
1876                 w: parseIso(match[8])
1877             };
1878         } else if (typeof duration === 'object' &&
1879                 ('from' in duration || 'to' in duration)) {
1880             diffRes = momentsDifference(moment(duration.from), moment(duration.to));
1881
1882             duration = {};
1883             duration.ms = diffRes.milliseconds;
1884             duration.M = diffRes.months;
1885         }
1886
1887         ret = new Duration(duration);
1888
1889         if (moment.isDuration(input) && input.hasOwnProperty('_locale')) {
1890             ret._locale = input._locale;
1891         }
1892
1893         return ret;
1894     };
1895
1896     // version number
1897     moment.version = VERSION;
1898
1899     // default format
1900     moment.defaultFormat = isoFormat;
1901
1902     // constant that refers to the ISO standard
1903     moment.ISO_8601 = function () {};
1904
1905     // Plugins that add properties should also add the key here (null value),
1906     // so we can properly clone ourselves.
1907     moment.momentProperties = momentProperties;
1908
1909     // This function will be called whenever a moment is mutated.
1910     // It is intended to keep the offset in sync with the timezone.
1911     moment.updateOffset = function () {};
1912
1913     // This function allows you to set a threshold for relative time strings
1914     moment.relativeTimeThreshold = function (threshold, limit) {
1915         if (relativeTimeThresholds[threshold] === undefined) {
1916             return false;
1917         }
1918         if (limit === undefined) {
1919             return relativeTimeThresholds[threshold];
1920         }
1921         relativeTimeThresholds[threshold] = limit;
1922         return true;
1923     };
1924
1925     moment.lang = deprecate(
1926         "moment.lang is deprecated. Use moment.locale instead.",
1927         function (key, value) {
1928             return moment.locale(key, value);
1929         }
1930     );
1931
1932     // This function will load locale and then set the global locale.  If
1933     // no arguments are passed in, it will simply return the current global
1934     // locale key.
1935     moment.locale = function (key, values) {
1936         var data;
1937         if (key) {
1938             if (typeof(values) !== "undefined") {
1939                 data = moment.defineLocale(key, values);
1940             }
1941             else {
1942                 data = moment.localeData(key);
1943             }
1944
1945             if (data) {
1946                 moment.duration._locale = moment._locale = data;
1947             }
1948         }
1949
1950         return moment._locale._abbr;
1951     };
1952
1953     moment.defineLocale = function (name, values) {
1954         if (values !== null) {
1955             values.abbr = name;
1956             if (!locales[name]) {
1957                 locales[name] = new Locale();
1958             }
1959             locales[name].set(values);
1960
1961             // backwards compat for now: also set the locale
1962             moment.locale(name);
1963
1964             return locales[name];
1965         } else {
1966             // useful for testing
1967             delete locales[name];
1968             return null;
1969         }
1970     };
1971
1972     moment.langData = deprecate(
1973         "moment.langData is deprecated. Use moment.localeData instead.",
1974         function (key) {
1975             return moment.localeData(key);
1976         }
1977     );
1978
1979     // returns locale data
1980     moment.localeData = function (key) {
1981         var locale;
1982
1983         if (key && key._locale && key._locale._abbr) {
1984             key = key._locale._abbr;
1985         }
1986
1987         if (!key) {
1988             return moment._locale;
1989         }
1990
1991         if (!isArray(key)) {
1992             //short-circuit everything else
1993             locale = loadLocale(key);
1994             if (locale) {
1995                 return locale;
1996             }
1997             key = [key];
1998         }
1999
2000         return chooseLocale(key);
2001     };
2002
2003     // compare moment object
2004     moment.isMoment = function (obj) {
2005         return obj instanceof Moment ||
2006             (obj != null &&  obj.hasOwnProperty('_isAMomentObject'));
2007     };
2008
2009     // for typechecking Duration objects
2010     moment.isDuration = function (obj) {
2011         return obj instanceof Duration;
2012     };
2013
2014     for (i = lists.length - 1; i >= 0; --i) {
2015         makeList(lists[i]);
2016     }
2017
2018     moment.normalizeUnits = function (units) {
2019         return normalizeUnits(units);
2020     };
2021
2022     moment.invalid = function (flags) {
2023         var m = moment.utc(NaN);
2024         if (flags != null) {
2025             extend(m._pf, flags);
2026         }
2027         else {
2028             m._pf.userInvalidated = true;
2029         }
2030
2031         return m;
2032     };
2033
2034     moment.parseZone = function () {
2035         return moment.apply(null, arguments).parseZone();
2036     };
2037
2038     moment.parseTwoDigitYear = function (input) {
2039         return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
2040     };
2041
2042     /************************************
2043         Moment Prototype
2044     ************************************/
2045
2046
2047     extend(moment.fn = Moment.prototype, {
2048
2049         clone : function () {
2050             return moment(this);
2051         },
2052
2053         valueOf : function () {
2054             return +this._d + ((this._offset || 0) * 60000);
2055         },
2056
2057         unix : function () {
2058             return Math.floor(+this / 1000);
2059         },
2060
2061         toString : function () {
2062             return this.clone().locale('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
2063         },
2064
2065         toDate : function () {
2066             return this._offset ? new Date(+this) : this._d;
2067         },
2068
2069         toISOString : function () {
2070             var m = moment(this).utc();
2071             if (0 < m.year() && m.year() <= 9999) {
2072                 return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
2073             } else {
2074                 return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
2075             }
2076         },
2077
2078         toArray : function () {
2079             var m = this;
2080             return [
2081                 m.year(),
2082                 m.month(),
2083                 m.date(),
2084                 m.hours(),
2085                 m.minutes(),
2086                 m.seconds(),
2087                 m.milliseconds()
2088             ];
2089         },
2090
2091         isValid : function () {
2092             return isValid(this);
2093         },
2094
2095         isDSTShifted : function () {
2096             if (this._a) {
2097                 return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
2098             }
2099
2100             return false;
2101         },
2102
2103         parsingFlags : function () {
2104             return extend({}, this._pf);
2105         },
2106
2107         invalidAt: function () {
2108             return this._pf.overflow;
2109         },
2110
2111         utc : function (keepLocalTime) {
2112             return this.zone(0, keepLocalTime);
2113         },
2114
2115         local : function (keepLocalTime) {
2116             if (this._isUTC) {
2117                 this.zone(0, keepLocalTime);
2118                 this._isUTC = false;
2119
2120                 if (keepLocalTime) {
2121                     this.add(this._d.getTimezoneOffset(), 'm');
2122                 }
2123             }
2124             return this;
2125         },
2126
2127         format : function (inputString) {
2128             var output = formatMoment(this, inputString || moment.defaultFormat);
2129             return this.localeData().postformat(output);
2130         },
2131
2132         add : createAdder(1, 'add'),
2133
2134         subtract : createAdder(-1, 'subtract'),
2135
2136         diff : function (input, units, asFloat) {
2137             var that = makeAs(input, this),
2138                 zoneDiff = (this.zone() - that.zone()) * 6e4,
2139                 diff, output;
2140
2141             units = normalizeUnits(units);
2142
2143             if (units === 'year' || units === 'month') {
2144                 // average number of days in the months in the given dates
2145                 diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
2146                 // difference in months
2147                 output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
2148                 // adjust by taking difference in days, average number of days
2149                 // and dst in the given months.
2150                 output += ((this - moment(this).startOf('month')) -
2151                         (that - moment(that).startOf('month'))) / diff;
2152                 // same as above but with zones, to negate all dst
2153                 output -= ((this.zone() - moment(this).startOf('month').zone()) -
2154                         (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
2155                 if (units === 'year') {
2156                     output = output / 12;
2157                 }
2158             } else {
2159                 diff = (this - that);
2160                 output = units === 'second' ? diff / 1e3 : // 1000
2161                     units === 'minute' ? diff / 6e4 : // 1000 * 60
2162                     units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
2163                     units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
2164                     units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
2165                     diff;
2166             }
2167             return asFloat ? output : absRound(output);
2168         },
2169
2170         from : function (time, withoutSuffix) {
2171             return moment.duration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
2172         },
2173
2174         fromNow : function (withoutSuffix) {
2175             return this.from(moment(), withoutSuffix);
2176         },
2177
2178         calendar : function (time) {
2179             // We want to compare the start of today, vs this.
2180             // Getting start-of-today depends on whether we're zone'd or not.
2181             var now = time || moment(),
2182                 sod = makeAs(now, this).startOf('day'),
2183                 diff = this.diff(sod, 'days', true),
2184                 format = diff < -6 ? 'sameElse' :
2185                     diff < -1 ? 'lastWeek' :
2186                     diff < 0 ? 'lastDay' :
2187                     diff < 1 ? 'sameDay' :
2188                     diff < 2 ? 'nextDay' :
2189                     diff < 7 ? 'nextWeek' : 'sameElse';
2190             return this.format(this.localeData().calendar(format, this));
2191         },
2192
2193         isLeapYear : function () {
2194             return isLeapYear(this.year());
2195         },
2196
2197         isDST : function () {
2198             return (this.zone() < this.clone().month(0).zone() ||
2199                 this.zone() < this.clone().month(5).zone());
2200         },
2201
2202         day : function (input) {
2203             var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
2204             if (input != null) {
2205                 input = parseWeekday(input, this.localeData());
2206                 return this.add(input - day, 'd');
2207             } else {
2208                 return day;
2209             }
2210         },
2211
2212         month : makeAccessor('Month', true),
2213
2214         startOf : function (units) {
2215             units = normalizeUnits(units);
2216             // the following switch intentionally omits break keywords
2217             // to utilize falling through the cases.
2218             switch (units) {
2219             case 'year':
2220                 this.month(0);
2221                 /* falls through */
2222             case 'quarter':
2223             case 'month':
2224                 this.date(1);
2225                 /* falls through */
2226             case 'week':
2227             case 'isoWeek':
2228             case 'day':
2229                 this.hours(0);
2230                 /* falls through */
2231             case 'hour':
2232                 this.minutes(0);
2233                 /* falls through */
2234             case 'minute':
2235                 this.seconds(0);
2236                 /* falls through */
2237             case 'second':
2238                 this.milliseconds(0);
2239                 /* falls through */
2240             }
2241
2242             // weeks are a special case
2243             if (units === 'week') {
2244                 this.weekday(0);
2245             } else if (units === 'isoWeek') {
2246                 this.isoWeekday(1);
2247             }
2248
2249             // quarters are also special
2250             if (units === 'quarter') {
2251                 this.month(Math.floor(this.month() / 3) * 3);
2252             }
2253
2254             return this;
2255         },
2256
2257         endOf: function (units) {
2258             units = normalizeUnits(units);
2259             return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
2260         },
2261
2262         isAfter: function (input, units) {
2263             units = typeof units !== 'undefined' ? units : 'millisecond';
2264             return +this.clone().startOf(units) > +moment(input).startOf(units);
2265         },
2266
2267         isBefore: function (input, units) {
2268             units = typeof units !== 'undefined' ? units : 'millisecond';
2269             return +this.clone().startOf(units) < +moment(input).startOf(units);
2270         },
2271
2272         isSame: function (input, units) {
2273             units = units || 'ms';
2274             return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
2275         },
2276
2277         min: deprecate(
2278                  'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548',
2279                  function (other) {
2280                      other = moment.apply(null, arguments);
2281                      return other < this ? this : other;
2282                  }
2283          ),
2284
2285         max: deprecate(
2286                 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548',
2287                 function (other) {
2288                     other = moment.apply(null, arguments);
2289                     return other > this ? this : other;
2290                 }
2291         ),
2292
2293         // keepLocalTime = true means only change the timezone, without
2294         // affecting the local hour. So 5:31:26 +0300 --[zone(2, true)]-->
2295         // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist int zone
2296         // +0200, so we adjust the time as needed, to be valid.
2297         //
2298         // Keeping the time actually adds/subtracts (one hour)
2299         // from the actual represented time. That is why we call updateOffset
2300         // a second time. In case it wants us to change the offset again
2301         // _changeInProgress == true case, then we have to adjust, because
2302         // there is no such time in the given timezone.
2303         zone : function (input, keepLocalTime) {
2304             var offset = this._offset || 0,
2305                 localAdjust;
2306             if (input != null) {
2307                 if (typeof input === 'string') {
2308                     input = timezoneMinutesFromString(input);
2309                 }
2310                 if (Math.abs(input) < 16) {
2311                     input = input * 60;
2312                 }
2313                 if (!this._isUTC && keepLocalTime) {
2314                     localAdjust = this._d.getTimezoneOffset();
2315                 }
2316                 this._offset = input;
2317                 this._isUTC = true;
2318                 if (localAdjust != null) {
2319                     this.subtract(localAdjust, 'm');
2320                 }
2321                 if (offset !== input) {
2322                     if (!keepLocalTime || this._changeInProgress) {
2323                         addOrSubtractDurationFromMoment(this,
2324                                 moment.duration(offset - input, 'm'), 1, false);
2325                     } else if (!this._changeInProgress) {
2326                         this._changeInProgress = true;
2327                         moment.updateOffset(this, true);
2328                         this._changeInProgress = null;
2329                     }
2330                 }
2331             } else {
2332                 return this._isUTC ? offset : this._d.getTimezoneOffset();
2333             }
2334             return this;
2335         },
2336
2337         zoneAbbr : function () {
2338             return this._isUTC ? 'UTC' : '';
2339         },
2340
2341         zoneName : function () {
2342             return this._isUTC ? 'Coordinated Universal Time' : '';
2343         },
2344
2345         parseZone : function () {
2346             if (this._tzm) {
2347                 this.zone(this._tzm);
2348             } else if (typeof this._i === 'string') {
2349                 this.zone(this._i);
2350             }
2351             return this;
2352         },
2353
2354         hasAlignedHourOffset : function (input) {
2355             if (!input) {
2356                 input = 0;
2357             }
2358             else {
2359                 input = moment(input).zone();
2360             }
2361
2362             return (this.zone() - input) % 60 === 0;
2363         },
2364
2365         daysInMonth : function () {
2366             return daysInMonth(this.year(), this.month());
2367         },
2368
2369         dayOfYear : function (input) {
2370             var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
2371             return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
2372         },
2373
2374         quarter : function (input) {
2375             return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
2376         },
2377
2378         weekYear : function (input) {
2379             var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year;
2380             return input == null ? year : this.add((input - year), 'y');
2381         },
2382
2383         isoWeekYear : function (input) {
2384             var year = weekOfYear(this, 1, 4).year;
2385             return input == null ? year : this.add((input - year), 'y');
2386         },
2387
2388         week : function (input) {
2389             var week = this.localeData().week(this);
2390             return input == null ? week : this.add((input - week) * 7, 'd');
2391         },
2392
2393         isoWeek : function (input) {
2394             var week = weekOfYear(this, 1, 4).week;
2395             return input == null ? week : this.add((input - week) * 7, 'd');
2396         },
2397
2398         weekday : function (input) {
2399             var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
2400             return input == null ? weekday : this.add(input - weekday, 'd');
2401         },
2402
2403         isoWeekday : function (input) {
2404             // behaves the same as moment#day except
2405             // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
2406             // as a setter, sunday should belong to the previous week.
2407             return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
2408         },
2409
2410         isoWeeksInYear : function () {
2411             return weeksInYear(this.year(), 1, 4);
2412         },
2413
2414         weeksInYear : function () {
2415             var weekInfo = this.localeData()._week;
2416             return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
2417         },
2418
2419         get : function (units) {
2420             units = normalizeUnits(units);
2421             return this[units]();
2422         },
2423
2424         set : function (units, value) {
2425             units = normalizeUnits(units);
2426             if (typeof this[units] === 'function') {
2427                 this[units](value);
2428             }
2429             return this;
2430         },
2431
2432         // If passed a locale key, it will set the locale for this
2433         // instance.  Otherwise, it will return the locale configuration
2434         // variables for this instance.
2435         locale : function (key) {
2436             if (key === undefined) {
2437                 return this._locale._abbr;
2438             } else {
2439                 this._locale = moment.localeData(key);
2440                 return this;
2441             }
2442         },
2443
2444         lang : deprecate(
2445             "moment().lang() is deprecated. Use moment().localeData() instead.",
2446             function (key) {
2447                 if (key === undefined) {
2448                     return this.localeData();
2449                 } else {
2450                     this._locale = moment.localeData(key);
2451                     return this;
2452                 }
2453             }
2454         ),
2455
2456         localeData : function () {
2457             return this._locale;
2458         }
2459     });
2460
2461     function rawMonthSetter(mom, value) {
2462         var dayOfMonth;
2463
2464         // TODO: Move this out of here!
2465         if (typeof value === 'string') {
2466             value = mom.localeData().monthsParse(value);
2467             // TODO: Another silent failure?
2468             if (typeof value !== 'number') {
2469                 return mom;
2470             }
2471         }
2472
2473         dayOfMonth = Math.min(mom.date(),
2474                 daysInMonth(mom.year(), value));
2475         mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
2476         return mom;
2477     }
2478
2479     function rawGetter(mom, unit) {
2480         return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]();
2481     }
2482
2483     function rawSetter(mom, unit, value) {
2484         if (unit === 'Month') {
2485             return rawMonthSetter(mom, value);
2486         } else {
2487             return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
2488         }
2489     }
2490
2491     function makeAccessor(unit, keepTime) {
2492         return function (value) {
2493             if (value != null) {
2494                 rawSetter(this, unit, value);
2495                 moment.updateOffset(this, keepTime);
2496                 return this;
2497             } else {
2498                 return rawGetter(this, unit);
2499             }
2500         };
2501     }
2502
2503     moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
2504     moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
2505     moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
2506     // Setting the hour should keep the time, because the user explicitly
2507     // specified which hour he wants. So trying to maintain the same hour (in
2508     // a new timezone) makes sense. Adding/subtracting hours does not follow
2509     // this rule.
2510     moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
2511     // moment.fn.month is defined separately
2512     moment.fn.date = makeAccessor('Date', true);
2513     moment.fn.dates = deprecate('dates accessor is deprecated. Use date instead.', makeAccessor('Date', true));
2514     moment.fn.year = makeAccessor('FullYear', true);
2515     moment.fn.years = deprecate('years accessor is deprecated. Use year instead.', makeAccessor('FullYear', true));
2516
2517     // add plural methods
2518     moment.fn.days = moment.fn.day;
2519     moment.fn.months = moment.fn.month;
2520     moment.fn.weeks = moment.fn.week;
2521     moment.fn.isoWeeks = moment.fn.isoWeek;
2522     moment.fn.quarters = moment.fn.quarter;
2523
2524     // add aliased format methods
2525     moment.fn.toJSON = moment.fn.toISOString;
2526
2527     /************************************
2528         Duration Prototype
2529     ************************************/
2530
2531
2532     function daysToYears (days) {
2533         // 400 years have 146097 days (taking into account leap year rules)
2534         return days * 400 / 146097;
2535     }
2536
2537     function yearsToDays (years) {
2538         // years * 365 + absRound(years / 4) -
2539         //     absRound(years / 100) + absRound(years / 400);
2540         return years * 146097 / 400;
2541     }
2542
2543     extend(moment.duration.fn = Duration.prototype, {
2544
2545         _bubble : function () {
2546             var milliseconds = this._milliseconds,
2547                 days = this._days,
2548                 months = this._months,
2549                 data = this._data,
2550                 seconds, minutes, hours, years = 0;
2551
2552             // The following code bubbles up values, see the tests for
2553             // examples of what that means.
2554             data.milliseconds = milliseconds % 1000;
2555
2556             seconds = absRound(milliseconds / 1000);
2557             data.seconds = seconds % 60;
2558
2559             minutes = absRound(seconds / 60);
2560             data.minutes = minutes % 60;
2561
2562             hours = absRound(minutes / 60);
2563             data.hours = hours % 24;
2564
2565             days += absRound(hours / 24);
2566
2567             // Accurately convert days to years, assume start from year 0.
2568             years = absRound(daysToYears(days));
2569             days -= absRound(yearsToDays(years));
2570
2571             // 30 days to a month
2572             // TODO (iskren): Use anchor date (like 1st Jan) to compute this.
2573             months += absRound(days / 30);
2574             days %= 30;
2575
2576             // 12 months -> 1 year
2577             years += absRound(months / 12);
2578             months %= 12;
2579
2580             data.days = days;
2581             data.months = months;
2582             data.years = years;
2583         },
2584
2585         abs : function () {
2586             this._milliseconds = Math.abs(this._milliseconds);
2587             this._days = Math.abs(this._days);
2588             this._months = Math.abs(this._months);
2589
2590             this._data.milliseconds = Math.abs(this._data.milliseconds);
2591             this._data.seconds = Math.abs(this._data.seconds);
2592             this._data.minutes = Math.abs(this._data.minutes);
2593             this._data.hours = Math.abs(this._data.hours);
2594             this._data.months = Math.abs(this._data.months);
2595             this._data.years = Math.abs(this._data.years);
2596
2597             return this;
2598         },
2599
2600         weeks : function () {
2601             return absRound(this.days() / 7);
2602         },
2603
2604         valueOf : function () {
2605             return this._milliseconds +
2606               this._days * 864e5 +
2607               (this._months % 12) * 2592e6 +
2608               toInt(this._months / 12) * 31536e6;
2609         },
2610
2611         humanize : function (withSuffix) {
2612             var output = relativeTime(this, !withSuffix, this.localeData());
2613
2614             if (withSuffix) {
2615                 output = this.localeData().pastFuture(+this, output);
2616             }
2617
2618             return this.localeData().postformat(output);
2619         },
2620
2621         add : function (input, val) {
2622             // supports only 2.0-style add(1, 's') or add(moment)
2623             var dur = moment.duration(input, val);
2624
2625             this._milliseconds += dur._milliseconds;
2626             this._days += dur._days;
2627             this._months += dur._months;
2628
2629             this._bubble();
2630
2631             return this;
2632         },
2633
2634         subtract : function (input, val) {
2635             var dur = moment.duration(input, val);
2636
2637             this._milliseconds -= dur._milliseconds;
2638             this._days -= dur._days;
2639             this._months -= dur._months;
2640
2641             this._bubble();
2642
2643             return this;
2644         },
2645
2646         get : function (units) {
2647             units = normalizeUnits(units);
2648             return this[units.toLowerCase() + 's']();
2649         },
2650
2651         as : function (units) {
2652             var days, months;
2653             units = normalizeUnits(units);
2654
2655             days = this._days + this._milliseconds / 864e5;
2656             if (units === 'month' || units === 'year') {
2657                 months = this._months + daysToYears(days) * 12;
2658                 return units === 'month' ? months : months / 12;
2659             } else {
2660                 days += yearsToDays(this._months / 12);
2661                 switch (units) {
2662                     case 'week': return days / 7;
2663                     case 'day': return days;
2664                     case 'hour': return days * 24;
2665                     case 'minute': return days * 24 * 60;
2666                     case 'second': return days * 24 * 60 * 60;
2667                     case 'millisecond': return days * 24 * 60 * 60 * 1000;
2668                     default: throw new Error('Unknown unit ' + units);
2669                 }
2670             }
2671         },
2672
2673         lang : moment.fn.lang,
2674         locale : moment.fn.locale,
2675
2676         toIsoString : deprecate(
2677             "toIsoString() is deprecated. Please use toISOString() instead " +
2678             "(notice the capitals)",
2679             function () {
2680                 return this.toISOString();
2681             }
2682         ),
2683
2684         toISOString : function () {
2685             // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
2686             var years = Math.abs(this.years()),
2687                 months = Math.abs(this.months()),
2688                 days = Math.abs(this.days()),
2689                 hours = Math.abs(this.hours()),
2690                 minutes = Math.abs(this.minutes()),
2691                 seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
2692
2693             if (!this.asSeconds()) {
2694                 // this is the same as C#'s (Noda) and python (isodate)...
2695                 // but not other JS (goog.date)
2696                 return 'P0D';
2697             }
2698
2699             return (this.asSeconds() < 0 ? '-' : '') +
2700                 'P' +
2701                 (years ? years + 'Y' : '') +
2702                 (months ? months + 'M' : '') +
2703                 (days ? days + 'D' : '') +
2704                 ((hours || minutes || seconds) ? 'T' : '') +
2705                 (hours ? hours + 'H' : '') +
2706                 (minutes ? minutes + 'M' : '') +
2707                 (seconds ? seconds + 'S' : '');
2708         },
2709
2710         localeData : function () {
2711             return this._locale;
2712         }
2713     });
2714
2715     function makeDurationGetter(name) {
2716         moment.duration.fn[name] = function () {
2717             return this._data[name];
2718         };
2719     }
2720
2721     for (i in unitMillisecondFactors) {
2722         if (unitMillisecondFactors.hasOwnProperty(i)) {
2723             makeDurationGetter(i.toLowerCase());
2724         }
2725     }
2726
2727     moment.duration.fn.asMilliseconds = function () {
2728         return this.as('ms');
2729     };
2730     moment.duration.fn.asSeconds = function () {
2731         return this.as('s');
2732     };
2733     moment.duration.fn.asMinutes = function () {
2734         return this.as('m');
2735     };
2736     moment.duration.fn.asHours = function () {
2737         return this.as('h');
2738     };
2739     moment.duration.fn.asDays = function () {
2740         return this.as('d');
2741     };
2742     moment.duration.fn.asWeeks = function () {
2743         return this.as('weeks');
2744     };
2745     moment.duration.fn.asMonths = function () {
2746         return this.as('M');
2747     };
2748     moment.duration.fn.asYears = function () {
2749         return this.as('y');
2750     };
2751
2752     /************************************
2753         Default Locale
2754     ************************************/
2755
2756
2757     // Set default locale, other locale will inherit from English.
2758     moment.locale('en', {
2759         ordinal : function (number) {
2760             var b = number % 10,
2761                 output = (toInt(number % 100 / 10) === 1) ? 'th' :
2762                 (b === 1) ? 'st' :
2763                 (b === 2) ? 'nd' :
2764                 (b === 3) ? 'rd' : 'th';
2765             return number + output;
2766         }
2767     });
2768
2769     /* EMBED_LOCALES */
2770
2771     /************************************
2772         Exposing Moment
2773     ************************************/
2774
2775     function makeGlobal(shouldDeprecate) {
2776         /*global ender:false */
2777         if (typeof ender !== 'undefined') {
2778             return;
2779         }
2780         oldGlobalMoment = globalScope.moment;
2781         if (shouldDeprecate) {
2782             globalScope.moment = deprecate(
2783                     'Accessing Moment through the global scope is ' +
2784                     'deprecated, and will be removed in an upcoming ' +
2785                     'release.',
2786                     moment);
2787         } else {
2788             globalScope.moment = moment;
2789         }
2790     }
2791
2792     // CommonJS module is defined
2793     if (hasModule) {
2794         module.exports = moment;
2795     } else if (typeof define === 'function' && define.amd) {
2796         define('moment', function (require, exports, module) {
2797             if (module.config && module.config() && module.config().noGlobal === true) {
2798                 // release the global variable
2799                 globalScope.moment = oldGlobalMoment;
2800             }
2801
2802             return moment;
2803         });
2804         makeGlobal(true);
2805     } else {
2806         makeGlobal();
2807     }
2808 }).call(this);