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