Advertisement
Ultroman

monthpicker.js

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