forked from jpoumailloux/jquery.ui.monthpicker
-
Notifications
You must be signed in to change notification settings - Fork 10
/
jquery.ui.monthpicker.js
1494 lines (1368 loc) · 57.7 KB
/
jquery.ui.monthpicker.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
/*!
* jQuery UI Monthpicker
*
* MIT License
* Copyright (c) 2011, Julien Poumailloux
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software i
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
(function ($) {
$.extend($.ui, { monthpicker: { version: "@VERSION" } });
var PROP_NAME = 'monthpicker';
var instActive;
/* Month picker manager.
Use the singleton instance of this class, $.monthpicker, to interact with the date picker.
Settings for (groups of) month pickers are maintained in an instance object,
allowing multiple different settings on the same page. */
function Monthpicker() {
this.uuid = 0;
this._keyEvent = false; // If the last event was a key event
this._curInst = null; // The current instance in use
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._monthpickerShowing = false; // True if the popup picker is showing , false if not
this._mainDivId = 'ui-monthpicker-div'; // The ID of the main monthpicker division
this._triggerClass = 'ui-monthpicker-trigger'; // The name of the trigger marker class
this._dialogClass = 'ui-monthpicker-dialog'; // The name of the dialog marker class
this._currentClass = "ui-datepicker-today"; // The name of the current day marker class
this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[''] = { // Default regional settings
closeText: "Done", // Display text for close link
prevText: 'Prev', // Display text for previous month link
nextText: 'Next', // Display text for next month link
currentText: "Current", // Display text for current month link
monthNames: ['January','February','March','April','May','June',
'July','August','September','October','November','December'], // Names of months for drop-down and formatting
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
dateFormat: 'mm/yy',
isRTL: false,
yearSuffix: '' // Additional text to append to the year in the month headers
};
this._defaults = { // Global defaults for all the date picker instances
showOn: 'focus', // 'focus' for popup on focus,
// 'button' for trigger button, or 'both' for either
showAnim: 'fadeIn', // Name of jQuery animation for popup
showButtonPanel: false, // True to show button panel, false to not show it
appendText: "", // Display text following the input box, e.g. showing the format
buttonText: '...', // Text for trigger button
buttonImage: '', // URL for trigger button image
gotoCurrent: false, // True if today link goes back to current selection instead
changeYear: false, // True if year can be selected directly, false if only prev/next
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
yearRange: 'c-10:c+10', // Range of years to display in drop-down,
// either relative to today's year (-nn:+nn), relative to currently displayed year
// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onChangeYear: null, // Define a callback function when the year is changed
onClose: null, // Define a callback function when the monthpicker is closed
stepYears: 1, // Number of months to step back/forward
stepBigYears: 3, // Number of months to step back/forward
defaultDate: null, // Used when field is blank: actual date,
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
altField: '', // Selector for an alternate field to store selected dates into
altFormat: '', // The date format to use for the alternate field
disabled: false // The initial disabled state
};
$.extend(this._defaults, this.regional['']);
this.dpDiv = bindHover($('<div id="' + this._mainDivId + '" class="ui-monthpicker ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'));
}
$.extend(Monthpicker.prototype, {
/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: 'hasMonthpicker',
/* Debug logging (if enabled). */
log: function () {
if (this.debug)
console.log.apply('', arguments);
},
// TODO rename to "widget" when switching to widget factory
_widgetMonthpicker: function() {
return this.dpDiv;
},
/* Override the default settings for all instances of the date picker.
* @param settings object - the new settings to use as defaults (anonymous object)
* @return the manager object
*/
setDefaults: function(settings) {
extendRemove(this._defaults, settings || {});
return this;
},
/* Retrieve the instance data for the target control.
@param target element - the target input field or division or span
@return object - the associated instance data
@throws error if a jQuery problem getting data */
_getInst: function(target) {
try {
return $.data(target, PROP_NAME);
}
catch (err) {
throw 'Missing instance data for this monthpicker';
}
},
/* Get a setting value, defaulting if necessary. */
_get: function(inst, name) {
return inst.settings[name] !== undefined ?
inst.settings[name] : this._defaults[name];
},
/* Attach the month picker to a jQuery selection.
@param target element - the target input field or division or span
@param settings object - the new settings to use for this month picker instance (anonymous) */
_attachMonthpicker: function(target, settings) {
// check for settings on the control itself - in namespace 'month:'
var inlineSettings = null;
for (var attrName in this._defaults) {
var attrValue = target.getAttribute('month:' + attrName);
if (attrValue) {
inlineSettings = inlineSettings || {};
try {
inlineSettings[attrName] = eval(attrValue);
} catch (err) {
inlineSettings[attrName] = attrValue;
}
}
}
var nodeName = target.nodeName.toLowerCase();
if (!target.id) {
this.uuid += 1;
target.id = 'dp' + this.uuid;
}
var inst = this._newInst($(target));
inst.settings = $.extend({}, settings || {}, inlineSettings || {});
if (nodeName == 'input') {
this._connectMonthpicker(target, inst);
}
},
/* Create a new instance object. */
_newInst: function(target) {
var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars
return {id: id, input: target, // associated target
selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
drawMonth: 0, drawYear: 0, // month being drawn
dpDiv: this.dpDiv // presentation div
};
},
/* Attach the date picker to an input field. */
_connectMonthpicker: function(target, inst) {
var input = $(target);
inst.append = $([]);
inst.trigger = $([]);
if (input.hasClass(this.markerClassName))
return;
this._attachments(input, inst);
input.addClass(this.markerClassName).keydown(this._doKeyDown).
bind("setData.monthpicker", function(event, key, value) {
inst.settings[key] = value;
}).bind("getData.monthpicker", function(event, key) {
return this._get(inst, key);
});
//this._autoSize(inst);
$.data(target, PROP_NAME, inst);
//If disabled option is true, disable the monthpicker once it has been attached to the input (see ticket #5665)
if( inst.settings.disabled ) {
this._disableMonthpicker( target );
}
},
/* Make attachments based on settings. */
_attachments: function(input, inst) {
var buttonText, buttonImage;
var appendText = this._get(inst, "appendText"),
isRTL = this._get(inst, "isRTL");
if (appendText) {
inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
input[isRTL ? "before" : "after"](inst.append);
}
input.unbind('focus', this._showMonthpicker);
if (inst.trigger)
inst.trigger.remove();
var showOn = this._get(inst, 'showOn');
if (showOn == 'focus' || showOn == 'both') // pop-up month picker when in the marked field
input.focus(this._showMonthpicker);
if (showOn === "button" || showOn === "both") { // pop-up month picker when button clicked
buttonText = this._get(inst, "buttonText");
buttonImage = this._get(inst, "buttonImage");
inst.trigger = $(this._get(inst, "buttonImageOnly") ?
$("<img/>").addClass(this._triggerClass).
attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
$("<button type='button'></button>").addClass(this._triggerClass).
html(!buttonImage ? buttonText : $("<img/>").attr(
{ src:buttonImage, alt:buttonText, title:buttonText })));
input[isRTL ? "before" : "after"](inst.trigger);
inst.trigger.click(function() {
if ($.monthpicker._monthpickerShowing && $.monthpicker._lastInput === input[0]) {
$.monthpicker._hideMonthpicker();
} else if ($.monthpicker._monthpickerShowing && $.monthpicker._lastInput !== input[0]) {
$.monthpicker._hideMonthpicker();
$.monthpicker._showMonthpicker(input[0]);
} else {
$.monthpicker._showMonthpicker(input[0]);
}
return false;
});
}
},
/* Close month picker if clicked elsewhere. */
_checkExternalClick: function(event) {
if (!$.monthpicker._curInst)
return;
var $target = $(event.target),
inst = $.monthpicker._getInst($target[0]);
if ( ( ( $target[0].id != $.monthpicker._mainDivId &&
$target.parents('#' + $.monthpicker._mainDivId).length == 0 &&
!$target.hasClass($.monthpicker.markerClassName) &&
!$target.hasClass($.monthpicker._triggerClass) &&
$.monthpicker._monthpickerShowing ) ) ||
( $target.hasClass($.monthpicker.markerClassName) && $.monthpicker._curInst != inst ) )
$.monthpicker._hideMonthpicker();
},
/* Pop-up the month picker for a given input field.
If false returned from beforeShow event handler do not show.
@param input element - the input field attached to the date picker or
event - if triggered by focus */
_showMonthpicker: function(input) {
input = input.target || input;
if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
input = $('input', input.parentNode)[0];
if ($.monthpicker._isDisabledMonthpicker(input) || $.monthpicker._lastInput == input) // already here
return;
var inst = $.monthpicker._getInst(input);
if ($.monthpicker._curInst && $.monthpicker._curInst != inst) {
$.monthpicker._curInst.dpDiv.stop(true, true);
if ( inst && $.monthpicker._monthpickerShowing ) {
$.monthpicker._hideMonthpicker( $.monthpicker._curInst.input[0] );
}
}
var beforeShow = $.monthpicker._get(inst, 'beforeShow');
var beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
if(beforeShowSettings === false){
//false
return;
}
extendRemove(inst.settings, beforeShowSettings);
inst.lastVal = null;
$.monthpicker._lastInput = input;
$.monthpicker._setDateFromField(inst);
if ($.monthpicker._inDialog) // hide cursor
input.value = '';
if (!$.monthpicker._pos) { // position below input
$.monthpicker._pos = $.monthpicker._findPos(input);
$.monthpicker._pos[1] += input.offsetHeight; // add the height
}
var isFixed = false;
$(input).parents().each(function() {
isFixed |= $(this).css('position') == 'fixed';
return !isFixed;
});
if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
$.monthpicker._pos[0] -= document.documentElement.scrollLeft;
$.monthpicker._pos[1] -= document.documentElement.scrollTop;
}
var offset = {left: $.monthpicker._pos[0], top: $.monthpicker._pos[1]};
$.monthpicker._pos = null;
//to avoid flashes on Firefox
inst.dpDiv.empty();
// determine sizing offscreen
inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
$.monthpicker._updateMonthpicker(inst);
// fix width for dynamic number of date pickers
// and adjust position before showing
offset = $.monthpicker._checkOffset(inst, offset, isFixed);
inst.dpDiv.css({position: ($.monthpicker._inDialog && $.blockUI ?
'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
left: offset.left + 'px', top: offset.top + 'px'});
var showAnim = $.monthpicker._get(inst, 'showAnim');
var duration = $.monthpicker._get(inst, 'duration');
var postProcess = function() {
var cover = inst.dpDiv.find('iframe.ui-monthpicker-cover'); // IE6- only
if( !! cover.length ){
var borders = $.monthpicker._getBorders(inst.dpDiv);
cover.css({left: -borders[0], top: -borders[1],
width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()});
}
};
$.monthpicker._zIndex(inst.dpDiv, $.monthpicker._zIndex(input)+1);
$.monthpicker._monthpickerShowing = true;
if ($.effects && $.effects.effect[showAnim])
inst.dpDiv.show(showAnim, $.monthpicker._get(inst, 'showOptions'), duration, postProcess);
else
inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess);
if (!showAnim || !duration)
postProcess();
if (inst.input.is(':visible') && !inst.input.is(':disabled'))
inst.input.focus();
$.monthpicker._curInst = inst;
},
_zIndex: function(el, zIndex) {
var $el = $(el);
if (zIndex !== undefined) {
return $el.css('zIndex', zIndex);
}
if ($el.length) {
var elem = $($el[0]), position, value;
while (elem.length && elem[0] !== document) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css('position');
if (position === 'absolute' || position === 'relative' || position === 'fixed') {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt(elem.css('zIndex'), 10);
if (!isNaN(value) && value !== 0) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
},
/* Generate the date picker content. */
_updateMonthpicker: function(inst) {
var self = this;
self.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
var borders = $.monthpicker._getBorders(inst.dpDiv);
instActive = inst; // for delegate hover events
inst.dpDiv.empty().append(this._generateHTML(inst));
this._attachHandlers(inst);
var cover = inst.dpDiv.find('iframe.ui-monthpicker-cover'); // IE6- only
if( !!cover.length ){ //avoid call to outerXXXX() when not in IE6
cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()})
}
inst.dpDiv.find('.' + this._dayOverClass + ' a').mouseover();
if (inst == $.monthpicker._curInst && $.monthpicker._monthpickerShowing && inst.input &&
// #6694 - don't focus the input if it's already focused
// this breaks the change event in IE
inst.input.is(':visible') && !inst.input.is(':disabled') && inst.input[0] != document.activeElement)
inst.input.focus();
// deffered render of the years select (to avoid flashes on Firefox)
if( inst.yearshtml ){
var origyearshtml = inst.yearshtml;
setTimeout(function(){
//assure that inst.yearshtml didn't change.
if( origyearshtml === inst.yearshtml && inst.yearshtml ){
inst.dpDiv.find('select.ui-monthpicker-year:first').replaceWith(inst.yearshtml);
}
origyearshtml = inst.yearshtml = null;
}, 0);
}
},
/* Trigger custom callback of onClose. */
_triggerOnClose: function(inst) {
var onClose = this._get(inst, 'onClose');
if (onClose)
onClose.apply((inst.input ? inst.input[0] : null),
[(inst.input ? inst.input.val() : ''), inst]);
},
/* Hide the month picker from view.
@param input element - the input field attached to the month picker */
_hideMonthpicker: function(input) {
var inst = this._curInst;
if (!inst || (input && inst != $.data(input, PROP_NAME)))
return;
if (this._monthpickerShowing) {
var showAnim = this._get(inst, 'showAnim');
var duration = this._get(inst, 'duration');
var postProcess = function() {
$.monthpicker._tidyDialog(inst);
$.monthpicker._curInst = null;
};
if ( $.effects && $.effects.effect[ showAnim ] )
inst.dpDiv.hide(showAnim, $.monthpicker._get(inst, 'showOptions'), duration, postProcess);
else
inst.dpDiv[(showAnim == 'slideDown' ? 'slideUp' :
(showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess);
if (!showAnim)
postProcess();
$.monthpicker._triggerOnClose(inst);
this._monthpickerShowing = false;
this._lastInput = null;
if (this._inDialog) {
this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
if ($.blockUI) {
$.unblockUI();
$('body').append(this.dpDiv);
}
}
this._inDialog = false;
}
},
/* Handle keystrokes. */
_doKeyDown: function(event) {
var onSelect, dateStr, sel,
inst = $.monthpicker._getInst(event.target),
handled = true,
isRTL = inst.dpDiv.is(".ui-datepicker-rtl");
inst._keyEvent = true;
if ($.monthpicker._monthpickerShowing) {
switch (event.keyCode) {
case 9: $.monthpicker._hideMonthpicker();
handled = false;
break; // hide on tab out
case 13: sel = $("td." + $.monthpicker._dayOverClass + ":not(." +
$.monthpicker._currentClass + ")", inst.dpDiv);
if (sel[0]) {
$.monthpicker._selectMonth(event.target, inst.selectedYear, inst.selectedMonth, sel[0]);
}
onSelect = $.monthpicker._get(inst, "onSelect");
if (onSelect) {
dateStr = $.monthpicker._formatDate(inst);
// trigger custom callback
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
} else {
$.monthpicker._hideMonthpicker();
}
return false; // don't submit the form
case 27: $.monthpicker._hideMonthpicker();
break; // hide on escape
case 33: $.monthpicker._adjustDate(event.target, (event.ctrlKey ?
-$.monthpicker._get(inst, "stepBigYears") :
-$.monthpicker._get(inst, "stepYears")), "Y");
break; // previous year on page up/+ ctrl
case 34: $.monthpicker._adjustDate(event.target, (event.ctrlKey ?
+$.monthpicker._get(inst, "stepBigYears") :
+$.monthpicker._get(inst, "stepYears")), "Y");
break; // next year on page down/+ ctrl
case 35: if (event.ctrlKey || event.metaKey) {
$.monthpicker._clearDate(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // clear on ctrl or command +end
case 36: if (event.ctrlKey || event.metaKey) {
$.monthpicker._gotoCurrent(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // current on ctrl or command +home
case 37: if (event.ctrlKey || event.metaKey) {
$.monthpicker._adjustDate(event.target, (isRTL ? +1 : -1), "M");
}
handled = event.ctrlKey || event.metaKey;
// -1 month on ctrl or command +left
if (event.originalEvent.altKey) {
$.monthpicker._adjustDate(event.target, (event.ctrlKey ?
-$.monthpicker._get(inst, "stepBigYears") :
-$.monthpicker._get(inst, "stepYears")), "Y");
}
// next year on alt +left on Mac
break;
case 38: if (event.ctrlKey || event.metaKey) {
$.monthpicker._adjustDate(event.target, -3, "M");
}
handled = event.ctrlKey || event.metaKey;
break; // -1 quarter on ctrl or command +up
case 39: if (event.ctrlKey || event.metaKey) {
$.monthpicker._adjustDate(event.target, (isRTL ? -1 : +1), "M");
}
handled = event.ctrlKey || event.metaKey;
// +1 month on ctrl or command +right
if (event.originalEvent.altKey) {
$.monthpicker._adjustDate(event.target, (event.ctrlKey ?
+$.monthpicker._get(inst, "stepBigYears") :
+$.monthpicker._get(inst, "stepYears")), "Y");
}
// next year on alt +right
break;
case 40: if (event.ctrlKey || event.metaKey) {
$.monthpicker._adjustDate(event.target, +3, "M");
}
handled = event.ctrlKey || event.metaKey;
break; // +1 quarter on ctrl or command +down
default: handled = false;
}
} else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
$.monthpicker._showMonthpicker(this);
} else {
handled = false;
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
},
/* Is the first field in a jQuery collection disabled as a monthpicker?
@param target element - the target input field or division or span
@return boolean - true if disabled, false if enabled */
_isDisabledMonthpicker: function(target) {
if (!target) {
return false;
}
for (var i = 0; i < this._disabledInputs.length; i++) {
if (this._disabledInputs[i] == target)
return true;
}
return false;
},
/* Tidy up after a dialog display. */
_tidyDialog: function(inst) {
inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-monthpicker-calendar');
},
/* Retrieve the size of left and top borders for an element.
@param elem (jQuery object) the element of interest
@return (number[2]) the left and top borders */
_getBorders: function(elem) {
var convert = function(value) {
return {thin: 1, medium: 2, thick: 3}[value] || value;
};
return [parseFloat(convert(elem.css('border-left-width'))),
parseFloat(convert(elem.css('border-top-width')))];
},
/* Check positioning to remain on screen. */
_checkOffset: function(inst, offset, isFixed) {
var dpWidth = inst.dpDiv.outerWidth();
var dpHeight = inst.dpDiv.outerHeight();
var inputWidth = inst.input ? inst.input.outerWidth() : 0;
var inputHeight = inst.input ? inst.input.outerHeight() : 0;
var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft();
var viewHeight = document.documentElement.clientHeight + $(document).scrollTop();
offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
// now check if monthpicker is showing outside window viewport - move to a better place if so.
offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
Math.abs(offset.left + dpWidth - viewWidth) : 0);
offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
Math.abs(dpHeight + inputHeight) : 0);
return offset;
},
/* Find an object's position on the screen. */
_findPos: function(obj) {
var inst = this._getInst(obj);
while (obj && (obj.type == 'hidden' || obj.nodeType != 1 || $.expr.filters.hidden(obj))) {
obj = obj['nextSibling'];
}
var position = $(obj).offset();
return [position.left, position.top];
},
/* Adjust one of the month sub-fields. */
_adjustDate: function(id, offset, period) {
var target = $(id);
var inst = this._getInst(target[0]);
if (this._isDisabledMonthpicker(target[0])) {
return;
}
this._adjustInstDate(inst, offset, period);
this._updateMonthpicker(inst);
},
/* Adjust one of the date sub-fields. */
_adjustInstDate: function(inst, offset, period) {
var year = inst.drawYear + (period == 'Y' ? offset : 0);
var month = Math.min(inst.selectedMonth, 12) + (period === "M" ? offset : 0);
var date = this._restrictMinMax(inst, new Date(year, month, 1));
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.selectedMonth = date.getMonth();
if (period == 'Y') {
this._notifyChange(inst);
}
},
/* Notify change of month/year. */
_notifyChange: function(inst) {
var onChange = this._get(inst, 'onChangeYear');
if (onChange)
onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst]);
},
/* Detach a datepicker from its control.
* @param target element - the target input field or division or span
*/
_destroyMonthpicker: function(target) {
var nodeName,
$target = $(target),
inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
$.removeData(target, PROP_NAME);
if (nodeName === "input") {
inst.append.remove();
inst.trigger.remove();
$target.removeClass(this.markerClassName).
unbind("focus", this._showMonthpicker).
unbind("keydown", this._doKeyDown)
} else if (nodeName === "div" || nodeName === "span") {
$target.removeClass(this.markerClassName).empty();
}
},
/* Enable the date picker to a jQuery selection.
@param target element - the target input field or division or span */
_enableMonthpicker: function(target) {
var $target = $(target);
var inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
if (nodeName == 'input') {
target.disabled = false;
inst.trigger.filter('button').
each(function() { this.disabled = false; }).end().
filter('img').css({opacity: '1.0', cursor: ''});
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value == target ? null : value); }); // delete entry
},
/* Disable the month picker to a jQuery selection.
@param target element - the target input field or division or span */
_disableMonthpicker: function(target) {
var $target = $(target);
var inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
if (nodeName == 'input') {
target.disabled = true;
inst.trigger.filter('button').
each(function() { this.disabled = true; }).end().
filter('img').css({opacity: '0.5', cursor: 'default'});
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value == target ? null : value); }); // delete entry
this._disabledInputs[this._disabledInputs.length] = target;
},
/* Generate the HTML for the current state of the date picker. */
_generateHTML: function(inst) {
var printDate, hideIfNoPrevNext, unselectable;
hideIfNoPrevNext = false;
var today = new Date();
today = new Date(today.getFullYear(), today.getMonth(), today.getDate()); // clear time
var currentDate = (!inst.currentMonth ? new Date(9999, 9, 9) :
new Date(inst.currentYear, inst.currentMonth, 1));
var minDate = this._getMinMaxDate(inst, "min");
var maxDate = this._getMinMaxDate(inst, "max");
var html = '';
var year = currentDate && currentDate.year ? currentDate.year : 2011;
var prevText = this._get(inst, 'prevText');
var nextText = this._get(inst, 'nextText');
var stepYears = this._get(inst, 'stepYears');
var monthNames = this._get(inst, 'monthNames');
var monthNamesShort = this._get(inst, 'monthNamesShort');
var drawYear = inst.drawYear;
var showButtonPanel = this._get(inst, "showButtonPanel");
var isRTL = this._get(inst, "isRTL");
var defaultDate = this._getDefaultDate(inst);
var navigationAsDateFormat = this._get(inst, "navigationAsDateFormat");
defaultDate.setDate(1);
prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
new Date(drawYear - stepYears, 1, 1),
this._getFormatConfig(inst)));
nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
new Date(drawYear + stepYears, 1, 1),
this._getFormatConfig(inst)));
var prev = (this._canAdjustYear(inst, -1, drawYear) ?
"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
" title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));
var next = (this._canAdjustYear(inst, +1, drawYear) ?
"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
" title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));
html += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-all">' +
prev + next + this._generateYearHeader(inst, drawYear, minDate, maxDate) + // draw year header
'</div><table class="ui-datepicker-calendar"><tbody>';
// draw months table
for(var month = 0; month <= 11; month++) {
if (month % 3 === 0) {
html += '<tr>';
}
printDate = new Date(drawYear, month, 1);
unselectable = (minDate && printDate < minDate) || (maxDate && printDate > maxDate);
var selectedDate = new Date(drawYear, inst.selectedMonth, 1);
html += '<td class="'
+ (drawYear == inst.currentYear && month == inst.currentMonth ? " " + this._currentClass : "") // highlight selected month
+ (unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") // highlight unselectable months
+ ((month === inst.selectedMonth && drawYear === inst.selectedYear && inst._keyEvent) || // user pressed key
(defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?
// or defaultDate is current printedDate and defaultDate is selectedDate
" " + this._dayOverClass : "") // highlight selected day
+ '" data-month="' + month + '" data-year="' + drawYear + '" data-handler="selectMonth" data-event="click">'
+ '<a class="ui-state-default'
+ (drawYear == inst.currentYear && month == inst.currentMonth ? ' ui-state-active' : '') // highlight selected month
+ (drawYear == today.getFullYear() && month == today.getMonth() ? ' ui-state-highlight' : '') // highlight today (if different)
+ '" href="#">' + (inst.settings && inst.settings.monthNamesShort ? inst.settings.monthNamesShort[month] : this._defaults.monthNamesShort[month]) + '</a>' + '</td>'; // display selectable date
if (month % 3 === 2) {
html += '</tr>';
}
}
html += '</tbody></table>';
var controls = "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
this._get(inst, "closeText") + "</button>";
var currentText = this._get(inst, "currentText");
var gotoDate = (this._get(inst, "gotoCurrent") && inst.currentMonth ? currentDate : today);
currentText = (!navigationAsDateFormat ? currentText :
this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
var buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='current' data-event='click'" +
">" + currentText + "</button>" + (isRTL ? "" : controls) + "</div>" : "";
html += buttonPanel;
return html;
},
/* Generate the year header. */
_generateYearHeader: function(inst, drawYear, minDate, maxDate) {
var inMinYear, inMaxYear;
var changeYear = this._get(inst, 'changeYear');
var html = '<div class="ui-datepicker-title">';
// year selection
if ( !inst.yearshtml ) {
inst.yearshtml = '';
if (changeYear) {
// determine range of years to display
var years = this._get(inst, 'yearRange').split(':');
var thisYear = new Date().getFullYear();
var determineYear = function(value) {
var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) :
(value.match(/[+-].*/) ? thisYear + parseInt(value, 10) :
parseInt(value, 10)));
return (isNaN(year) ? thisYear : year);
};
var year = determineYear(years[0]);
var endYear = Math.max(year, determineYear(years[1] || ''));
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
inst.yearshtml += '<select class="ui-datepicker-year" ' +
"data-handler='selectYear' data-event='change'>";
for (; year <= endYear; year++) {
inst.yearshtml += '<option value="' + year + '"' +
(year == drawYear ? ' selected="selected"' : '') +
'>' + year + '</option>';
}
inst.yearshtml += '</select>';
} else {
inst.yearshtml += '<span class="ui-datepicker-year">' + drawYear + '</span>';
}
html += inst.yearshtml;
inst.yearshtml = null;
}
html += this._get(inst, 'yearSuffix');
html += '</div>'; // Close monthpicker_header
return html;
},
/* Provide the configuration settings for formatting/parsing. */
_getFormatConfig: function(inst) {
var shortYearCutoff = this._get(inst, 'shortYearCutoff');
shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
return {shortYearCutoff: shortYearCutoff,
dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
},
/* Parse existing date and initialise date picker. */
_setDateFromField: function(inst, noDefault) {
if (inst.input.val() == inst.lastVal) {
return;
}
var dateFormat = this._get(inst, 'dateFormat');
var dates = inst.lastVal = inst.input ? inst.input.val() : null;
var date, defaultDate;
date = defaultDate = this._getDefaultDate(inst);
var settings = this._getFormatConfig(inst);
try {
date = this.parseDate(dateFormat, dates, settings) || defaultDate;
} catch (event) {
this.log(event);
dates = (noDefault ? '' : dates);
}
inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentMonth = (dates ? date.getMonth() : 0);
inst.currentYear = (dates ? date.getFullYear() : 0);
this._adjustInstDate(inst);
},
/* Retrieve the default date shown on opening. */
_getDefaultDate: function(inst) {
return this._restrictMinMax(inst,
this._determineDate(inst, this._get(inst, 'defaultDate'), new Date()));
},
/* A date may be specified as an exact value or a relative one. */
_determineDate: function(inst, date, defaultDate) {
var offsetNumeric = function(offset) {
var date = new Date();
date.setDate(1);
date.setMonth(date.getMonth() + offset);
return date;
};
var offsetString = function(offset) {
try {
return $.monthpicker.parseDate($.monthpicker._get(inst, 'dateFormat'),
offset, $.monthpicker._getFormatConfig(inst));
}
catch (e) {
// Ignore
}
var date = (offset.toLowerCase().match(/^c/) ?
$.monthpicker._getDate(inst) : null) || new Date();
var year = date.getFullYear();
var month = date.getMonth();
var day = 1;
var pattern = /([+-]?[0-9]+)\s*(m|M|y|Y)?/g;
var matches = pattern.exec(offset);
while (matches) {
switch (matches[2] || 'm') {
case 'm' : case 'M' :
month += parseInt(matches[1],10);
day = 1
break;
case 'y': case 'Y' :
year += parseInt(matches[1],10);
day = 1
break;
}
matches = pattern.exec(offset);
}
return new Date(year, month, day);
};
var newDate = (date == null || date === '' ? defaultDate : (typeof date == 'string' ? offsetString(date) :
(typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
newDate = (newDate && newDate.toString() == 'Invalid Date' ? defaultDate : newDate);
if (newDate) {
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
}
return newDate;
},
/* Determine the current maximum date - ensure no time components are set. */
_getMinMaxDate: function(inst, minMax) {
return this._determineDate(inst, this._get(inst, minMax + 'Date'), null);
},
/* Ensure a date is within any min/max bounds. */
_restrictMinMax: function(inst, date) {
var minDate = this._getMinMaxDate(inst, 'min');
var maxDate = this._getMinMaxDate(inst, 'max');
var newDate = (minDate && date < minDate ? minDate : date);
newDate = (maxDate && newDate > maxDate ? maxDate : newDate);
return newDate;
},
/* Determines if we should allow a "next/prev" year display change. */
_canAdjustYear: function(inst, offset, curYear) {
var firstMonth = new Date(curYear + offset, 0, 1);
var lastMonth = new Date(curYear + offset, 11, 1);
return this._isInRange(inst, firstMonth) || this._isInRange(inst, lastMonth);
},
/* Is the given date in the accepted range? */
_isInRange: function(inst, date) {
var yearSplit, currentYear,
minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
minYear = null,
maxYear = null,
years = this._get(inst, "yearRange");
if (years){
yearSplit = years.split(":");
currentYear = new Date().getFullYear();
minYear = parseInt(yearSplit[0], 10);
maxYear = parseInt(yearSplit[1], 10);
if ( yearSplit[0].match(/[+\-].*/) ) {
minYear += currentYear;
}
if ( yearSplit[1].match(/[+\-].*/) ) {
maxYear += currentYear;
}
}
return ((!minDate || date.getTime() >= minDate.getTime()) &&
(!maxDate || date.getTime() <= maxDate.getTime()) &&
(!minYear || date.getFullYear() >= minYear) &&
(!maxYear || date.getFullYear() <= maxYear));
},
/* Action for selecting a new month/year. */
_selectYear: function(id, select, period) {
var target = $(id);
var inst = this._getInst(target[0]);
inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
parseInt(select.options[select.selectedIndex].value,10);
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for current link. */
_gotoCurrent: function(id) {
var date,
target = $(id),
inst = this._getInst(target[0]);
if (this._get(inst, "gotoCurrent") && inst.currentYear) {
inst.selectedDay = inst.currentDay;
inst.drawMonth = inst.selectedMonth = inst.currentMonth;
inst.drawYear = inst.selectedYear = inst.currentYear;
} else {
date = new Date();
inst.selectedDay = date.getDate();