Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / resources / lib / jquery.ui / jquery.ui.datepicker.js
blobcd5d49018d4d11eb564942ba4c18def307239ea5
1 /*!
2  * jQuery UI Datepicker 1.9.2
3  * http://jqueryui.com
4  *
5  * Copyright 2012 jQuery Foundation and other contributors
6  * Released under the MIT license.
7  * http://jquery.org/license
8  *
9  * http://api.jqueryui.com/datepicker/
10  *
11  * Depends:
12  *      jquery.ui.core.js
13  */
14 (function( $, undefined ) {
16 $.extend($.ui, { datepicker: { version: "1.9.2" } });
18 var PROP_NAME = 'datepicker';
19 var dpuuid = new Date().getTime();
20 var instActive;
22 /* Date picker manager.
23    Use the singleton instance of this class, $.datepicker, to interact with the date picker.
24    Settings for (groups of) date pickers are maintained in an instance object,
25    allowing multiple different settings on the same page. */
27 function Datepicker() {
28         this.debug = false; // Change this to true to start debugging
29         this._curInst = null; // The current instance in use
30         this._keyEvent = false; // If the last event was a key event
31         this._disabledInputs = []; // List of date picker inputs that have been disabled
32         this._datepickerShowing = false; // True if the popup picker is showing , false if not
33         this._inDialog = false; // True if showing within a "dialog", false if not
34         this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
35         this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
36         this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
37         this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
38         this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
39         this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
40         this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
41         this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
42         this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
43         this.regional = []; // Available regional settings, indexed by language code
44         this.regional[''] = { // Default regional settings
45                 closeText: 'Done', // Display text for close link
46                 prevText: 'Prev', // Display text for previous month link
47                 nextText: 'Next', // Display text for next month link
48                 currentText: 'Today', // Display text for current month link
49                 monthNames: ['January','February','March','April','May','June',
50                         'July','August','September','October','November','December'], // Names of months for drop-down and formatting
51                 monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
52                 dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
53                 dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
54                 dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
55                 weekHeader: 'Wk', // Column header for week of the year
56                 dateFormat: 'mm/dd/yy', // See format options on parseDate
57                 firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
58                 isRTL: false, // True if right-to-left language, false if left-to-right
59                 showMonthAfterYear: false, // True if the year select precedes month, false for month then year
60                 yearSuffix: '' // Additional text to append to the year in the month headers
61         };
62         this._defaults = { // Global defaults for all the date picker instances
63                 showOn: 'focus', // 'focus' for popup on focus,
64                         // 'button' for trigger button, or 'both' for either
65                 showAnim: 'fadeIn', // Name of jQuery animation for popup
66                 showOptions: {}, // Options for enhanced animations
67                 defaultDate: null, // Used when field is blank: actual date,
68                         // +/-number for offset from today, null for today
69                 appendText: '', // Display text following the input box, e.g. showing the format
70                 buttonText: '...', // Text for trigger button
71                 buttonImage: '', // URL for trigger button image
72                 buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
73                 hideIfNoPrevNext: false, // True to hide next/previous month links
74                         // if not applicable, false to just disable them
75                 navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
76                 gotoCurrent: false, // True if today link goes back to current selection instead
77                 changeMonth: false, // True if month can be selected directly, false if only prev/next
78                 changeYear: false, // True if year can be selected directly, false if only prev/next
79                 yearRange: 'c-10:c+10', // Range of years to display in drop-down,
80                         // either relative to today's year (-nn:+nn), relative to currently displayed year
81                         // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
82                 showOtherMonths: false, // True to show dates in other months, false to leave blank
83                 selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
84                 showWeek: false, // True to show week of the year, false to not show it
85                 calculateWeek: this.iso8601Week, // How to calculate the week of the year,
86                         // takes a Date and returns the number of the week for it
87                 shortYearCutoff: '+10', // Short year values < this are in the current century,
88                         // > this are in the previous century,
89                         // string value starting with '+' for current year + value
90                 minDate: null, // The earliest selectable date, or null for no limit
91                 maxDate: null, // The latest selectable date, or null for no limit
92                 duration: 'fast', // Duration of display/closure
93                 beforeShowDay: null, // Function that takes a date and returns an array with
94                         // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
95                         // [2] = cell title (optional), e.g. $.datepicker.noWeekends
96                 beforeShow: null, // Function that takes an input field and
97                         // returns a set of custom settings for the date picker
98                 onSelect: null, // Define a callback function when a date is selected
99                 onChangeMonthYear: null, // Define a callback function when the month or year is changed
100                 onClose: null, // Define a callback function when the datepicker is closed
101                 numberOfMonths: 1, // Number of months to show at a time
102                 showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
103                 stepMonths: 1, // Number of months to step back/forward
104                 stepBigMonths: 12, // Number of months to step back/forward for the big links
105                 altField: '', // Selector for an alternate field to store selected dates into
106                 altFormat: '', // The date format to use for the alternate field
107                 constrainInput: true, // The input is constrained by the current date format
108                 showButtonPanel: false, // True to show button panel, false to not show it
109                 autoSize: false, // True to size the input for the date format, false to leave as is
110                 disabled: false // The initial disabled state
111         };
112         $.extend(this._defaults, this.regional['']);
113         this.dpDiv = bindHover($('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'));
116 $.extend(Datepicker.prototype, {
117         /* Class name added to elements to indicate already configured with a date picker. */
118         markerClassName: 'hasDatepicker',
120         //Keep track of the maximum number of rows displayed (see #7043)
121         maxRows: 4,
123         /* Debug logging (if enabled). */
124         log: function () {
125                 if (this.debug)
126                         console.log.apply('', arguments);
127         },
129         // TODO rename to "widget" when switching to widget factory
130         _widgetDatepicker: function() {
131                 return this.dpDiv;
132         },
134         /* Override the default settings for all instances of the date picker.
135            @param  settings  object - the new settings to use as defaults (anonymous object)
136            @return the manager object */
137         setDefaults: function(settings) {
138                 extendRemove(this._defaults, settings || {});
139                 return this;
140         },
142         /* Attach the date picker to a jQuery selection.
143            @param  target    element - the target input field or division or span
144            @param  settings  object - the new settings to use for this date picker instance (anonymous) */
145         _attachDatepicker: function(target, settings) {
146                 // check for settings on the control itself - in namespace 'date:'
147                 var inlineSettings = null;
148                 for (var attrName in this._defaults) {
149                         var attrValue = target.getAttribute('date:' + attrName);
150                         if (attrValue) {
151                                 inlineSettings = inlineSettings || {};
152                                 try {
153                                         inlineSettings[attrName] = eval(attrValue);
154                                 } catch (err) {
155                                         inlineSettings[attrName] = attrValue;
156                                 }
157                         }
158                 }
159                 var nodeName = target.nodeName.toLowerCase();
160                 var inline = (nodeName == 'div' || nodeName == 'span');
161                 if (!target.id) {
162                         this.uuid += 1;
163                         target.id = 'dp' + this.uuid;
164                 }
165                 var inst = this._newInst($(target), inline);
166                 inst.settings = $.extend({}, settings || {}, inlineSettings || {});
167                 if (nodeName == 'input') {
168                         this._connectDatepicker(target, inst);
169                 } else if (inline) {
170                         this._inlineDatepicker(target, inst);
171                 }
172         },
174         /* Create a new instance object. */
175         _newInst: function(target, inline) {
176                 var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars
177                 return {id: id, input: target, // associated target
178                         selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
179                         drawMonth: 0, drawYear: 0, // month being drawn
180                         inline: inline, // is datepicker inline or not
181                         dpDiv: (!inline ? this.dpDiv : // presentation div
182                         bindHover($('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')))};
183         },
185         /* Attach the date picker to an input field. */
186         _connectDatepicker: function(target, inst) {
187                 var input = $(target);
188                 inst.append = $([]);
189                 inst.trigger = $([]);
190                 if (input.hasClass(this.markerClassName))
191                         return;
192                 this._attachments(input, inst);
193                 input.addClass(this.markerClassName).keydown(this._doKeyDown).
194                         keypress(this._doKeyPress).keyup(this._doKeyUp).
195                         bind("setData.datepicker", function(event, key, value) {
196                                 inst.settings[key] = value;
197                         }).bind("getData.datepicker", function(event, key) {
198                                 return this._get(inst, key);
199                         });
200                 this._autoSize(inst);
201                 $.data(target, PROP_NAME, inst);
202                 //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
203                 if( inst.settings.disabled ) {
204                         this._disableDatepicker( target );
205                 }
206         },
208         /* Make attachments based on settings. */
209         _attachments: function(input, inst) {
210                 var appendText = this._get(inst, 'appendText');
211                 var isRTL = this._get(inst, 'isRTL');
212                 if (inst.append)
213                         inst.append.remove();
214                 if (appendText) {
215                         inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>');
216                         input[isRTL ? 'before' : 'after'](inst.append);
217                 }
218                 input.unbind('focus', this._showDatepicker);
219                 if (inst.trigger)
220                         inst.trigger.remove();
221                 var showOn = this._get(inst, 'showOn');
222                 if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
223                         input.focus(this._showDatepicker);
224                 if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
225                         var buttonText = this._get(inst, 'buttonText');
226                         var buttonImage = this._get(inst, 'buttonImage');
227                         inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
228                                 $('<img/>').addClass(this._triggerClass).
229                                         attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
230                                 $('<button type="button"></button>').addClass(this._triggerClass).
231                                         html(buttonImage == '' ? buttonText : $('<img/>').attr(
232                                         { src:buttonImage, alt:buttonText, title:buttonText })));
233                         input[isRTL ? 'before' : 'after'](inst.trigger);
234                         inst.trigger.click(function() {
235                                 if ($.datepicker._datepickerShowing && $.datepicker._lastInput == input[0])
236                                         $.datepicker._hideDatepicker();
237                                 else if ($.datepicker._datepickerShowing && $.datepicker._lastInput != input[0]) {
238                                         $.datepicker._hideDatepicker();
239                                         $.datepicker._showDatepicker(input[0]);
240                                 } else
241                                         $.datepicker._showDatepicker(input[0]);
242                                 return false;
243                         });
244                 }
245         },
247         /* Apply the maximum length for the date format. */
248         _autoSize: function(inst) {
249                 if (this._get(inst, 'autoSize') && !inst.inline) {
250                         var date = new Date(2009, 12 - 1, 20); // Ensure double digits
251                         var dateFormat = this._get(inst, 'dateFormat');
252                         if (dateFormat.match(/[DM]/)) {
253                                 var findMax = function(names) {
254                                         var max = 0;
255                                         var maxI = 0;
256                                         for (var i = 0; i < names.length; i++) {
257                                                 if (names[i].length > max) {
258                                                         max = names[i].length;
259                                                         maxI = i;
260                                                 }
261                                         }
262                                         return maxI;
263                                 };
264                                 date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
265                                         'monthNames' : 'monthNamesShort'))));
266                                 date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
267                                         'dayNames' : 'dayNamesShort'))) + 20 - date.getDay());
268                         }
269                         inst.input.attr('size', this._formatDate(inst, date).length);
270                 }
271         },
273         /* Attach an inline date picker to a div. */
274         _inlineDatepicker: function(target, inst) {
275                 var divSpan = $(target);
276                 if (divSpan.hasClass(this.markerClassName))
277                         return;
278                 divSpan.addClass(this.markerClassName).append(inst.dpDiv).
279                         bind("setData.datepicker", function(event, key, value){
280                                 inst.settings[key] = value;
281                         }).bind("getData.datepicker", function(event, key){
282                                 return this._get(inst, key);
283                         });
284                 $.data(target, PROP_NAME, inst);
285                 this._setDate(inst, this._getDefaultDate(inst), true);
286                 this._updateDatepicker(inst);
287                 this._updateAlternate(inst);
288                 //If disabled option is true, disable the datepicker before showing it (see ticket #5665)
289                 if( inst.settings.disabled ) {
290                         this._disableDatepicker( target );
291                 }
292                 // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
293                 // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
294                 inst.dpDiv.css( "display", "block" );
295         },
297         /* Pop-up the date picker in a "dialog" box.
298            @param  input     element - ignored
299            @param  date      string or Date - the initial date to display
300            @param  onSelect  function - the function to call when a date is selected
301            @param  settings  object - update the dialog date picker instance's settings (anonymous object)
302            @param  pos       int[2] - coordinates for the dialog's position within the screen or
303                              event - with x/y coordinates or
304                              leave empty for default (screen centre)
305            @return the manager object */
306         _dialogDatepicker: function(input, date, onSelect, settings, pos) {
307                 var inst = this._dialogInst; // internal instance
308                 if (!inst) {
309                         this.uuid += 1;
310                         var id = 'dp' + this.uuid;
311                         this._dialogInput = $('<input type="text" id="' + id +
312                                 '" style="position: absolute; top: -100px; width: 0px;"/>');
313                         this._dialogInput.keydown(this._doKeyDown);
314                         $('body').append(this._dialogInput);
315                         inst = this._dialogInst = this._newInst(this._dialogInput, false);
316                         inst.settings = {};
317                         $.data(this._dialogInput[0], PROP_NAME, inst);
318                 }
319                 extendRemove(inst.settings, settings || {});
320                 date = (date && date.constructor == Date ? this._formatDate(inst, date) : date);
321                 this._dialogInput.val(date);
323                 this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
324                 if (!this._pos) {
325                         var browserWidth = document.documentElement.clientWidth;
326                         var browserHeight = document.documentElement.clientHeight;
327                         var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
328                         var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
329                         this._pos = // should use actual width/height below
330                                 [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
331                 }
333                 // move input on screen for focus, but hidden behind dialog
334                 this._dialogInput.css('left', (this._pos[0] + 20) + 'px').css('top', this._pos[1] + 'px');
335                 inst.settings.onSelect = onSelect;
336                 this._inDialog = true;
337                 this.dpDiv.addClass(this._dialogClass);
338                 this._showDatepicker(this._dialogInput[0]);
339                 if ($.blockUI)
340                         $.blockUI(this.dpDiv);
341                 $.data(this._dialogInput[0], PROP_NAME, inst);
342                 return this;
343         },
345         /* Detach a datepicker from its control.
346            @param  target    element - the target input field or division or span */
347         _destroyDatepicker: function(target) {
348                 var $target = $(target);
349                 var inst = $.data(target, PROP_NAME);
350                 if (!$target.hasClass(this.markerClassName)) {
351                         return;
352                 }
353                 var nodeName = target.nodeName.toLowerCase();
354                 $.removeData(target, PROP_NAME);
355                 if (nodeName == 'input') {
356                         inst.append.remove();
357                         inst.trigger.remove();
358                         $target.removeClass(this.markerClassName).
359                                 unbind('focus', this._showDatepicker).
360                                 unbind('keydown', this._doKeyDown).
361                                 unbind('keypress', this._doKeyPress).
362                                 unbind('keyup', this._doKeyUp);
363                 } else if (nodeName == 'div' || nodeName == 'span')
364                         $target.removeClass(this.markerClassName).empty();
365         },
367         /* Enable the date picker to a jQuery selection.
368            @param  target    element - the target input field or division or span */
369         _enableDatepicker: function(target) {
370                 var $target = $(target);
371                 var inst = $.data(target, PROP_NAME);
372                 if (!$target.hasClass(this.markerClassName)) {
373                         return;
374                 }
375                 var nodeName = target.nodeName.toLowerCase();
376                 if (nodeName == 'input') {
377                         target.disabled = false;
378                         inst.trigger.filter('button').
379                                 each(function() { this.disabled = false; }).end().
380                                 filter('img').css({opacity: '1.0', cursor: ''});
381                 }
382                 else if (nodeName == 'div' || nodeName == 'span') {
383                         var inline = $target.children('.' + this._inlineClass);
384                         inline.children().removeClass('ui-state-disabled');
385                         inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
386                                 prop("disabled", false);
387                 }
388                 this._disabledInputs = $.map(this._disabledInputs,
389                         function(value) { return (value == target ? null : value); }); // delete entry
390         },
392         /* Disable the date picker to a jQuery selection.
393            @param  target    element - the target input field or division or span */
394         _disableDatepicker: function(target) {
395                 var $target = $(target);
396                 var inst = $.data(target, PROP_NAME);
397                 if (!$target.hasClass(this.markerClassName)) {
398                         return;
399                 }
400                 var nodeName = target.nodeName.toLowerCase();
401                 if (nodeName == 'input') {
402                         target.disabled = true;
403                         inst.trigger.filter('button').
404                                 each(function() { this.disabled = true; }).end().
405                                 filter('img').css({opacity: '0.5', cursor: 'default'});
406                 }
407                 else if (nodeName == 'div' || nodeName == 'span') {
408                         var inline = $target.children('.' + this._inlineClass);
409                         inline.children().addClass('ui-state-disabled');
410                         inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
411                                 prop("disabled", true);
412                 }
413                 this._disabledInputs = $.map(this._disabledInputs,
414                         function(value) { return (value == target ? null : value); }); // delete entry
415                 this._disabledInputs[this._disabledInputs.length] = target;
416         },
418         /* Is the first field in a jQuery collection disabled as a datepicker?
419            @param  target    element - the target input field or division or span
420            @return boolean - true if disabled, false if enabled */
421         _isDisabledDatepicker: function(target) {
422                 if (!target) {
423                         return false;
424                 }
425                 for (var i = 0; i < this._disabledInputs.length; i++) {
426                         if (this._disabledInputs[i] == target)
427                                 return true;
428                 }
429                 return false;
430         },
432         /* Retrieve the instance data for the target control.
433            @param  target  element - the target input field or division or span
434            @return  object - the associated instance data
435            @throws  error if a jQuery problem getting data */
436         _getInst: function(target) {
437                 try {
438                         return $.data(target, PROP_NAME);
439                 }
440                 catch (err) {
441                         throw 'Missing instance data for this datepicker';
442                 }
443         },
445         /* Update or retrieve the settings for a date picker attached to an input field or division.
446            @param  target  element - the target input field or division or span
447            @param  name    object - the new settings to update or
448                            string - the name of the setting to change or retrieve,
449                            when retrieving also 'all' for all instance settings or
450                            'defaults' for all global defaults
451            @param  value   any - the new value for the setting
452                            (omit if above is an object or to retrieve a value) */
453         _optionDatepicker: function(target, name, value) {
454                 var inst = this._getInst(target);
455                 if (arguments.length == 2 && typeof name == 'string') {
456                         return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) :
457                                 (inst ? (name == 'all' ? $.extend({}, inst.settings) :
458                                 this._get(inst, name)) : null));
459                 }
460                 var settings = name || {};
461                 if (typeof name == 'string') {
462                         settings = {};
463                         settings[name] = value;
464                 }
465                 if (inst) {
466                         if (this._curInst == inst) {
467                                 this._hideDatepicker();
468                         }
469                         var date = this._getDateDatepicker(target, true);
470                         var minDate = this._getMinMaxDate(inst, 'min');
471                         var maxDate = this._getMinMaxDate(inst, 'max');
472                         extendRemove(inst.settings, settings);
473                         // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
474                         if (minDate !== null && settings['dateFormat'] !== undefined && settings['minDate'] === undefined)
475                                 inst.settings.minDate = this._formatDate(inst, minDate);
476                         if (maxDate !== null && settings['dateFormat'] !== undefined && settings['maxDate'] === undefined)
477                                 inst.settings.maxDate = this._formatDate(inst, maxDate);
478                         this._attachments($(target), inst);
479                         this._autoSize(inst);
480                         this._setDate(inst, date);
481                         this._updateAlternate(inst);
482                         this._updateDatepicker(inst);
483                 }
484         },
486         // change method deprecated
487         _changeDatepicker: function(target, name, value) {
488                 this._optionDatepicker(target, name, value);
489         },
491         /* Redraw the date picker attached to an input field or division.
492            @param  target  element - the target input field or division or span */
493         _refreshDatepicker: function(target) {
494                 var inst = this._getInst(target);
495                 if (inst) {
496                         this._updateDatepicker(inst);
497                 }
498         },
500         /* Set the dates for a jQuery selection.
501            @param  target   element - the target input field or division or span
502            @param  date     Date - the new date */
503         _setDateDatepicker: function(target, date) {
504                 var inst = this._getInst(target);
505                 if (inst) {
506                         this._setDate(inst, date);
507                         this._updateDatepicker(inst);
508                         this._updateAlternate(inst);
509                 }
510         },
512         /* Get the date(s) for the first entry in a jQuery selection.
513            @param  target     element - the target input field or division or span
514            @param  noDefault  boolean - true if no default date is to be used
515            @return Date - the current date */
516         _getDateDatepicker: function(target, noDefault) {
517                 var inst = this._getInst(target);
518                 if (inst && !inst.inline)
519                         this._setDateFromField(inst, noDefault);
520                 return (inst ? this._getDate(inst) : null);
521         },
523         /* Handle keystrokes. */
524         _doKeyDown: function(event) {
525                 var inst = $.datepicker._getInst(event.target);
526                 var handled = true;
527                 var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
528                 inst._keyEvent = true;
529                 if ($.datepicker._datepickerShowing)
530                         switch (event.keyCode) {
531                                 case 9: $.datepicker._hideDatepicker();
532                                                 handled = false;
533                                                 break; // hide on tab out
534                                 case 13: var sel = $('td.' + $.datepicker._dayOverClass + ':not(.' +
535                                                                         $.datepicker._currentClass + ')', inst.dpDiv);
536                                                 if (sel[0])
537                                                         $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
538                                                         var onSelect = $.datepicker._get(inst, 'onSelect');
539                                                         if (onSelect) {
540                                                                 var dateStr = $.datepicker._formatDate(inst);
542                                                                 // trigger custom callback
543                                                                 onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
544                                                         }
545                                                 else
546                                                         $.datepicker._hideDatepicker();
547                                                 return false; // don't submit the form
548                                                 break; // select the value on enter
549                                 case 27: $.datepicker._hideDatepicker();
550                                                 break; // hide on escape
551                                 case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
552                                                         -$.datepicker._get(inst, 'stepBigMonths') :
553                                                         -$.datepicker._get(inst, 'stepMonths')), 'M');
554                                                 break; // previous month/year on page up/+ ctrl
555                                 case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
556                                                         +$.datepicker._get(inst, 'stepBigMonths') :
557                                                         +$.datepicker._get(inst, 'stepMonths')), 'M');
558                                                 break; // next month/year on page down/+ ctrl
559                                 case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
560                                                 handled = event.ctrlKey || event.metaKey;
561                                                 break; // clear on ctrl or command +end
562                                 case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
563                                                 handled = event.ctrlKey || event.metaKey;
564                                                 break; // current on ctrl or command +home
565                                 case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
566                                                 handled = event.ctrlKey || event.metaKey;
567                                                 // -1 day on ctrl or command +left
568                                                 if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
569                                                                         -$.datepicker._get(inst, 'stepBigMonths') :
570                                                                         -$.datepicker._get(inst, 'stepMonths')), 'M');
571                                                 // next month/year on alt +left on Mac
572                                                 break;
573                                 case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
574                                                 handled = event.ctrlKey || event.metaKey;
575                                                 break; // -1 week on ctrl or command +up
576                                 case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
577                                                 handled = event.ctrlKey || event.metaKey;
578                                                 // +1 day on ctrl or command +right
579                                                 if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
580                                                                         +$.datepicker._get(inst, 'stepBigMonths') :
581                                                                         +$.datepicker._get(inst, 'stepMonths')), 'M');
582                                                 // next month/year on alt +right
583                                                 break;
584                                 case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
585                                                 handled = event.ctrlKey || event.metaKey;
586                                                 break; // +1 week on ctrl or command +down
587                                 default: handled = false;
588                         }
589                 else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
590                         $.datepicker._showDatepicker(this);
591                 else {
592                         handled = false;
593                 }
594                 if (handled) {
595                         event.preventDefault();
596                         event.stopPropagation();
597                 }
598         },
600         /* Filter entered characters - based on date format. */
601         _doKeyPress: function(event) {
602                 var inst = $.datepicker._getInst(event.target);
603                 if ($.datepicker._get(inst, 'constrainInput')) {
604                         var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
605                         var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
606                         return event.ctrlKey || event.metaKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
607                 }
608         },
610         /* Synchronise manual entry and field/alternate field. */
611         _doKeyUp: function(event) {
612                 var inst = $.datepicker._getInst(event.target);
613                 if (inst.input.val() != inst.lastVal) {
614                         try {
615                                 var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
616                                         (inst.input ? inst.input.val() : null),
617                                         $.datepicker._getFormatConfig(inst));
618                                 if (date) { // only if valid
619                                         $.datepicker._setDateFromField(inst);
620                                         $.datepicker._updateAlternate(inst);
621                                         $.datepicker._updateDatepicker(inst);
622                                 }
623                         }
624                         catch (err) {
625                                 $.datepicker.log(err);
626                         }
627                 }
628                 return true;
629         },
631         /* Pop-up the date picker for a given input field.
632            If false returned from beforeShow event handler do not show.
633            @param  input  element - the input field attached to the date picker or
634                           event - if triggered by focus */
635         _showDatepicker: function(input) {
636                 input = input.target || input;
637                 if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
638                         input = $('input', input.parentNode)[0];
639                 if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
640                         return;
641                 var inst = $.datepicker._getInst(input);
642                 if ($.datepicker._curInst && $.datepicker._curInst != inst) {
643                         $.datepicker._curInst.dpDiv.stop(true, true);
644                         if ( inst && $.datepicker._datepickerShowing ) {
645                                 $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
646                         }
647                 }
648                 var beforeShow = $.datepicker._get(inst, 'beforeShow');
649                 var beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
650                 if(beforeShowSettings === false){
651                         //false
652                         return;
653                 }
654                 extendRemove(inst.settings, beforeShowSettings);
655                 inst.lastVal = null;
656                 $.datepicker._lastInput = input;
657                 $.datepicker._setDateFromField(inst);
658                 if ($.datepicker._inDialog) // hide cursor
659                         input.value = '';
660                 if (!$.datepicker._pos) { // position below input
661                         $.datepicker._pos = $.datepicker._findPos(input);
662                         $.datepicker._pos[1] += input.offsetHeight; // add the height
663                 }
664                 var isFixed = false;
665                 $(input).parents().each(function() {
666                         isFixed |= $(this).css('position') == 'fixed';
667                         return !isFixed;
668                 });
669                 var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
670                 $.datepicker._pos = null;
671                 //to avoid flashes on Firefox
672                 inst.dpDiv.empty();
673                 // determine sizing offscreen
674                 inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
675                 $.datepicker._updateDatepicker(inst);
676                 // fix width for dynamic number of date pickers
677                 // and adjust position before showing
678                 offset = $.datepicker._checkOffset(inst, offset, isFixed);
679                 inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
680                         'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
681                         left: offset.left + 'px', top: offset.top + 'px'});
682                 if (!inst.inline) {
683                         var showAnim = $.datepicker._get(inst, 'showAnim');
684                         var duration = $.datepicker._get(inst, 'duration');
685                         var postProcess = function() {
686                                 var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only
687                                 if( !! cover.length ){
688                                         var borders = $.datepicker._getBorders(inst.dpDiv);
689                                         cover.css({left: -borders[0], top: -borders[1],
690                                                 width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()});
691                                 }
692                         };
693                         inst.dpDiv.zIndex($(input).zIndex()+1);
694                         $.datepicker._datepickerShowing = true;
696                         // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
697                         if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) )
698                                 inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
699                         else
700                                 inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess);
701                         if (!showAnim || !duration)
702                                 postProcess();
703                         if (inst.input.is(':visible') && !inst.input.is(':disabled'))
704                                 inst.input.focus();
705                         $.datepicker._curInst = inst;
706                 }
707         },
709         /* Generate the date picker content. */
710         _updateDatepicker: function(inst) {
711                 this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
712                 var borders = $.datepicker._getBorders(inst.dpDiv);
713                 instActive = inst; // for delegate hover events
714                 inst.dpDiv.empty().append(this._generateHTML(inst));
715                 this._attachHandlers(inst);
716                 var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only
717                 if( !!cover.length ){ //avoid call to outerXXXX() when not in IE6
718                         cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()})
719                 }
720                 inst.dpDiv.find('.' + this._dayOverClass + ' a').mouseover();
721                 var numMonths = this._getNumberOfMonths(inst);
722                 var cols = numMonths[1];
723                 var width = 17;
724                 inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
725                 if (cols > 1)
726                         inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
727                 inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
728                         'Class']('ui-datepicker-multi');
729                 inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
730                         'Class']('ui-datepicker-rtl');
731                 if (inst == $.datepicker._curInst && $.datepicker._datepickerShowing && inst.input &&
732                                 // #6694 - don't focus the input if it's already focused
733                                 // this breaks the change event in IE
734                                 inst.input.is(':visible') && !inst.input.is(':disabled') && inst.input[0] != document.activeElement)
735                         inst.input.focus();
736                 // deffered render of the years select (to avoid flashes on Firefox)
737                 if( inst.yearshtml ){
738                         var origyearshtml = inst.yearshtml;
739                         setTimeout(function(){
740                                 //assure that inst.yearshtml didn't change.
741                                 if( origyearshtml === inst.yearshtml && inst.yearshtml ){
742                                         inst.dpDiv.find('select.ui-datepicker-year:first').replaceWith(inst.yearshtml);
743                                 }
744                                 origyearshtml = inst.yearshtml = null;
745                         }, 0);
746                 }
747         },
749         /* Retrieve the size of left and top borders for an element.
750            @param  elem  (jQuery object) the element of interest
751            @return  (number[2]) the left and top borders */
752         _getBorders: function(elem) {
753                 var convert = function(value) {
754                         return {thin: 1, medium: 2, thick: 3}[value] || value;
755                 };
756                 return [parseFloat(convert(elem.css('border-left-width'))),
757                         parseFloat(convert(elem.css('border-top-width')))];
758         },
760         /* Check positioning to remain on screen. */
761         _checkOffset: function(inst, offset, isFixed) {
762                 var dpWidth = inst.dpDiv.outerWidth();
763                 var dpHeight = inst.dpDiv.outerHeight();
764                 var inputWidth = inst.input ? inst.input.outerWidth() : 0;
765                 var inputHeight = inst.input ? inst.input.outerHeight() : 0;
766                 var viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft());
767                 var viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());
769                 offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
770                 offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
771                 offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
773                 // now check if datepicker is showing outside window viewport - move to a better place if so.
774                 offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
775                         Math.abs(offset.left + dpWidth - viewWidth) : 0);
776                 offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
777                         Math.abs(dpHeight + inputHeight) : 0);
779                 return offset;
780         },
782         /* Find an object's position on the screen. */
783         _findPos: function(obj) {
784                 var inst = this._getInst(obj);
785                 var isRTL = this._get(inst, 'isRTL');
786                 while (obj && (obj.type == 'hidden' || obj.nodeType != 1 || $.expr.filters.hidden(obj))) {
787                         obj = obj[isRTL ? 'previousSibling' : 'nextSibling'];
788                 }
789                 var position = $(obj).offset();
790                 return [position.left, position.top];
791         },
793         /* Hide the date picker from view.
794            @param  input  element - the input field attached to the date picker */
795         _hideDatepicker: function(input) {
796                 var inst = this._curInst;
797                 if (!inst || (input && inst != $.data(input, PROP_NAME)))
798                         return;
799                 if (this._datepickerShowing) {
800                         var showAnim = this._get(inst, 'showAnim');
801                         var duration = this._get(inst, 'duration');
802                         var postProcess = function() {
803                                 $.datepicker._tidyDialog(inst);
804                         };
806                         // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
807                         if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) )
808                                 inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
809                         else
810                                 inst.dpDiv[(showAnim == 'slideDown' ? 'slideUp' :
811                                         (showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess);
812                         if (!showAnim)
813                                 postProcess();
814                         this._datepickerShowing = false;
815                         var onClose = this._get(inst, 'onClose');
816                         if (onClose)
817                                 onClose.apply((inst.input ? inst.input[0] : null),
818                                         [(inst.input ? inst.input.val() : ''), inst]);
819                         this._lastInput = null;
820                         if (this._inDialog) {
821                                 this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
822                                 if ($.blockUI) {
823                                         $.unblockUI();
824                                         $('body').append(this.dpDiv);
825                                 }
826                         }
827                         this._inDialog = false;
828                 }
829         },
831         /* Tidy up after a dialog display. */
832         _tidyDialog: function(inst) {
833                 inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
834         },
836         /* Close date picker if clicked elsewhere. */
837         _checkExternalClick: function(event) {
838                 if (!$.datepicker._curInst)
839                         return;
841                 var $target = $(event.target),
842                         inst = $.datepicker._getInst($target[0]);
844                 if ( ( ( $target[0].id != $.datepicker._mainDivId &&
845                                 $target.parents('#' + $.datepicker._mainDivId).length == 0 &&
846                                 !$target.hasClass($.datepicker.markerClassName) &&
847                                 !$target.closest("." + $.datepicker._triggerClass).length &&
848                                 $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
849                         ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst != inst ) )
850                         $.datepicker._hideDatepicker();
851         },
853         /* Adjust one of the date sub-fields. */
854         _adjustDate: function(id, offset, period) {
855                 var target = $(id);
856                 var inst = this._getInst(target[0]);
857                 if (this._isDisabledDatepicker(target[0])) {
858                         return;
859                 }
860                 this._adjustInstDate(inst, offset +
861                         (period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
862                         period);
863                 this._updateDatepicker(inst);
864         },
866         /* Action for current link. */
867         _gotoToday: function(id) {
868                 var target = $(id);
869                 var inst = this._getInst(target[0]);
870                 if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
871                         inst.selectedDay = inst.currentDay;
872                         inst.drawMonth = inst.selectedMonth = inst.currentMonth;
873                         inst.drawYear = inst.selectedYear = inst.currentYear;
874                 }
875                 else {
876                         var date = new Date();
877                         inst.selectedDay = date.getDate();
878                         inst.drawMonth = inst.selectedMonth = date.getMonth();
879                         inst.drawYear = inst.selectedYear = date.getFullYear();
880                 }
881                 this._notifyChange(inst);
882                 this._adjustDate(target);
883         },
885         /* Action for selecting a new month/year. */
886         _selectMonthYear: function(id, select, period) {
887                 var target = $(id);
888                 var inst = this._getInst(target[0]);
889                 inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
890                 inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
891                         parseInt(select.options[select.selectedIndex].value,10);
892                 this._notifyChange(inst);
893                 this._adjustDate(target);
894         },
896         /* Action for selecting a day. */
897         _selectDay: function(id, month, year, td) {
898                 var target = $(id);
899                 if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
900                         return;
901                 }
902                 var inst = this._getInst(target[0]);
903                 inst.selectedDay = inst.currentDay = $('a', td).html();
904                 inst.selectedMonth = inst.currentMonth = month;
905                 inst.selectedYear = inst.currentYear = year;
906                 this._selectDate(id, this._formatDate(inst,
907                         inst.currentDay, inst.currentMonth, inst.currentYear));
908         },
910         /* Erase the input field and hide the date picker. */
911         _clearDate: function(id) {
912                 var target = $(id);
913                 var inst = this._getInst(target[0]);
914                 this._selectDate(target, '');
915         },
917         /* Update the input field with the selected date. */
918         _selectDate: function(id, dateStr) {
919                 var target = $(id);
920                 var inst = this._getInst(target[0]);
921                 dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
922                 if (inst.input)
923                         inst.input.val(dateStr);
924                 this._updateAlternate(inst);
925                 var onSelect = this._get(inst, 'onSelect');
926                 if (onSelect)
927                         onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
928                 else if (inst.input)
929                         inst.input.trigger('change'); // fire the change event
930                 if (inst.inline)
931                         this._updateDatepicker(inst);
932                 else {
933                         this._hideDatepicker();
934                         this._lastInput = inst.input[0];
935                         if (typeof(inst.input[0]) != 'object')
936                                 inst.input.focus(); // restore focus
937                         this._lastInput = null;
938                 }
939         },
941         /* Update any alternate field to synchronise with the main field. */
942         _updateAlternate: function(inst) {
943                 var altField = this._get(inst, 'altField');
944                 if (altField) { // update alternate field too
945                         var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
946                         var date = this._getDate(inst);
947                         var dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
948                         $(altField).each(function() { $(this).val(dateStr); });
949                 }
950         },
952         /* Set as beforeShowDay function to prevent selection of weekends.
953            @param  date  Date - the date to customise
954            @return [boolean, string] - is this date selectable?, what is its CSS class? */
955         noWeekends: function(date) {
956                 var day = date.getDay();
957                 return [(day > 0 && day < 6), ''];
958         },
960         /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
961            @param  date  Date - the date to get the week for
962            @return  number - the number of the week within the year that contains this date */
963         iso8601Week: function(date) {
964                 var checkDate = new Date(date.getTime());
965                 // Find Thursday of this week starting on Monday
966                 checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
967                 var time = checkDate.getTime();
968                 checkDate.setMonth(0); // Compare with Jan 1
969                 checkDate.setDate(1);
970                 return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
971         },
973         /* Parse a string value into a date object.
974            See formatDate below for the possible formats.
976            @param  format    string - the expected format of the date
977            @param  value     string - the date in the above format
978            @param  settings  Object - attributes include:
979                              shortYearCutoff  number - the cutoff year for determining the century (optional)
980                              dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
981                              dayNames         string[7] - names of the days from Sunday (optional)
982                              monthNamesShort  string[12] - abbreviated names of the months (optional)
983                              monthNames       string[12] - names of the months (optional)
984            @return  Date - the extracted date value or null if value is blank */
985         parseDate: function (format, value, settings) {
986                 if (format == null || value == null)
987                         throw 'Invalid arguments';
988                 value = (typeof value == 'object' ? value.toString() : value + '');
989                 if (value == '')
990                         return null;
991                 var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
992                 shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
993                                 new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
994                 var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
995                 var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
996                 var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
997                 var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
998                 var year = -1;
999                 var month = -1;
1000                 var day = -1;
1001                 var doy = -1;
1002                 var literal = false;
1003                 // Check whether a format character is doubled
1004                 var lookAhead = function(match) {
1005                         var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
1006                         if (matches)
1007                                 iFormat++;
1008                         return matches;
1009                 };
1010                 // Extract a number from the string value
1011                 var getNumber = function(match) {
1012                         var isDoubled = lookAhead(match);
1013                         var size = (match == '@' ? 14 : (match == '!' ? 20 :
1014                                 (match == 'y' && isDoubled ? 4 : (match == 'o' ? 3 : 2))));
1015                         var digits = new RegExp('^\\d{1,' + size + '}');
1016                         var num = value.substring(iValue).match(digits);
1017                         if (!num)
1018                                 throw 'Missing number at position ' + iValue;
1019                         iValue += num[0].length;
1020                         return parseInt(num[0], 10);
1021                 };
1022                 // Extract a name from the string value and convert to an index
1023                 var getName = function(match, shortNames, longNames) {
1024                         var names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
1025                                 return [ [k, v] ];
1026                         }).sort(function (a, b) {
1027                                 return -(a[1].length - b[1].length);
1028                         });
1029                         var index = -1;
1030                         $.each(names, function (i, pair) {
1031                                 var name = pair[1];
1032                                 if (value.substr(iValue, name.length).toLowerCase() == name.toLowerCase()) {
1033                                         index = pair[0];
1034                                         iValue += name.length;
1035                                         return false;
1036                                 }
1037                         });
1038                         if (index != -1)
1039                                 return index + 1;
1040                         else
1041                                 throw 'Unknown name at position ' + iValue;
1042                 };
1043                 // Confirm that a literal character matches the string value
1044                 var checkLiteral = function() {
1045                         if (value.charAt(iValue) != format.charAt(iFormat))
1046                                 throw 'Unexpected literal at position ' + iValue;
1047                         iValue++;
1048                 };
1049                 var iValue = 0;
1050                 for (var iFormat = 0; iFormat < format.length; iFormat++) {
1051                         if (literal)
1052                                 if (format.charAt(iFormat) == "'" && !lookAhead("'"))
1053                                         literal = false;
1054                                 else
1055                                         checkLiteral();
1056                         else
1057                                 switch (format.charAt(iFormat)) {
1058                                         case 'd':
1059                                                 day = getNumber('d');
1060                                                 break;
1061                                         case 'D':
1062                                                 getName('D', dayNamesShort, dayNames);
1063                                                 break;
1064                                         case 'o':
1065                                                 doy = getNumber('o');
1066                                                 break;
1067                                         case 'm':
1068                                                 month = getNumber('m');
1069                                                 break;
1070                                         case 'M':
1071                                                 month = getName('M', monthNamesShort, monthNames);
1072                                                 break;
1073                                         case 'y':
1074                                                 year = getNumber('y');
1075                                                 break;
1076                                         case '@':
1077                                                 var date = new Date(getNumber('@'));
1078                                                 year = date.getFullYear();
1079                                                 month = date.getMonth() + 1;
1080                                                 day = date.getDate();
1081                                                 break;
1082                                         case '!':
1083                                                 var date = new Date((getNumber('!') - this._ticksTo1970) / 10000);
1084                                                 year = date.getFullYear();
1085                                                 month = date.getMonth() + 1;
1086                                                 day = date.getDate();
1087                                                 break;
1088                                         case "'":
1089                                                 if (lookAhead("'"))
1090                                                         checkLiteral();
1091                                                 else
1092                                                         literal = true;
1093                                                 break;
1094                                         default:
1095                                                 checkLiteral();
1096                                 }
1097                 }
1098                 if (iValue < value.length){
1099                         var extra = value.substr(iValue);
1100                         if (!/^\s+/.test(extra)) {
1101                                 throw "Extra/unparsed characters found in date: " + extra;
1102                         }
1103                 }
1104                 if (year == -1)
1105                         year = new Date().getFullYear();
1106                 else if (year < 100)
1107                         year += new Date().getFullYear() - new Date().getFullYear() % 100 +
1108                                 (year <= shortYearCutoff ? 0 : -100);
1109                 if (doy > -1) {
1110                         month = 1;
1111                         day = doy;
1112                         do {
1113                                 var dim = this._getDaysInMonth(year, month - 1);
1114                                 if (day <= dim)
1115                                         break;
1116                                 month++;
1117                                 day -= dim;
1118                         } while (true);
1119                 }
1120                 var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
1121                 if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
1122                         throw 'Invalid date'; // E.g. 31/02/00
1123                 return date;
1124         },
1126         /* Standard date formats. */
1127         ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
1128         COOKIE: 'D, dd M yy',
1129         ISO_8601: 'yy-mm-dd',
1130         RFC_822: 'D, d M y',
1131         RFC_850: 'DD, dd-M-y',
1132         RFC_1036: 'D, d M y',
1133         RFC_1123: 'D, d M yy',
1134         RFC_2822: 'D, d M yy',
1135         RSS: 'D, d M y', // RFC 822
1136         TICKS: '!',
1137         TIMESTAMP: '@',
1138         W3C: 'yy-mm-dd', // ISO 8601
1140         _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
1141                 Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
1143         /* Format a date object into a string value.
1144            The format can be combinations of the following:
1145            d  - day of month (no leading zero)
1146            dd - day of month (two digit)
1147            o  - day of year (no leading zeros)
1148            oo - day of year (three digit)
1149            D  - day name short
1150            DD - day name long
1151            m  - month of year (no leading zero)
1152            mm - month of year (two digit)
1153            M  - month name short
1154            MM - month name long
1155            y  - year (two digit)
1156            yy - year (four digit)
1157            @ - Unix timestamp (ms since 01/01/1970)
1158            ! - Windows ticks (100ns since 01/01/0001)
1159            '...' - literal text
1160            '' - single quote
1162            @param  format    string - the desired format of the date
1163            @param  date      Date - the date value to format
1164            @param  settings  Object - attributes include:
1165                              dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
1166                              dayNames         string[7] - names of the days from Sunday (optional)
1167                              monthNamesShort  string[12] - abbreviated names of the months (optional)
1168                              monthNames       string[12] - names of the months (optional)
1169            @return  string - the date in the above format */
1170         formatDate: function (format, date, settings) {
1171                 if (!date)
1172                         return '';
1173                 var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
1174                 var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
1175                 var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
1176                 var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
1177                 // Check whether a format character is doubled
1178                 var lookAhead = function(match) {
1179                         var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
1180                         if (matches)
1181                                 iFormat++;
1182                         return matches;
1183                 };
1184                 // Format a number, with leading zero if necessary
1185                 var formatNumber = function(match, value, len) {
1186                         var num = '' + value;
1187                         if (lookAhead(match))
1188                                 while (num.length < len)
1189                                         num = '0' + num;
1190                         return num;
1191                 };
1192                 // Format a name, short or long as requested
1193                 var formatName = function(match, value, shortNames, longNames) {
1194                         return (lookAhead(match) ? longNames[value] : shortNames[value]);
1195                 };
1196                 var output = '';
1197                 var literal = false;
1198                 if (date)
1199                         for (var iFormat = 0; iFormat < format.length; iFormat++) {
1200                                 if (literal)
1201                                         if (format.charAt(iFormat) == "'" && !lookAhead("'"))
1202                                                 literal = false;
1203                                         else
1204                                                 output += format.charAt(iFormat);
1205                                 else
1206                                         switch (format.charAt(iFormat)) {
1207                                                 case 'd':
1208                                                         output += formatNumber('d', date.getDate(), 2);
1209                                                         break;
1210                                                 case 'D':
1211                                                         output += formatName('D', date.getDay(), dayNamesShort, dayNames);
1212                                                         break;
1213                                                 case 'o':
1214                                                         output += formatNumber('o',
1215                                                                 Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
1216                                                         break;
1217                                                 case 'm':
1218                                                         output += formatNumber('m', date.getMonth() + 1, 2);
1219                                                         break;
1220                                                 case 'M':
1221                                                         output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
1222                                                         break;
1223                                                 case 'y':
1224                                                         output += (lookAhead('y') ? date.getFullYear() :
1225                                                                 (date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
1226                                                         break;
1227                                                 case '@':
1228                                                         output += date.getTime();
1229                                                         break;
1230                                                 case '!':
1231                                                         output += date.getTime() * 10000 + this._ticksTo1970;
1232                                                         break;
1233                                                 case "'":
1234                                                         if (lookAhead("'"))
1235                                                                 output += "'";
1236                                                         else
1237                                                                 literal = true;
1238                                                         break;
1239                                                 default:
1240                                                         output += format.charAt(iFormat);
1241                                         }
1242                         }
1243                 return output;
1244         },
1246         /* Extract all possible characters from the date format. */
1247         _possibleChars: function (format) {
1248                 var chars = '';
1249                 var literal = false;
1250                 // Check whether a format character is doubled
1251                 var lookAhead = function(match) {
1252                         var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
1253                         if (matches)
1254                                 iFormat++;
1255                         return matches;
1256                 };
1257                 for (var iFormat = 0; iFormat < format.length; iFormat++)
1258                         if (literal)
1259                                 if (format.charAt(iFormat) == "'" && !lookAhead("'"))
1260                                         literal = false;
1261                                 else
1262                                         chars += format.charAt(iFormat);
1263                         else
1264                                 switch (format.charAt(iFormat)) {
1265                                         case 'd': case 'm': case 'y': case '@':
1266                                                 chars += '0123456789';
1267                                                 break;
1268                                         case 'D': case 'M':
1269                                                 return null; // Accept anything
1270                                         case "'":
1271                                                 if (lookAhead("'"))
1272                                                         chars += "'";
1273                                                 else
1274                                                         literal = true;
1275                                                 break;
1276                                         default:
1277                                                 chars += format.charAt(iFormat);
1278                                 }
1279                 return chars;
1280         },
1282         /* Get a setting value, defaulting if necessary. */
1283         _get: function(inst, name) {
1284                 return inst.settings[name] !== undefined ?
1285                         inst.settings[name] : this._defaults[name];
1286         },
1288         /* Parse existing date and initialise date picker. */
1289         _setDateFromField: function(inst, noDefault) {
1290                 if (inst.input.val() == inst.lastVal) {
1291                         return;
1292                 }
1293                 var dateFormat = this._get(inst, 'dateFormat');
1294                 var dates = inst.lastVal = inst.input ? inst.input.val() : null;
1295                 var date, defaultDate;
1296                 date = defaultDate = this._getDefaultDate(inst);
1297                 var settings = this._getFormatConfig(inst);
1298                 try {
1299                         date = this.parseDate(dateFormat, dates, settings) || defaultDate;
1300                 } catch (event) {
1301                         this.log(event);
1302                         dates = (noDefault ? '' : dates);
1303                 }
1304                 inst.selectedDay = date.getDate();
1305                 inst.drawMonth = inst.selectedMonth = date.getMonth();
1306                 inst.drawYear = inst.selectedYear = date.getFullYear();
1307                 inst.currentDay = (dates ? date.getDate() : 0);
1308                 inst.currentMonth = (dates ? date.getMonth() : 0);
1309                 inst.currentYear = (dates ? date.getFullYear() : 0);
1310                 this._adjustInstDate(inst);
1311         },
1313         /* Retrieve the default date shown on opening. */
1314         _getDefaultDate: function(inst) {
1315                 return this._restrictMinMax(inst,
1316                         this._determineDate(inst, this._get(inst, 'defaultDate'), new Date()));
1317         },
1319         /* A date may be specified as an exact value or a relative one. */
1320         _determineDate: function(inst, date, defaultDate) {
1321                 var offsetNumeric = function(offset) {
1322                         var date = new Date();
1323                         date.setDate(date.getDate() + offset);
1324                         return date;
1325                 };
1326                 var offsetString = function(offset) {
1327                         try {
1328                                 return $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
1329                                         offset, $.datepicker._getFormatConfig(inst));
1330                         }
1331                         catch (e) {
1332                                 // Ignore
1333                         }
1334                         var date = (offset.toLowerCase().match(/^c/) ?
1335                                 $.datepicker._getDate(inst) : null) || new Date();
1336                         var year = date.getFullYear();
1337                         var month = date.getMonth();
1338                         var day = date.getDate();
1339                         var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
1340                         var matches = pattern.exec(offset);
1341                         while (matches) {
1342                                 switch (matches[2] || 'd') {
1343                                         case 'd' : case 'D' :
1344                                                 day += parseInt(matches[1],10); break;
1345                                         case 'w' : case 'W' :
1346                                                 day += parseInt(matches[1],10) * 7; break;
1347                                         case 'm' : case 'M' :
1348                                                 month += parseInt(matches[1],10);
1349                                                 day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
1350                                                 break;
1351                                         case 'y': case 'Y' :
1352                                                 year += parseInt(matches[1],10);
1353                                                 day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
1354                                                 break;
1355                                 }
1356                                 matches = pattern.exec(offset);
1357                         }
1358                         return new Date(year, month, day);
1359                 };
1360                 var newDate = (date == null || date === '' ? defaultDate : (typeof date == 'string' ? offsetString(date) :
1361                         (typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
1362                 newDate = (newDate && newDate.toString() == 'Invalid Date' ? defaultDate : newDate);
1363                 if (newDate) {
1364                         newDate.setHours(0);
1365                         newDate.setMinutes(0);
1366                         newDate.setSeconds(0);
1367                         newDate.setMilliseconds(0);
1368                 }
1369                 return this._daylightSavingAdjust(newDate);
1370         },
1372         /* Handle switch to/from daylight saving.
1373            Hours may be non-zero on daylight saving cut-over:
1374            > 12 when midnight changeover, but then cannot generate
1375            midnight datetime, so jump to 1AM, otherwise reset.
1376            @param  date  (Date) the date to check
1377            @return  (Date) the corrected date */
1378         _daylightSavingAdjust: function(date) {
1379                 if (!date) return null;
1380                 date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
1381                 return date;
1382         },
1384         /* Set the date(s) directly. */
1385         _setDate: function(inst, date, noChange) {
1386                 var clear = !date;
1387                 var origMonth = inst.selectedMonth;
1388                 var origYear = inst.selectedYear;
1389                 var newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
1390                 inst.selectedDay = inst.currentDay = newDate.getDate();
1391                 inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
1392                 inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
1393                 if ((origMonth != inst.selectedMonth || origYear != inst.selectedYear) && !noChange)
1394                         this._notifyChange(inst);
1395                 this._adjustInstDate(inst);
1396                 if (inst.input) {
1397                         inst.input.val(clear ? '' : this._formatDate(inst));
1398                 }
1399         },
1401         /* Retrieve the date(s) directly. */
1402         _getDate: function(inst) {
1403                 var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
1404                         this._daylightSavingAdjust(new Date(
1405                         inst.currentYear, inst.currentMonth, inst.currentDay)));
1406                         return startDate;
1407         },
1409         /* Attach the onxxx handlers.  These are declared statically so
1410          * they work with static code transformers like Caja.
1411          */
1412         _attachHandlers: function(inst) {
1413                 var stepMonths = this._get(inst, 'stepMonths');
1414                 var id = '#' + inst.id.replace( /\\\\/g, "\\" );
1415                 inst.dpDiv.find('[data-handler]').map(function () {
1416                         var handler = {
1417                                 prev: function () {
1418                                         window['DP_jQuery_' + dpuuid].datepicker._adjustDate(id, -stepMonths, 'M');
1419                                 },
1420                                 next: function () {
1421                                         window['DP_jQuery_' + dpuuid].datepicker._adjustDate(id, +stepMonths, 'M');
1422                                 },
1423                                 hide: function () {
1424                                         window['DP_jQuery_' + dpuuid].datepicker._hideDatepicker();
1425                                 },
1426                                 today: function () {
1427                                         window['DP_jQuery_' + dpuuid].datepicker._gotoToday(id);
1428                                 },
1429                                 selectDay: function () {
1430                                         window['DP_jQuery_' + dpuuid].datepicker._selectDay(id, +this.getAttribute('data-month'), +this.getAttribute('data-year'), this);
1431                                         return false;
1432                                 },
1433                                 selectMonth: function () {
1434                                         window['DP_jQuery_' + dpuuid].datepicker._selectMonthYear(id, this, 'M');
1435                                         return false;
1436                                 },
1437                                 selectYear: function () {
1438                                         window['DP_jQuery_' + dpuuid].datepicker._selectMonthYear(id, this, 'Y');
1439                                         return false;
1440                                 }
1441                         };
1442                         $(this).bind(this.getAttribute('data-event'), handler[this.getAttribute('data-handler')]);
1443                 });
1444         },
1446         /* Generate the HTML for the current state of the date picker. */
1447         _generateHTML: function(inst) {
1448                 var today = new Date();
1449                 today = this._daylightSavingAdjust(
1450                         new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
1451                 var isRTL = this._get(inst, 'isRTL');
1452                 var showButtonPanel = this._get(inst, 'showButtonPanel');
1453                 var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
1454                 var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
1455                 var numMonths = this._getNumberOfMonths(inst);
1456                 var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
1457                 var stepMonths = this._get(inst, 'stepMonths');
1458                 var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
1459                 var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
1460                         new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
1461                 var minDate = this._getMinMaxDate(inst, 'min');
1462                 var maxDate = this._getMinMaxDate(inst, 'max');
1463                 var drawMonth = inst.drawMonth - showCurrentAtPos;
1464                 var drawYear = inst.drawYear;
1465                 if (drawMonth < 0) {
1466                         drawMonth += 12;
1467                         drawYear--;
1468                 }
1469                 if (maxDate) {
1470                         var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
1471                                 maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
1472                         maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
1473                         while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
1474                                 drawMonth--;
1475                                 if (drawMonth < 0) {
1476                                         drawMonth = 11;
1477                                         drawYear--;
1478                                 }
1479                         }
1480                 }
1481                 inst.drawMonth = drawMonth;
1482                 inst.drawYear = drawYear;
1483                 var prevText = this._get(inst, 'prevText');
1484                 prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
1485                         this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
1486                         this._getFormatConfig(inst)));
1487                 var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
1488                         '<a class="ui-datepicker-prev ui-corner-all" data-handler="prev" data-event="click"' +
1489                         ' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
1490                         (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>'));
1491                 var nextText = this._get(inst, 'nextText');
1492                 nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
1493                         this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
1494                         this._getFormatConfig(inst)));
1495                 var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
1496                         '<a class="ui-datepicker-next ui-corner-all" data-handler="next" data-event="click"' +
1497                         ' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
1498                         (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>'));
1499                 var currentText = this._get(inst, 'currentText');
1500                 var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
1501                 currentText = (!navigationAsDateFormat ? currentText :
1502                         this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
1503                 var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">' +
1504                         this._get(inst, 'closeText') + '</button>' : '');
1505                 var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
1506                         (this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" data-handler="today" data-event="click"' +
1507                         '>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
1508                 var firstDay = parseInt(this._get(inst, 'firstDay'),10);
1509                 firstDay = (isNaN(firstDay) ? 0 : firstDay);
1510                 var showWeek = this._get(inst, 'showWeek');
1511                 var dayNames = this._get(inst, 'dayNames');
1512                 var dayNamesShort = this._get(inst, 'dayNamesShort');
1513                 var dayNamesMin = this._get(inst, 'dayNamesMin');
1514                 var monthNames = this._get(inst, 'monthNames');
1515                 var monthNamesShort = this._get(inst, 'monthNamesShort');
1516                 var beforeShowDay = this._get(inst, 'beforeShowDay');
1517                 var showOtherMonths = this._get(inst, 'showOtherMonths');
1518                 var selectOtherMonths = this._get(inst, 'selectOtherMonths');
1519                 var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
1520                 var defaultDate = this._getDefaultDate(inst);
1521                 var html = '';
1522                 for (var row = 0; row < numMonths[0]; row++) {
1523                         var group = '';
1524                         this.maxRows = 4;
1525                         for (var col = 0; col < numMonths[1]; col++) {
1526                                 var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
1527                                 var cornerClass = ' ui-corner-all';
1528                                 var calender = '';
1529                                 if (isMultiMonth) {
1530                                         calender += '<div class="ui-datepicker-group';
1531                                         if (numMonths[1] > 1)
1532                                                 switch (col) {
1533                                                         case 0: calender += ' ui-datepicker-group-first';
1534                                                                 cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
1535                                                         case numMonths[1]-1: calender += ' ui-datepicker-group-last';
1536                                                                 cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
1537                                                         default: calender += ' ui-datepicker-group-middle'; cornerClass = ''; break;
1538                                                 }
1539                                         calender += '">';
1540                                 }
1541                                 calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
1542                                         (/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
1543                                         (/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
1544                                         this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
1545                                         row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
1546                                         '</div><table class="ui-datepicker-calendar"><thead>' +
1547                                         '<tr>';
1548                                 var thead = (showWeek ? '<th class="ui-datepicker-week-col">' + this._get(inst, 'weekHeader') + '</th>' : '');
1549                                 for (var dow = 0; dow < 7; dow++) { // days of the week
1550                                         var day = (dow + firstDay) % 7;
1551                                         thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
1552                                                 '<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
1553                                 }
1554                                 calender += thead + '</tr></thead><tbody>';
1555                                 var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
1556                                 if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
1557                                         inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
1558                                 var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
1559                                 var curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
1560                                 var numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
1561                                 this.maxRows = numRows;
1562                                 var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
1563                                 for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
1564                                         calender += '<tr>';
1565                                         var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' +
1566                                                 this._get(inst, 'calculateWeek')(printDate) + '</td>');
1567                                         for (var dow = 0; dow < 7; dow++) { // create date picker days
1568                                                 var daySettings = (beforeShowDay ?
1569                                                         beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
1570                                                 var otherMonth = (printDate.getMonth() != drawMonth);
1571                                                 var unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
1572                                                         (minDate && printDate < minDate) || (maxDate && printDate > maxDate);
1573                                                 tbody += '<td class="' +
1574                                                         ((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
1575                                                         (otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
1576                                                         ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
1577                                                         (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
1578                                                         // or defaultDate is current printedDate and defaultDate is selectedDate
1579                                                         ' ' + this._dayOverClass : '') + // highlight selected day
1580                                                         (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') +  // highlight unselectable days
1581                                                         (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
1582                                                         (printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day
1583                                                         (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
1584                                                         ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
1585                                                         (unselectable ? '' : ' data-handler="selectDay" data-event="click" data-month="' + printDate.getMonth() + '" data-year="' + printDate.getFullYear() + '"') + '>' + // actions
1586                                                         (otherMonth && !showOtherMonths ? '&#xa0;' : // display for other months
1587                                                         (unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
1588                                                         (printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
1589                                                         (printDate.getTime() == currentDate.getTime() ? ' ui-state-active' : '') + // highlight selected day
1590                                                         (otherMonth ? ' ui-priority-secondary' : '') + // distinguish dates from other months
1591                                                         '" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display selectable date
1592                                                 printDate.setDate(printDate.getDate() + 1);
1593                                                 printDate = this._daylightSavingAdjust(printDate);
1594                                         }
1595                                         calender += tbody + '</tr>';
1596                                 }
1597                                 drawMonth++;
1598                                 if (drawMonth > 11) {
1599                                         drawMonth = 0;
1600                                         drawYear++;
1601                                 }
1602                                 calender += '</tbody></table>' + (isMultiMonth ? '</div>' +
1603                                                         ((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
1604                                 group += calender;
1605                         }
1606                         html += group;
1607                 }
1608                 html += buttonPanel + ($.ui.ie6 && !inst.inline ?
1609                         '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
1610                 inst._keyEvent = false;
1611                 return html;
1612         },
1614         /* Generate the month and year header. */
1615         _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
1616                         secondary, monthNames, monthNamesShort) {
1617                 var changeMonth = this._get(inst, 'changeMonth');
1618                 var changeYear = this._get(inst, 'changeYear');
1619                 var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
1620                 var html = '<div class="ui-datepicker-title">';
1621                 var monthHtml = '';
1622                 // month selection
1623                 if (secondary || !changeMonth)
1624                         monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>';
1625                 else {
1626                         var inMinYear = (minDate && minDate.getFullYear() == drawYear);
1627                         var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
1628                         monthHtml += '<select class="ui-datepicker-month" data-handler="selectMonth" data-event="change">';
1629                         for (var month = 0; month < 12; month++) {
1630                                 if ((!inMinYear || month >= minDate.getMonth()) &&
1631                                                 (!inMaxYear || month <= maxDate.getMonth()))
1632                                         monthHtml += '<option value="' + month + '"' +
1633                                                 (month == drawMonth ? ' selected="selected"' : '') +
1634                                                 '>' + monthNamesShort[month] + '</option>';
1635                         }
1636                         monthHtml += '</select>';
1637                 }
1638                 if (!showMonthAfterYear)
1639                         html += monthHtml + (secondary || !(changeMonth && changeYear) ? '&#xa0;' : '');
1640                 // year selection
1641                 if ( !inst.yearshtml ) {
1642                         inst.yearshtml = '';
1643                         if (secondary || !changeYear)
1644                                 html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
1645                         else {
1646                                 // determine range of years to display
1647                                 var years = this._get(inst, 'yearRange').split(':');
1648                                 var thisYear = new Date().getFullYear();
1649                                 var determineYear = function(value) {
1650                                         var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) :
1651                                                 (value.match(/[+-].*/) ? thisYear + parseInt(value, 10) :
1652                                                 parseInt(value, 10)));
1653                                         return (isNaN(year) ? thisYear : year);
1654                                 };
1655                                 var year = determineYear(years[0]);
1656                                 var endYear = Math.max(year, determineYear(years[1] || ''));
1657                                 year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
1658                                 endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
1659                                 inst.yearshtml += '<select class="ui-datepicker-year" data-handler="selectYear" data-event="change">';
1660                                 for (; year <= endYear; year++) {
1661                                         inst.yearshtml += '<option value="' + year + '"' +
1662                                                 (year == drawYear ? ' selected="selected"' : '') +
1663                                                 '>' + year + '</option>';
1664                                 }
1665                                 inst.yearshtml += '</select>';
1667                                 html += inst.yearshtml;
1668                                 inst.yearshtml = null;
1669                         }
1670                 }
1671                 html += this._get(inst, 'yearSuffix');
1672                 if (showMonthAfterYear)
1673                         html += (secondary || !(changeMonth && changeYear) ? '&#xa0;' : '') + monthHtml;
1674                 html += '</div>'; // Close datepicker_header
1675                 return html;
1676         },
1678         /* Adjust one of the date sub-fields. */
1679         _adjustInstDate: function(inst, offset, period) {
1680                 var year = inst.drawYear + (period == 'Y' ? offset : 0);
1681                 var month = inst.drawMonth + (period == 'M' ? offset : 0);
1682                 var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
1683                         (period == 'D' ? offset : 0);
1684                 var date = this._restrictMinMax(inst,
1685                         this._daylightSavingAdjust(new Date(year, month, day)));
1686                 inst.selectedDay = date.getDate();
1687                 inst.drawMonth = inst.selectedMonth = date.getMonth();
1688                 inst.drawYear = inst.selectedYear = date.getFullYear();
1689                 if (period == 'M' || period == 'Y')
1690                         this._notifyChange(inst);
1691         },
1693         /* Ensure a date is within any min/max bounds. */
1694         _restrictMinMax: function(inst, date) {
1695                 var minDate = this._getMinMaxDate(inst, 'min');
1696                 var maxDate = this._getMinMaxDate(inst, 'max');
1697                 var newDate = (minDate && date < minDate ? minDate : date);
1698                 newDate = (maxDate && newDate > maxDate ? maxDate : newDate);
1699                 return newDate;
1700         },
1702         /* Notify change of month/year. */
1703         _notifyChange: function(inst) {
1704                 var onChange = this._get(inst, 'onChangeMonthYear');
1705                 if (onChange)
1706                         onChange.apply((inst.input ? inst.input[0] : null),
1707                                 [inst.selectedYear, inst.selectedMonth + 1, inst]);
1708         },
1710         /* Determine the number of months to show. */
1711         _getNumberOfMonths: function(inst) {
1712                 var numMonths = this._get(inst, 'numberOfMonths');
1713                 return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
1714         },
1716         /* Determine the current maximum date - ensure no time components are set. */
1717         _getMinMaxDate: function(inst, minMax) {
1718                 return this._determineDate(inst, this._get(inst, minMax + 'Date'), null);
1719         },
1721         /* Find the number of days in a given month. */
1722         _getDaysInMonth: function(year, month) {
1723                 return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
1724         },
1726         /* Find the day of the week of the first of a month. */
1727         _getFirstDayOfMonth: function(year, month) {
1728                 return new Date(year, month, 1).getDay();
1729         },
1731         /* Determines if we should allow a "next/prev" month display change. */
1732         _canAdjustMonth: function(inst, offset, curYear, curMonth) {
1733                 var numMonths = this._getNumberOfMonths(inst);
1734                 var date = this._daylightSavingAdjust(new Date(curYear,
1735                         curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
1736                 if (offset < 0)
1737                         date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
1738                 return this._isInRange(inst, date);
1739         },
1741         /* Is the given date in the accepted range? */
1742         _isInRange: function(inst, date) {
1743                 var minDate = this._getMinMaxDate(inst, 'min');
1744                 var maxDate = this._getMinMaxDate(inst, 'max');
1745                 return ((!minDate || date.getTime() >= minDate.getTime()) &&
1746                         (!maxDate || date.getTime() <= maxDate.getTime()));
1747         },
1749         /* Provide the configuration settings for formatting/parsing. */
1750         _getFormatConfig: function(inst) {
1751                 var shortYearCutoff = this._get(inst, 'shortYearCutoff');
1752                 shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
1753                         new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
1754                 return {shortYearCutoff: shortYearCutoff,
1755                         dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
1756                         monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
1757         },
1759         /* Format the given date for display. */
1760         _formatDate: function(inst, day, month, year) {
1761                 if (!day) {
1762                         inst.currentDay = inst.selectedDay;
1763                         inst.currentMonth = inst.selectedMonth;
1764                         inst.currentYear = inst.selectedYear;
1765                 }
1766                 var date = (day ? (typeof day == 'object' ? day :
1767                         this._daylightSavingAdjust(new Date(year, month, day))) :
1768                         this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
1769                 return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
1770         }
1774  * Bind hover events for datepicker elements.
1775  * Done via delegate so the binding only occurs once in the lifetime of the parent div.
1776  * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
1777  */
1778 function bindHover(dpDiv) {
1779         var selector = 'button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a';
1780         return dpDiv.delegate(selector, 'mouseout', function() {
1781                         $(this).removeClass('ui-state-hover');
1782                         if (this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover');
1783                         if (this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover');
1784                 })
1785                 .delegate(selector, 'mouseover', function(){
1786                         if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0])) {
1787                                 $(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
1788                                 $(this).addClass('ui-state-hover');
1789                                 if (this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover');
1790                                 if (this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover');
1791                         }
1792                 });
1795 /* jQuery extend now ignores nulls! */
1796 function extendRemove(target, props) {
1797         $.extend(target, props);
1798         for (var name in props)
1799                 if (props[name] == null || props[name] == undefined)
1800                         target[name] = props[name];
1801         return target;
1804 /* Invoke the datepicker functionality.
1805    @param  options  string - a command, optionally followed by additional parameters or
1806                         Object - settings for attaching new datepicker functionality
1807    @return  jQuery object */
1808 $.fn.datepicker = function(options){
1810         /* Verify an empty collection wasn't passed - Fixes #6976 */
1811         if ( !this.length ) {
1812                 return this;
1813         }
1815         /* Initialise the date picker. */
1816         if (!$.datepicker.initialized) {
1817                 $(document).mousedown($.datepicker._checkExternalClick).
1818                         find(document.body).append($.datepicker.dpDiv);
1819                 $.datepicker.initialized = true;
1820         }
1822         var otherArgs = Array.prototype.slice.call(arguments, 1);
1823         if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget'))
1824                 return $.datepicker['_' + options + 'Datepicker'].
1825                         apply($.datepicker, [this[0]].concat(otherArgs));
1826         if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string')
1827                 return $.datepicker['_' + options + 'Datepicker'].
1828                         apply($.datepicker, [this[0]].concat(otherArgs));
1829         return this.each(function() {
1830                 typeof options == 'string' ?
1831                         $.datepicker['_' + options + 'Datepicker'].
1832                                 apply($.datepicker, [this].concat(otherArgs)) :
1833                         $.datepicker._attachDatepicker(this, options);
1834         });
1837 $.datepicker = new Datepicker(); // singleton instance
1838 $.datepicker.initialized = false;
1839 $.datepicker.uuid = new Date().getTime();
1840 $.datepicker.version = "1.9.2";
1842 // Workaround for #4055
1843 // Add another global to avoid noConflict issues with inline event handlers
1844 window['DP_jQuery_' + dpuuid] = $;
1846 })(jQuery);