潘志宝
5 天以前 6d75723f3e3bd43895db2470bc5fabb2314dbe8b
提交 | 用户 | 时间
e7c126 1 /**
H 2 * @version: 2.1.27
3 * @author: Dan Grossman http://www.dangrossman.info/
4 * @copyright: Copyright (c) 2012-2017 Dan Grossman. All rights reserved.
5 * @license: Licensed under the MIT license. See http://www.opensource.org/licenses/mit-license.php
6 * @website: http://www.daterangepicker.com/
7 */
8 // Follow the UMD template https://github.com/umdjs/umd/blob/master/templates/returnExportsGlobal.js
9 (function (root, factory) {
10     if (typeof define === 'function' && define.amd) {
11         // AMD. Make globaly available as well
12         define(['moment', 'jquery'], function (moment, jquery) {
13             if (!jquery.fn) jquery.fn = {}; // webpack server rendering
14             return factory(moment, jquery);
15         });
16     } else if (typeof module === 'object' && module.exports) {
17         // Node / Browserify
18         //isomorphic issue
19         var jQuery = (typeof window != 'undefined') ? window.jQuery : undefined;
20         if (!jQuery) {
21             jQuery = require('jquery');
22             if (!jQuery.fn) jQuery.fn = {};
23         }
24         var moment = (typeof window != 'undefined' && typeof window.moment != 'undefined') ? window.moment : require('moment');
25         module.exports = factory(moment, jQuery);
26     } else {
27         // Browser globals
28         root.daterangepicker = factory(root.moment, root.jQuery);
29     }
30 }(this, function(moment, $) {
31     var DateRangePicker = function(element, options, cb) {
32
33         //default settings for options
34         this.parentEl = 'body';
35         this.element = $(element);
36         this.startDate = moment().startOf('day');
37         this.endDate = moment().endOf('day');
38         this.minDate = false;
39         this.maxDate = false;
40         this.dateLimit = false;
41         this.autoApply = false;
42         this.singleDatePicker = false;
43         this.showDropdowns = false;
44         this.showWeekNumbers = false;
45         this.showISOWeekNumbers = false;
46         this.showCustomRangeLabel = true;
47         this.timePicker = false;
48         this.timePicker24Hour = false;
49         this.timePickerIncrement = 1;
50         this.timePickerSeconds = false;
51         this.linkedCalendars = true;
52         this.autoUpdateInput = true;
53         this.alwaysShowCalendars = false;
54         this.ranges = {};
55
56         this.opens = 'right';
57         if (this.element.hasClass('pull-right'))
58             this.opens = 'left';
59
60         this.drops = 'down';
61         if (this.element.hasClass('dropup'))
62             this.drops = 'up';
63
64         this.buttonClasses = 'btn btn-sm';
65         this.applyClass = 'btn-success';
66         this.cancelClass = 'btn-default';
67
68         this.locale = {
69             direction: 'ltr',
70             format: moment.localeData().longDateFormat('L'),
71             separator: ' - ',
72             applyLabel: 'Apply',
73             cancelLabel: 'Cancel',
74             weekLabel: 'W',
75             customRangeLabel: 'Custom Range',
76             daysOfWeek: moment.weekdaysMin(),
77             monthNames: moment.monthsShort(),
78             firstDay: moment.localeData().firstDayOfWeek()
79         };
80
81         this.callback = function() { };
82
83         //some state information
84         this.isShowing = false;
85         this.leftCalendar = {};
86         this.rightCalendar = {};
87
88         //custom options from user
89         if (typeof options !== 'object' || options === null)
90             options = {};
91
92         //allow setting options with data attributes
93         //data-api options will be overwritten with custom javascript options
94         options = $.extend(this.element.data(), options);
95
96         //html template for the picker UI
97         if (typeof options.template !== 'string' && !(options.template instanceof $))
98             options.template = '<div class="daterangepicker dropdown-menu">' +
99                 '<div class="calendar left">' +
100                     '<div class="daterangepicker_input">' +
101                       '<input class="input-mini form-control" type="text" name="daterangepicker_start" value="" />' +
102                       '<i class="fa fa-calendar glyphicon glyphicon-calendar"></i>' +
103                       '<div class="calendar-time">' +
104                         '<div></div>' +
105                         '<i class="fa fa-clock-o glyphicon glyphicon-time"></i>' +
106                       '</div>' +
107                     '</div>' +
108                     '<div class="calendar-table"></div>' +
109                 '</div>' +
110                 '<div class="calendar right">' +
111                     '<div class="daterangepicker_input">' +
112                       '<input class="input-mini form-control" type="text" name="daterangepicker_end" value="" />' +
113                       '<i class="fa fa-calendar glyphicon glyphicon-calendar"></i>' +
114                       '<div class="calendar-time">' +
115                         '<div></div>' +
116                         '<i class="fa fa-clock-o glyphicon glyphicon-time"></i>' +
117                       '</div>' +
118                     '</div>' +
119                     '<div class="calendar-table"></div>' +
120                 '</div>' +
121                 '<div class="ranges">' +
122                     '<div class="range_inputs">' +
123                         '<button class="applyBtn" disabled="disabled" type="button"></button> ' +
124                         '<button class="cancelBtn" type="button"></button>' +
125                     '</div>' +
126                 '</div>' +
127             '</div>';
128
129         this.parentEl = (options.parentEl && $(options.parentEl).length) ? $(options.parentEl) : $(this.parentEl);
130         this.container = $(options.template).appendTo(this.parentEl);
131
132         //
133         // handle all the possible options overriding defaults
134         //
135
136         if (typeof options.locale === 'object') {
137
138             if (typeof options.locale.direction === 'string')
139                 this.locale.direction = options.locale.direction;
140
141             if (typeof options.locale.format === 'string')
142                 this.locale.format = options.locale.format;
143
144             if (typeof options.locale.separator === 'string')
145                 this.locale.separator = options.locale.separator;
146
147             if (typeof options.locale.daysOfWeek === 'object')
148                 this.locale.daysOfWeek = options.locale.daysOfWeek.slice();
149
150             if (typeof options.locale.monthNames === 'object')
151               this.locale.monthNames = options.locale.monthNames.slice();
152
153             if (typeof options.locale.firstDay === 'number')
154               this.locale.firstDay = options.locale.firstDay;
155
156             if (typeof options.locale.applyLabel === 'string')
157               this.locale.applyLabel = options.locale.applyLabel;
158
159             if (typeof options.locale.cancelLabel === 'string')
160               this.locale.cancelLabel = options.locale.cancelLabel;
161
162             if (typeof options.locale.weekLabel === 'string')
163               this.locale.weekLabel = options.locale.weekLabel;
164
165             if (typeof options.locale.customRangeLabel === 'string'){
166                 //Support unicode chars in the custom range name.
167                 var elem = document.createElement('textarea');
168                 elem.innerHTML = options.locale.customRangeLabel;
169                 var rangeHtml = elem.value;
170                 this.locale.customRangeLabel = rangeHtml;
171             }
172         }
173         this.container.addClass(this.locale.direction);
174
175         if (typeof options.startDate === 'string')
176             this.startDate = moment(options.startDate, this.locale.format);
177
178         if (typeof options.endDate === 'string')
179             this.endDate = moment(options.endDate, this.locale.format);
180
181         if (typeof options.minDate === 'string')
182             this.minDate = moment(options.minDate, this.locale.format);
183
184         if (typeof options.maxDate === 'string')
185             this.maxDate = moment(options.maxDate, this.locale.format);
186
187         if (typeof options.startDate === 'object')
188             this.startDate = moment(options.startDate);
189
190         if (typeof options.endDate === 'object')
191             this.endDate = moment(options.endDate);
192
193         if (typeof options.minDate === 'object')
194             this.minDate = moment(options.minDate);
195
196         if (typeof options.maxDate === 'object')
197             this.maxDate = moment(options.maxDate);
198
199         // sanity check for bad options
200         if (this.minDate && this.startDate.isBefore(this.minDate))
201             this.startDate = this.minDate.clone();
202
203         // sanity check for bad options
204         if (this.maxDate && this.endDate.isAfter(this.maxDate))
205             this.endDate = this.maxDate.clone();
206
207         if (typeof options.applyClass === 'string')
208             this.applyClass = options.applyClass;
209
210         if (typeof options.cancelClass === 'string')
211             this.cancelClass = options.cancelClass;
212
213         if (typeof options.dateLimit === 'object')
214             this.dateLimit = options.dateLimit;
215
216         if (typeof options.opens === 'string')
217             this.opens = options.opens;
218
219         if (typeof options.drops === 'string')
220             this.drops = options.drops;
221
222         if (typeof options.showWeekNumbers === 'boolean')
223             this.showWeekNumbers = options.showWeekNumbers;
224
225         if (typeof options.showISOWeekNumbers === 'boolean')
226             this.showISOWeekNumbers = options.showISOWeekNumbers;
227
228         if (typeof options.buttonClasses === 'string')
229             this.buttonClasses = options.buttonClasses;
230
231         if (typeof options.buttonClasses === 'object')
232             this.buttonClasses = options.buttonClasses.join(' ');
233
234         if (typeof options.showDropdowns === 'boolean')
235             this.showDropdowns = options.showDropdowns;
236
237         if (typeof options.showCustomRangeLabel === 'boolean')
238             this.showCustomRangeLabel = options.showCustomRangeLabel;
239
240         if (typeof options.singleDatePicker === 'boolean') {
241             this.singleDatePicker = options.singleDatePicker;
242             if (this.singleDatePicker)
243                 this.endDate = this.startDate.clone();
244         }
245
246         if (typeof options.timePicker === 'boolean')
247             this.timePicker = options.timePicker;
248
249         if (typeof options.timePickerSeconds === 'boolean')
250             this.timePickerSeconds = options.timePickerSeconds;
251
252         if (typeof options.timePickerIncrement === 'number')
253             this.timePickerIncrement = options.timePickerIncrement;
254
255         if (typeof options.timePicker24Hour === 'boolean')
256             this.timePicker24Hour = options.timePicker24Hour;
257
258         if (typeof options.autoApply === 'boolean')
259             this.autoApply = options.autoApply;
260
261         if (typeof options.autoUpdateInput === 'boolean')
262             this.autoUpdateInput = options.autoUpdateInput;
263
264         if (typeof options.linkedCalendars === 'boolean')
265             this.linkedCalendars = options.linkedCalendars;
266
267         if (typeof options.isInvalidDate === 'function')
268             this.isInvalidDate = options.isInvalidDate;
269
270         if (typeof options.isCustomDate === 'function')
271             this.isCustomDate = options.isCustomDate;
272
273         if (typeof options.alwaysShowCalendars === 'boolean')
274             this.alwaysShowCalendars = options.alwaysShowCalendars;
275
276         // update day names order to firstDay
277         if (this.locale.firstDay != 0) {
278             var iterator = this.locale.firstDay;
279             while (iterator > 0) {
280                 this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift());
281                 iterator--;
282             }
283         }
284
285         var start, end, range;
286
287         //if no start/end dates set, check if an input element contains initial values
288         if (typeof options.startDate === 'undefined' && typeof options.endDate === 'undefined') {
289             if ($(this.element).is('input[type=text]')) {
290                 var val = $(this.element).val(),
291                     split = val.split(this.locale.separator);
292
293                 start = end = null;
294
295                 if (split.length == 2) {
296                     start = moment(split[0], this.locale.format);
297                     end = moment(split[1], this.locale.format);
298                 } else if (this.singleDatePicker && val !== "") {
299                     start = moment(val, this.locale.format);
300                     end = moment(val, this.locale.format);
301                 }
302                 if (start !== null && end !== null) {
303                     this.setStartDate(start);
304                     this.setEndDate(end);
305                 }
306             }
307         }
308
309         if (typeof options.ranges === 'object') {
310             for (range in options.ranges) {
311
312                 if (typeof options.ranges[range][0] === 'string')
313                     start = moment(options.ranges[range][0], this.locale.format);
314                 else
315                     start = moment(options.ranges[range][0]);
316
317                 if (typeof options.ranges[range][1] === 'string')
318                     end = moment(options.ranges[range][1], this.locale.format);
319                 else
320                     end = moment(options.ranges[range][1]);
321
322                 // If the start or end date exceed those allowed by the minDate or dateLimit
323                 // options, shorten the range to the allowable period.
324                 if (this.minDate && start.isBefore(this.minDate))
325                     start = this.minDate.clone();
326
327                 var maxDate = this.maxDate;
328                 if (this.dateLimit && maxDate && start.clone().add(this.dateLimit).isAfter(maxDate))
329                     maxDate = start.clone().add(this.dateLimit);
330                 if (maxDate && end.isAfter(maxDate))
331                     end = maxDate.clone();
332
333                 // If the end of the range is before the minimum or the start of the range is
334                 // after the maximum, don't display this range option at all.
335                 if ((this.minDate && end.isBefore(this.minDate, this.timepicker ? 'minute' : 'day')) 
336                   || (maxDate && start.isAfter(maxDate, this.timepicker ? 'minute' : 'day')))
337                     continue;
338
339                 //Support unicode chars in the range names.
340                 var elem = document.createElement('textarea');
341                 elem.innerHTML = range;
342                 var rangeHtml = elem.value;
343
344                 this.ranges[rangeHtml] = [start, end];
345             }
346
347             var list = '<ul>';
348             for (range in this.ranges) {
349                 list += '<li data-range-key="' + range + '">' + range + '</li>';
350             }
351             if (this.showCustomRangeLabel) {
352                 list += '<li data-range-key="' + this.locale.customRangeLabel + '">' + this.locale.customRangeLabel + '</li>';
353             }
354             list += '</ul>';
355             this.container.find('.ranges').prepend(list);
356         }
357
358         if (typeof cb === 'function') {
359             this.callback = cb;
360         }
361
362         if (!this.timePicker) {
363             this.startDate = this.startDate.startOf('day');
364             this.endDate = this.endDate.endOf('day');
365             this.container.find('.calendar-time').hide();
366         }
367
368         //can't be used together for now
369         if (this.timePicker && this.autoApply)
370             this.autoApply = false;
371
372         if (this.autoApply && typeof options.ranges !== 'object') {
373             this.container.find('.ranges').hide();
374         } else if (this.autoApply) {
375             this.container.find('.applyBtn, .cancelBtn').addClass('hide');
376         }
377
378         if (this.singleDatePicker) {
379             this.container.addClass('single');
380             this.container.find('.calendar.left').addClass('single');
381             this.container.find('.calendar.left').show();
382             this.container.find('.calendar.right').hide();
383             this.container.find('.daterangepicker_input input, .daterangepicker_input > i').hide();
384             if (this.timePicker) {
385                 this.container.find('.ranges ul').hide();
386             } else {
387                 this.container.find('.ranges').hide();
388             }
389         }
390
391         if ((typeof options.ranges === 'undefined' && !this.singleDatePicker) || this.alwaysShowCalendars) {
392             this.container.addClass('show-calendar');
393         }
394
395         this.container.addClass('opens' + this.opens);
396
397         //swap the position of the predefined ranges if opens right
398         if (typeof options.ranges !== 'undefined' && this.opens == 'right') {
399             this.container.find('.ranges').prependTo( this.container.find('.calendar.left').parent() );
400         }
401
402         //apply CSS classes and labels to buttons
403         this.container.find('.applyBtn, .cancelBtn').addClass(this.buttonClasses);
404         if (this.applyClass.length)
405             this.container.find('.applyBtn').addClass(this.applyClass);
406         if (this.cancelClass.length)
407             this.container.find('.cancelBtn').addClass(this.cancelClass);
408         this.container.find('.applyBtn').html(this.locale.applyLabel);
409         this.container.find('.cancelBtn').html(this.locale.cancelLabel);
410
411         //
412         // event listeners
413         //
414
415         this.container.find('.calendar')
416             .on('click.daterangepicker', '.prev', $.proxy(this.clickPrev, this))
417             .on('click.daterangepicker', '.next', $.proxy(this.clickNext, this))
418             .on('mousedown.daterangepicker', 'td.available', $.proxy(this.clickDate, this))
419             .on('mouseenter.daterangepicker', 'td.available', $.proxy(this.hoverDate, this))
420             .on('mouseleave.daterangepicker', 'td.available', $.proxy(this.updateFormInputs, this))
421             .on('change.daterangepicker', 'select.yearselect', $.proxy(this.monthOrYearChanged, this))
422             .on('change.daterangepicker', 'select.monthselect', $.proxy(this.monthOrYearChanged, this))
423             .on('change.daterangepicker', 'select.hourselect,select.minuteselect,select.secondselect,select.ampmselect', $.proxy(this.timeChanged, this))
424             .on('click.daterangepicker', '.daterangepicker_input input', $.proxy(this.showCalendars, this))
425             .on('focus.daterangepicker', '.daterangepicker_input input', $.proxy(this.formInputsFocused, this))
426             .on('blur.daterangepicker', '.daterangepicker_input input', $.proxy(this.formInputsBlurred, this))
427             .on('change.daterangepicker', '.daterangepicker_input input', $.proxy(this.formInputsChanged, this))
428             .on('keydown.daterangepicker', '.daterangepicker_input input', $.proxy(this.formInputsKeydown, this));
429
430         this.container.find('.ranges')
431             .on('click.daterangepicker', 'button.applyBtn', $.proxy(this.clickApply, this))
432             .on('click.daterangepicker', 'button.cancelBtn', $.proxy(this.clickCancel, this))
433             .on('click.daterangepicker', 'li', $.proxy(this.clickRange, this))
434             .on('mouseenter.daterangepicker', 'li', $.proxy(this.hoverRange, this))
435             .on('mouseleave.daterangepicker', 'li', $.proxy(this.updateFormInputs, this));
436
437         if (this.element.is('input') || this.element.is('button')) {
438             this.element.on({
439                 'click.daterangepicker': $.proxy(this.show, this),
440                 'focus.daterangepicker': $.proxy(this.show, this),
441                 'keyup.daterangepicker': $.proxy(this.elementChanged, this),
442                 'keydown.daterangepicker': $.proxy(this.keydown, this) //IE 11 compatibility
443             });
444         } else {
445             this.element.on('click.daterangepicker', $.proxy(this.toggle, this));
446             this.element.on('keydown.daterangepicker', $.proxy(this.toggle, this));
447         }
448
449         //
450         // if attached to a text input, set the initial value
451         //
452
453         if (this.element.is('input') && !this.singleDatePicker && this.autoUpdateInput) {
454             this.element.val(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format));
455             this.element.trigger('change');
456         } else if (this.element.is('input') && this.autoUpdateInput) {
457             this.element.val(this.startDate.format(this.locale.format));
458             this.element.trigger('change');
459         }
460
461     };
462
463     DateRangePicker.prototype = {
464
465         constructor: DateRangePicker,
466
467         setStartDate: function(startDate) {
468             if (typeof startDate === 'string')
469                 this.startDate = moment(startDate, this.locale.format);
470
471             if (typeof startDate === 'object')
472                 this.startDate = moment(startDate);
473
474             if (!this.timePicker)
475                 this.startDate = this.startDate.startOf('day');
476
477             if (this.timePicker && this.timePickerIncrement)
478                 this.startDate.minute(Math.round(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
479
480             if (this.minDate && this.startDate.isBefore(this.minDate)) {
481                 this.startDate = this.minDate.clone();
482                 if (this.timePicker && this.timePickerIncrement)
483                     this.startDate.minute(Math.round(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
484             }
485
486             if (this.maxDate && this.startDate.isAfter(this.maxDate)) {
487                 this.startDate = this.maxDate.clone();
488                 if (this.timePicker && this.timePickerIncrement)
489                     this.startDate.minute(Math.floor(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
490             }
491
492             if (!this.isShowing)
493                 this.updateElement();
494
495             this.updateMonthsInView();
496         },
497
498         setEndDate: function(endDate) {
499             if (typeof endDate === 'string')
500                 this.endDate = moment(endDate, this.locale.format);
501
502             if (typeof endDate === 'object')
503                 this.endDate = moment(endDate);
504
505             if (!this.timePicker)
506                 this.endDate = this.endDate.add(1,'d').startOf('day').subtract(1,'second');
507
508             if (this.timePicker && this.timePickerIncrement)
509                 this.endDate.minute(Math.round(this.endDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
510
511             if (this.endDate.isBefore(this.startDate))
512                 this.endDate = this.startDate.clone();
513
514             if (this.maxDate && this.endDate.isAfter(this.maxDate))
515                 this.endDate = this.maxDate.clone();
516
517             if (this.dateLimit && this.startDate.clone().add(this.dateLimit).isBefore(this.endDate))
518                 this.endDate = this.startDate.clone().add(this.dateLimit);
519
520             this.previousRightTime = this.endDate.clone();
521
522             if (!this.isShowing)
523                 this.updateElement();
524
525             this.updateMonthsInView();
526         },
527
528         isInvalidDate: function() {
529             return false;
530         },
531
532         isCustomDate: function() {
533             return false;
534         },
535
536         updateView: function() {
537             if (this.timePicker) {
538                 this.renderTimePicker('left');
539                 this.renderTimePicker('right');
540                 if (!this.endDate) {
541                     this.container.find('.right .calendar-time select').attr('disabled', 'disabled').addClass('disabled');
542                 } else {
543                     this.container.find('.right .calendar-time select').removeAttr('disabled').removeClass('disabled');
544                 }
545             }
546             if (this.endDate) {
547                 this.container.find('input[name="daterangepicker_end"]').removeClass('active');
548                 this.container.find('input[name="daterangepicker_start"]').addClass('active');
549             } else {
550                 this.container.find('input[name="daterangepicker_end"]').addClass('active');
551                 this.container.find('input[name="daterangepicker_start"]').removeClass('active');
552             }
553             this.updateMonthsInView();
554             this.updateCalendars();
555             this.updateFormInputs();
556         },
557
558         updateMonthsInView: function() {
559             if (this.endDate) {
560
561                 //if both dates are visible already, do nothing
562                 if (!this.singleDatePicker && this.leftCalendar.month && this.rightCalendar.month &&
563                     (this.startDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.startDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM'))
564                     &&
565                     (this.endDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.endDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM'))
566                     ) {
567                     return;
568                 }
569
570                 this.leftCalendar.month = this.startDate.clone().date(2);
571                 if (!this.linkedCalendars && (this.endDate.month() != this.startDate.month() || this.endDate.year() != this.startDate.year())) {
572                     this.rightCalendar.month = this.endDate.clone().date(2);
573                 } else {
574                     this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month');
575                 }
576
577             } else {
578                 if (this.leftCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM') && this.rightCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM')) {
579                     this.leftCalendar.month = this.startDate.clone().date(2);
580                     this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month');
581                 }
582             }
583             if (this.maxDate && this.linkedCalendars && !this.singleDatePicker && this.rightCalendar.month > this.maxDate) {
584               this.rightCalendar.month = this.maxDate.clone().date(2);
585               this.leftCalendar.month = this.maxDate.clone().date(2).subtract(1, 'month');
586             }
587         },
588
589         updateCalendars: function() {
590
591             if (this.timePicker) {
592                 var hour, minute, second;
593                 if (this.endDate) {
594                     hour = parseInt(this.container.find('.left .hourselect').val(), 10);
595                     minute = parseInt(this.container.find('.left .minuteselect').val(), 10);
596                     second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0;
597                     if (!this.timePicker24Hour) {
598                         var ampm = this.container.find('.left .ampmselect').val();
599                         if (ampm === 'PM' && hour < 12)
600                             hour += 12;
601                         if (ampm === 'AM' && hour === 12)
602                             hour = 0;
603                     }
604                 } else {
605                     hour = parseInt(this.container.find('.right .hourselect').val(), 10);
606                     minute = parseInt(this.container.find('.right .minuteselect').val(), 10);
607                     second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0;
608                     if (!this.timePicker24Hour) {
609                         var ampm = this.container.find('.right .ampmselect').val();
610                         if (ampm === 'PM' && hour < 12)
611                             hour += 12;
612                         if (ampm === 'AM' && hour === 12)
613                             hour = 0;
614                     }
615                 }
616                 this.leftCalendar.month.hour(hour).minute(minute).second(second);
617                 this.rightCalendar.month.hour(hour).minute(minute).second(second);
618             }
619
620             this.renderCalendar('left');
621             this.renderCalendar('right');
622
623             //highlight any predefined range matching the current start and end dates
624             this.container.find('.ranges li').removeClass('active');
625             if (this.endDate == null) return;
626
627             this.calculateChosenLabel();
628         },
629
630         renderCalendar: function(side) {
631
632             //
633             // Build the matrix of dates that will populate the calendar
634             //
635
636             var calendar = side == 'left' ? this.leftCalendar : this.rightCalendar;
637             var month = calendar.month.month();
638             var year = calendar.month.year();
639             var hour = calendar.month.hour();
640             var minute = calendar.month.minute();
641             var second = calendar.month.second();
642             var daysInMonth = moment([year, month]).daysInMonth();
643             var firstDay = moment([year, month, 1]);
644             var lastDay = moment([year, month, daysInMonth]);
645             var lastMonth = moment(firstDay).subtract(1, 'month').month();
646             var lastYear = moment(firstDay).subtract(1, 'month').year();
647             var daysInLastMonth = moment([lastYear, lastMonth]).daysInMonth();
648             var dayOfWeek = firstDay.day();
649
650             //initialize a 6 rows x 7 columns array for the calendar
651             var calendar = [];
652             calendar.firstDay = firstDay;
653             calendar.lastDay = lastDay;
654
655             for (var i = 0; i < 6; i++) {
656                 calendar[i] = [];
657             }
658
659             //populate the calendar with date objects
660             var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1;
661             if (startDay > daysInLastMonth)
662                 startDay -= 7;
663
664             if (dayOfWeek == this.locale.firstDay)
665                 startDay = daysInLastMonth - 6;
666
667             var curDate = moment([lastYear, lastMonth, startDay, 12, minute, second]);
668
669             var col, row;
670             for (var i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = moment(curDate).add(24, 'hour')) {
671                 if (i > 0 && col % 7 === 0) {
672                     col = 0;
673                     row++;
674                 }
675                 calendar[row][col] = curDate.clone().hour(hour).minute(minute).second(second);
676                 curDate.hour(12);
677
678                 if (this.minDate && calendar[row][col].format('YYYY-MM-DD') == this.minDate.format('YYYY-MM-DD') && calendar[row][col].isBefore(this.minDate) && side == 'left') {
679                     calendar[row][col] = this.minDate.clone();
680                 }
681
682                 if (this.maxDate && calendar[row][col].format('YYYY-MM-DD') == this.maxDate.format('YYYY-MM-DD') && calendar[row][col].isAfter(this.maxDate) && side == 'right') {
683                     calendar[row][col] = this.maxDate.clone();
684                 }
685
686             }
687
688             //make the calendar object available to hoverDate/clickDate
689             if (side == 'left') {
690                 this.leftCalendar.calendar = calendar;
691             } else {
692                 this.rightCalendar.calendar = calendar;
693             }
694
695             //
696             // Display the calendar
697             //
698
699             var minDate = side == 'left' ? this.minDate : this.startDate;
700             var maxDate = this.maxDate;
701             var selected = side == 'left' ? this.startDate : this.endDate;
702             var arrow = this.locale.direction == 'ltr' ? {left: 'chevron-left', right: 'chevron-right'} : {left: 'chevron-right', right: 'chevron-left'};
703
704             var html = '<table class="table-condensed">';
705             html += '<thead>';
706             html += '<tr>';
707
708             // add empty cell for week number
709             if (this.showWeekNumbers || this.showISOWeekNumbers)
710                 html += '<th></th>';
711
712             if ((!minDate || minDate.isBefore(calendar.firstDay)) && (!this.linkedCalendars || side == 'left')) {
713                 html += '<th class="prev available"><i class="fa fa-' + arrow.left + ' glyphicon glyphicon-' + arrow.left + '"></i></th>';
714             } else {
715                 html += '<th></th>';
716             }
717
718             var dateHtml = this.locale.monthNames[calendar[1][1].month()] + calendar[1][1].format(" YYYY");
719
720             if (this.showDropdowns) {
721                 var currentMonth = calendar[1][1].month();
722                 var currentYear = calendar[1][1].year();
723                 var maxYear = (maxDate && maxDate.year()) || (currentYear + 5);
724                 var minYear = (minDate && minDate.year()) || (currentYear - 50);
725                 var inMinYear = currentYear == minYear;
726                 var inMaxYear = currentYear == maxYear;
727
728                 var monthHtml = '<select class="monthselect">';
729                 for (var m = 0; m < 12; m++) {
730                     if ((!inMinYear || m >= minDate.month()) && (!inMaxYear || m <= maxDate.month())) {
731                         monthHtml += "<option value='" + m + "'" +
732                             (m === currentMonth ? " selected='selected'" : "") +
733                             ">" + this.locale.monthNames[m] + "</option>";
734                     } else {
735                         monthHtml += "<option value='" + m + "'" +
736                             (m === currentMonth ? " selected='selected'" : "") +
737                             " disabled='disabled'>" + this.locale.monthNames[m] + "</option>";
738                     }
739                 }
740                 monthHtml += "</select>";
741
742                 var yearHtml = '<select class="yearselect">';
743                 for (var y = minYear; y <= maxYear; y++) {
744                     yearHtml += '<option value="' + y + '"' +
745                         (y === currentYear ? ' selected="selected"' : '') +
746                         '>' + y + '</option>';
747                 }
748                 yearHtml += '</select>';
749
750                 dateHtml = monthHtml + yearHtml;
751             }
752
753             html += '<th colspan="5" class="month">' + dateHtml + '</th>';
754             if ((!maxDate || maxDate.isAfter(calendar.lastDay)) && (!this.linkedCalendars || side == 'right' || this.singleDatePicker)) {
755                 html += '<th class="next available"><i class="fa fa-' + arrow.right + ' glyphicon glyphicon-' + arrow.right + '"></i></th>';
756             } else {
757                 html += '<th></th>';
758             }
759
760             html += '</tr>';
761             html += '<tr>';
762
763             // add week number label
764             if (this.showWeekNumbers || this.showISOWeekNumbers)
765                 html += '<th class="week">' + this.locale.weekLabel + '</th>';
766
767             $.each(this.locale.daysOfWeek, function(index, dayOfWeek) {
768                 html += '<th>' + dayOfWeek + '</th>';
769             });
770
771             html += '</tr>';
772             html += '</thead>';
773             html += '<tbody>';
774
775             //adjust maxDate to reflect the dateLimit setting in order to
776             //grey out end dates beyond the dateLimit
777             if (this.endDate == null && this.dateLimit) {
778                 var maxLimit = this.startDate.clone().add(this.dateLimit).endOf('day');
779                 if (!maxDate || maxLimit.isBefore(maxDate)) {
780                     maxDate = maxLimit;
781                 }
782             }
783
784             for (var row = 0; row < 6; row++) {
785                 html += '<tr>';
786
787                 // add week number
788                 if (this.showWeekNumbers)
789                     html += '<td class="week">' + calendar[row][0].week() + '</td>';
790                 else if (this.showISOWeekNumbers)
791                     html += '<td class="week">' + calendar[row][0].isoWeek() + '</td>';
792
793                 for (var col = 0; col < 7; col++) {
794
795                     var classes = [];
796
797                     //highlight today's date
798                     if (calendar[row][col].isSame(new Date(), "day"))
799                         classes.push('today');
800
801                     //highlight weekends
802                     if (calendar[row][col].isoWeekday() > 5)
803                         classes.push('weekend');
804
805                     //grey out the dates in other months displayed at beginning and end of this calendar
806                     if (calendar[row][col].month() != calendar[1][1].month())
807                         classes.push('off');
808
809                     //don't allow selection of dates before the minimum date
810                     if (this.minDate && calendar[row][col].isBefore(this.minDate, 'day'))
811                         classes.push('off', 'disabled');
812
813                     //don't allow selection of dates after the maximum date
814                     if (maxDate && calendar[row][col].isAfter(maxDate, 'day'))
815                         classes.push('off', 'disabled');
816
817                     //don't allow selection of date if a custom function decides it's invalid
818                     if (this.isInvalidDate(calendar[row][col]))
819                         classes.push('off', 'disabled');
820
821                     //highlight the currently selected start date
822                     if (calendar[row][col].format('YYYY-MM-DD') == this.startDate.format('YYYY-MM-DD'))
823                         classes.push('active', 'start-date');
824
825                     //highlight the currently selected end date
826                     if (this.endDate != null && calendar[row][col].format('YYYY-MM-DD') == this.endDate.format('YYYY-MM-DD'))
827                         classes.push('active', 'end-date');
828
829                     //highlight dates in-between the selected dates
830                     if (this.endDate != null && calendar[row][col] > this.startDate && calendar[row][col] < this.endDate)
831                         classes.push('in-range');
832
833                     //apply custom classes for this date
834                     var isCustom = this.isCustomDate(calendar[row][col]);
835                     if (isCustom !== false) {
836                         if (typeof isCustom === 'string')
837                             classes.push(isCustom);
838                         else
839                             Array.prototype.push.apply(classes, isCustom);
840                     }
841
842                     var cname = '', disabled = false;
843                     for (var i = 0; i < classes.length; i++) {
844                         cname += classes[i] + ' ';
845                         if (classes[i] == 'disabled')
846                             disabled = true;
847                     }
848                     if (!disabled)
849                         cname += 'available';
850
851                     html += '<td class="' + cname.replace(/^\s+|\s+$/g, '') + '" data-title="' + 'r' + row + 'c' + col + '">' + calendar[row][col].date() + '</td>';
852
853                 }
854                 html += '</tr>';
855             }
856
857             html += '</tbody>';
858             html += '</table>';
859
860             this.container.find('.calendar.' + side + ' .calendar-table').html(html);
861
862         },
863
864         renderTimePicker: function(side) {
865
866             // Don't bother updating the time picker if it's currently disabled
867             // because an end date hasn't been clicked yet
868             if (side == 'right' && !this.endDate) return;
869
870             var html, selected, minDate, maxDate = this.maxDate;
871
872             if (this.dateLimit && (!this.maxDate || this.startDate.clone().add(this.dateLimit).isAfter(this.maxDate)))
873                 maxDate = this.startDate.clone().add(this.dateLimit);
874
875             if (side == 'left') {
876                 selected = this.startDate.clone();
877                 minDate = this.minDate;
878             } else if (side == 'right') {
879                 selected = this.endDate.clone();
880                 minDate = this.startDate;
881
882                 //Preserve the time already selected
883                 var timeSelector = this.container.find('.calendar.right .calendar-time div');
884                 if (timeSelector.html() != '') {
885
886                     selected.hour(timeSelector.find('.hourselect option:selected').val() || selected.hour());
887                     selected.minute(timeSelector.find('.minuteselect option:selected').val() || selected.minute());
888                     selected.second(timeSelector.find('.secondselect option:selected').val() || selected.second());
889
890                     if (!this.timePicker24Hour) {
891                         var ampm = timeSelector.find('.ampmselect option:selected').val();
892                         if (ampm === 'PM' && selected.hour() < 12)
893                             selected.hour(selected.hour() + 12);
894                         if (ampm === 'AM' && selected.hour() === 12)
895                             selected.hour(0);
896                     }
897
898                 }
899
900                 if (selected.isBefore(this.startDate))
901                     selected = this.startDate.clone();
902
903                 if (maxDate && selected.isAfter(maxDate))
904                     selected = maxDate.clone();
905
906             }
907
908             //
909             // hours
910             //
911
912             html = '<select class="hourselect">';
913
914             var start = this.timePicker24Hour ? 0 : 1;
915             var end = this.timePicker24Hour ? 23 : 12;
916
917             for (var i = start; i <= end; i++) {
918                 var i_in_24 = i;
919                 if (!this.timePicker24Hour)
920                     i_in_24 = selected.hour() >= 12 ? (i == 12 ? 12 : i + 12) : (i == 12 ? 0 : i);
921
922                 var time = selected.clone().hour(i_in_24);
923                 var disabled = false;
924                 if (minDate && time.minute(59).isBefore(minDate))
925                     disabled = true;
926                 if (maxDate && time.minute(0).isAfter(maxDate))
927                     disabled = true;
928
929                 if (i_in_24 == selected.hour() && !disabled) {
930                     html += '<option value="' + i + '" selected="selected">' + i + '</option>';
931                 } else if (disabled) {
932                     html += '<option value="' + i + '" disabled="disabled" class="disabled">' + i + '</option>';
933                 } else {
934                     html += '<option value="' + i + '">' + i + '</option>';
935                 }
936             }
937
938             html += '</select> ';
939
940             //
941             // minutes
942             //
943
944             html += ': <select class="minuteselect">';
945
946             for (var i = 0; i < 60; i += this.timePickerIncrement) {
947                 var padded = i < 10 ? '0' + i : i;
948                 var time = selected.clone().minute(i);
949
950                 var disabled = false;
951                 if (minDate && time.second(59).isBefore(minDate))
952                     disabled = true;
953                 if (maxDate && time.second(0).isAfter(maxDate))
954                     disabled = true;
955
956                 if (selected.minute() == i && !disabled) {
957                     html += '<option value="' + i + '" selected="selected">' + padded + '</option>';
958                 } else if (disabled) {
959                     html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>';
960                 } else {
961                     html += '<option value="' + i + '">' + padded + '</option>';
962                 }
963             }
964
965             html += '</select> ';
966
967             //
968             // seconds
969             //
970
971             if (this.timePickerSeconds) {
972                 html += ': <select class="secondselect">';
973
974                 for (var i = 0; i < 60; i++) {
975                     var padded = i < 10 ? '0' + i : i;
976                     var time = selected.clone().second(i);
977
978                     var disabled = false;
979                     if (minDate && time.isBefore(minDate))
980                         disabled = true;
981                     if (maxDate && time.isAfter(maxDate))
982                         disabled = true;
983
984                     if (selected.second() == i && !disabled) {
985                         html += '<option value="' + i + '" selected="selected">' + padded + '</option>';
986                     } else if (disabled) {
987                         html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>';
988                     } else {
989                         html += '<option value="' + i + '">' + padded + '</option>';
990                     }
991                 }
992
993                 html += '</select> ';
994             }
995
996             //
997             // AM/PM
998             //
999
1000             if (!this.timePicker24Hour) {
1001                 html += '<select class="ampmselect">';
1002
1003                 var am_html = '';
1004                 var pm_html = '';
1005
1006                 if (minDate && selected.clone().hour(12).minute(0).second(0).isBefore(minDate))
1007                     am_html = ' disabled="disabled" class="disabled"';
1008
1009                 if (maxDate && selected.clone().hour(0).minute(0).second(0).isAfter(maxDate))
1010                     pm_html = ' disabled="disabled" class="disabled"';
1011
1012                 if (selected.hour() >= 12) {
1013                     html += '<option value="AM"' + am_html + '>AM</option><option value="PM" selected="selected"' + pm_html + '>PM</option>';
1014                 } else {
1015                     html += '<option value="AM" selected="selected"' + am_html + '>AM</option><option value="PM"' + pm_html + '>PM</option>';
1016                 }
1017
1018                 html += '</select>';
1019             }
1020
1021             this.container.find('.calendar.' + side + ' .calendar-time div').html(html);
1022
1023         },
1024
1025         updateFormInputs: function() {
1026
1027             //ignore mouse movements while an above-calendar text input has focus
1028             if (this.container.find('input[name=daterangepicker_start]').is(":focus") || this.container.find('input[name=daterangepicker_end]').is(":focus"))
1029                 return;
1030
1031             this.container.find('input[name=daterangepicker_start]').val(this.startDate.format(this.locale.format));
1032             if (this.endDate)
1033                 this.container.find('input[name=daterangepicker_end]').val(this.endDate.format(this.locale.format));
1034
1035             if (this.singleDatePicker || (this.endDate && (this.startDate.isBefore(this.endDate) || this.startDate.isSame(this.endDate)))) {
1036                 this.container.find('button.applyBtn').removeAttr('disabled');
1037             } else {
1038                 this.container.find('button.applyBtn').attr('disabled', 'disabled');
1039             }
1040
1041         },
1042
1043         move: function() {
1044             var parentOffset = { top: 0, left: 0 },
1045                 containerTop;
1046             var parentRightEdge = $(window).width();
1047             if (!this.parentEl.is('body')) {
1048                 parentOffset = {
1049                     top: this.parentEl.offset().top - this.parentEl.scrollTop(),
1050                     left: this.parentEl.offset().left - this.parentEl.scrollLeft()
1051                 };
1052                 parentRightEdge = this.parentEl[0].clientWidth + this.parentEl.offset().left;
1053             }
1054
1055             if (this.drops == 'up')
1056                 containerTop = this.element.offset().top - this.container.outerHeight() - parentOffset.top;
1057             else
1058                 containerTop = this.element.offset().top + this.element.outerHeight() - parentOffset.top;
1059             this.container[this.drops == 'up' ? 'addClass' : 'removeClass']('dropup');
1060
1061             if (this.opens == 'left') {
1062                 this.container.css({
1063                     top: containerTop,
1064                     right: parentRightEdge - this.element.offset().left - this.element.outerWidth(),
1065                     left: 'auto'
1066                 });
1067                 if (this.container.offset().left < 0) {
1068                     this.container.css({
1069                         right: 'auto',
1070                         left: 9
1071                     });
1072                 }
1073             } else if (this.opens == 'center') {
1074                 this.container.css({
1075                     top: containerTop,
1076                     left: this.element.offset().left - parentOffset.left + this.element.outerWidth() / 2
1077                             - this.container.outerWidth() / 2,
1078                     right: 'auto'
1079                 });
1080                 if (this.container.offset().left < 0) {
1081                     this.container.css({
1082                         right: 'auto',
1083                         left: 9
1084                     });
1085                 }
1086             } else {
1087                 this.container.css({
1088                     top: containerTop,
1089                     left: this.element.offset().left - parentOffset.left,
1090                     right: 'auto'
1091                 });
1092                 if (this.container.offset().left + this.container.outerWidth() > $(window).width()) {
1093                     this.container.css({
1094                         left: 'auto',
1095                         right: 0
1096                     });
1097                 }
1098             }
1099         },
1100
1101         show: function(e) {
1102             if (this.isShowing) return;
1103
1104             // Create a click proxy that is private to this instance of datepicker, for unbinding
1105             this._outsideClickProxy = $.proxy(function(e) { this.outsideClick(e); }, this);
1106
1107             // Bind global datepicker mousedown for hiding and
1108             $(document)
1109               .on('mousedown.daterangepicker', this._outsideClickProxy)
1110               // also support mobile devices
1111               .on('touchend.daterangepicker', this._outsideClickProxy)
1112               // also explicitly play nice with Bootstrap dropdowns, which stopPropagation when clicking them
1113               .on('click.daterangepicker', '[data-toggle=dropdown]', this._outsideClickProxy)
1114               // and also close when focus changes to outside the picker (eg. tabbing between controls)
1115               .on('focusin.daterangepicker', this._outsideClickProxy);
1116
1117             // Reposition the picker if the window is resized while it's open
1118             $(window).on('resize.daterangepicker', $.proxy(function(e) { this.move(e); }, this));
1119
1120             this.oldStartDate = this.startDate.clone();
1121             this.oldEndDate = this.endDate.clone();
1122             this.previousRightTime = this.endDate.clone();
1123
1124             this.updateView();
1125             this.container.show();
1126             this.move();
1127             this.element.trigger('show.daterangepicker', this);
1128             this.isShowing = true;
1129         },
1130
1131         hide: function(e) {
1132             if (!this.isShowing) return;
1133
1134             //incomplete date selection, revert to last values
1135             if (!this.endDate) {
1136                 this.startDate = this.oldStartDate.clone();
1137                 this.endDate = this.oldEndDate.clone();
1138             }
1139
1140             //if a new date range was selected, invoke the user callback function
1141             if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
1142                 this.callback(this.startDate, this.endDate, this.chosenLabel);
1143
1144             //if picker is attached to a text input, update it
1145             this.updateElement();
1146
1147             $(document).off('.daterangepicker');
1148             $(window).off('.daterangepicker');
1149             this.container.hide();
1150             this.element.trigger('hide.daterangepicker', this);
1151             this.isShowing = false;
1152         },
1153
1154         toggle: function(e) {
1155             if (this.isShowing) {
1156                 this.hide();
1157             } else {
1158                 this.show();
1159             }
1160         },
1161
1162         outsideClick: function(e) {
1163             var target = $(e.target);
1164             // if the page is clicked anywhere except within the daterangerpicker/button
1165             // itself then call this.hide()
1166             if (
1167                 // ie modal dialog fix
1168                 e.type == "focusin" ||
1169                 target.closest(this.element).length ||
1170                 target.closest(this.container).length ||
1171                 target.closest('.calendar-table').length
1172                 ) return;
1173             this.hide();
1174             this.element.trigger('outsideClick.daterangepicker', this);
1175         },
1176
1177         showCalendars: function() {
1178             this.container.addClass('show-calendar');
1179             this.move();
1180             this.element.trigger('showCalendar.daterangepicker', this);
1181         },
1182
1183         hideCalendars: function() {
1184             this.container.removeClass('show-calendar');
1185             this.element.trigger('hideCalendar.daterangepicker', this);
1186         },
1187
1188         hoverRange: function(e) {
1189
1190             //ignore mouse movements while an above-calendar text input has focus
1191             if (this.container.find('input[name=daterangepicker_start]').is(":focus") || this.container.find('input[name=daterangepicker_end]').is(":focus"))
1192                 return;
1193
1194             var label = e.target.getAttribute('data-range-key');
1195
1196             if (label == this.locale.customRangeLabel) {
1197                 this.updateView();
1198             } else {
1199                 var dates = this.ranges[label];
1200                 this.container.find('input[name=daterangepicker_start]').val(dates[0].format(this.locale.format));
1201                 this.container.find('input[name=daterangepicker_end]').val(dates[1].format(this.locale.format));
1202             }
1203
1204         },
1205
1206         clickRange: function(e) {
1207             var label = e.target.getAttribute('data-range-key');
1208             this.chosenLabel = label;
1209             if (label == this.locale.customRangeLabel) {
1210                 this.showCalendars();
1211             } else {
1212                 var dates = this.ranges[label];
1213                 this.startDate = dates[0];
1214                 this.endDate = dates[1];
1215
1216                 if (!this.timePicker) {
1217                     this.startDate.startOf('day');
1218                     this.endDate.endOf('day');
1219                 }
1220
1221                 if (!this.alwaysShowCalendars)
1222                     this.hideCalendars();
1223                 this.clickApply();
1224             }
1225         },
1226
1227         clickPrev: function(e) {
1228             var cal = $(e.target).parents('.calendar');
1229             if (cal.hasClass('left')) {
1230                 this.leftCalendar.month.subtract(1, 'month');
1231                 if (this.linkedCalendars)
1232                     this.rightCalendar.month.subtract(1, 'month');
1233             } else {
1234                 this.rightCalendar.month.subtract(1, 'month');
1235             }
1236             this.updateCalendars();
1237         },
1238
1239         clickNext: function(e) {
1240             var cal = $(e.target).parents('.calendar');
1241             if (cal.hasClass('left')) {
1242                 this.leftCalendar.month.add(1, 'month');
1243             } else {
1244                 this.rightCalendar.month.add(1, 'month');
1245                 if (this.linkedCalendars)
1246                     this.leftCalendar.month.add(1, 'month');
1247             }
1248             this.updateCalendars();
1249         },
1250
1251         hoverDate: function(e) {
1252
1253             //ignore mouse movements while an above-calendar text input has focus
1254             //if (this.container.find('input[name=daterangepicker_start]').is(":focus") || this.container.find('input[name=daterangepicker_end]').is(":focus"))
1255             //    return;
1256
1257             //ignore dates that can't be selected
1258             if (!$(e.target).hasClass('available')) return;
1259
1260             //have the text inputs above calendars reflect the date being hovered over
1261             var title = $(e.target).attr('data-title');
1262             var row = title.substr(1, 1);
1263             var col = title.substr(3, 1);
1264             var cal = $(e.target).parents('.calendar');
1265             var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col];
1266
1267             if (this.endDate && !this.container.find('input[name=daterangepicker_start]').is(":focus")) {
1268                 this.container.find('input[name=daterangepicker_start]').val(date.format(this.locale.format));
1269             } else if (!this.endDate && !this.container.find('input[name=daterangepicker_end]').is(":focus")) {
1270                 this.container.find('input[name=daterangepicker_end]').val(date.format(this.locale.format));
1271             }
1272
1273             //highlight the dates between the start date and the date being hovered as a potential end date
1274             var leftCalendar = this.leftCalendar;
1275             var rightCalendar = this.rightCalendar;
1276             var startDate = this.startDate;
1277             if (!this.endDate) {
1278                 this.container.find('.calendar tbody td').each(function(index, el) {
1279
1280                     //skip week numbers, only look at dates
1281                     if ($(el).hasClass('week')) return;
1282
1283                     var title = $(el).attr('data-title');
1284                     var row = title.substr(1, 1);
1285                     var col = title.substr(3, 1);
1286                     var cal = $(el).parents('.calendar');
1287                     var dt = cal.hasClass('left') ? leftCalendar.calendar[row][col] : rightCalendar.calendar[row][col];
1288
1289                     if ((dt.isAfter(startDate) && dt.isBefore(date)) || dt.isSame(date, 'day')) {
1290                         $(el).addClass('in-range');
1291                     } else {
1292                         $(el).removeClass('in-range');
1293                     }
1294
1295                 });
1296             }
1297
1298         },
1299
1300         clickDate: function(e) {
1301
1302             if (!$(e.target).hasClass('available')) return;
1303
1304             var title = $(e.target).attr('data-title');
1305             var row = title.substr(1, 1);
1306             var col = title.substr(3, 1);
1307             var cal = $(e.target).parents('.calendar');
1308             var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col];
1309
1310             //
1311             // this function needs to do a few things:
1312             // * alternate between selecting a start and end date for the range,
1313             // * if the time picker is enabled, apply the hour/minute/second from the select boxes to the clicked date
1314             // * if autoapply is enabled, and an end date was chosen, apply the selection
1315             // * if single date picker mode, and time picker isn't enabled, apply the selection immediately
1316             // * if one of the inputs above the calendars was focused, cancel that manual input
1317             //
1318
1319             if (this.endDate || date.isBefore(this.startDate, 'day')) { //picking start
1320                 if (this.timePicker) {
1321                     var hour = parseInt(this.container.find('.left .hourselect').val(), 10);
1322                     if (!this.timePicker24Hour) {
1323                         var ampm = this.container.find('.left .ampmselect').val();
1324                         if (ampm === 'PM' && hour < 12)
1325                             hour += 12;
1326                         if (ampm === 'AM' && hour === 12)
1327                             hour = 0;
1328                     }
1329                     var minute = parseInt(this.container.find('.left .minuteselect').val(), 10);
1330                     var second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0;
1331                     date = date.clone().hour(hour).minute(minute).second(second);
1332                 }
1333                 this.endDate = null;
1334                 this.setStartDate(date.clone());
1335             } else if (!this.endDate && date.isBefore(this.startDate)) {
1336                 //special case: clicking the same date for start/end,
1337                 //but the time of the end date is before the start date
1338                 this.setEndDate(this.startDate.clone());
1339             } else { // picking end
1340                 if (this.timePicker) {
1341                     var hour = parseInt(this.container.find('.right .hourselect').val(), 10);
1342                     if (!this.timePicker24Hour) {
1343                         var ampm = this.container.find('.right .ampmselect').val();
1344                         if (ampm === 'PM' && hour < 12)
1345                             hour += 12;
1346                         if (ampm === 'AM' && hour === 12)
1347                             hour = 0;
1348                     }
1349                     var minute = parseInt(this.container.find('.right .minuteselect').val(), 10);
1350                     var second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0;
1351                     date = date.clone().hour(hour).minute(minute).second(second);
1352                 }
1353                 this.setEndDate(date.clone());
1354                 if (this.autoApply) {
1355                   this.calculateChosenLabel();
1356                   this.clickApply();
1357                 }
1358             }
1359
1360             if (this.singleDatePicker) {
1361                 this.setEndDate(this.startDate);
1362                 if (!this.timePicker)
1363                     this.clickApply();
1364             }
1365
1366             this.updateView();
1367
1368             //This is to cancel the blur event handler if the mouse was in one of the inputs
1369             e.stopPropagation();
1370
1371         },
1372
1373         calculateChosenLabel: function () {
1374             var customRange = true;
1375             var i = 0;
1376             for (var range in this.ranges) {
1377               if (this.timePicker) {
1378                     var format = this.timePickerSeconds ? "YYYY-MM-DD hh:mm:ss" : "YYYY-MM-DD hh:mm";
1379                     //ignore times when comparing dates if time picker seconds is not enabled
1380                     if (this.startDate.format(format) == this.ranges[range][0].format(format) && this.endDate.format(format) == this.ranges[range][1].format(format)) {
1381                         customRange = false;
1382                         this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').html();
1383                         break;
1384                     }
1385                 } else {
1386                     //ignore times when comparing dates if time picker is not enabled
1387                     if (this.startDate.format('YYYY-MM-DD') == this.ranges[range][0].format('YYYY-MM-DD') && this.endDate.format('YYYY-MM-DD') == this.ranges[range][1].format('YYYY-MM-DD')) {
1388                         customRange = false;
1389                         this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').html();
1390                         break;
1391                     }
1392                 }
1393                 i++;
1394             }
1395             if (customRange) {
1396                 if (this.showCustomRangeLabel) {
1397                     this.chosenLabel = this.container.find('.ranges li:last').addClass('active').html();
1398                 } else {
1399                     this.chosenLabel = null;
1400                 }
1401                 this.showCalendars();
1402             }
1403         },
1404
1405         clickApply: function(e) {
1406             this.hide();
1407             this.element.trigger('apply.daterangepicker', this);
1408         },
1409
1410         clickCancel: function(e) {
1411             this.startDate = this.oldStartDate;
1412             this.endDate = this.oldEndDate;
1413             this.hide();
1414             this.element.trigger('cancel.daterangepicker', this);
1415         },
1416
1417         monthOrYearChanged: function(e) {
1418             var isLeft = $(e.target).closest('.calendar').hasClass('left'),
1419                 leftOrRight = isLeft ? 'left' : 'right',
1420                 cal = this.container.find('.calendar.'+leftOrRight);
1421
1422             // Month must be Number for new moment versions
1423             var month = parseInt(cal.find('.monthselect').val(), 10);
1424             var year = cal.find('.yearselect').val();
1425
1426             if (!isLeft) {
1427                 if (year < this.startDate.year() || (year == this.startDate.year() && month < this.startDate.month())) {
1428                     month = this.startDate.month();
1429                     year = this.startDate.year();
1430                 }
1431             }
1432
1433             if (this.minDate) {
1434                 if (year < this.minDate.year() || (year == this.minDate.year() && month < this.minDate.month())) {
1435                     month = this.minDate.month();
1436                     year = this.minDate.year();
1437                 }
1438             }
1439
1440             if (this.maxDate) {
1441                 if (year > this.maxDate.year() || (year == this.maxDate.year() && month > this.maxDate.month())) {
1442                     month = this.maxDate.month();
1443                     year = this.maxDate.year();
1444                 }
1445             }
1446
1447             if (isLeft) {
1448                 this.leftCalendar.month.month(month).year(year);
1449                 if (this.linkedCalendars)
1450                     this.rightCalendar.month = this.leftCalendar.month.clone().add(1, 'month');
1451             } else {
1452                 this.rightCalendar.month.month(month).year(year);
1453                 if (this.linkedCalendars)
1454                     this.leftCalendar.month = this.rightCalendar.month.clone().subtract(1, 'month');
1455             }
1456             this.updateCalendars();
1457         },
1458
1459         timeChanged: function(e) {
1460
1461             var cal = $(e.target).closest('.calendar'),
1462                 isLeft = cal.hasClass('left');
1463
1464             var hour = parseInt(cal.find('.hourselect').val(), 10);
1465             var minute = parseInt(cal.find('.minuteselect').val(), 10);
1466             var second = this.timePickerSeconds ? parseInt(cal.find('.secondselect').val(), 10) : 0;
1467
1468             if (!this.timePicker24Hour) {
1469                 var ampm = cal.find('.ampmselect').val();
1470                 if (ampm === 'PM' && hour < 12)
1471                     hour += 12;
1472                 if (ampm === 'AM' && hour === 12)
1473                     hour = 0;
1474             }
1475
1476             if (isLeft) {
1477                 var start = this.startDate.clone();
1478                 start.hour(hour);
1479                 start.minute(minute);
1480                 start.second(second);
1481                 this.setStartDate(start);
1482                 if (this.singleDatePicker) {
1483                     this.endDate = this.startDate.clone();
1484                 } else if (this.endDate && this.endDate.format('YYYY-MM-DD') == start.format('YYYY-MM-DD') && this.endDate.isBefore(start)) {
1485                     this.setEndDate(start.clone());
1486                 }
1487             } else if (this.endDate) {
1488                 var end = this.endDate.clone();
1489                 end.hour(hour);
1490                 end.minute(minute);
1491                 end.second(second);
1492                 this.setEndDate(end);
1493             }
1494
1495             //update the calendars so all clickable dates reflect the new time component
1496             this.updateCalendars();
1497
1498             //update the form inputs above the calendars with the new time
1499             this.updateFormInputs();
1500
1501             //re-render the time pickers because changing one selection can affect what's enabled in another
1502             this.renderTimePicker('left');
1503             this.renderTimePicker('right');
1504
1505         },
1506
1507         formInputsChanged: function(e) {
1508             var isRight = $(e.target).closest('.calendar').hasClass('right');
1509             var start = moment(this.container.find('input[name="daterangepicker_start"]').val(), this.locale.format);
1510             var end = moment(this.container.find('input[name="daterangepicker_end"]').val(), this.locale.format);
1511
1512             if (start.isValid() && end.isValid()) {
1513
1514                 if (isRight && end.isBefore(start))
1515                     start = end.clone();
1516
1517                 this.setStartDate(start);
1518                 this.setEndDate(end);
1519
1520                 if (isRight) {
1521                     this.container.find('input[name="daterangepicker_start"]').val(this.startDate.format(this.locale.format));
1522                 } else {
1523                     this.container.find('input[name="daterangepicker_end"]').val(this.endDate.format(this.locale.format));
1524                 }
1525
1526             }
1527
1528             this.updateView();
1529         },
1530
1531         formInputsFocused: function(e) {
1532
1533             // Highlight the focused input
1534             this.container.find('input[name="daterangepicker_start"], input[name="daterangepicker_end"]').removeClass('active');
1535             $(e.target).addClass('active');
1536
1537             // Set the state such that if the user goes back to using a mouse, 
1538             // the calendars are aware we're selecting the end of the range, not
1539             // the start. This allows someone to edit the end of a date range without
1540             // re-selecting the beginning, by clicking on the end date input then
1541             // using the calendar.
1542             var isRight = $(e.target).closest('.calendar').hasClass('right');
1543             if (isRight) {
1544                 this.endDate = null;
1545                 this.setStartDate(this.startDate.clone());
1546                 this.updateView();
1547             }
1548
1549         },
1550
1551         formInputsBlurred: function(e) {
1552
1553             // this function has one purpose right now: if you tab from the first
1554             // text input to the second in the UI, the endDate is nulled so that
1555             // you can click another, but if you tab out without clicking anything
1556             // or changing the input value, the old endDate should be retained
1557
1558             if (!this.endDate) {
1559                 var val = this.container.find('input[name="daterangepicker_end"]').val();
1560                 var end = moment(val, this.locale.format);
1561                 if (end.isValid()) {
1562                     this.setEndDate(end);
1563                     this.updateView();
1564                 }
1565             }
1566
1567         },
1568
1569         formInputsKeydown: function(e) {
1570             // This function ensures that if the 'enter' key was pressed in the input, then the calendars
1571             // are updated with the startDate and endDate.
1572             // This behaviour is automatic in Chrome/Firefox/Edge but not in IE 11 hence why this exists.
1573             // Other browsers and versions of IE are untested and the behaviour is unknown.
1574             if (e.keyCode === 13) {
1575                 // Prevent the calendar from being updated twice on Chrome/Firefox/Edge
1576                 e.preventDefault(); 
1577                 this.formInputsChanged(e);
1578             }
1579         },
1580
1581
1582         elementChanged: function() {
1583             if (!this.element.is('input')) return;
1584             if (!this.element.val().length) return;
1585
1586             var dateString = this.element.val().split(this.locale.separator),
1587                 start = null,
1588                 end = null;
1589
1590             if (dateString.length === 2) {
1591                 start = moment(dateString[0], this.locale.format);
1592                 end = moment(dateString[1], this.locale.format);
1593             }
1594
1595             if (this.singleDatePicker || start === null || end === null) {
1596                 start = moment(this.element.val(), this.locale.format);
1597                 end = start;
1598             }
1599
1600             if (!start.isValid() || !end.isValid()) return;
1601
1602             this.setStartDate(start);
1603             this.setEndDate(end);
1604             this.updateView();
1605         },
1606
1607         keydown: function(e) {
1608             //hide on tab or enter
1609             if ((e.keyCode === 9) || (e.keyCode === 13)) {
1610                 this.hide();
1611             }
1612
1613             //hide on esc and prevent propagation
1614             if (e.keyCode === 27) {
1615                 e.preventDefault();
1616                 e.stopPropagation();
1617
1618                 this.hide();
1619             }
1620         },
1621
1622         updateElement: function() {
1623             if (this.element.is('input') && !this.singleDatePicker && this.autoUpdateInput) {
1624                 this.element.val(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format));
1625                 this.element.trigger('change');
1626             } else if (this.element.is('input') && this.autoUpdateInput) {
1627                 this.element.val(this.startDate.format(this.locale.format));
1628                 this.element.trigger('change');
1629             }
1630         },
1631
1632         remove: function() {
1633             this.container.remove();
1634             this.element.off('.daterangepicker');
1635             this.element.removeData();
1636         }
1637
1638     };
1639
1640     $.fn.daterangepicker = function(options, callback) {
1641         var implementOptions = $.extend(true, {}, $.fn.daterangepicker.defaultOptions, options);
1642         this.each(function() {
1643             var el = $(this);
1644             if (el.data('daterangepicker'))
1645                 el.data('daterangepicker').remove();
1646             el.data('daterangepicker', new DateRangePicker(el, implementOptions, callback));
1647         });
1648         return this;
1649     };
1650
1651     return DateRangePicker;
1652
1653 }));