forked from owenmead/Pikaday
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pikaday.js
1344 lines (1168 loc) · 43.9 KB
/
pikaday.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Pikaday
*
* Copyright © 2014 David Bushell | BSD & MIT license | https://github.com/dbushell/Pikaday
*/
(function (root, factory)
{
'use strict';
var moment;
if (typeof exports === 'object') {
// CommonJS module
// Load moment.js as an optional dependency
try { moment = require('moment'); } catch (e) {}
module.exports = factory(moment);
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(function (req)
{
// Load moment.js as an optional dependency
var id = 'moment';
try { moment = req(id); } catch (e) {}
return factory(moment);
});
} else {
root.Pikaday = factory(root.moment);
}
}(this, function (moment)
{
'use strict';
/**
* feature detection and helper functions
*/
var hasMoment = typeof moment === 'function',
hasEventListeners = !!window.addEventListener,
document = window.document,
sto = window.setTimeout,
addEvent = function(el, e, callback, capture)
{
if (hasEventListeners) {
el.addEventListener(e, callback, !!capture);
} else {
el.attachEvent('on' + e, callback);
}
},
removeEvent = function(el, e, callback, capture)
{
if (hasEventListeners) {
el.removeEventListener(e, callback, !!capture);
} else {
el.detachEvent('on' + e, callback);
}
},
fireEvent = function(el, eventName, data)
{
var ev;
if (document.createEvent) {
ev = document.createEvent('HTMLEvents');
ev.initEvent(eventName, true, false);
ev = extend(ev, data);
el.dispatchEvent(ev);
} else if (document.createEventObject) {
ev = document.createEventObject();
ev = extend(ev, data);
el.fireEvent('on' + eventName, ev);
}
},
trim = function(str)
{
return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g,'');
},
hasClass = function(el, cn)
{
return (' ' + el.className + ' ').indexOf(' ' + cn + ' ') !== -1;
},
addClass = function(el, cn)
{
if (!hasClass(el, cn)) {
el.className = (el.className === '') ? cn : el.className + ' ' + cn;
}
},
removeClass = function(el, cn)
{
el.className = trim((' ' + el.className + ' ').replace(' ' + cn + ' ', ' '));
},
isArray = function(obj)
{
return (/Array/).test(Object.prototype.toString.call(obj));
},
isDate = function(obj)
{
return (/Date/).test(Object.prototype.toString.call(obj)) && !isNaN(obj.getTime());
},
isWeekend = function(date)
{
var day = date.getDay();
return day === 0 || day === 6;
},
isLeapYear = function(year)
{
// solution by Matti Virkkunen: http://stackoverflow.com/a/4881951
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
},
getDaysInMonth = function(year, month)
{
return [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
},
setToStartOfDay = function(date)
{
if (isDate(date)) date.setHours(0,0,0,0);
},
compareDates = function(a,b)
{
// Copy so we don't change the dates being passed in
var _a = new Date(a.getTime());
var _b = new Date(b.getTime());
setToStartOfDay(_a);
setToStartOfDay(_b);
return _a.getTime() === _b.getTime();
},
extend = function(to, from, overwrite)
{
var prop, hasProp;
for (prop in from) {
hasProp = to[prop] !== undefined;
if (hasProp && typeof from[prop] === 'object' && from[prop] !== null && from[prop].nodeName === undefined) {
if (isDate(from[prop])) {
if (overwrite) {
to[prop] = new Date(from[prop].getTime());
}
}
else if (isArray(from[prop])) {
if (overwrite) {
to[prop] = from[prop].slice(0);
}
} else {
to[prop] = extend({}, from[prop], overwrite);
}
} else if (overwrite || !hasProp) {
to[prop] = from[prop];
}
}
return to;
},
adjustCalendar = function(calendar) {
if (calendar.month < 0) {
calendar.year -= Math.ceil(Math.abs(calendar.month)/12);
calendar.month += 12;
}
if (calendar.month > 11) {
calendar.year += Math.floor(Math.abs(calendar.month)/12);
calendar.month -= 12;
}
return calendar;
},
/**
* defaults and localisation
*/
defaults = {
// bind the picker to a form field
field: null,
// automatically show/hide the picker on `field` focus (default `true` if `field` is set)
bound: undefined,
// position of the datepicker, relative to the field (default to bottom & left)
// ('bottom' & 'left' keywords are not used, 'top' & 'right' are modifier on the bottom/left position)
position: 'bottom left',
// automatically fit in the viewport even if it means repositioning from the position option
reposition: true,
// the default output format for `.toString()` and `field` value
// set in `config` based on if showTime is set
format: null,
// an array giving the allowable input format(s). As with moment,
// the input formats may be either a single string or an array of strings.
// Usually set in `config`
inputFormats: null,
// the initial date to view when first opened
defaultDate: null,
// make the `defaultDate` the initial selected value
setDefaultDate: false,
// first day of week (0: Sunday, 1: Monday etc)
firstDay: 0,
// the default flag for moment's strict date parsing
formatStrict: false,
// the minimum/earliest date that can be selected
minDate: null,
// the maximum/latest date that can be selected
maxDate: null,
// number of years either side, or array of upper/lower range
yearRange: 10,
// show week numbers at head of row
showWeekNumber: false,
// used internally (don't config outside)
minYear: 0,
maxYear: 9999,
minMonth: undefined,
maxMonth: undefined,
startRange: null,
endRange: null,
isRTL: false,
// Additional text to append to the year in the calendar title
yearSuffix: '',
// Render the month after year in the calendar title
showMonthAfterYear: false,
// Render days of the calendar grid that fall in the next or previous month
showDaysInNextAndPreviousMonths: false,
// how many months are visible
numberOfMonths: 1,
// time
showTime: true,
showMinutes: true,
showSeconds: false,
use24hour: false,
incrementHourBy: 1,
incrementMinuteBy: 1,
incrementSecondBy: 1,
timeLabel: null,
// option to prevent calendar from auto-closing after date is selected
autoClose: true,
// when numberOfMonths is used, this will help you to choose where the main calendar will be (default `left`, can be set to `right`)
// only used for the first display or when a selected date is not visible
mainCalendar: 'left',
// Specify a DOM element to render the calendar in
container: undefined,
// internationalization
i18n: {
previousMonth : 'Previous Month',
nextMonth : 'Next Month',
months : ['January','February','March','April','May','June','July','August','September','October','November','December'],
weekdays : ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
weekdaysShort : ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
midnight : 'Midnight',
noon : 'Noon'
},
// Theme Classname
theme: null,
// callback function
onSelect: null,
onOpen: null,
onClose: null,
onDraw: null
},
/**
* templating functions to abstract HTML rendering
*/
renderDayName = function(opts, day, abbr)
{
day += opts.firstDay;
while (day >= 7) {
day -= 7;
}
return abbr ? opts.i18n.weekdaysShort[day] : opts.i18n.weekdays[day];
},
renderDay = function(opts)
{
var arr = [];
var ariaSelected = 'false';
if (opts.isEmpty) {
if (opts.showDaysInNextAndPreviousMonths) {
arr.push('is-outside-current-month');
} else {
return '<td class="is-empty"></td>';
}
}
if (opts.isDisabled) {
arr.push('is-disabled');
}
if (opts.isToday) {
arr.push('is-today');
}
if (opts.isSelected) {
arr.push('is-selected');
ariaSelected = 'true';
}
if (opts.isInRange) {
arr.push('is-inrange');
}
if (opts.isStartRange) {
arr.push('is-startrange');
}
if (opts.isEndRange) {
arr.push('is-endrange');
}
return '<td data-day="' + opts.day + '" class="' + arr.join(' ') + '" aria-selected="' + ariaSelected + '">' +
'<button class="pika-button pika-day" type="button" ' +
'data-pika-year="' + opts.year + '" data-pika-month="' + opts.month + '" data-pika-day="' + opts.day + '">' +
opts.day +
'</button>' +
'</td>';
},
renderWeek = function (d, m, y) {
// Lifted from http://javascript.about.com/library/blweekyear.htm, lightly modified.
var onejan = new Date(y, 0, 1),
weekNum = Math.ceil((((new Date(y, m, d) - onejan) / 86400000) + onejan.getDay()+1)/7);
return '<td class="pika-week">' + weekNum + '</td>';
},
renderRow = function(days, isRTL)
{
return '<tr>' + (isRTL ? days.reverse() : days).join('') + '</tr>';
},
renderBody = function(rows)
{
return '<tbody>' + rows.join('') + '</tbody>';
},
renderHead = function(opts)
{
var i, arr = [];
if (opts.showWeekNumber) {
arr.push('<th></th>');
}
for (i = 0; i < 7; i++) {
arr.push('<th scope="col"><abbr title="' + renderDayName(opts, i) + '">' + renderDayName(opts, i, true) + '</abbr></th>');
}
return '<thead><tr>' + (opts.isRTL ? arr.reverse() : arr).join('') + '</tr></thead>';
},
renderTitle = function(instance, c, year, month, refYear, randId)
{
var i, j, arr,
opts = instance._o,
isMinYear = year === opts.minYear,
isMaxYear = year === opts.maxYear,
html = '<div id="' + randId + '" class="pika-title" role="heading" aria-live="assertive">',
monthHtml,
yearHtml,
prev = true,
next = true;
for (arr = [], i = 0; i < 12; i++) {
arr.push('<option value="' + (year === refYear ? i - c : 12 + i - c) + '"' +
(i === month ? ' selected="selected"': '') +
((isMinYear && i < opts.minMonth) || (isMaxYear && i > opts.maxMonth) ? 'disabled="disabled"' : '') + '>' +
opts.i18n.months[i] + '</option>');
}
monthHtml = '<div class="pika-label">' + opts.i18n.months[month] + '<select class="pika-select pika-select-month" tabindex="-1">' + arr.join('') + '</select></div>';
if (isArray(opts.yearRange)) {
i = opts.yearRange[0];
j = opts.yearRange[1] + 1;
} else {
i = year - opts.yearRange;
j = 1 + year + opts.yearRange;
}
for (arr = []; i < j && i <= opts.maxYear; i++) {
if (i >= opts.minYear) {
arr.push('<option value="' + i + '"' + (i === year ? ' selected="selected"': '') + '>' + (i) + '</option>');
}
}
yearHtml = '<div class="pika-label">' + year + opts.yearSuffix + '<select class="pika-select pika-select-year" tabindex="-1">' + arr.join('') + '</select></div>';
if (opts.showMonthAfterYear) {
html += yearHtml + monthHtml;
} else {
html += monthHtml + yearHtml;
}
if (isMinYear && (month === 0 || opts.minMonth >= month)) {
prev = false;
}
if (isMaxYear && (month === 11 || opts.maxMonth <= month)) {
next = false;
}
if (c === 0) {
html += '<button class="pika-prev' + (prev ? '' : ' is-disabled') + '" type="button">' + opts.i18n.previousMonth + '</button>';
}
if (c === (instance._o.numberOfMonths - 1) ) {
html += '<button class="pika-next' + (next ? '' : ' is-disabled') + '" type="button">' + opts.i18n.nextMonth + '</button>';
}
return html += '</div>';
},
renderTable = function(opts, data, randId)
{
return '<table cellpadding="0" cellspacing="0" class="pika-table" role="grid" aria-labelledby="' + randId + '">' + renderHead(opts) + renderBody(data) + '</table>';
},
renderTimePicker = function(num_options, selected_val, select_class, display_func, increment_by) {
increment_by = increment_by || 1;
var to_return = '<td><select class="pika-select '+select_class+'">';
for (var i = 0; i < num_options; i += increment_by) {
to_return += '<option value="'+i+'" '+(i==selected_val ? 'selected' : '')+'>'+display_func(i)+'</option>'
}
to_return += '</select></td>';
return to_return;
},
renderTime = function(hh, mm, ss, opts)
{
var to_return = '<table cellpadding="0" cellspacing="0" class="pika-time"><tbody><tr>' +
(opts.timeLabel !== null ? '<td class="pika-time-label">'+opts.timeLabel+'</td>' : '') +
renderTimePicker(24, hh, 'pika-select-hour', function(i) {
if (opts.use24hour) {
return i;
} else {
var to_return = (i%12) + (i<12 ? ' AM' : ' PM');
if (to_return == '0 AM') {
return opts.i18n.midnight;
} else if (to_return == '0 PM') {
return opts.i18n.noon;
} else {
return to_return;
}
}
},
opts.incrementHourBy);
if (opts.showMinutes) {
to_return += '<td>:</td>' +
renderTimePicker(60, mm, 'pika-select-minute', function(i) { if (i < 10) return "0" + i; return i }, opts.incrementMinuteBy);
}
if (opts.showSeconds) {
to_return += '<td>:</td>' +
renderTimePicker(60, ss, 'pika-select-second', function(i) { if (i < 10) return "0" + i; return i }, opts.incrementSecondBy);
}
return to_return + '</tr></tbody></table>';
},
/**
* Pikaday constructor
*/
Pikaday = function(options)
{
var self = this,
opts = self.config(options);
self._onMouseDown = function(e)
{
if (!self._v) {
return;
}
e = e || window.event;
var target = e.target || e.srcElement;
if (!target) {
return;
}
if (!hasClass(target, 'is-disabled')) {
if (hasClass(target, 'pika-button') && !hasClass(target, 'is-empty') && !hasClass(target.parentNode, 'is-disabled')) {
var newDate = new Date(
target.getAttribute('data-pika-year'),
target.getAttribute('data-pika-month'),
target.getAttribute('data-pika-day')
);
// Preserve time selection when date changed
var prevDate = self._d || opts.defaultDate;
if (prevDate && isDate(prevDate) && opts.showTime) {
newDate.setHours(prevDate.getHours());
newDate.setMinutes(prevDate.getMinutes());
if (opts.showSeconds) {
newDate.setSeconds(prevDate.getSeconds());
}
}
self.setDate(newDate);
if (opts.bound) {
sto(function() {
if (opts.autoClose) {
self.hide();
}
if (opts.field) {
opts.field.blur();
}
}, 100);
}
}
else if (hasClass(target, 'pika-prev')) {
self.prevMonth();
}
else if (hasClass(target, 'pika-next')) {
self.nextMonth();
}
}
if (!hasClass(target, 'pika-select')) {
// if this is touch event prevent mouse events emulation
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
return false;
}
} else {
self._c = true;
}
};
self._onChange = function(e)
{
e = e || window.event;
var target = e.target || e.srcElement;
if (!target) {
return;
}
if (hasClass(target, 'pika-select-month')) {
self.gotoMonth(target.value);
}
else if (hasClass(target, 'pika-select-year')) {
self.gotoYear(target.value);
}
else if (hasClass(target, 'pika-select-hour')) {
self.setTime(target.value);
}
else if (hasClass(target, 'pika-select-minute')) {
self.setTime(null, target.value);
}
else if (hasClass(target, 'pika-select-second')) {
self.setTime(null, null, target.value);
}
};
self._onKeyChange = function(e)
{
e = e || window.event;
if (self.isVisible()) {
switch(e.keyCode){
case 13:
case 27:
opts.field.blur();
break;
case 37:
e.preventDefault();
self.adjustDate('subtract', 1);
break;
case 38:
self.adjustDate('subtract', 7);
break;
case 39:
self.adjustDate('add', 1);
break;
case 40:
self.adjustDate('add', 7);
break;
}
}
};
self._onInputChange = function(e)
{
var date;
if (e.firedBy === self) {
return;
}
if (hasMoment) {
date = moment(opts.field.value, opts.inputFormats, opts.formatStrict);
date = (date && date.isValid()) ? date.toDate() : null;
}
else {
date = new Date(Date.parse(opts.field.value));
}
if (isDate(date)) {
self.setDate(date);
}
if (!self._v) {
self.show();
}
};
self._onInputFocus = function()
{
self.show();
};
self._onInputClick = function()
{
self.show();
};
self._onInputBlur = function()
{
// IE allows pika div to gain focus; catch blur the input field
var pEl = document.activeElement;
do {
if (hasClass(pEl, 'pika-single')) {
return;
}
}
while ((pEl = pEl.parentNode));
if (opts.autoClose && !self._c) {
self._b = sto(function() {
self.hide();
}, 50);
}
self._c = false;
};
self._onClick = function(e)
{
e = e || window.event;
var target = e.target || e.srcElement,
pEl = target;
if (!target) {
return;
}
if (!hasEventListeners && hasClass(target, 'pika-select')) {
if (!target.onchange) {
target.setAttribute('onchange', 'return;');
addEvent(target, 'change', self._onChange);
}
}
do {
if (hasClass(pEl, 'pika-single') ||
pEl === opts.trigger ||
(opts.showTime && hasClass(pEl, 'pika-time-container'))) {
return;
}
}
while ((pEl = pEl.parentNode));
if (self._v && target !== opts.trigger && pEl !== opts.trigger) {
self.hide();
}
};
self.el = document.createElement('div');
self.el.className = 'pika-single' + (opts.isRTL ? ' is-rtl' : '') + (opts.theme ? ' ' + opts.theme : '');
addEvent(self.el, 'mousedown', self._onMouseDown, true);
addEvent(self.el, 'touchend', self._onMouseDown, true);
addEvent(self.el, 'change', self._onChange);
addEvent(document, 'keydown', self._onKeyChange);
if (opts.field) {
if (opts.container) {
opts.container.appendChild(self.el);
} else if (opts.bound) {
document.body.appendChild(self.el);
} else {
opts.field.parentNode.insertBefore(self.el, opts.field.nextSibling);
}
addEvent(opts.field, 'change', self._onInputChange);
if (!opts.defaultDate) {
if (hasMoment && opts.field.value) {
opts.defaultDate = moment(opts.field.value, opts.inputFormats).toDate();
} else {
opts.defaultDate = new Date(Date.parse(opts.field.value));
}
opts.setDefaultDate = true;
}
}
var defDate = opts.defaultDate;
if (isDate(defDate)) {
if (opts.setDefaultDate) {
self.setDate(defDate, true);
} else {
self.gotoDate(defDate);
}
} else {
self.gotoDate(new Date());
}
if (opts.bound) {
this.hide();
self.el.className += ' is-bound';
addEvent(opts.trigger, 'click', self._onInputClick);
addEvent(opts.trigger, 'focus', self._onInputFocus);
addEvent(opts.trigger, 'blur', self._onInputBlur);
} else {
this.show();
}
};
/**
* public Pikaday API
*/
Pikaday.prototype = {
/**
* configure functionality
*/
config: function(options)
{
if (!this._o) {
this._o = extend({}, defaults, true);
}
var opts = extend(this._o, options, true);
opts.isRTL = !!opts.isRTL;
opts.autoClose = !!opts.autoClose;
opts.field = (opts.field && opts.field.nodeName) ? opts.field : null;
opts.theme = (typeof opts.theme) === 'string' && opts.theme ? opts.theme : null;
opts.bound = !!(opts.bound !== undefined ? opts.field && opts.bound : opts.field);
opts.trigger = (opts.trigger && opts.trigger.nodeName) ? opts.trigger : opts.field;
opts.disableWeekends = !!opts.disableWeekends;
opts.disableDayFn = (typeof opts.disableDayFn) === 'function' ? opts.disableDayFn : null;
var nom = parseInt(opts.numberOfMonths, 10) || 1;
opts.numberOfMonths = nom > 4 ? 4 : nom;
if (!isDate(opts.minDate)) {
opts.minDate = false;
}
if (!isDate(opts.maxDate)) {
opts.maxDate = false;
}
if ((opts.minDate && opts.maxDate) && opts.maxDate < opts.minDate) {
opts.maxDate = opts.minDate = false;
}
if (opts.minDate) {
this.setMinDate(opts.minDate);
}
if (opts.maxDate) {
this.setMaxDate(opts.maxDate);
}
if (isArray(opts.yearRange)) {
var fallback = new Date().getFullYear() - 10;
opts.yearRange[0] = parseInt(opts.yearRange[0], 10) || fallback;
opts.yearRange[1] = parseInt(opts.yearRange[1], 10) || fallback;
} else {
opts.yearRange = Math.abs(parseInt(opts.yearRange, 10)) || defaults.yearRange;
if (opts.yearRange > 100) {
opts.yearRange = 100;
}
}
// If no format is given, set based on showTime
if (opts.format === null) {
opts.format = 'YYYY-MM-DD';
if (opts.showTime) {
opts.format += ' HH:mm:ss';
}
}
if(!opts.inputFormats) {
opts.inputFormats = opts.format;
}
return opts;
},
/**
* return a formatted string of the current selection (using Moment.js if available)
*/
toString: function(format)
{
return !isDate(this._d) ? '' : hasMoment ? moment(this._d).format(format || this._o.format) : this._o.showTime ? this._d.toString() : this._d.toDateString();
},
/**
* return a Moment.js object of the current selection (if available)
*/
getMoment: function()
{
return hasMoment ? moment(this._d) : null;
},
/**
* set the current selection from a Moment.js object (if available)
*/
setMoment: function(date, preventOnSelect)
{
if (hasMoment && moment.isMoment(date)) {
this.setDate(date.toDate(), preventOnSelect);
}
},
/**
* return a Date object of the current selection with fallback for the current date
*/
getDate: function()
{
return isDate(this._d) ? new Date(this._d.getTime()) : new Date();
},
/**
* set time components
* Currently defaulting to setting date to today if not set
*/
setTime: function(hours, minutes, seconds) {
if (!this._d) {
this._d = new Date();
this._d.setHours(0,0,0,0);
}
if (hours) {
this._d.setHours(hours);
}
if (minutes) {
this._d.setMinutes(minutes);
}
if (seconds) {
this._d.setSeconds(seconds);
}
this.setDate(this._d, false, true);
},
/**
* set the current selection
*/
setDate: function(date, preventOnSelect, fromTime)
{
if (!date) {
this._d = null;
if (this._o.field) {
this._o.field.value = '';
fireEvent(this._o.field, 'change', { firedBy: this });
}
return this.draw();
}
if (typeof date === 'string') {
date = new Date(Date.parse(date));
}
if (!isDate(date)) {
return;
}
var min = this._o.minDate,
max = this._o.maxDate;
if (isDate(min) && date < min) {
date = min;
} else if (isDate(max) && date > max) {
date = max;
}
this._d = new Date(date.getTime());
if (this._o.showTime && !this._o.showSeconds) {
this._d.setSeconds(0);
} else if (!this._o.showTime) {
setToStartOfDay(this._d);
}
if (!fromTime) {
this.gotoDate(this._d);
}
if (this._o.field) {
this._o.field.value = this.toString();
fireEvent(this._o.field, 'change', { firedBy: this });
}
if (!preventOnSelect && typeof this._o.onSelect === 'function') {
this._o.onSelect.call(this, this.getDate());
}
},
/**
* change view to a specific date
*/
gotoDate: function(date)
{
var newCalendar = true;
if (!isDate(date)) {
return;
}
if (this.calendars) {
var firstVisibleDate = new Date(this.calendars[0].year, this.calendars[0].month, 1),
lastVisibleDate = new Date(this.calendars[this.calendars.length-1].year, this.calendars[this.calendars.length-1].month, 1),
visibleDate = date.getTime();
// get the end of the month
lastVisibleDate.setMonth(lastVisibleDate.getMonth()+1);
lastVisibleDate.setDate(lastVisibleDate.getDate()-1);
newCalendar = (visibleDate < firstVisibleDate.getTime() || lastVisibleDate.getTime() < visibleDate);
}
if (newCalendar) {
this.calendars = [{
month: date.getMonth(),
year: date.getFullYear(),
hour: date.getHours(),
minute: date.getMinutes(),
second: date.getSeconds()
}];
if (this._o.mainCalendar === 'right') {
this.calendars[0].month += 1 - this._o.numberOfMonths;
}
}
this.adjustCalendars();
},
adjustDate: function(sign, days) {
var day = this.getDate();
var difference = parseInt(days)*24*60*60*1000;
var newDay;
if (sign === 'add') {
newDay = new Date(day.valueOf() + difference);
} else if (sign === 'subtract') {
newDay = new Date(day.valueOf() - difference);
}
if (hasMoment) {
if (sign === 'add') {
newDay = moment(day).add(days, "days").toDate();
} else if (sign === 'subtract') {
newDay = moment(day).subtract(days, "days").toDate();
}
}
this.setDate(newDay);
},
adjustCalendars: function() {
this.calendars[0] = adjustCalendar(this.calendars[0]);
for (var c = 1; c < this._o.numberOfMonths; c++) {
this.calendars[c] = adjustCalendar({
month: this.calendars[0].month + c,
year: this.calendars[0].year
});
}
this.draw();
},
gotoToday: function()
{
this.gotoDate(new Date());
},
/**
* change view to a specific month (zero-index, e.g. 0: January)
*/
gotoMonth: function(month)
{
if (!isNaN(month)) {
this.calendars[0].month = parseInt(month, 10);
this.adjustCalendars();
}
},
nextMonth: function()