2 * jQuery UI Datepicker 1.8.4
4 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
5 * Dual licensed under the MIT or GPL Version 2 licenses.
6 * http://jquery.org/license
8 * http://docs.jquery.com/UI/Datepicker
13 (function( $, undefined ) {
15 $.extend($.ui, { datepicker: { version: "1.8.4" } });
17 var PROP_NAME = 'datepicker';
18 var dpuuid = new Date().getTime();
20 /* Date picker manager.
21 Use the singleton instance of this class, $.datepicker, to interact with the date picker.
22 Settings for (groups of) date pickers are maintained in an instance object,
23 allowing multiple different settings on the same page. */
25 function Datepicker() {
26 this.debug = false; // Change this to true to start debugging
27 this._curInst = null; // The current instance in use
28 this._keyEvent = false; // If the last event was a key event
29 this._disabledInputs = []; // List of date picker inputs that have been disabled
30 this._datepickerShowing = false; // True if the popup picker is showing , false if not
31 this._inDialog = false; // True if showing within a "dialog", false if not
32 this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
33 this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
34 this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
35 this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
36 this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
37 this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
38 this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
39 this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
40 this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
41 this.regional = []; // Available regional settings, indexed by language code
42 this.regional[''] = { // Default regional settings
43 closeText: 'Done', // Display text for close link
44 prevText: 'Prev', // Display text for previous month link
45 nextText: 'Next', // Display text for next month link
46 currentText: 'Today', // Display text for current month link
47 monthNames: ['January','February','March','April','May','June',
48 'July','August','September','October','November','December'], // Names of months for drop-down and formatting
49 monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
50 dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
51 dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
52 dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
53 weekHeader: 'Wk', // Column header for week of the year
54 dateFormat: 'mm/dd/yy', // See format options on parseDate
55 firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
56 isRTL: false, // True if right-to-left language, false if left-to-right
57 showMonthAfterYear: false, // True if the year select precedes month, false for month then year
58 yearSuffix: '' // Additional text to append to the year in the month headers
60 this._defaults = { // Global defaults for all the date picker instances
61 showOn: 'focus', // 'focus' for popup on focus,
62 // 'button' for trigger button, or 'both' for either
63 showAnim: 'fadeIn', // Name of jQuery animation for popup
64 showOptions: {}, // Options for enhanced animations
65 defaultDate: null, // Used when field is blank: actual date,
66 // +/-number for offset from today, null for today
67 appendText: '', // Display text following the input box, e.g. showing the format
68 buttonText: '...', // Text for trigger button
69 buttonImage: '', // URL for trigger button image
70 buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
71 hideIfNoPrevNext: false, // True to hide next/previous month links
72 // if not applicable, false to just disable them
73 navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
74 gotoCurrent: false, // True if today link goes back to current selection instead
75 changeMonth: false, // True if month can be selected directly, false if only prev/next
76 changeYear: false, // True if year can be selected directly, false if only prev/next
77 yearRange: 'c-10:c+10', // Range of years to display in drop-down,
78 // either relative to today's year (-nn:+nn), relative to currently displayed year
79 // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
80 showOtherMonths: false, // True to show dates in other months, false to leave blank
81 selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
82 showWeek: false, // True to show week of the year, false to not show it
83 calculateWeek: this.iso8601Week, // How to calculate the week of the year,
84 // takes a Date and returns the number of the week for it
85 shortYearCutoff: '+10', // Short year values < this are in the current century,
86 // > this are in the previous century,
87 // string value starting with '+' for current year + value
88 minDate: null, // The earliest selectable date, or null for no limit
89 maxDate: null, // The latest selectable date, or null for no limit
90 duration: 'fast', // Duration of display/closure
91 beforeShowDay: null, // Function that takes a date and returns an array with
92 // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
93 // [2] = cell title (optional), e.g. $.datepicker.noWeekends
94 beforeShow: null, // Function that takes an input field and
95 // returns a set of custom settings for the date picker
96 onSelect: null, // Define a callback function when a date is selected
97 onChangeMonthYear: null, // Define a callback function when the month or year is changed
98 onClose: null, // Define a callback function when the datepicker is closed
99 numberOfMonths: 1, // Number of months to show at a time
100 showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
101 stepMonths: 1, // Number of months to step back/forward
102 stepBigMonths: 12, // Number of months to step back/forward for the big links
103 altField: '', // Selector for an alternate field to store selected dates into
104 altFormat: '', // The date format to use for the alternate field
105 constrainInput: true, // The input is constrained by the current date format
106 showButtonPanel: false, // True to show button panel, false to not show it
107 autoSize: false // True to size the input for the date format, false to leave as is
109 $.extend(this._defaults, this.regional['']);
110 this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>');
113 $.extend(Datepicker.prototype, {
114 /* Class name added to elements to indicate already configured with a date picker. */
115 markerClassName: 'hasDatepicker',
117 /* Debug logging (if enabled). */
120 console.log.apply('', arguments);
123 // TODO rename to "widget" when switching to widget factory
124 _widgetDatepicker: function() {
128 /* Override the default settings for all instances of the date picker.
129 @param settings object - the new settings to use as defaults (anonymous object)
130 @return the manager object */
131 setDefaults: function(settings) {
132 extendRemove(this._defaults, settings || {});
136 /* Attach the date picker to a jQuery selection.
137 @param target element - the target input field or division or span
138 @param settings object - the new settings to use for this date picker instance (anonymous) */
139 _attachDatepicker: function(target, settings) {
140 // check for settings on the control itself - in namespace 'date:'
141 var inlineSettings = null;
142 for (var attrName in this._defaults) {
143 var attrValue = target.getAttribute('date:' + attrName);
145 inlineSettings = inlineSettings || {};
147 inlineSettings[attrName] = eval(attrValue);
149 inlineSettings[attrName] = attrValue;
153 var nodeName = target.nodeName.toLowerCase();
154 var inline = (nodeName == 'div' || nodeName == 'span');
157 target.id = 'dp' + this.uuid;
159 var inst = this._newInst($(target), inline);
160 inst.settings = $.extend({}, settings || {}, inlineSettings || {});
161 if (nodeName == 'input') {
162 this._connectDatepicker(target, inst);
164 this._inlineDatepicker(target, inst);
168 /* Create a new instance object. */
169 _newInst: function(target, inline) {
170 var id = target[0].id.replace(/([^A-Za-z0-9_])/g, '\\\\$1'); // escape jQuery meta chars
171 return {id: id, input: target, // associated target
172 selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
173 drawMonth: 0, drawYear: 0, // month being drawn
174 inline: inline, // is datepicker inline or not
175 dpDiv: (!inline ? this.dpDiv : // presentation div
176 $('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))};
179 /* Attach the date picker to an input field. */
180 _connectDatepicker: function(target, inst) {
181 var input = $(target);
183 inst.trigger = $([]);
184 if (input.hasClass(this.markerClassName))
186 this._attachments(input, inst);
187 input.addClass(this.markerClassName).keydown(this._doKeyDown).
188 keypress(this._doKeyPress).keyup(this._doKeyUp).
189 bind("setData.datepicker", function(event, key, value) {
190 inst.settings[key] = value;
191 }).bind("getData.datepicker", function(event, key) {
192 return this._get(inst, key);
194 this._autoSize(inst);
195 $.data(target, PROP_NAME, inst);
198 /* Make attachments based on settings. */
199 _attachments: function(input, inst) {
200 var appendText = this._get(inst, 'appendText');
201 var isRTL = this._get(inst, 'isRTL');
203 inst.append.remove();
205 inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>');
206 input[isRTL ? 'before' : 'after'](inst.append);
208 input.unbind('focus', this._showDatepicker);
210 inst.trigger.remove();
211 var showOn = this._get(inst, 'showOn');
212 if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
213 input.focus(this._showDatepicker);
214 if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
215 var buttonText = this._get(inst, 'buttonText');
216 var buttonImage = this._get(inst, 'buttonImage');
217 inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
218 $('<img/>').addClass(this._triggerClass).
219 attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
220 $('<button type="button"></button>').addClass(this._triggerClass).
221 html(buttonImage == '' ? buttonText : $('<img/>').attr(
222 { src:buttonImage, alt:buttonText, title:buttonText })));
223 input[isRTL ? 'before' : 'after'](inst.trigger);
224 inst.trigger.click(function() {
225 if ($.datepicker._datepickerShowing && $.datepicker._lastInput == input[0])
226 $.datepicker._hideDatepicker();
228 $.datepicker._showDatepicker(input[0]);
234 /* Apply the maximum length for the date format. */
235 _autoSize: function(inst) {
236 if (this._get(inst, 'autoSize') && !inst.inline) {
237 var date = new Date(2009, 12 - 1, 20); // Ensure double digits
238 var dateFormat = this._get(inst, 'dateFormat');
239 if (dateFormat.match(/[DM]/)) {
240 var findMax = function(names) {
243 for (var i = 0; i < names.length; i++) {
244 if (names[i].length > max) {
245 max = names[i].length;
251 date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
252 'monthNames' : 'monthNamesShort'))));
253 date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
254 'dayNames' : 'dayNamesShort'))) + 20 - date.getDay());
256 inst.input.attr('size', this._formatDate(inst, date).length);
260 /* Attach an inline date picker to a div. */
261 _inlineDatepicker: function(target, inst) {
262 var divSpan = $(target);
263 if (divSpan.hasClass(this.markerClassName))
265 divSpan.addClass(this.markerClassName).append(inst.dpDiv).
266 bind("setData.datepicker", function(event, key, value){
267 inst.settings[key] = value;
268 }).bind("getData.datepicker", function(event, key){
269 return this._get(inst, key);
271 $.data(target, PROP_NAME, inst);
272 this._setDate(inst, this._getDefaultDate(inst), true);
273 this._updateDatepicker(inst);
274 this._updateAlternate(inst);
277 /* Pop-up the date picker in a "dialog" box.
278 @param input element - ignored
279 @param date string or Date - the initial date to display
280 @param onSelect function - the function to call when a date is selected
281 @param settings object - update the dialog date picker instance's settings (anonymous object)
282 @param pos int[2] - coordinates for the dialog's position within the screen or
283 event - with x/y coordinates or
284 leave empty for default (screen centre)
285 @return the manager object */
286 _dialogDatepicker: function(input, date, onSelect, settings, pos) {
287 var inst = this._dialogInst; // internal instance
290 var id = 'dp' + this.uuid;
291 this._dialogInput = $('<input type="text" id="' + id +
292 '" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>');
293 this._dialogInput.keydown(this._doKeyDown);
294 $('body').append(this._dialogInput);
295 inst = this._dialogInst = this._newInst(this._dialogInput, false);
297 $.data(this._dialogInput[0], PROP_NAME, inst);
299 extendRemove(inst.settings, settings || {});
300 date = (date && date.constructor == Date ? this._formatDate(inst, date) : date);
301 this._dialogInput.val(date);
303 this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
305 var browserWidth = document.documentElement.clientWidth;
306 var browserHeight = document.documentElement.clientHeight;
307 var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
308 var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
309 this._pos = // should use actual width/height below
310 [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
313 // move input on screen for focus, but hidden behind dialog
314 this._dialogInput.css('left', (this._pos[0] + 20) + 'px').css('top', this._pos[1] + 'px');
315 inst.settings.onSelect = onSelect;
316 this._inDialog = true;
317 this.dpDiv.addClass(this._dialogClass);
318 this._showDatepicker(this._dialogInput[0]);
320 $.blockUI(this.dpDiv);
321 $.data(this._dialogInput[0], PROP_NAME, inst);
325 /* Detach a datepicker from its control.
326 @param target element - the target input field or division or span */
327 _destroyDatepicker: function(target) {
328 var $target = $(target);
329 var inst = $.data(target, PROP_NAME);
330 if (!$target.hasClass(this.markerClassName)) {
333 var nodeName = target.nodeName.toLowerCase();
334 $.removeData(target, PROP_NAME);
335 if (nodeName == 'input') {
336 inst.append.remove();
337 inst.trigger.remove();
338 $target.removeClass(this.markerClassName).
339 unbind('focus', this._showDatepicker).
340 unbind('keydown', this._doKeyDown).
341 unbind('keypress', this._doKeyPress).
342 unbind('keyup', this._doKeyUp);
343 } else if (nodeName == 'div' || nodeName == 'span')
344 $target.removeClass(this.markerClassName).empty();
347 /* Enable the date picker to a jQuery selection.
348 @param target element - the target input field or division or span */
349 _enableDatepicker: function(target) {
350 var $target = $(target);
351 var inst = $.data(target, PROP_NAME);
352 if (!$target.hasClass(this.markerClassName)) {
355 var nodeName = target.nodeName.toLowerCase();
356 if (nodeName == 'input') {
357 target.disabled = false;
358 inst.trigger.filter('button').
359 each(function() { this.disabled = false; }).end().
360 filter('img').css({opacity: '1.0', cursor: ''});
362 else if (nodeName == 'div' || nodeName == 'span') {
363 var inline = $target.children('.' + this._inlineClass);
364 inline.children().removeClass('ui-state-disabled');
366 this._disabledInputs = $.map(this._disabledInputs,
367 function(value) { return (value == target ? null : value); }); // delete entry
370 /* Disable the date picker to a jQuery selection.
371 @param target element - the target input field or division or span */
372 _disableDatepicker: function(target) {
373 var $target = $(target);
374 var inst = $.data(target, PROP_NAME);
375 if (!$target.hasClass(this.markerClassName)) {
378 var nodeName = target.nodeName.toLowerCase();
379 if (nodeName == 'input') {
380 target.disabled = true;
381 inst.trigger.filter('button').
382 each(function() { this.disabled = true; }).end().
383 filter('img').css({opacity: '0.5', cursor: 'default'});
385 else if (nodeName == 'div' || nodeName == 'span') {
386 var inline = $target.children('.' + this._inlineClass);
387 inline.children().addClass('ui-state-disabled');
389 this._disabledInputs = $.map(this._disabledInputs,
390 function(value) { return (value == target ? null : value); }); // delete entry
391 this._disabledInputs[this._disabledInputs.length] = target;
394 /* Is the first field in a jQuery collection disabled as a datepicker?
395 @param target element - the target input field or division or span
396 @return boolean - true if disabled, false if enabled */
397 _isDisabledDatepicker: function(target) {
401 for (var i = 0; i < this._disabledInputs.length; i++) {
402 if (this._disabledInputs[i] == target)
408 /* Retrieve the instance data for the target control.
409 @param target element - the target input field or division or span
410 @return object - the associated instance data
411 @throws error if a jQuery problem getting data */
412 _getInst: function(target) {
414 return $.data(target, PROP_NAME);
417 throw 'Missing instance data for this datepicker';
421 /* Update or retrieve the settings for a date picker attached to an input field or division.
422 @param target element - the target input field or division or span
423 @param name object - the new settings to update or
424 string - the name of the setting to change or retrieve,
425 when retrieving also 'all' for all instance settings or
426 'defaults' for all global defaults
427 @param value any - the new value for the setting
428 (omit if above is an object or to retrieve a value) */
429 _optionDatepicker: function(target, name, value) {
430 var inst = this._getInst(target);
431 if (arguments.length == 2 && typeof name == 'string') {
432 return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) :
433 (inst ? (name == 'all' ? $.extend({}, inst.settings) :
434 this._get(inst, name)) : null));
436 var settings = name || {};
437 if (typeof name == 'string') {
439 settings[name] = value;
442 if (this._curInst == inst) {
443 this._hideDatepicker();
445 var date = this._getDateDatepicker(target, true);
446 extendRemove(inst.settings, settings);
447 this._attachments($(target), inst);
448 this._autoSize(inst);
449 this._setDateDatepicker(target, date);
450 this._updateDatepicker(inst);
454 // change method deprecated
455 _changeDatepicker: function(target, name, value) {
456 this._optionDatepicker(target, name, value);
459 /* Redraw the date picker attached to an input field or division.
460 @param target element - the target input field or division or span */
461 _refreshDatepicker: function(target) {
462 var inst = this._getInst(target);
464 this._updateDatepicker(inst);
468 /* Set the dates for a jQuery selection.
469 @param target element - the target input field or division or span
470 @param date Date - the new date */
471 _setDateDatepicker: function(target, date) {
472 var inst = this._getInst(target);
474 this._setDate(inst, date);
475 this._updateDatepicker(inst);
476 this._updateAlternate(inst);
480 /* Get the date(s) for the first entry in a jQuery selection.
481 @param target element - the target input field or division or span
482 @param noDefault boolean - true if no default date is to be used
483 @return Date - the current date */
484 _getDateDatepicker: function(target, noDefault) {
485 var inst = this._getInst(target);
486 if (inst && !inst.inline)
487 this._setDateFromField(inst, noDefault);
488 return (inst ? this._getDate(inst) : null);
491 /* Handle keystrokes. */
492 _doKeyDown: function(event) {
493 var inst = $.datepicker._getInst(event.target);
495 var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
496 inst._keyEvent = true;
497 if ($.datepicker._datepickerShowing)
498 switch (event.keyCode) {
499 case 9: $.datepicker._hideDatepicker();
501 break; // hide on tab out
502 case 13: var sel = $('td.' + $.datepicker._dayOverClass, inst.dpDiv).
503 add($('td.' + $.datepicker._currentClass, inst.dpDiv));
505 $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
507 $.datepicker._hideDatepicker();
508 return false; // don't submit the form
509 break; // select the value on enter
510 case 27: $.datepicker._hideDatepicker();
511 break; // hide on escape
512 case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
513 -$.datepicker._get(inst, 'stepBigMonths') :
514 -$.datepicker._get(inst, 'stepMonths')), 'M');
515 break; // previous month/year on page up/+ ctrl
516 case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
517 +$.datepicker._get(inst, 'stepBigMonths') :
518 +$.datepicker._get(inst, 'stepMonths')), 'M');
519 break; // next month/year on page down/+ ctrl
520 case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
521 handled = event.ctrlKey || event.metaKey;
522 break; // clear on ctrl or command +end
523 case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
524 handled = event.ctrlKey || event.metaKey;
525 break; // current on ctrl or command +home
526 case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
527 handled = event.ctrlKey || event.metaKey;
528 // -1 day on ctrl or command +left
529 if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
530 -$.datepicker._get(inst, 'stepBigMonths') :
531 -$.datepicker._get(inst, 'stepMonths')), 'M');
532 // next month/year on alt +left on Mac
534 case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
535 handled = event.ctrlKey || event.metaKey;
536 break; // -1 week on ctrl or command +up
537 case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
538 handled = event.ctrlKey || event.metaKey;
539 // +1 day on ctrl or command +right
540 if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
541 +$.datepicker._get(inst, 'stepBigMonths') :
542 +$.datepicker._get(inst, 'stepMonths')), 'M');
543 // next month/year on alt +right
545 case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
546 handled = event.ctrlKey || event.metaKey;
547 break; // +1 week on ctrl or command +down
548 default: handled = false;
550 else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
551 $.datepicker._showDatepicker(this);
556 event.preventDefault();
557 event.stopPropagation();
561 /* Filter entered characters - based on date format. */
562 _doKeyPress: function(event) {
563 var inst = $.datepicker._getInst(event.target);
564 if ($.datepicker._get(inst, 'constrainInput')) {
565 var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
566 var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
567 return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
571 /* Synchronise manual entry and field/alternate field. */
572 _doKeyUp: function(event) {
573 var inst = $.datepicker._getInst(event.target);
574 if (inst.input.val() != inst.lastVal) {
576 var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
577 (inst.input ? inst.input.val() : null),
578 $.datepicker._getFormatConfig(inst));
579 if (date) { // only if valid
580 $.datepicker._setDateFromField(inst);
581 $.datepicker._updateAlternate(inst);
582 $.datepicker._updateDatepicker(inst);
586 $.datepicker.log(event);
592 /* Pop-up the date picker for a given input field.
593 @param input element - the input field attached to the date picker or
594 event - if triggered by focus */
595 _showDatepicker: function(input) {
596 input = input.target || input;
597 if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
598 input = $('input', input.parentNode)[0];
599 if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
601 var inst = $.datepicker._getInst(input);
602 if ($.datepicker._curInst && $.datepicker._curInst != inst) {
603 $.datepicker._curInst.dpDiv.stop(true, true);
605 var beforeShow = $.datepicker._get(inst, 'beforeShow');
606 extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
608 $.datepicker._lastInput = input;
609 $.datepicker._setDateFromField(inst);
610 if ($.datepicker._inDialog) // hide cursor
612 if (!$.datepicker._pos) { // position below input
613 $.datepicker._pos = $.datepicker._findPos(input);
614 $.datepicker._pos[1] += input.offsetHeight; // add the height
617 $(input).parents().each(function() {
618 isFixed |= $(this).css('position') == 'fixed';
621 if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
622 $.datepicker._pos[0] -= document.documentElement.scrollLeft;
623 $.datepicker._pos[1] -= document.documentElement.scrollTop;
625 var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
626 $.datepicker._pos = null;
627 // determine sizing offscreen
628 inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
629 $.datepicker._updateDatepicker(inst);
630 // fix width for dynamic number of date pickers
631 // and adjust position before showing
632 offset = $.datepicker._checkOffset(inst, offset, isFixed);
633 inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
634 'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
635 left: offset.left + 'px', top: offset.top + 'px'});
637 var showAnim = $.datepicker._get(inst, 'showAnim');
638 var duration = $.datepicker._get(inst, 'duration');
639 var postProcess = function() {
640 $.datepicker._datepickerShowing = true;
641 var borders = $.datepicker._getBorders(inst.dpDiv);
642 inst.dpDiv.find('iframe.ui-datepicker-cover'). // IE6- only
643 css({left: -borders[0], top: -borders[1],
644 width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()});
646 inst.dpDiv.zIndex($(input).zIndex()+1);
647 if ($.effects && $.effects[showAnim])
648 inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
650 inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess);
651 if (!showAnim || !duration)
653 if (inst.input.is(':visible') && !inst.input.is(':disabled'))
655 $.datepicker._curInst = inst;
659 /* Generate the date picker content. */
660 _updateDatepicker: function(inst) {
662 var borders = $.datepicker._getBorders(inst.dpDiv);
663 inst.dpDiv.empty().append(this._generateHTML(inst))
664 .find('iframe.ui-datepicker-cover') // IE6- only
665 .css({left: -borders[0], top: -borders[1],
666 width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()})
668 .find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a')
669 .bind('mouseout', function(){
670 $(this).removeClass('ui-state-hover');
671 if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover');
672 if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover');
674 .bind('mouseover', function(){
675 if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) {
676 $(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
677 $(this).addClass('ui-state-hover');
678 if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover');
679 if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover');
683 .find('.' + this._dayOverClass + ' a')
684 .trigger('mouseover')
686 var numMonths = this._getNumberOfMonths(inst);
687 var cols = numMonths[1];
690 inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
692 inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
693 inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
694 'Class']('ui-datepicker-multi');
695 inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
696 'Class']('ui-datepicker-rtl');
697 if (inst == $.datepicker._curInst && $.datepicker._datepickerShowing && inst.input &&
698 inst.input.is(':visible') && !inst.input.is(':disabled'))
702 /* Retrieve the size of left and top borders for an element.
703 @param elem (jQuery object) the element of interest
704 @return (number[2]) the left and top borders */
705 _getBorders: function(elem) {
706 var convert = function(value) {
707 return {thin: 1, medium: 2, thick: 3}[value] || value;
709 return [parseFloat(convert(elem.css('border-left-width'))),
710 parseFloat(convert(elem.css('border-top-width')))];
713 /* Check positioning to remain on screen. */
714 _checkOffset: function(inst, offset, isFixed) {
715 var dpWidth = inst.dpDiv.outerWidth();
716 var dpHeight = inst.dpDiv.outerHeight();
717 var inputWidth = inst.input ? inst.input.outerWidth() : 0;
718 var inputHeight = inst.input ? inst.input.outerHeight() : 0;
719 var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft();
720 var viewHeight = document.documentElement.clientHeight + $(document).scrollTop();
722 offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
723 offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
724 offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
726 // now check if datepicker is showing outside window viewport - move to a better place if so.
727 offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
728 Math.abs(offset.left + dpWidth - viewWidth) : 0);
729 offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
730 Math.abs(dpHeight + inputHeight) : 0);
735 /* Find an object's position on the screen. */
736 _findPos: function(obj) {
737 var inst = this._getInst(obj);
738 var isRTL = this._get(inst, 'isRTL');
739 while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
740 obj = obj[isRTL ? 'previousSibling' : 'nextSibling'];
742 var position = $(obj).offset();
743 return [position.left, position.top];
746 /* Hide the date picker from view.
747 @param input element - the input field attached to the date picker */
748 _hideDatepicker: function(input) {
749 var inst = this._curInst;
750 if (!inst || (input && inst != $.data(input, PROP_NAME)))
752 if (this._datepickerShowing) {
753 var showAnim = this._get(inst, 'showAnim');
754 var duration = this._get(inst, 'duration');
755 var postProcess = function() {
756 $.datepicker._tidyDialog(inst);
757 this._curInst = null;
759 if ($.effects && $.effects[showAnim])
760 inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
762 inst.dpDiv[(showAnim == 'slideDown' ? 'slideUp' :
763 (showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess);
766 var onClose = this._get(inst, 'onClose');
768 onClose.apply((inst.input ? inst.input[0] : null),
769 [(inst.input ? inst.input.val() : ''), inst]); // trigger custom callback
770 this._datepickerShowing = false;
771 this._lastInput = null;
772 if (this._inDialog) {
773 this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
776 $('body').append(this.dpDiv);
779 this._inDialog = false;
783 /* Tidy up after a dialog display. */
784 _tidyDialog: function(inst) {
785 inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
788 /* Close date picker if clicked elsewhere. */
789 _checkExternalClick: function(event) {
790 if (!$.datepicker._curInst)
792 var $target = $(event.target);
793 if ($target[0].id != $.datepicker._mainDivId &&
794 $target.parents('#' + $.datepicker._mainDivId).length == 0 &&
795 !$target.hasClass($.datepicker.markerClassName) &&
796 !$target.hasClass($.datepicker._triggerClass) &&
797 $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))
798 $.datepicker._hideDatepicker();
801 /* Adjust one of the date sub-fields. */
802 _adjustDate: function(id, offset, period) {
804 var inst = this._getInst(target[0]);
805 if (this._isDisabledDatepicker(target[0])) {
808 this._adjustInstDate(inst, offset +
809 (period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
811 this._updateDatepicker(inst);
814 /* Action for current link. */
815 _gotoToday: function(id) {
817 var inst = this._getInst(target[0]);
818 if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
819 inst.selectedDay = inst.currentDay;
820 inst.drawMonth = inst.selectedMonth = inst.currentMonth;
821 inst.drawYear = inst.selectedYear = inst.currentYear;
824 var date = new Date();
825 inst.selectedDay = date.getDate();
826 inst.drawMonth = inst.selectedMonth = date.getMonth();
827 inst.drawYear = inst.selectedYear = date.getFullYear();
829 this._notifyChange(inst);
830 this._adjustDate(target);
833 /* Action for selecting a new month/year. */
834 _selectMonthYear: function(id, select, period) {
836 var inst = this._getInst(target[0]);
837 inst._selectingMonthYear = false;
838 inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
839 inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
840 parseInt(select.options[select.selectedIndex].value,10);
841 this._notifyChange(inst);
842 this._adjustDate(target);
845 /* Restore input focus after not changing month/year. */
846 _clickMonthYear: function(id) {
848 var inst = this._getInst(target[0]);
849 if (inst.input && inst._selectingMonthYear) {
850 setTimeout(function() {
854 inst._selectingMonthYear = !inst._selectingMonthYear;
857 /* Action for selecting a day. */
858 _selectDay: function(id, month, year, td) {
860 if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
863 var inst = this._getInst(target[0]);
864 inst.selectedDay = inst.currentDay = $('a', td).html();
865 inst.selectedMonth = inst.currentMonth = month;
866 inst.selectedYear = inst.currentYear = year;
867 this._selectDate(id, this._formatDate(inst,
868 inst.currentDay, inst.currentMonth, inst.currentYear));
871 /* Erase the input field and hide the date picker. */
872 _clearDate: function(id) {
874 var inst = this._getInst(target[0]);
875 this._selectDate(target, '');
878 /* Update the input field with the selected date. */
879 _selectDate: function(id, dateStr) {
881 var inst = this._getInst(target[0]);
882 dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
884 inst.input.val(dateStr);
885 this._updateAlternate(inst);
886 var onSelect = this._get(inst, 'onSelect');
888 onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
890 inst.input.trigger('change'); // fire the change event
892 this._updateDatepicker(inst);
894 this._hideDatepicker();
895 this._lastInput = inst.input[0];
896 if (typeof(inst.input[0]) != 'object')
897 inst.input.focus(); // restore focus
898 this._lastInput = null;
902 /* Update any alternate field to synchronise with the main field. */
903 _updateAlternate: function(inst) {
904 var altField = this._get(inst, 'altField');
905 if (altField) { // update alternate field too
906 var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
907 var date = this._getDate(inst);
908 var dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
909 $(altField).each(function() { $(this).val(dateStr); });
913 /* Set as beforeShowDay function to prevent selection of weekends.
914 @param date Date - the date to customise
915 @return [boolean, string] - is this date selectable?, what is its CSS class? */
916 noWeekends: function(date) {
917 var day = date.getDay();
918 return [(day > 0 && day < 6), ''];
921 /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
922 @param date Date - the date to get the week for
923 @return number - the number of the week within the year that contains this date */
924 iso8601Week: function(date) {
925 var checkDate = new Date(date.getTime());
926 // Find Thursday of this week starting on Monday
927 checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
928 var time = checkDate.getTime();
929 checkDate.setMonth(0); // Compare with Jan 1
930 checkDate.setDate(1);
931 return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
934 /* Parse a string value into a date object.
935 See formatDate below for the possible formats.
937 @param format string - the expected format of the date
938 @param value string - the date in the above format
939 @param settings Object - attributes include:
940 shortYearCutoff number - the cutoff year for determining the century (optional)
941 dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
942 dayNames string[7] - names of the days from Sunday (optional)
943 monthNamesShort string[12] - abbreviated names of the months (optional)
944 monthNames string[12] - names of the months (optional)
945 @return Date - the extracted date value or null if value is blank */
946 parseDate: function (format, value, settings) {
947 if (format == null || value == null)
948 throw 'Invalid arguments';
949 value = (typeof value == 'object' ? value.toString() : value + '');
952 var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
953 var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
954 var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
955 var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
956 var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
962 // Check whether a format character is doubled
963 var lookAhead = function(match) {
964 var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
969 // Extract a number from the string value
970 var getNumber = function(match) {
972 var size = (match == '@' ? 14 : (match == '!' ? 20 :
973 (match == 'y' ? 4 : (match == 'o' ? 3 : 2))));
974 var digits = new RegExp('^\\d{1,' + size + '}');
975 var num = value.substring(iValue).match(digits);
977 throw 'Missing number at position ' + iValue;
978 iValue += num[0].length;
979 return parseInt(num[0], 10);
981 // Extract a name from the string value and convert to an index
982 var getName = function(match, shortNames, longNames) {
983 var names = (lookAhead(match) ? longNames : shortNames);
984 for (var i = 0; i < names.length; i++) {
985 if (value.substr(iValue, names[i].length) == names[i]) {
986 iValue += names[i].length;
990 throw 'Unknown name at position ' + iValue;
992 // Confirm that a literal character matches the string value
993 var checkLiteral = function() {
994 if (value.charAt(iValue) != format.charAt(iFormat))
995 throw 'Unexpected literal at position ' + iValue;
999 for (var iFormat = 0; iFormat < format.length; iFormat++) {
1001 if (format.charAt(iFormat) == "'" && !lookAhead("'"))
1006 switch (format.charAt(iFormat)) {
1008 day = getNumber('d');
1011 getName('D', dayNamesShort, dayNames);
1014 doy = getNumber('o');
1017 month = getNumber('m');
1020 month = getName('M', monthNamesShort, monthNames);
1023 year = getNumber('y');
1026 var date = new Date(getNumber('@'));
1027 year = date.getFullYear();
1028 month = date.getMonth() + 1;
1029 day = date.getDate();
1032 var date = new Date((getNumber('!') - this._ticksTo1970) / 10000);
1033 year = date.getFullYear();
1034 month = date.getMonth() + 1;
1035 day = date.getDate();
1048 year = new Date().getFullYear();
1049 else if (year < 100)
1050 year += new Date().getFullYear() - new Date().getFullYear() % 100 +
1051 (year <= shortYearCutoff ? 0 : -100);
1056 var dim = this._getDaysInMonth(year, month - 1);
1063 var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
1064 if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
1065 throw 'Invalid date'; // E.g. 31/02/*
1069 /* Standard date formats. */
1070 ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
1071 COOKIE: 'D, dd M yy',
1072 ISO_8601: 'yy-mm-dd',
1073 RFC_822: 'D, d M y',
1074 RFC_850: 'DD, dd-M-y',
1075 RFC_1036: 'D, d M y',
1076 RFC_1123: 'D, d M yy',
1077 RFC_2822: 'D, d M yy',
1078 RSS: 'D, d M y', // RFC 822
1081 W3C: 'yy-mm-dd', // ISO 8601
1083 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
1084 Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
1086 /* Format a date object into a string value.
1087 The format can be combinations of the following:
1088 d - day of month (no leading zero)
1089 dd - day of month (two digit)
1090 o - day of year (no leading zeros)
1091 oo - day of year (three digit)
1094 m - month of year (no leading zero)
1095 mm - month of year (two digit)
1096 M - month name short
1097 MM - month name long
1098 y - year (two digit)
1099 yy - year (four digit)
1100 @ - Unix timestamp (ms since 01/01/1970)
1101 ! - Windows ticks (100ns since 01/01/0001)
1102 '...' - literal text
1105 @param format string - the desired format of the date
1106 @param date Date - the date value to format
1107 @param settings Object - attributes include:
1108 dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
1109 dayNames string[7] - names of the days from Sunday (optional)
1110 monthNamesShort string[12] - abbreviated names of the months (optional)
1111 monthNames string[12] - names of the months (optional)
1112 @return string - the date in the above format */
1113 formatDate: function (format, date, settings) {
1116 var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
1117 var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
1118 var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
1119 var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
1120 // Check whether a format character is doubled
1121 var lookAhead = function(match) {
1122 var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
1127 // Format a number, with leading zero if necessary
1128 var formatNumber = function(match, value, len) {
1129 var num = '' + value;
1130 if (lookAhead(match))
1131 while (num.length < len)
1135 // Format a name, short or long as requested
1136 var formatName = function(match, value, shortNames, longNames) {
1137 return (lookAhead(match) ? longNames[value] : shortNames[value]);
1140 var literal = false;
1142 for (var iFormat = 0; iFormat < format.length; iFormat++) {
1144 if (format.charAt(iFormat) == "'" && !lookAhead("'"))
1147 output += format.charAt(iFormat);
1149 switch (format.charAt(iFormat)) {
1151 output += formatNumber('d', date.getDate(), 2);
1154 output += formatName('D', date.getDay(), dayNamesShort, dayNames);
1157 output += formatNumber('o',
1158 (date.getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000, 3);
1161 output += formatNumber('m', date.getMonth() + 1, 2);
1164 output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
1167 output += (lookAhead('y') ? date.getFullYear() :
1168 (date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
1171 output += date.getTime();
1174 output += date.getTime() * 10000 + this._ticksTo1970;
1183 output += format.charAt(iFormat);
1189 /* Extract all possible characters from the date format. */
1190 _possibleChars: function (format) {
1192 var literal = false;
1193 // Check whether a format character is doubled
1194 var lookAhead = function(match) {
1195 var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
1200 for (var iFormat = 0; iFormat < format.length; iFormat++)
1202 if (format.charAt(iFormat) == "'" && !lookAhead("'"))
1205 chars += format.charAt(iFormat);
1207 switch (format.charAt(iFormat)) {
1208 case 'd': case 'm': case 'y': case '@':
1209 chars += '0123456789';
1212 return null; // Accept anything
1220 chars += format.charAt(iFormat);
1225 /* Get a setting value, defaulting if necessary. */
1226 _get: function(inst, name) {
1227 return inst.settings[name] !== undefined ?
1228 inst.settings[name] : this._defaults[name];
1231 /* Parse existing date and initialise date picker. */
1232 _setDateFromField: function(inst, noDefault) {
1233 if (inst.input.val() == inst.lastVal) {
1236 var dateFormat = this._get(inst, 'dateFormat');
1237 var dates = inst.lastVal = inst.input ? inst.input.val() : null;
1238 var date, defaultDate;
1239 date = defaultDate = this._getDefaultDate(inst);
1240 var settings = this._getFormatConfig(inst);
1242 date = this.parseDate(dateFormat, dates, settings) || defaultDate;
1245 dates = (noDefault ? '' : dates);
1247 inst.selectedDay = date.getDate();
1248 inst.drawMonth = inst.selectedMonth = date.getMonth();
1249 inst.drawYear = inst.selectedYear = date.getFullYear();
1250 inst.currentDay = (dates ? date.getDate() : 0);
1251 inst.currentMonth = (dates ? date.getMonth() : 0);
1252 inst.currentYear = (dates ? date.getFullYear() : 0);
1253 this._adjustInstDate(inst);
1256 /* Retrieve the default date shown on opening. */
1257 _getDefaultDate: function(inst) {
1258 return this._restrictMinMax(inst,
1259 this._determineDate(inst, this._get(inst, 'defaultDate'), new Date()));
1262 /* A date may be specified as an exact value or a relative one. */
1263 _determineDate: function(inst, date, defaultDate) {
1264 var offsetNumeric = function(offset) {
1265 var date = new Date();
1266 date.setDate(date.getDate() + offset);
1269 var offsetString = function(offset) {
1271 return $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
1272 offset, $.datepicker._getFormatConfig(inst));
1277 var date = (offset.toLowerCase().match(/^c/) ?
1278 $.datepicker._getDate(inst) : null) || new Date();
1279 var year = date.getFullYear();
1280 var month = date.getMonth();
1281 var day = date.getDate();
1282 var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
1283 var matches = pattern.exec(offset);
1285 switch (matches[2] || 'd') {
1286 case 'd' : case 'D' :
1287 day += parseInt(matches[1],10); break;
1288 case 'w' : case 'W' :
1289 day += parseInt(matches[1],10) * 7; break;
1290 case 'm' : case 'M' :
1291 month += parseInt(matches[1],10);
1292 day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
1294 case 'y': case 'Y' :
1295 year += parseInt(matches[1],10);
1296 day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
1299 matches = pattern.exec(offset);
1301 return new Date(year, month, day);
1303 date = (date == null ? defaultDate : (typeof date == 'string' ? offsetString(date) :
1304 (typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date)));
1305 date = (date && date.toString() == 'Invalid Date' ? defaultDate : date);
1310 date.setMilliseconds(0);
1312 return this._daylightSavingAdjust(date);
1315 /* Handle switch to/from daylight saving.
1316 Hours may be non-zero on daylight saving cut-over:
1317 > 12 when midnight changeover, but then cannot generate
1318 midnight datetime, so jump to 1AM, otherwise reset.
1319 @param date (Date) the date to check
1320 @return (Date) the corrected date */
1321 _daylightSavingAdjust: function(date) {
1322 if (!date) return null;
1323 date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
1327 /* Set the date(s) directly. */
1328 _setDate: function(inst, date, noChange) {
1329 var clear = !(date);
1330 var origMonth = inst.selectedMonth;
1331 var origYear = inst.selectedYear;
1332 date = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
1333 inst.selectedDay = inst.currentDay = date.getDate();
1334 inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth();
1335 inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear();
1336 if ((origMonth != inst.selectedMonth || origYear != inst.selectedYear) && !noChange)
1337 this._notifyChange(inst);
1338 this._adjustInstDate(inst);
1340 inst.input.val(clear ? '' : this._formatDate(inst));
1344 /* Retrieve the date(s) directly. */
1345 _getDate: function(inst) {
1346 var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
1347 this._daylightSavingAdjust(new Date(
1348 inst.currentYear, inst.currentMonth, inst.currentDay)));
1352 /* Generate the HTML for the current state of the date picker. */
1353 _generateHTML: function(inst) {
1354 var today = new Date();
1355 today = this._daylightSavingAdjust(
1356 new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
1357 var isRTL = this._get(inst, 'isRTL');
1358 var showButtonPanel = this._get(inst, 'showButtonPanel');
1359 var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
1360 var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
1361 var numMonths = this._getNumberOfMonths(inst);
1362 var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
1363 var stepMonths = this._get(inst, 'stepMonths');
1364 var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
1365 var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
1366 new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
1367 var minDate = this._getMinMaxDate(inst, 'min');
1368 var maxDate = this._getMinMaxDate(inst, 'max');
1369 var drawMonth = inst.drawMonth - showCurrentAtPos;
1370 var drawYear = inst.drawYear;
1371 if (drawMonth < 0) {
1376 var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
1377 maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
1378 maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
1379 while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
1381 if (drawMonth < 0) {
1387 inst.drawMonth = drawMonth;
1388 inst.drawYear = drawYear;
1389 var prevText = this._get(inst, 'prevText');
1390 prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
1391 this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
1392 this._getFormatConfig(inst)));
1393 var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
1394 '<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_' + dpuuid +
1395 '.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
1396 ' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
1397 (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>'));
1398 var nextText = this._get(inst, 'nextText');
1399 nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
1400 this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
1401 this._getFormatConfig(inst)));
1402 var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
1403 '<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_' + dpuuid +
1404 '.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
1405 ' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
1406 (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>'));
1407 var currentText = this._get(inst, 'currentText');
1408 var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
1409 currentText = (!navigationAsDateFormat ? currentText :
1410 this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
1411 var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_' + dpuuid +
1412 '.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : '');
1413 var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
1414 (this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_' + dpuuid +
1415 '.datepicker._gotoToday(\'#' + inst.id + '\');"' +
1416 '>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
1417 var firstDay = parseInt(this._get(inst, 'firstDay'),10);
1418 firstDay = (isNaN(firstDay) ? 0 : firstDay);
1419 var showWeek = this._get(inst, 'showWeek');
1420 var dayNames = this._get(inst, 'dayNames');
1421 var dayNamesShort = this._get(inst, 'dayNamesShort');
1422 var dayNamesMin = this._get(inst, 'dayNamesMin');
1423 var monthNames = this._get(inst, 'monthNames');
1424 var monthNamesShort = this._get(inst, 'monthNamesShort');
1425 var beforeShowDay = this._get(inst, 'beforeShowDay');
1426 var showOtherMonths = this._get(inst, 'showOtherMonths');
1427 var selectOtherMonths = this._get(inst, 'selectOtherMonths');
1428 var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
1429 var defaultDate = this._getDefaultDate(inst);
1431 for (var row = 0; row < numMonths[0]; row++) {
1433 for (var col = 0; col < numMonths[1]; col++) {
1434 var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
1435 var cornerClass = ' ui-corner-all';
1438 calender += '<div class="ui-datepicker-group';
1439 if (numMonths[1] > 1)
1441 case 0: calender += ' ui-datepicker-group-first';
1442 cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
1443 case numMonths[1]-1: calender += ' ui-datepicker-group-last';
1444 cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
1445 default: calender += ' ui-datepicker-group-middle'; cornerClass = ''; break;
1449 calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
1450 (/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
1451 (/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
1452 this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
1453 row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
1454 '</div><table class="ui-datepicker-calendar"><thead>' +
1456 var thead = (showWeek ? '<th class="ui-datepicker-week-col">' + this._get(inst, 'weekHeader') + '</th>' : '');
1457 for (var dow = 0; dow < 7; dow++) { // days of the week
1458 var day = (dow + firstDay) % 7;
1459 thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
1460 '<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
1462 calender += thead + '</tr></thead><tbody>';
1463 var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
1464 if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
1465 inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
1466 var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
1467 var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
1468 var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
1469 for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
1471 var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' +
1472 this._get(inst, 'calculateWeek')(printDate) + '</td>');
1473 for (var dow = 0; dow < 7; dow++) { // create date picker days
1474 var daySettings = (beforeShowDay ?
1475 beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
1476 var otherMonth = (printDate.getMonth() != drawMonth);
1477 var unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
1478 (minDate && printDate < minDate) || (maxDate && printDate > maxDate);
1479 tbody += '<td class="' +
1480 ((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
1481 (otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
1482 ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
1483 (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
1484 // or defaultDate is current printedDate and defaultDate is selectedDate
1485 ' ' + this._dayOverClass : '') + // highlight selected day
1486 (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') + // highlight unselectable days
1487 (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
1488 (printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day
1489 (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
1490 ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
1491 (unselectable ? '' : ' onclick="DP_jQuery_' + dpuuid + '.datepicker._selectDay(\'#' +
1492 inst.id + '\',' + printDate.getMonth() + ',' + printDate.getFullYear() + ', this);return false;"') + '>' + // actions
1493 (otherMonth && !showOtherMonths ? ' ' : // display for other months
1494 (unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
1495 (printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
1496 (printDate.getTime() == selectedDate.getTime() ? ' ui-state-active' : '') + // highlight selected day
1497 (otherMonth ? ' ui-priority-secondary' : '') + // distinguish dates from other months
1498 '" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display selectable date
1499 printDate.setDate(printDate.getDate() + 1);
1500 printDate = this._daylightSavingAdjust(printDate);
1502 calender += tbody + '</tr>';
1505 if (drawMonth > 11) {
1509 calender += '</tbody></table>' + (isMultiMonth ? '</div>' +
1510 ((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
1515 html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
1516 '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
1517 inst._keyEvent = false;
1521 /* Generate the month and year header. */
1522 _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
1523 secondary, monthNames, monthNamesShort) {
1524 var changeMonth = this._get(inst, 'changeMonth');
1525 var changeYear = this._get(inst, 'changeYear');
1526 var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
1527 var html = '<div class="ui-datepicker-title">';
1530 if (secondary || !changeMonth)
1531 monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>';
1533 var inMinYear = (minDate && minDate.getFullYear() == drawYear);
1534 var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
1535 monthHtml += '<select class="ui-datepicker-month" ' +
1536 'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' +
1537 'onclick="DP_jQuery_' + dpuuid + '.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
1539 for (var month = 0; month < 12; month++) {
1540 if ((!inMinYear || month >= minDate.getMonth()) &&
1541 (!inMaxYear || month <= maxDate.getMonth()))
1542 monthHtml += '<option value="' + month + '"' +
1543 (month == drawMonth ? ' selected="selected"' : '') +
1544 '>' + monthNamesShort[month] + '</option>';
1546 monthHtml += '</select>';
1548 if (!showMonthAfterYear)
1549 html += monthHtml + (secondary || !(changeMonth && changeYear) ? ' ' : '');
1551 if (secondary || !changeYear)
1552 html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
1554 // determine range of years to display
1555 var years = this._get(inst, 'yearRange').split(':');
1556 var thisYear = new Date().getFullYear();
1557 var determineYear = function(value) {
1558 var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) :
1559 (value.match(/[+-].*/) ? thisYear + parseInt(value, 10) :
1560 parseInt(value, 10)));
1561 return (isNaN(year) ? thisYear : year);
1563 var year = determineYear(years[0]);
1564 var endYear = Math.max(year, determineYear(years[1] || ''));
1565 year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
1566 endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
1567 html += '<select class="ui-datepicker-year" ' +
1568 'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
1569 'onclick="DP_jQuery_' + dpuuid + '.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
1571 for (; year <= endYear; year++) {
1572 html += '<option value="' + year + '"' +
1573 (year == drawYear ? ' selected="selected"' : '') +
1574 '>' + year + '</option>';
1576 html += '</select>';
1578 html += this._get(inst, 'yearSuffix');
1579 if (showMonthAfterYear)
1580 html += (secondary || !(changeMonth && changeYear) ? ' ' : '') + monthHtml;
1581 html += '</div>'; // Close datepicker_header
1585 /* Adjust one of the date sub-fields. */
1586 _adjustInstDate: function(inst, offset, period) {
1587 var year = inst.drawYear + (period == 'Y' ? offset : 0);
1588 var month = inst.drawMonth + (period == 'M' ? offset : 0);
1589 var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
1590 (period == 'D' ? offset : 0);
1591 var date = this._restrictMinMax(inst,
1592 this._daylightSavingAdjust(new Date(year, month, day)));
1593 inst.selectedDay = date.getDate();
1594 inst.drawMonth = inst.selectedMonth = date.getMonth();
1595 inst.drawYear = inst.selectedYear = date.getFullYear();
1596 if (period == 'M' || period == 'Y')
1597 this._notifyChange(inst);
1600 /* Ensure a date is within any min/max bounds. */
1601 _restrictMinMax: function(inst, date) {
1602 var minDate = this._getMinMaxDate(inst, 'min');
1603 var maxDate = this._getMinMaxDate(inst, 'max');
1604 date = (minDate && date < minDate ? minDate : date);
1605 date = (maxDate && date > maxDate ? maxDate : date);
1609 /* Notify change of month/year. */
1610 _notifyChange: function(inst) {
1611 var onChange = this._get(inst, 'onChangeMonthYear');
1613 onChange.apply((inst.input ? inst.input[0] : null),
1614 [inst.selectedYear, inst.selectedMonth + 1, inst]);
1617 /* Determine the number of months to show. */
1618 _getNumberOfMonths: function(inst) {
1619 var numMonths = this._get(inst, 'numberOfMonths');
1620 return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
1623 /* Determine the current maximum date - ensure no time components are set. */
1624 _getMinMaxDate: function(inst, minMax) {
1625 return this._determineDate(inst, this._get(inst, minMax + 'Date'), null);
1628 /* Find the number of days in a given month. */
1629 _getDaysInMonth: function(year, month) {
1630 return 32 - new Date(year, month, 32).getDate();
1633 /* Find the day of the week of the first of a month. */
1634 _getFirstDayOfMonth: function(year, month) {
1635 return new Date(year, month, 1).getDay();
1638 /* Determines if we should allow a "next/prev" month display change. */
1639 _canAdjustMonth: function(inst, offset, curYear, curMonth) {
1640 var numMonths = this._getNumberOfMonths(inst);
1641 var date = this._daylightSavingAdjust(new Date(curYear,
1642 curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
1644 date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
1645 return this._isInRange(inst, date);
1648 /* Is the given date in the accepted range? */
1649 _isInRange: function(inst, date) {
1650 var minDate = this._getMinMaxDate(inst, 'min');
1651 var maxDate = this._getMinMaxDate(inst, 'max');
1652 return ((!minDate || date.getTime() >= minDate.getTime()) &&
1653 (!maxDate || date.getTime() <= maxDate.getTime()));
1656 /* Provide the configuration settings for formatting/parsing. */
1657 _getFormatConfig: function(inst) {
1658 var shortYearCutoff = this._get(inst, 'shortYearCutoff');
1659 shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
1660 new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
1661 return {shortYearCutoff: shortYearCutoff,
1662 dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
1663 monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
1666 /* Format the given date for display. */
1667 _formatDate: function(inst, day, month, year) {
1669 inst.currentDay = inst.selectedDay;
1670 inst.currentMonth = inst.selectedMonth;
1671 inst.currentYear = inst.selectedYear;
1673 var date = (day ? (typeof day == 'object' ? day :
1674 this._daylightSavingAdjust(new Date(year, month, day))) :
1675 this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
1676 return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
1680 /* jQuery extend now ignores nulls! */
1681 function extendRemove(target, props) {
1682 $.extend(target, props);
1683 for (var name in props)
1684 if (props[name] == null || props[name] == undefined)
1685 target[name] = props[name];
1689 /* Determine whether an object is an array. */
1690 function isArray(a) {
1691 return (a && (($.browser.safari && typeof a == 'object' && a.length) ||
1692 (a.constructor && a.constructor.toString().match(/\Array\(\)/))));
1695 /* Invoke the datepicker functionality.
1696 @param options string - a command, optionally followed by additional parameters or
1697 Object - settings for attaching new datepicker functionality
1698 @return jQuery object */
1699 $.fn.datepicker = function(options){
1701 /* Initialise the date picker. */
1702 if (!$.datepicker.initialized) {
1703 $(document).mousedown($.datepicker._checkExternalClick).
1704 find('body').append($.datepicker.dpDiv);
1705 $.datepicker.initialized = true;
1708 var otherArgs = Array.prototype.slice.call(arguments, 1);
1709 if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget'))
1710 return $.datepicker['_' + options + 'Datepicker'].
1711 apply($.datepicker, [this[0]].concat(otherArgs));
1712 if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string')
1713 return $.datepicker['_' + options + 'Datepicker'].
1714 apply($.datepicker, [this[0]].concat(otherArgs));
1715 return this.each(function() {
1716 typeof options == 'string' ?
1717 $.datepicker['_' + options + 'Datepicker'].
1718 apply($.datepicker, [this].concat(otherArgs)) :
1719 $.datepicker._attachDatepicker(this, options);
1723 $.datepicker = new Datepicker(); // singleton instance
1724 $.datepicker.initialized = false;
1725 $.datepicker.uuid = new Date().getTime();
1726 $.datepicker.version = "1.8.4";
1728 // Workaround for #4055
1729 // Add another global to avoid noConflict issues with inline event handlers
1730 window['DP_jQuery_' + dpuuid] = $;