Bug 20489 Configure illegal file characters https://bugzilla.wikimedia.org/show_bug...
[mediawiki.git] / js2 / mwEmbed / jquery / jquery.ui / ui / ui.datepicker.js
blobd3aa5c2b470dfa613949037747b41ad973115824
1 /*
2  * jQuery UI Datepicker 1.7.1
3  *
4  * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
5  * Dual licensed under the MIT (MIT-LICENSE.txt)
6  * and GPL (GPL-LICENSE.txt) licenses.
7  *
8  * http://docs.jquery.com/UI/Datepicker
9  *
10  * Depends:
11  *      ui.core.js
12  */
14 (function($) { // hide the namespace
16 $.extend($.ui, { datepicker: { version: "1.7.1" } });
18 var PROP_NAME = 'datepicker';
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                 dateFormat: 'mm/dd/yy', // See format options on parseDate
54                 firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
55                 isRTL: false // True if right-to-left language, false if left-to-right
56         };
57         this._defaults = { // Global defaults for all the date picker instances
58                 showOn: 'focus', // 'focus' for popup on focus,
59                         // 'button' for trigger button, or 'both' for either
60                 showAnim: 'show', // Name of jQuery animation for popup
61                 showOptions: {}, // Options for enhanced animations
62                 defaultDate: null, // Used when field is blank: actual date,
63                         // +/-number for offset from today, null for today
64                 appendText: '', // Display text following the input box, e.g. showing the format
65                 buttonText: '...', // Text for trigger button
66                 buttonImage: '', // URL for trigger button image
67                 buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
68                 hideIfNoPrevNext: false, // True to hide next/previous month links
69                         // if not applicable, false to just disable them
70                 navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
71                 gotoCurrent: false, // True if today link goes back to current selection instead
72                 changeMonth: false, // True if month can be selected directly, false if only prev/next
73                 changeYear: false, // True if year can be selected directly, false if only prev/next
74                 showMonthAfterYear: false, // True if the year select precedes month, false for month then year
75                 yearRange: '-10:+10', // Range of years to display in drop-down,
76                         // either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
77                 showOtherMonths: false, // True to show dates in other months, false to leave blank
78                 calculateWeek: this.iso8601Week, // How to calculate the week of the year,
79                         // takes a Date and returns the number of the week for it
80                 shortYearCutoff: '+10', // Short year values < this are in the current century,
81                         // > this are in the previous century,
82                         // string value starting with '+' for current year + value
83                 minDate: null, // The earliest selectable date, or null for no limit
84                 maxDate: null, // The latest selectable date, or null for no limit
85                 duration: 'normal', // Duration of display/closure
86                 beforeShowDay: null, // Function that takes a date and returns an array with
87                         // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
88                         // [2] = cell title (optional), e.g. $.datepicker.noWeekends
89                 beforeShow: null, // Function that takes an input field and
90                         // returns a set of custom settings for the date picker
91                 onSelect: null, // Define a callback function when a date is selected
92                 onChangeMonthYear: null, // Define a callback function when the month or year is changed
93                 onClose: null, // Define a callback function when the datepicker is closed
94                 numberOfMonths: 1, // Number of months to show at a time
95                 showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
96                 stepMonths: 1, // Number of months to step back/forward
97                 stepBigMonths: 12, // Number of months to step back/forward for the big links
98                 altField: '', // Selector for an alternate field to store selected dates into
99                 altFormat: '', // The date format to use for the alternate field
100                 constrainInput: true, // The input is constrained by the current date format
101                 showButtonPanel: false // True to show button panel, false to not show it
102         };
103         $.extend(this._defaults, this.regional['']);
104         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>');
107 $.extend(Datepicker.prototype, {
108         /* Class name added to elements to indicate already configured with a date picker. */
109         markerClassName: 'hasDatepicker',
111         /* Debug logging (if enabled). */
112         log: function () {
113                 if (this.debug)
114                         console.log.apply('', arguments);
115         },
117         /* Override the default settings for all instances of the date picker.
118            @param  settings  object - the new settings to use as defaults (anonymous object)
119            @return the manager object */
120         setDefaults: function(settings) {
121                 extendRemove(this._defaults, settings || {});
122                 return this;
123         },
125         /* Attach the date picker to a jQuery selection.
126            @param  target    element - the target input field or division or span
127            @param  settings  object - the new settings to use for this date picker instance (anonymous) */
128         _attachDatepicker: function(target, settings) {
129                 // check for settings on the control itself - in namespace 'date:'
130                 var inlineSettings = null;
131                 for (var attrName in this._defaults) {
132                         var attrValue = target.getAttribute('date:' + attrName);
133                         if (attrValue) {
134                                 inlineSettings = inlineSettings || {};
135                                 try {
136                                         inlineSettings[attrName] = eval(attrValue);
137                                 } catch (err) {
138                                         inlineSettings[attrName] = attrValue;
139                                 }
140                         }
141                 }
142                 var nodeName = target.nodeName.toLowerCase();
143                 var inline = (nodeName == 'div' || nodeName == 'span');
144                 if (!target.id)
145                         target.id = 'dp' + (++this.uuid);
146                 var inst = this._newInst($(target), inline);
147                 inst.settings = $.extend({}, settings || {}, inlineSettings || {});
148                 if (nodeName == 'input') {
149                         this._connectDatepicker(target, inst);
150                 } else if (inline) {
151                         this._inlineDatepicker(target, inst);
152                 }
153         },
155         /* Create a new instance object. */
156         _newInst: function(target, inline) {
157                 var id = target[0].id.replace(/([:\[\]\.])/g, '\\\\$1'); // escape jQuery meta chars
158                 return {id: id, input: target, // associated target
159                         selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
160                         drawMonth: 0, drawYear: 0, // month being drawn
161                         inline: inline, // is datepicker inline or not
162                         dpDiv: (!inline ? this.dpDiv : // presentation div
163                         $('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))};
164         },
166         /* Attach the date picker to an input field. */
167         _connectDatepicker: function(target, inst) {
168                 var input = $(target);
169                 inst.trigger = $([]);
170                 if (input.hasClass(this.markerClassName))
171                         return;
172                 var appendText = this._get(inst, 'appendText');
173                 var isRTL = this._get(inst, 'isRTL');
174                 if (appendText)
175                         input[isRTL ? 'before' : 'after']('<span class="' + this._appendClass + '">' + appendText + '</span>');
176                 var showOn = this._get(inst, 'showOn');
177                 if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
178                         input.focus(this._showDatepicker);
179                 if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
180                         var buttonText = this._get(inst, 'buttonText');
181                         var buttonImage = this._get(inst, 'buttonImage');
182                         inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
183                                 $('<img/>').addClass(this._triggerClass).
184                                         attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
185                                 $('<button type="button"></button>').addClass(this._triggerClass).
186                                         html(buttonImage == '' ? buttonText : $('<img/>').attr(
187                                         { src:buttonImage, alt:buttonText, title:buttonText })));
188                         input[isRTL ? 'before' : 'after'](inst.trigger);
189                         inst.trigger.click(function() {
190                                 if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target)
191                                         $.datepicker._hideDatepicker();
192                                 else
193                                         $.datepicker._showDatepicker(target);
194                                 return false;
195                         });
196                 }
197                 input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).
198                         bind("setData.datepicker", function(event, key, value) {
199                                 inst.settings[key] = value;
200                         }).bind("getData.datepicker", function(event, key) {
201                                 return this._get(inst, key);
202                         });
203                 $.data(target, PROP_NAME, inst);
204         },
206         /* Attach an inline date picker to a div. */
207         _inlineDatepicker: function(target, inst) {
208                 var divSpan = $(target);
209                 if (divSpan.hasClass(this.markerClassName))
210                         return;
211                 divSpan.addClass(this.markerClassName).append(inst.dpDiv).
212                         bind("setData.datepicker", function(event, key, value){
213                                 inst.settings[key] = value;
214                         }).bind("getData.datepicker", function(event, key){
215                                 return this._get(inst, key);
216                         });
217                 $.data(target, PROP_NAME, inst);
218                 this._setDate(inst, this._getDefaultDate(inst));
219                 this._updateDatepicker(inst);
220                 this._updateAlternate(inst);
221         },
223         /* Pop-up the date picker in a "dialog" box.
224            @param  input     element - ignored
225            @param  dateText  string - the initial date to display (in the current format)
226            @param  onSelect  function - the function(dateText) to call when a date is selected
227            @param  settings  object - update the dialog date picker instance's settings (anonymous object)
228            @param  pos       int[2] - coordinates for the dialog's position within the screen or
229                              event - with x/y coordinates or
230                              leave empty for default (screen centre)
231            @return the manager object */
232         _dialogDatepicker: function(input, dateText, onSelect, settings, pos) {
233                 var inst = this._dialogInst; // internal instance
234                 if (!inst) {
235                         var id = 'dp' + (++this.uuid);
236                         this._dialogInput = $('<input type="text" id="' + id +
237                                 '" size="1" style="position: absolute; top: -100px;"/>');
238                         this._dialogInput.keydown(this._doKeyDown);
239                         $('body').append(this._dialogInput);
240                         inst = this._dialogInst = this._newInst(this._dialogInput, false);
241                         inst.settings = {};
242                         $.data(this._dialogInput[0], PROP_NAME, inst);
243                 }
244                 extendRemove(inst.settings, settings || {});
245                 this._dialogInput.val(dateText);
247                 this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
248                 if (!this._pos) {
249                         var browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
250                         var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
251                         var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
252                         var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
253                         this._pos = // should use actual width/height below
254                                 [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
255                 }
257                 // move input on screen for focus, but hidden behind dialog
258                 this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px');
259                 inst.settings.onSelect = onSelect;
260                 this._inDialog = true;
261                 this.dpDiv.addClass(this._dialogClass);
262                 this._showDatepicker(this._dialogInput[0]);
263                 if ($.blockUI)
264                         $.blockUI(this.dpDiv);
265                 $.data(this._dialogInput[0], PROP_NAME, inst);
266                 return this;
267         },
269         /* Detach a datepicker from its control.
270            @param  target    element - the target input field or division or span */
271         _destroyDatepicker: function(target) {
272                 var $target = $(target);
273                 var inst = $.data(target, PROP_NAME);
274                 if (!$target.hasClass(this.markerClassName)) {
275                         return;
276                 }
277                 var nodeName = target.nodeName.toLowerCase();
278                 $.removeData(target, PROP_NAME);
279                 if (nodeName == 'input') {
280                         inst.trigger.remove();
281                         $target.siblings('.' + this._appendClass).remove().end().
282                                 removeClass(this.markerClassName).
283                                 unbind('focus', this._showDatepicker).
284                                 unbind('keydown', this._doKeyDown).
285                                 unbind('keypress', this._doKeyPress);
286                 } else if (nodeName == 'div' || nodeName == 'span')
287                         $target.removeClass(this.markerClassName).empty();
288         },
290         /* Enable the date picker to a jQuery selection.
291            @param  target    element - the target input field or division or span */
292         _enableDatepicker: function(target) {
293                 var $target = $(target);
294                 var inst = $.data(target, PROP_NAME);
295                 if (!$target.hasClass(this.markerClassName)) {
296                         return;
297                 }
298                 var nodeName = target.nodeName.toLowerCase();
299                 if (nodeName == 'input') {
300                 target.disabled = false;
301                         inst.trigger.filter("button").
302                         each(function() { this.disabled = false; }).end().
303                                 filter("img").
304                                 css({opacity: '1.0', cursor: ''});
305                 }
306                 else if (nodeName == 'div' || nodeName == 'span') {
307                         var inline = $target.children('.' + this._inlineClass);
308                         inline.children().removeClass('ui-state-disabled');
309                 }
310                 this._disabledInputs = $.map(this._disabledInputs,
311                         function(value) { return (value == target ? null : value); }); // delete entry
312         },
314         /* Disable the date picker to a jQuery selection.
315            @param  target    element - the target input field or division or span */
316         _disableDatepicker: function(target) {
317                 var $target = $(target);
318                 var inst = $.data(target, PROP_NAME);
319                 if (!$target.hasClass(this.markerClassName)) {
320                         return;
321                 }
322                 var nodeName = target.nodeName.toLowerCase();
323                 if (nodeName == 'input') {
324                 target.disabled = true;
325                         inst.trigger.filter("button").
326                         each(function() { this.disabled = true; }).end().
327                                 filter("img").
328                                 css({opacity: '0.5', cursor: 'default'});
329                 }
330                 else if (nodeName == 'div' || nodeName == 'span') {
331                         var inline = $target.children('.' + this._inlineClass);
332                         inline.children().addClass('ui-state-disabled');
333                 }
334                 this._disabledInputs = $.map(this._disabledInputs,
335                         function(value) { return (value == target ? null : value); }); // delete entry
336                 this._disabledInputs[this._disabledInputs.length] = target;
337         },
339         /* Is the first field in a jQuery collection disabled as a datepicker?
340            @param  target    element - the target input field or division or span
341            @return boolean - true if disabled, false if enabled */
342         _isDisabledDatepicker: function(target) {
343                 if (!target) {
344                         return false;
345                 }
346                 for (var i = 0; i < this._disabledInputs.length; i++) {
347                         if (this._disabledInputs[i] == target)
348                                 return true;
349                 }
350                 return false;
351         },
353         /* Retrieve the instance data for the target control.
354            @param  target  element - the target input field or division or span
355            @return  object - the associated instance data
356            @throws  error if a jQuery problem getting data */
357         _getInst: function(target) {
358                 try {
359                         return $.data(target, PROP_NAME);
360                 }
361                 catch (err) {
362                         throw 'Missing instance data for this datepicker';
363                 }
364         },
366         /* Update the settings for a date picker attached to an input field or division.
367            @param  target  element - the target input field or division or span
368            @param  name    object - the new settings to update or
369                            string - the name of the setting to change or
370            @param  value   any - the new value for the setting (omit if above is an object) */
371         _optionDatepicker: function(target, name, value) {
372                 var settings = name || {};
373                 if (typeof name == 'string') {
374                         settings = {};
375                         settings[name] = value;
376                 }
377                 var inst = this._getInst(target);
378                 if (inst) {
379                         if (this._curInst == inst) {
380                                 this._hideDatepicker(null);
381                         }
382                         extendRemove(inst.settings, settings);
383                         var date = new Date();
384                         extendRemove(inst, {rangeStart: null, // start of range
385                                 endDay: null, endMonth: null, endYear: null, // end of range
386                                 selectedDay: date.getDate(), selectedMonth: date.getMonth(),
387                                 selectedYear: date.getFullYear(), // starting point
388                                 currentDay: date.getDate(), currentMonth: date.getMonth(),
389                                 currentYear: date.getFullYear(), // current selection
390                                 drawMonth: date.getMonth(), drawYear: date.getFullYear()}); // month being drawn
391                         this._updateDatepicker(inst);
392                 }
393         },
395         // change method deprecated
396         _changeDatepicker: function(target, name, value) {
397                 this._optionDatepicker(target, name, value);
398         },
400         /* Redraw the date picker attached to an input field or division.
401            @param  target  element - the target input field or division or span */
402         _refreshDatepicker: function(target) {
403                 var inst = this._getInst(target);
404                 if (inst) {
405                         this._updateDatepicker(inst);
406                 }
407         },
409         /* Set the dates for a jQuery selection.
410            @param  target   element - the target input field or division or span
411            @param  date     Date - the new date
412            @param  endDate  Date - the new end date for a range (optional) */
413         _setDateDatepicker: function(target, date, endDate) {
414                 var inst = this._getInst(target);
415                 if (inst) {
416                         this._setDate(inst, date, endDate);
417                         this._updateDatepicker(inst);
418                         this._updateAlternate(inst);
419                 }
420         },
422         /* Get the date(s) for the first entry in a jQuery selection.
423            @param  target  element - the target input field or division or span
424            @return Date - the current date or
425                    Date[2] - the current dates for a range */
426         _getDateDatepicker: function(target) {
427                 var inst = this._getInst(target);
428                 if (inst && !inst.inline)
429                         this._setDateFromField(inst);
430                 return (inst ? this._getDate(inst) : null);
431         },
433         /* Handle keystrokes. */
434         _doKeyDown: function(event) {
435                 var inst = $.datepicker._getInst(event.target);
436                 var handled = true;
437                 var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
438                 inst._keyEvent = true;
439                 if ($.datepicker._datepickerShowing)
440                         switch (event.keyCode) {
441                                 case 9:  $.datepicker._hideDatepicker(null, '');
442                                                 break; // hide on tab out
443                                 case 13: var sel = $('td.' + $.datepicker._dayOverClass +
444                                                         ', td.' + $.datepicker._currentClass, inst.dpDiv);
445                                                 if (sel[0])
446                                                         $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
447                                                 else
448                                                         $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
449                                                 return false; // don't submit the form
450                                                 break; // select the value on enter
451                                 case 27: $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
452                                                 break; // hide on escape
453                                 case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
454                                                         -$.datepicker._get(inst, 'stepBigMonths') :
455                                                         -$.datepicker._get(inst, 'stepMonths')), 'M');
456                                                 break; // previous month/year on page up/+ ctrl
457                                 case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
458                                                         +$.datepicker._get(inst, 'stepBigMonths') :
459                                                         +$.datepicker._get(inst, 'stepMonths')), 'M');
460                                                 break; // next month/year on page down/+ ctrl
461                                 case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
462                                                 handled = event.ctrlKey || event.metaKey;
463                                                 break; // clear on ctrl or command +end
464                                 case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
465                                                 handled = event.ctrlKey || event.metaKey;
466                                                 break; // current on ctrl or command +home
467                                 case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
468                                                 handled = event.ctrlKey || event.metaKey;
469                                                 // -1 day on ctrl or command +left
470                                                 if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
471                                                                         -$.datepicker._get(inst, 'stepBigMonths') :
472                                                                         -$.datepicker._get(inst, 'stepMonths')), 'M');
473                                                 // next month/year on alt +left on Mac
474                                                 break;
475                                 case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
476                                                 handled = event.ctrlKey || event.metaKey;
477                                                 break; // -1 week on ctrl or command +up
478                                 case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
479                                                 handled = event.ctrlKey || event.metaKey;
480                                                 // +1 day on ctrl or command +right
481                                                 if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
482                                                                         +$.datepicker._get(inst, 'stepBigMonths') :
483                                                                         +$.datepicker._get(inst, 'stepMonths')), 'M');
484                                                 // next month/year on alt +right
485                                                 break;
486                                 case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
487                                                 handled = event.ctrlKey || event.metaKey;
488                                                 break; // +1 week on ctrl or command +down
489                                 default: handled = false;
490                         }
491                 else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
492                         $.datepicker._showDatepicker(this);
493                 else {
494                         handled = false;
495                 }
496                 if (handled) {
497                         event.preventDefault();
498                         event.stopPropagation();
499                 }
500         },
502         /* Filter entered characters - based on date format. */
503         _doKeyPress: function(event) {
504                 var inst = $.datepicker._getInst(event.target);
505                 if ($.datepicker._get(inst, 'constrainInput')) {
506                         var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
507                         var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
508                         return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
509                 }
510         },
512         /* Pop-up the date picker for a given input field.
513            @param  input  element - the input field attached to the date picker or
514                           event - if triggered by focus */
515         _showDatepicker: function(input) {
516                 input = input.target || input;
517                 if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
518                         input = $('input', input.parentNode)[0];
519                 if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
520                         return;
521                 var inst = $.datepicker._getInst(input);
522                 var beforeShow = $.datepicker._get(inst, 'beforeShow');
523                 extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
524                 $.datepicker._hideDatepicker(null, '');
525                 $.datepicker._lastInput = input;
526                 $.datepicker._setDateFromField(inst);
527                 if ($.datepicker._inDialog) // hide cursor
528                         input.value = '';
529                 if (!$.datepicker._pos) { // position below input
530                         $.datepicker._pos = $.datepicker._findPos(input);
531                         $.datepicker._pos[1] += input.offsetHeight; // add the height
532                 }
533                 var isFixed = false;
534                 $(input).parents().each(function() {
535                         isFixed |= $(this).css('position') == 'fixed';
536                         return !isFixed;
537                 });
538                 if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
539                         $.datepicker._pos[0] -= document.documentElement.scrollLeft;
540                         $.datepicker._pos[1] -= document.documentElement.scrollTop;
541                 }
542                 var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
543                 $.datepicker._pos = null;
544                 inst.rangeStart = null;
545                 // determine sizing offscreen
546                 inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
547                 $.datepicker._updateDatepicker(inst);
548                 // fix width for dynamic number of date pickers
549                 // and adjust position before showing
550                 offset = $.datepicker._checkOffset(inst, offset, isFixed);
551                 inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
552                         'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
553                         left: offset.left + 'px', top: offset.top + 'px'});
554                 if (!inst.inline) {
555                         var showAnim = $.datepicker._get(inst, 'showAnim') || 'show';
556                         var duration = $.datepicker._get(inst, 'duration');
557                         var postProcess = function() {
558                                 $.datepicker._datepickerShowing = true;
559                                 if ($.browser.msie && parseInt($.browser.version,10) < 7) // fix IE < 7 select problems
560                                         $('iframe.ui-datepicker-cover').css({width: inst.dpDiv.width() + 4,
561                                                 height: inst.dpDiv.height() + 4});
562                         };
563                         if ($.effects && $.effects[showAnim])
564                                 inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
565                         else
566                                 inst.dpDiv[showAnim](duration, postProcess);
567                         if (duration == '')
568                                 postProcess();
569                         if (inst.input[0].type != 'hidden')
570                                 inst.input[0].focus();
571                         $.datepicker._curInst = inst;
572                 }
573         },
575         /* Generate the date picker content. */
576         _updateDatepicker: function(inst) {
577                 var dims = {width: inst.dpDiv.width() + 4,
578                         height: inst.dpDiv.height() + 4};
579                 var self = this;
580                 inst.dpDiv.empty().append(this._generateHTML(inst))
581                         .find('iframe.ui-datepicker-cover').
582                                 css({width: dims.width, height: dims.height})
583                         .end()
584                         .find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a')
585                                 .bind('mouseout', function(){
586                                         $(this).removeClass('ui-state-hover');
587                                         if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover');
588                                         if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover');
589                                 })
590                                 .bind('mouseover', function(){
591                                         if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) {
592                                                 $(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
593                                                 $(this).addClass('ui-state-hover');
594                                                 if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover');
595                                                 if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover');
596                                         }
597                                 })
598                         .end()
599                         .find('.' + this._dayOverClass + ' a')
600                                 .trigger('mouseover')
601                         .end();
602                 var numMonths = this._getNumberOfMonths(inst);
603                 var cols = numMonths[1];
604                 var width = 17;
605                 if (cols > 1) {
606                         inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
607                 } else {
608                         inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
609                 }
610                 inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
611                         'Class']('ui-datepicker-multi');
612                 inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
613                         'Class']('ui-datepicker-rtl');
614                 if (inst.input && inst.input[0].type != 'hidden' && inst == $.datepicker._curInst)
615                         $(inst.input[0]).focus();
616         },
618         /* Check positioning to remain on screen. */
619         _checkOffset: function(inst, offset, isFixed) {
620                 var dpWidth = inst.dpDiv.outerWidth();
621                 var dpHeight = inst.dpDiv.outerHeight();
622                 var inputWidth = inst.input ? inst.input.outerWidth() : 0;
623                 var inputHeight = inst.input ? inst.input.outerHeight() : 0;
624                 var viewWidth = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) + $(document).scrollLeft();
625                 var viewHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) + $(document).scrollTop();
627                 offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
628                 offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
629                 offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
631                 // now check if datepicker is showing outside window viewport - move to a better place if so.
632                 offset.left -= (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0;
633                 offset.top -= (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(offset.top + dpHeight + inputHeight*2 - viewHeight) : 0;
635                 return offset;
636         },
638         /* Find an object's position on the screen. */
639         _findPos: function(obj) {
640         while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
641             obj = obj.nextSibling;
642         }
643         var position = $(obj).offset();
644             return [position.left, position.top];
645         },
647         /* Hide the date picker from view.
648            @param  input  element - the input field attached to the date picker
649            @param  duration  string - the duration over which to close the date picker */
650         _hideDatepicker: function(input, duration) {
651                 var inst = this._curInst;
652                 if (!inst || (input && inst != $.data(input, PROP_NAME)))
653                         return;
654                 if (inst.stayOpen)
655                         this._selectDate('#' + inst.id, this._formatDate(inst,
656                                 inst.currentDay, inst.currentMonth, inst.currentYear));
657                 inst.stayOpen = false;
658                 if (this._datepickerShowing) {
659                         duration = (duration != null ? duration : this._get(inst, 'duration'));
660                         var showAnim = this._get(inst, 'showAnim');
661                         var postProcess = function() {
662                                 $.datepicker._tidyDialog(inst);
663                         };
664                         if (duration != '' && $.effects && $.effects[showAnim])
665                                 inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'),
666                                         duration, postProcess);
667                         else
668                                 inst.dpDiv[(duration == '' ? 'hide' : (showAnim == 'slideDown' ? 'slideUp' :
669                                         (showAnim == 'fadeIn' ? 'fadeOut' : 'hide')))](duration, postProcess);
670                         if (duration == '')
671                                 this._tidyDialog(inst);
672                         var onClose = this._get(inst, 'onClose');
673                         if (onClose)
674                                 onClose.apply((inst.input ? inst.input[0] : null),
675                                         [(inst.input ? inst.input.val() : ''), inst]);  // trigger custom callback
676                         this._datepickerShowing = false;
677                         this._lastInput = null;
678                         if (this._inDialog) {
679                                 this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
680                                 if ($.blockUI) {
681                                         $.unblockUI();
682                                         $('body').append(this.dpDiv);
683                                 }
684                         }
685                         this._inDialog = false;
686                 }
687                 this._curInst = null;
688         },
690         /* Tidy up after a dialog display. */
691         _tidyDialog: function(inst) {
692                 inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
693         },
695         /* Close date picker if clicked elsewhere. */
696         _checkExternalClick: function(event) {
697                 if (!$.datepicker._curInst)
698                         return;
699                 var $target = $(event.target);
700                 if (($target.parents('#' + $.datepicker._mainDivId).length == 0) &&
701                                 !$target.hasClass($.datepicker.markerClassName) &&
702                                 !$target.hasClass($.datepicker._triggerClass) &&
703                                 $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))
704                         $.datepicker._hideDatepicker(null, '');
705         },
707         /* Adjust one of the date sub-fields. */
708         _adjustDate: function(id, offset, period) {
709                 var target = $(id);
710                 var inst = this._getInst(target[0]);
711                 if (this._isDisabledDatepicker(target[0])) {
712                         return;
713                 }
714                 this._adjustInstDate(inst, offset +
715                         (period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
716                         period);
717                 this._updateDatepicker(inst);
718         },
720         /* Action for current link. */
721         _gotoToday: function(id) {
722                 var target = $(id);
723                 var inst = this._getInst(target[0]);
724                 if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
725                         inst.selectedDay = inst.currentDay;
726                         inst.drawMonth = inst.selectedMonth = inst.currentMonth;
727                         inst.drawYear = inst.selectedYear = inst.currentYear;
728                 }
729                 else {
730                 var date = new Date();
731                 inst.selectedDay = date.getDate();
732                 inst.drawMonth = inst.selectedMonth = date.getMonth();
733                 inst.drawYear = inst.selectedYear = date.getFullYear();
734                 }
735                 this._notifyChange(inst);
736                 this._adjustDate(target);
737         },
739         /* Action for selecting a new month/year. */
740         _selectMonthYear: function(id, select, period) {
741                 var target = $(id);
742                 var inst = this._getInst(target[0]);
743                 inst._selectingMonthYear = false;
744                 inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
745                 inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
746                         parseInt(select.options[select.selectedIndex].value,10);
747                 this._notifyChange(inst);
748                 this._adjustDate(target);
749         },
751         /* Restore input focus after not changing month/year. */
752         _clickMonthYear: function(id) {
753                 var target = $(id);
754                 var inst = this._getInst(target[0]);
755                 if (inst.input && inst._selectingMonthYear && !$.browser.msie)
756                         inst.input[0].focus();
757                 inst._selectingMonthYear = !inst._selectingMonthYear;
758         },
760         /* Action for selecting a day. */
761         _selectDay: function(id, month, year, td) {
762                 var target = $(id);
763                 if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
764                         return;
765                 }
766                 var inst = this._getInst(target[0]);
767                 inst.selectedDay = inst.currentDay = $('a', td).html();
768                 inst.selectedMonth = inst.currentMonth = month;
769                 inst.selectedYear = inst.currentYear = year;
770                 if (inst.stayOpen) {
771                         inst.endDay = inst.endMonth = inst.endYear = null;
772                 }
773                 this._selectDate(id, this._formatDate(inst,
774                         inst.currentDay, inst.currentMonth, inst.currentYear));
775                 if (inst.stayOpen) {
776                         inst.rangeStart = this._daylightSavingAdjust(
777                                 new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
778                         this._updateDatepicker(inst);
779                 }
780         },
782         /* Erase the input field and hide the date picker. */
783         _clearDate: function(id) {
784                 var target = $(id);
785                 var inst = this._getInst(target[0]);
786                 inst.stayOpen = false;
787                 inst.endDay = inst.endMonth = inst.endYear = inst.rangeStart = null;
788                 this._selectDate(target, '');
789         },
791         /* Update the input field with the selected date. */
792         _selectDate: function(id, dateStr) {
793                 var target = $(id);
794                 var inst = this._getInst(target[0]);
795                 dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
796                 if (inst.input)
797                         inst.input.val(dateStr);
798                 this._updateAlternate(inst);
799                 var onSelect = this._get(inst, 'onSelect');
800                 if (onSelect)
801                         onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
802                 else if (inst.input)
803                         inst.input.trigger('change'); // fire the change event
804                 if (inst.inline)
805                         this._updateDatepicker(inst);
806                 else if (!inst.stayOpen) {
807                         this._hideDatepicker(null, this._get(inst, 'duration'));
808                         this._lastInput = inst.input[0];
809                         if (typeof(inst.input[0]) != 'object')
810                                 inst.input[0].focus(); // restore focus
811                         this._lastInput = null;
812                 }
813         },
815         /* Update any alternate field to synchronise with the main field. */
816         _updateAlternate: function(inst) {
817                 var altField = this._get(inst, 'altField');
818                 if (altField) { // update alternate field too
819                         var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
820                         var date = this._getDate(inst);
821                         dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
822                         $(altField).each(function() { $(this).val(dateStr); });
823                 }
824         },
826         /* Set as beforeShowDay function to prevent selection of weekends.
827            @param  date  Date - the date to customise
828            @return [boolean, string] - is this date selectable?, what is its CSS class? */
829         noWeekends: function(date) {
830                 var day = date.getDay();
831                 return [(day > 0 && day < 6), ''];
832         },
834         /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
835            @param  date  Date - the date to get the week for
836            @return  number - the number of the week within the year that contains this date */
837         iso8601Week: function(date) {
838                 var checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
839                 var firstMon = new Date(checkDate.getFullYear(), 1 - 1, 4); // First week always contains 4 Jan
840                 var firstDay = firstMon.getDay() || 7; // Day of week: Mon = 1, ..., Sun = 7
841                 firstMon.setDate(firstMon.getDate() + 1 - firstDay); // Preceding Monday
842                 if (firstDay < 4 && checkDate < firstMon) { // Adjust first three days in year if necessary
843                         checkDate.setDate(checkDate.getDate() - 3); // Generate for previous year
844                         return $.datepicker.iso8601Week(checkDate);
845                 } else if (checkDate > new Date(checkDate.getFullYear(), 12 - 1, 28)) { // Check last three days in year
846                         firstDay = new Date(checkDate.getFullYear() + 1, 1 - 1, 4).getDay() || 7;
847                         if (firstDay > 4 && (checkDate.getDay() || 7) < firstDay - 3) { // Adjust if necessary
848                                 return 1;
849                         }
850                 }
851                 return Math.floor(((checkDate - firstMon) / 86400000) / 7) + 1; // Weeks to given date
852         },
854         /* Parse a string value into a date object.
855            See formatDate below for the possible formats.
857            @param  format    string - the expected format of the date
858            @param  value     string - the date in the above format
859            @param  settings  Object - attributes include:
860                              shortYearCutoff  number - the cutoff year for determining the century (optional)
861                              dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
862                              dayNames         string[7] - names of the days from Sunday (optional)
863                              monthNamesShort  string[12] - abbreviated names of the months (optional)
864                              monthNames       string[12] - names of the months (optional)
865            @return  Date - the extracted date value or null if value is blank */
866         parseDate: function (format, value, settings) {
867                 if (format == null || value == null)
868                         throw 'Invalid arguments';
869                 value = (typeof value == 'object' ? value.toString() : value + '');
870                 if (value == '')
871                         return null;
872                 var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
873                 var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
874                 var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
875                 var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
876                 var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
877                 var year = -1;
878                 var month = -1;
879                 var day = -1;
880                 var doy = -1;
881                 var literal = false;
882                 // Check whether a format character is doubled
883                 var lookAhead = function(match) {
884                         var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
885                         if (matches)
886                                 iFormat++;
887                         return matches;
888                 };
889                 // Extract a number from the string value
890                 var getNumber = function(match) {
891                         lookAhead(match);
892                         var origSize = (match == '@' ? 14 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2)));
893                         var size = origSize;
894                         var num = 0;
895                         while (size > 0 && iValue < value.length &&
896                                         value.charAt(iValue) >= '0' && value.charAt(iValue) <= '9') {
897                                 num = num * 10 + parseInt(value.charAt(iValue++),10);
898                                 size--;
899                         }
900                         if (size == origSize)
901                                 throw 'Missing number at position ' + iValue;
902                         return num;
903                 };
904                 // Extract a name from the string value and convert to an index
905                 var getName = function(match, shortNames, longNames) {
906                         var names = (lookAhead(match) ? longNames : shortNames);
907                         var size = 0;
908                         for (var j = 0; j < names.length; j++)
909                                 size = Math.max(size, names[j].length);
910                         var name = '';
911                         var iInit = iValue;
912                         while (size > 0 && iValue < value.length) {
913                                 name += value.charAt(iValue++);
914                                 for (var i = 0; i < names.length; i++)
915                                         if (name == names[i])
916                                                 return i + 1;
917                                 size--;
918                         }
919                         throw 'Unknown name at position ' + iInit;
920                 };
921                 // Confirm that a literal character matches the string value
922                 var checkLiteral = function() {
923                         if (value.charAt(iValue) != format.charAt(iFormat))
924                                 throw 'Unexpected literal at position ' + iValue;
925                         iValue++;
926                 };
927                 var iValue = 0;
928                 for (var iFormat = 0; iFormat < format.length; iFormat++) {
929                         if (literal)
930                                 if (format.charAt(iFormat) == "'" && !lookAhead("'"))
931                                         literal = false;
932                                 else
933                                         checkLiteral();
934                         else
935                                 switch (format.charAt(iFormat)) {
936                                         case 'd':
937                                                 day = getNumber('d');
938                                                 break;
939                                         case 'D':
940                                                 getName('D', dayNamesShort, dayNames);
941                                                 break;
942                                         case 'o':
943                                                 doy = getNumber('o');
944                                                 break;
945                                         case 'm':
946                                                 month = getNumber('m');
947                                                 break;
948                                         case 'M':
949                                                 month = getName('M', monthNamesShort, monthNames);
950                                                 break;
951                                         case 'y':
952                                                 year = getNumber('y');
953                                                 break;
954                                         case '@':
955                                                 var date = new Date(getNumber('@'));
956                                                 year = date.getFullYear();
957                                                 month = date.getMonth() + 1;
958                                                 day = date.getDate();
959                                                 break;
960                                         case "'":
961                                                 if (lookAhead("'"))
962                                                         checkLiteral();
963                                                 else
964                                                         literal = true;
965                                                 break;
966                                         default:
967                                                 checkLiteral();
968                                 }
969                 }
970                 if (year == -1)
971                         year = new Date().getFullYear();
972                 else if (year < 100)
973                         year += new Date().getFullYear() - new Date().getFullYear() % 100 +
974                                 (year <= shortYearCutoff ? 0 : -100);
975                 if (doy > -1) {
976                         month = 1;
977                         day = doy;
978                         do {
979                                 var dim = this._getDaysInMonth(year, month - 1);
980                                 if (day <= dim)
981                                         break;
982                                 month++;
983                                 day -= dim;
984                         } while (true);
985                 }
986                 var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
987                 if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
988                         throw 'Invalid date'; // E.g. 31/02/*
989                 return date;
990         },
992         /* Standard date formats. */
993         ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
994         COOKIE: 'D, dd M yy',
995         ISO_8601: 'yy-mm-dd',
996         RFC_822: 'D, d M y',
997         RFC_850: 'DD, dd-M-y',
998         RFC_1036: 'D, d M y',
999         RFC_1123: 'D, d M yy',
1000         RFC_2822: 'D, d M yy',
1001         RSS: 'D, d M y', // RFC 822
1002         TIMESTAMP: '@',
1003         W3C: 'yy-mm-dd', // ISO 8601
1005         /* Format a date object into a string value.
1006            The format can be combinations of the following:
1007            d  - day of month (no leading zero)
1008            dd - day of month (two digit)
1009            o  - day of year (no leading zeros)
1010            oo - day of year (three digit)
1011            D  - day name short
1012            DD - day name long
1013            m  - month of year (no leading zero)
1014            mm - month of year (two digit)
1015            M  - month name short
1016            MM - month name long
1017            y  - year (two digit)
1018            yy - year (four digit)
1019            @ - Unix timestamp (ms since 01/01/1970)
1020            '...' - literal text
1021            '' - single quote
1023            @param  format    string - the desired format of the date
1024            @param  date      Date - the date value to format
1025            @param  settings  Object - attributes include:
1026                              dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
1027                              dayNames         string[7] - names of the days from Sunday (optional)
1028                              monthNamesShort  string[12] - abbreviated names of the months (optional)
1029                              monthNames       string[12] - names of the months (optional)
1030            @return  string - the date in the above format */
1031         formatDate: function (format, date, settings) {
1032                 if (!date)
1033                         return '';
1034                 var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
1035                 var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
1036                 var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
1037                 var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
1038                 // Check whether a format character is doubled
1039                 var lookAhead = function(match) {
1040                         var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
1041                         if (matches)
1042                                 iFormat++;
1043                         return matches;
1044                 };
1045                 // Format a number, with leading zero if necessary
1046                 var formatNumber = function(match, value, len) {
1047                         var num = '' + value;
1048                         if (lookAhead(match))
1049                                 while (num.length < len)
1050                                         num = '0' + num;
1051                         return num;
1052                 };
1053                 // Format a name, short or long as requested
1054                 var formatName = function(match, value, shortNames, longNames) {
1055                         return (lookAhead(match) ? longNames[value] : shortNames[value]);
1056                 };
1057                 var output = '';
1058                 var literal = false;
1059                 if (date)
1060                         for (var iFormat = 0; iFormat < format.length; iFormat++) {
1061                                 if (literal)
1062                                         if (format.charAt(iFormat) == "'" && !lookAhead("'"))
1063                                                 literal = false;
1064                                         else
1065                                                 output += format.charAt(iFormat);
1066                                 else
1067                                         switch (format.charAt(iFormat)) {
1068                                                 case 'd':
1069                                                         output += formatNumber('d', date.getDate(), 2);
1070                                                         break;
1071                                                 case 'D':
1072                                                         output += formatName('D', date.getDay(), dayNamesShort, dayNames);
1073                                                         break;
1074                                                 case 'o':
1075                                                         var doy = date.getDate();
1076                                                         for (var m = date.getMonth() - 1; m >= 0; m--)
1077                                                                 doy += this._getDaysInMonth(date.getFullYear(), m);
1078                                                         output += formatNumber('o', doy, 3);
1079                                                         break;
1080                                                 case 'm':
1081                                                         output += formatNumber('m', date.getMonth() + 1, 2);
1082                                                         break;
1083                                                 case 'M':
1084                                                         output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
1085                                                         break;
1086                                                 case 'y':
1087                                                         output += (lookAhead('y') ? date.getFullYear() :
1088                                                                 (date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
1089                                                         break;
1090                                                 case '@':
1091                                                         output += date.getTime();
1092                                                         break;
1093                                                 case "'":
1094                                                         if (lookAhead("'"))
1095                                                                 output += "'";
1096                                                         else
1097                                                                 literal = true;
1098                                                         break;
1099                                                 default:
1100                                                         output += format.charAt(iFormat);
1101                                         }
1102                         }
1103                 return output;
1104         },
1106         /* Extract all possible characters from the date format. */
1107         _possibleChars: function (format) {
1108                 var chars = '';
1109                 var literal = false;
1110                 for (var iFormat = 0; iFormat < format.length; iFormat++)
1111                         if (literal)
1112                                 if (format.charAt(iFormat) == "'" && !lookAhead("'"))
1113                                         literal = false;
1114                                 else
1115                                         chars += format.charAt(iFormat);
1116                         else
1117                                 switch (format.charAt(iFormat)) {
1118                                         case 'd': case 'm': case 'y': case '@':
1119                                                 chars += '0123456789';
1120                                                 break;
1121                                         case 'D': case 'M':
1122                                                 return null; // Accept anything
1123                                         case "'":
1124                                                 if (lookAhead("'"))
1125                                                         chars += "'";
1126                                                 else
1127                                                         literal = true;
1128                                                 break;
1129                                         default:
1130                                                 chars += format.charAt(iFormat);
1131                                 }
1132                 return chars;
1133         },
1135         /* Get a setting value, defaulting if necessary. */
1136         _get: function(inst, name) {
1137                 return inst.settings[name] !== undefined ?
1138                         inst.settings[name] : this._defaults[name];
1139         },
1141         /* Parse existing date and initialise date picker. */
1142         _setDateFromField: function(inst) {
1143                 var dateFormat = this._get(inst, 'dateFormat');
1144                 var dates = inst.input ? inst.input.val() : null;
1145                 inst.endDay = inst.endMonth = inst.endYear = null;
1146                 var date = defaultDate = this._getDefaultDate(inst);
1147                 var settings = this._getFormatConfig(inst);
1148                 try {
1149                         date = this.parseDate(dateFormat, dates, settings) || defaultDate;
1150                 } catch (event) {
1151                         this.log(event);
1152                         date = defaultDate;
1153                 }
1154                 inst.selectedDay = date.getDate();
1155                 inst.drawMonth = inst.selectedMonth = date.getMonth();
1156                 inst.drawYear = inst.selectedYear = date.getFullYear();
1157                 inst.currentDay = (dates ? date.getDate() : 0);
1158                 inst.currentMonth = (dates ? date.getMonth() : 0);
1159                 inst.currentYear = (dates ? date.getFullYear() : 0);
1160                 this._adjustInstDate(inst);
1161         },
1163         /* Retrieve the default date shown on opening. */
1164         _getDefaultDate: function(inst) {
1165                 var date = this._determineDate(this._get(inst, 'defaultDate'), new Date());
1166                 var minDate = this._getMinMaxDate(inst, 'min', true);
1167                 var maxDate = this._getMinMaxDate(inst, 'max');
1168                 date = (minDate && date < minDate ? minDate : date);
1169                 date = (maxDate && date > maxDate ? maxDate : date);
1170                 return date;
1171         },
1173         /* A date may be specified as an exact value or a relative one. */
1174         _determineDate: function(date, defaultDate) {
1175                 var offsetNumeric = function(offset) {
1176                         var date = new Date();
1177                         date.setDate(date.getDate() + offset);
1178                         return date;
1179                 };
1180                 var offsetString = function(offset, getDaysInMonth) {
1181                         var date = new Date();
1182                         var year = date.getFullYear();
1183                         var month = date.getMonth();
1184                         var day = date.getDate();
1185                         var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
1186                         var matches = pattern.exec(offset);
1187                         while (matches) {
1188                                 switch (matches[2] || 'd') {
1189                                         case 'd' : case 'D' :
1190                                                 day += parseInt(matches[1],10); break;
1191                                         case 'w' : case 'W' :
1192                                                 day += parseInt(matches[1],10) * 7; break;
1193                                         case 'm' : case 'M' :
1194                                                 month += parseInt(matches[1],10);
1195                                                 day = Math.min(day, getDaysInMonth(year, month));
1196                                                 break;
1197                                         case 'y': case 'Y' :
1198                                                 year += parseInt(matches[1],10);
1199                                                 day = Math.min(day, getDaysInMonth(year, month));
1200                                                 break;
1201                                 }
1202                                 matches = pattern.exec(offset);
1203                         }
1204                         return new Date(year, month, day);
1205                 };
1206                 date = (date == null ? defaultDate :
1207                         (typeof date == 'string' ? offsetString(date, this._getDaysInMonth) :
1208                         (typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date)));
1209                 date = (date && date.toString() == 'Invalid Date' ? defaultDate : date);
1210                 if (date) {
1211                         date.setHours(0);
1212                         date.setMinutes(0);
1213                         date.setSeconds(0);
1214                         date.setMilliseconds(0);
1215                 }
1216                 return this._daylightSavingAdjust(date);
1217         },
1219         /* Handle switch to/from daylight saving.
1220            Hours may be non-zero on daylight saving cut-over:
1221            > 12 when midnight changeover, but then cannot generate
1222            midnight datetime, so jump to 1AM, otherwise reset.
1223            @param  date  (Date) the date to check
1224            @return  (Date) the corrected date */
1225         _daylightSavingAdjust: function(date) {
1226                 if (!date) return null;
1227                 date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
1228                 return date;
1229         },
1231         /* Set the date(s) directly. */
1232         _setDate: function(inst, date, endDate) {
1233                 var clear = !(date);
1234                 var origMonth = inst.selectedMonth;
1235                 var origYear = inst.selectedYear;
1236                 date = this._determineDate(date, new Date());
1237                 inst.selectedDay = inst.currentDay = date.getDate();
1238                 inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth();
1239                 inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear();
1240                 if (origMonth != inst.selectedMonth || origYear != inst.selectedYear)
1241                         this._notifyChange(inst);
1242                 this._adjustInstDate(inst);
1243                 if (inst.input) {
1244                         inst.input.val(clear ? '' : this._formatDate(inst));
1245                 }
1246         },
1248         /* Retrieve the date(s) directly. */
1249         _getDate: function(inst) {
1250                 var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
1251                         this._daylightSavingAdjust(new Date(
1252                         inst.currentYear, inst.currentMonth, inst.currentDay)));
1253                         return startDate;
1254         },
1256         /* Generate the HTML for the current state of the date picker. */
1257         _generateHTML: function(inst) {
1258                 var today = new Date();
1259                 today = this._daylightSavingAdjust(
1260                         new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
1261                 var isRTL = this._get(inst, 'isRTL');
1262                 var showButtonPanel = this._get(inst, 'showButtonPanel');
1263                 var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
1264                 var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
1265                 var numMonths = this._getNumberOfMonths(inst);
1266                 var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
1267                 var stepMonths = this._get(inst, 'stepMonths');
1268                 var stepBigMonths = this._get(inst, 'stepBigMonths');
1269                 var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
1270                 var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
1271                         new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
1272                 var minDate = this._getMinMaxDate(inst, 'min', true);
1273                 var maxDate = this._getMinMaxDate(inst, 'max');
1274                 var drawMonth = inst.drawMonth - showCurrentAtPos;
1275                 var drawYear = inst.drawYear;
1276                 if (drawMonth < 0) {
1277                         drawMonth += 12;
1278                         drawYear--;
1279                 }
1280                 if (maxDate) {
1281                         var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
1282                                 maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate()));
1283                         maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
1284                         while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
1285                                 drawMonth--;
1286                                 if (drawMonth < 0) {
1287                                         drawMonth = 11;
1288                                         drawYear--;
1289                                 }
1290                         }
1291                 }
1292                 inst.drawMonth = drawMonth;
1293                 inst.drawYear = drawYear;
1294                 var prevText = this._get(inst, 'prevText');
1295                 prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
1296                         this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
1297                         this._getFormatConfig(inst)));
1298                 var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
1299                         '<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
1300                         ' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
1301                         (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>'));
1302                 var nextText = this._get(inst, 'nextText');
1303                 nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
1304                         this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
1305                         this._getFormatConfig(inst)));
1306                 var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
1307                         '<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
1308                         ' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
1309                         (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>'));
1310                 var currentText = this._get(inst, 'currentText');
1311                 var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
1312                 currentText = (!navigationAsDateFormat ? currentText :
1313                         this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
1314                 var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : '');
1315                 var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
1316                         (this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery.datepicker._gotoToday(\'#' + inst.id + '\');"' +
1317                         '>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
1318                 var firstDay = parseInt(this._get(inst, 'firstDay'),10);
1319                 firstDay = (isNaN(firstDay) ? 0 : firstDay);
1320                 var dayNames = this._get(inst, 'dayNames');
1321                 var dayNamesShort = this._get(inst, 'dayNamesShort');
1322                 var dayNamesMin = this._get(inst, 'dayNamesMin');
1323                 var monthNames = this._get(inst, 'monthNames');
1324                 var monthNamesShort = this._get(inst, 'monthNamesShort');
1325                 var beforeShowDay = this._get(inst, 'beforeShowDay');
1326                 var showOtherMonths = this._get(inst, 'showOtherMonths');
1327                 var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
1328                 var endDate = inst.endDay ? this._daylightSavingAdjust(
1329                         new Date(inst.endYear, inst.endMonth, inst.endDay)) : currentDate;
1330                 var defaultDate = this._getDefaultDate(inst);
1331                 var html = '';
1332                 for (var row = 0; row < numMonths[0]; row++) {
1333                         var group = '';
1334                         for (var col = 0; col < numMonths[1]; col++) {
1335                                 var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
1336                                 var cornerClass = ' ui-corner-all';
1337                                 var calender = '';
1338                                 if (isMultiMonth) {
1339                                         calender += '<div class="ui-datepicker-group ui-datepicker-group-';
1340                                         switch (col) {
1341                                                 case 0: calender += 'first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
1342                                                 case numMonths[1]-1: calender += 'last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
1343                                                 default: calender += 'middle'; cornerClass = ''; break;
1344                                         }
1345                                         calender += '">';
1346                                 }
1347                                 calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
1348                                         (/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
1349                                         (/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
1350                                         this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
1351                                         selectedDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
1352                                         '</div><table class="ui-datepicker-calendar"><thead>' +
1353                                         '<tr>';
1354                                 var thead = '';
1355                                 for (var dow = 0; dow < 7; dow++) { // days of the week
1356                                         var day = (dow + firstDay) % 7;
1357                                         thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
1358                                                 '<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
1359                                 }
1360                                 calender += thead + '</tr></thead><tbody>';
1361                                 var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
1362                                 if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
1363                                         inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
1364                                 var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
1365                                 var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
1366                                 var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
1367                                 for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
1368                                         calender += '<tr>';
1369                                         var tbody = '';
1370                                         for (var dow = 0; dow < 7; dow++) { // create date picker days
1371                                                 var daySettings = (beforeShowDay ?
1372                                                         beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
1373                                                 var otherMonth = (printDate.getMonth() != drawMonth);
1374                                                 var unselectable = otherMonth || !daySettings[0] ||
1375                                                         (minDate && printDate < minDate) || (maxDate && printDate > maxDate);
1376                                                 tbody += '<td class="' +
1377                                                         ((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
1378                                                         (otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
1379                                                         ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
1380                                                         (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
1381                                                         // or defaultDate is current printedDate and defaultDate is selectedDate
1382                                                         ' ' + this._dayOverClass : '') + // highlight selected day
1383                                                         (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') +  // highlight unselectable days
1384                                                         (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
1385                                                         (printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
1386                                                         ' ' + this._currentClass : '') + // highlight selected day
1387                                                         (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
1388                                                         ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
1389                                                         (unselectable ? '' : ' onclick="DP_jQuery.datepicker._selectDay(\'#' +
1390                                                         inst.id + '\',' + drawMonth + ',' + drawYear + ', this);return false;"') + '>' + // actions
1391                                                         (otherMonth ? (showOtherMonths ? printDate.getDate() : '&#xa0;') : // display for other months
1392                                                         (unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
1393                                                         (printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
1394                                                         (printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
1395                                                         ' ui-state-active' : '') + // highlight selected day
1396                                                         '" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display for this month
1397                                                 printDate.setDate(printDate.getDate() + 1);
1398                                                 printDate = this._daylightSavingAdjust(printDate);
1399                                         }
1400                                         calender += tbody + '</tr>';
1401                                 }
1402                                 drawMonth++;
1403                                 if (drawMonth > 11) {
1404                                         drawMonth = 0;
1405                                         drawYear++;
1406                                 }
1407                                 calender += '</tbody></table>' + (isMultiMonth ? '</div>' + 
1408                                                         ((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
1409                                 group += calender;
1410                         }
1411                         html += group;
1412                 }
1413                 html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
1414                         '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
1415                 inst._keyEvent = false;
1416                 return html;
1417         },
1419         /* Generate the month and year header. */
1420         _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
1421                         selectedDate, secondary, monthNames, monthNamesShort) {
1422                 minDate = (inst.rangeStart && minDate && selectedDate < minDate ? selectedDate : minDate);
1423                 var changeMonth = this._get(inst, 'changeMonth');
1424                 var changeYear = this._get(inst, 'changeYear');
1425                 var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
1426                 var html = '<div class="ui-datepicker-title">';
1427                 var monthHtml = '';
1428                 // month selection
1429                 if (secondary || !changeMonth)
1430                         monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span> ';
1431                 else {
1432                         var inMinYear = (minDate && minDate.getFullYear() == drawYear);
1433                         var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
1434                         monthHtml += '<select class="ui-datepicker-month" ' +
1435                                 'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' +
1436                                 'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
1437                                 '>';
1438                         for (var month = 0; month < 12; month++) {
1439                                 if ((!inMinYear || month >= minDate.getMonth()) &&
1440                                                 (!inMaxYear || month <= maxDate.getMonth()))
1441                                         monthHtml += '<option value="' + month + '"' +
1442                                                 (month == drawMonth ? ' selected="selected"' : '') +
1443                                                 '>' + monthNamesShort[month] + '</option>';
1444                         }
1445                         monthHtml += '</select>';
1446                 }
1447                 if (!showMonthAfterYear)
1448                         html += monthHtml + ((secondary || changeMonth || changeYear) && (!(changeMonth && changeYear)) ? '&#xa0;' : '');
1449                 // year selection
1450                 if (secondary || !changeYear)
1451                         html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
1452                 else {
1453                         // determine range of years to display
1454                         var years = this._get(inst, 'yearRange').split(':');
1455                         var year = 0;
1456                         var endYear = 0;
1457                         if (years.length != 2) {
1458                                 year = drawYear - 10;
1459                                 endYear = drawYear + 10;
1460                         } else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
1461                                 year = drawYear + parseInt(years[0], 10);
1462                                 endYear = drawYear + parseInt(years[1], 10);
1463                         } else {
1464                                 year = parseInt(years[0], 10);
1465                                 endYear = parseInt(years[1], 10);
1466                         }
1467                         year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
1468                         endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
1469                         html += '<select class="ui-datepicker-year" ' +
1470                                 'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
1471                                 'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
1472                                 '>';
1473                         for (; year <= endYear; year++) {
1474                                 html += '<option value="' + year + '"' +
1475                                         (year == drawYear ? ' selected="selected"' : '') +
1476                                         '>' + year + '</option>';
1477                         }
1478                         html += '</select>';
1479                 }
1480                 if (showMonthAfterYear)
1481                         html += (secondary || changeMonth || changeYear ? '&#xa0;' : '') + monthHtml;
1482                 html += '</div>'; // Close datepicker_header
1483                 return html;
1484         },
1486         /* Adjust one of the date sub-fields. */
1487         _adjustInstDate: function(inst, offset, period) {
1488                 var year = inst.drawYear + (period == 'Y' ? offset : 0);
1489                 var month = inst.drawMonth + (period == 'M' ? offset : 0);
1490                 var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
1491                         (period == 'D' ? offset : 0);
1492                 var date = this._daylightSavingAdjust(new Date(year, month, day));
1493                 // ensure it is within the bounds set
1494                 var minDate = this._getMinMaxDate(inst, 'min', true);
1495                 var maxDate = this._getMinMaxDate(inst, 'max');
1496                 date = (minDate && date < minDate ? minDate : date);
1497                 date = (maxDate && date > maxDate ? maxDate : date);
1498                 inst.selectedDay = date.getDate();
1499                 inst.drawMonth = inst.selectedMonth = date.getMonth();
1500                 inst.drawYear = inst.selectedYear = date.getFullYear();
1501                 if (period == 'M' || period == 'Y')
1502                         this._notifyChange(inst);
1503         },
1505         /* Notify change of month/year. */
1506         _notifyChange: function(inst) {
1507                 var onChange = this._get(inst, 'onChangeMonthYear');
1508                 if (onChange)
1509                         onChange.apply((inst.input ? inst.input[0] : null),
1510                                 [inst.selectedYear, inst.selectedMonth + 1, inst]);
1511         },
1513         /* Determine the number of months to show. */
1514         _getNumberOfMonths: function(inst) {
1515                 var numMonths = this._get(inst, 'numberOfMonths');
1516                 return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
1517         },
1519         /* Determine the current maximum date - ensure no time components are set - may be overridden for a range. */
1520         _getMinMaxDate: function(inst, minMax, checkRange) {
1521                 var date = this._determineDate(this._get(inst, minMax + 'Date'), null);
1522                 return (!checkRange || !inst.rangeStart ? date :
1523                         (!date || inst.rangeStart > date ? inst.rangeStart : date));
1524         },
1526         /* Find the number of days in a given month. */
1527         _getDaysInMonth: function(year, month) {
1528                 return 32 - new Date(year, month, 32).getDate();
1529         },
1531         /* Find the day of the week of the first of a month. */
1532         _getFirstDayOfMonth: function(year, month) {
1533                 return new Date(year, month, 1).getDay();
1534         },
1536         /* Determines if we should allow a "next/prev" month display change. */
1537         _canAdjustMonth: function(inst, offset, curYear, curMonth) {
1538                 var numMonths = this._getNumberOfMonths(inst);
1539                 var date = this._daylightSavingAdjust(new Date(
1540                         curYear, curMonth + (offset < 0 ? offset : numMonths[1]), 1));
1541                 if (offset < 0)
1542                         date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
1543                 return this._isInRange(inst, date);
1544         },
1546         /* Is the given date in the accepted range? */
1547         _isInRange: function(inst, date) {
1548                 // during range selection, use minimum of selected date and range start
1549                 var newMinDate = (!inst.rangeStart ? null : this._daylightSavingAdjust(
1550                         new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay)));
1551                 newMinDate = (newMinDate && inst.rangeStart < newMinDate ? inst.rangeStart : newMinDate);
1552                 var minDate = newMinDate || this._getMinMaxDate(inst, 'min');
1553                 var maxDate = this._getMinMaxDate(inst, 'max');
1554                 return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate));
1555         },
1557         /* Provide the configuration settings for formatting/parsing. */
1558         _getFormatConfig: function(inst) {
1559                 var shortYearCutoff = this._get(inst, 'shortYearCutoff');
1560                 shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
1561                         new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
1562                 return {shortYearCutoff: shortYearCutoff,
1563                         dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
1564                         monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
1565         },
1567         /* Format the given date for display. */
1568         _formatDate: function(inst, day, month, year) {
1569                 if (!day) {
1570                         inst.currentDay = inst.selectedDay;
1571                         inst.currentMonth = inst.selectedMonth;
1572                         inst.currentYear = inst.selectedYear;
1573                 }
1574                 var date = (day ? (typeof day == 'object' ? day :
1575                         this._daylightSavingAdjust(new Date(year, month, day))) :
1576                         this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
1577                 return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
1578         }
1581 /* jQuery extend now ignores nulls! */
1582 function extendRemove(target, props) {
1583         $.extend(target, props);
1584         for (var name in props)
1585                 if (props[name] == null || props[name] == undefined)
1586                         target[name] = props[name];
1587         return target;
1590 /* Determine whether an object is an array. */
1591 function isArray(a) {
1592         return (a && (($.browser.safari && typeof a == 'object' && a.length) ||
1593                 (a.constructor && a.constructor.toString().match(/\Array\(\)/))));
1596 /* Invoke the datepicker functionality.
1597    @param  options  string - a command, optionally followed by additional parameters or
1598                     Object - settings for attaching new datepicker functionality
1599    @return  jQuery object */
1600 $.fn.datepicker = function(options){
1602         /* Initialise the date picker. */
1603         if (!$.datepicker.initialized) {
1604                 $(document).mousedown($.datepicker._checkExternalClick).
1605                         find('body').append($.datepicker.dpDiv);
1606                 $.datepicker.initialized = true;
1607         }
1609         var otherArgs = Array.prototype.slice.call(arguments, 1);
1610         if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate'))
1611                 return $.datepicker['_' + options + 'Datepicker'].
1612                         apply($.datepicker, [this[0]].concat(otherArgs));
1613         return this.each(function() {
1614                 typeof options == 'string' ?
1615                         $.datepicker['_' + options + 'Datepicker'].
1616                                 apply($.datepicker, [this].concat(otherArgs)) :
1617                         $.datepicker._attachDatepicker(this, options);
1618         });
1621 $.datepicker = new Datepicker(); // singleton instance
1622 $.datepicker.initialized = false;
1623 $.datepicker.uuid = new Date().getTime();
1624 $.datepicker.version = "1.7.1";
1626 // Workaround for #4055
1627 // Add another global to avoid noConflict issues with inline event handlers
1628 window.DP_jQuery = $;
1630 })(jQuery);