8cc894ac54f0ecf350b41974ed432644d9bd62e2
[vnfsdk/refrepo.git] /
1 /*!
2  * Angular Material Design
3  * https://github.com/angular/material
4  * @license MIT
5  * v1.1.3
6  */
7 goog.provide('ngmaterial.components.datepicker');
8 goog.require('ngmaterial.components.icon');
9 goog.require('ngmaterial.components.virtualRepeat');
10 goog.require('ngmaterial.core');
11 /**
12  * @ngdoc module
13  * @name material.components.datepicker
14  * @description Module for the datepicker component.
15  */
16
17 angular.module('material.components.datepicker', [
18   'material.core',
19   'material.components.icon',
20   'material.components.virtualRepeat'
21 ]);
22
23 (function() {
24   'use strict';
25
26   /**
27    * @ngdoc directive
28    * @name mdCalendar
29    * @module material.components.datepicker
30    *
31    * @param {Date} ng-model The component's model. Should be a Date object.
32    * @param {Date=} md-min-date Expression representing the minimum date.
33    * @param {Date=} md-max-date Expression representing the maximum date.
34    * @param {(function(Date): boolean)=} md-date-filter Function expecting a date and returning a boolean whether it can be selected or not.
35    *
36    * @description
37    * `<md-calendar>` is a component that renders a calendar that can be used to select a date.
38    * It is a part of the `<md-datepicker` pane, however it can also be used on it's own.
39    *
40    * @usage
41    *
42    * <hljs lang="html">
43    *   <md-calendar ng-model="birthday"></md-calendar>
44    * </hljs>
45    */
46   CalendarCtrl['$inject'] = ["$element", "$scope", "$$mdDateUtil", "$mdUtil", "$mdConstant", "$mdTheming", "$$rAF", "$attrs", "$mdDateLocale"];
47   angular.module('material.components.datepicker')
48     .directive('mdCalendar', calendarDirective);
49
50   // POST RELEASE
51   // TODO(jelbourn): Mac Cmd + left / right == Home / End
52   // TODO(jelbourn): Refactor month element creation to use cloneNode (performance).
53   // TODO(jelbourn): Define virtual scrolling constants (compactness) users can override.
54   // TODO(jelbourn): Animated month transition on ng-model change (virtual-repeat)
55   // TODO(jelbourn): Scroll snapping (virtual repeat)
56   // TODO(jelbourn): Remove superfluous row from short months (virtual-repeat)
57   // TODO(jelbourn): Month headers stick to top when scrolling.
58   // TODO(jelbourn): Previous month opacity is lowered when partially scrolled out of view.
59   // TODO(jelbourn): Support md-calendar standalone on a page (as a tabstop w/ aria-live
60   //     announcement and key handling).
61   // Read-only calendar (not just date-picker).
62
63   function calendarDirective() {
64     return {
65       template: function(tElement, tAttr) {
66         // TODO(crisbeto): This is a workaround that allows the calendar to work, without
67         // a datepicker, until issue #8585 gets resolved. It can safely be removed
68         // afterwards. This ensures that the virtual repeater scrolls to the proper place on load by
69         // deferring the execution until the next digest. It's necessary only if the calendar is used
70         // without a datepicker, otherwise it's already wrapped in an ngIf.
71         var extraAttrs = tAttr.hasOwnProperty('ngIf') ? '' : 'ng-if="calendarCtrl.isInitialized"';
72         var template = '' +
73           '<div ng-switch="calendarCtrl.currentView" ' + extraAttrs + '>' +
74             '<md-calendar-year ng-switch-when="year"></md-calendar-year>' +
75             '<md-calendar-month ng-switch-default></md-calendar-month>' +
76           '</div>';
77
78         return template;
79       },
80       scope: {
81         minDate: '=mdMinDate',
82         maxDate: '=mdMaxDate',
83         dateFilter: '=mdDateFilter',
84         _currentView: '@mdCurrentView'
85       },
86       require: ['ngModel', 'mdCalendar'],
87       controller: CalendarCtrl,
88       controllerAs: 'calendarCtrl',
89       bindToController: true,
90       link: function(scope, element, attrs, controllers) {
91         var ngModelCtrl = controllers[0];
92         var mdCalendarCtrl = controllers[1];
93         mdCalendarCtrl.configureNgModel(ngModelCtrl);
94       }
95     };
96   }
97
98   /**
99    * Occasionally the hideVerticalScrollbar method might read an element's
100    * width as 0, because it hasn't been laid out yet. This value will be used
101    * as a fallback, in order to prevent scenarios where the element's width
102    * would otherwise have been set to 0. This value is the "usual" width of a
103    * calendar within a floating calendar pane.
104    */
105   var FALLBACK_WIDTH = 340;
106
107   /** Next identifier for calendar instance. */
108   var nextUniqueId = 0;
109
110   /**
111    * Controller for the mdCalendar component.
112    * ngInject @constructor
113    */
114   function CalendarCtrl($element, $scope, $$mdDateUtil, $mdUtil,
115     $mdConstant, $mdTheming, $$rAF, $attrs, $mdDateLocale) {
116
117     $mdTheming($element);
118
119     /** @final {!angular.JQLite} */
120     this.$element = $element;
121
122     /** @final {!angular.Scope} */
123     this.$scope = $scope;
124
125     /** @final */
126     this.dateUtil = $$mdDateUtil;
127
128     /** @final */
129     this.$mdUtil = $mdUtil;
130
131     /** @final */
132     this.keyCode = $mdConstant.KEY_CODE;
133
134     /** @final */
135     this.$$rAF = $$rAF;
136
137     /** @final */
138     this.$mdDateLocale = $mdDateLocale;
139
140     /** @final {Date} */
141     this.today = this.dateUtil.createDateAtMidnight();
142
143     /** @type {!angular.NgModelController} */
144     this.ngModelCtrl = null;
145
146     /** @type {String} Class applied to the selected date cell. */
147     this.SELECTED_DATE_CLASS = 'md-calendar-selected-date';
148
149     /** @type {String} Class applied to the cell for today. */
150     this.TODAY_CLASS = 'md-calendar-date-today';
151
152     /** @type {String} Class applied to the focused cell. */
153     this.FOCUSED_DATE_CLASS = 'md-focus';
154
155     /** @final {number} Unique ID for this calendar instance. */
156     this.id = nextUniqueId++;
157
158     /**
159      * The date that is currently focused or showing in the calendar. This will initially be set
160      * to the ng-model value if set, otherwise to today. It will be updated as the user navigates
161      * to other months. The cell corresponding to the displayDate does not necesarily always have
162      * focus in the document (such as for cases when the user is scrolling the calendar).
163      * @type {Date}
164      */
165     this.displayDate = null;
166
167     /**
168      * The selected date. Keep track of this separately from the ng-model value so that we
169      * can know, when the ng-model value changes, what the previous value was before it's updated
170      * in the component's UI.
171      *
172      * @type {Date}
173      */
174     this.selectedDate = null;
175
176     /**
177      * The first date that can be rendered by the calendar. The default is taken
178      * from the mdDateLocale provider and is limited by the mdMinDate.
179      * @type {Date}
180      */
181     this.firstRenderableDate = null;
182
183     /**
184      * The last date that can be rendered by the calendar. The default comes
185      * from the mdDateLocale provider and is limited by the maxDate.
186      * @type {Date}
187      */
188     this.lastRenderableDate = null;
189
190     /**
191      * Used to toggle initialize the root element in the next digest.
192      * @type {Boolean}
193      */
194     this.isInitialized = false;
195
196     /**
197      * Cache for the  width of the element without a scrollbar. Used to hide the scrollbar later on
198      * and to avoid extra reflows when switching between views.
199      * @type {Number}
200      */
201     this.width = 0;
202
203     /**
204      * Caches the width of the scrollbar in order to be used when hiding it and to avoid extra reflows.
205      * @type {Number}
206      */
207     this.scrollbarWidth = 0;
208
209     // Unless the user specifies so, the calendar should not be a tab stop.
210     // This is necessary because ngAria might add a tabindex to anything with an ng-model
211     // (based on whether or not the user has turned that particular feature on/off).
212     if (!$attrs.tabindex) {
213       $element.attr('tabindex', '-1');
214     }
215
216     var boundKeyHandler = angular.bind(this, this.handleKeyEvent);
217
218
219
220     // If use the md-calendar directly in the body without datepicker,
221     // handleKeyEvent will disable other inputs on the page.
222     // So only apply the handleKeyEvent on the body when the md-calendar inside datepicker,
223     // otherwise apply on the calendar element only.
224
225     var handleKeyElement;
226     if ($element.parent().hasClass('md-datepicker-calendar')) {
227       handleKeyElement = angular.element(document.body);
228     } else {
229       handleKeyElement = $element;
230     }
231
232     // Bind the keydown handler to the body, in order to handle cases where the focused
233     // element gets removed from the DOM and stops propagating click events.
234     handleKeyElement.on('keydown', boundKeyHandler);
235
236     $scope.$on('$destroy', function() {
237       handleKeyElement.off('keydown', boundKeyHandler);
238     });
239
240     // For Angular 1.4 and older, where there are no lifecycle hooks but bindings are pre-assigned,
241     // manually call the $onInit hook.
242     if (angular.version.major === 1 && angular.version.minor <= 4) {
243       this.$onInit();
244     }
245
246   }
247
248   /**
249    * Angular Lifecycle hook for newer Angular versions.
250    * Bindings are not guaranteed to have been assigned in the controller, but they are in the $onInit hook.
251    */
252   CalendarCtrl.prototype.$onInit = function() {
253
254     /**
255      * The currently visible calendar view. Note the prefix on the scope value,
256      * which is necessary, because the datepicker seems to reset the real one value if the
257      * calendar is open, but the value on the datepicker's scope is empty.
258      * @type {String}
259      */
260     this.currentView = this._currentView || 'month';
261
262     var dateLocale = this.$mdDateLocale;
263
264     if (this.minDate && this.minDate > dateLocale.firstRenderableDate) {
265       this.firstRenderableDate = this.minDate;
266     } else {
267       this.firstRenderableDate = dateLocale.firstRenderableDate;
268     }
269
270     if (this.maxDate && this.maxDate < dateLocale.lastRenderableDate) {
271       this.lastRenderableDate = this.maxDate;
272     } else {
273       this.lastRenderableDate = dateLocale.lastRenderableDate;
274     }
275   };
276
277   /**
278    * Sets up the controller's reference to ngModelController.
279    * @param {!angular.NgModelController} ngModelCtrl
280    */
281   CalendarCtrl.prototype.configureNgModel = function(ngModelCtrl) {
282     var self = this;
283
284     self.ngModelCtrl = ngModelCtrl;
285
286     self.$mdUtil.nextTick(function() {
287       self.isInitialized = true;
288     });
289
290     ngModelCtrl.$render = function() {
291       var value = this.$viewValue;
292
293       // Notify the child scopes of any changes.
294       self.$scope.$broadcast('md-calendar-parent-changed', value);
295
296       // Set up the selectedDate if it hasn't been already.
297       if (!self.selectedDate) {
298         self.selectedDate = value;
299       }
300
301       // Also set up the displayDate.
302       if (!self.displayDate) {
303         self.displayDate = self.selectedDate || self.today;
304       }
305     };
306   };
307
308   /**
309    * Sets the ng-model value for the calendar and emits a change event.
310    * @param {Date} date
311    */
312   CalendarCtrl.prototype.setNgModelValue = function(date) {
313     var value = this.dateUtil.createDateAtMidnight(date);
314     this.focus(value);
315     this.$scope.$emit('md-calendar-change', value);
316     this.ngModelCtrl.$setViewValue(value);
317     this.ngModelCtrl.$render();
318     return value;
319   };
320
321   /**
322    * Sets the current view that should be visible in the calendar
323    * @param {string} newView View name to be set.
324    * @param {number|Date} time Date object or a timestamp for the new display date.
325    */
326   CalendarCtrl.prototype.setCurrentView = function(newView, time) {
327     var self = this;
328
329     self.$mdUtil.nextTick(function() {
330       self.currentView = newView;
331
332       if (time) {
333         self.displayDate = angular.isDate(time) ? time : new Date(time);
334       }
335     });
336   };
337
338   /**
339    * Focus the cell corresponding to the given date.
340    * @param {Date} date The date to be focused.
341    */
342   CalendarCtrl.prototype.focus = function(date) {
343     if (this.dateUtil.isValidDate(date)) {
344       var previousFocus = this.$element[0].querySelector('.md-focus');
345       if (previousFocus) {
346         previousFocus.classList.remove(this.FOCUSED_DATE_CLASS);
347       }
348
349       var cellId = this.getDateId(date, this.currentView);
350       var cell = document.getElementById(cellId);
351       if (cell) {
352         cell.classList.add(this.FOCUSED_DATE_CLASS);
353         cell.focus();
354         this.displayDate = date;
355       }
356     } else {
357       var rootElement = this.$element[0].querySelector('[ng-switch]');
358
359       if (rootElement) {
360         rootElement.focus();
361       }
362     }
363   };
364
365   /**
366    * Normalizes the key event into an action name. The action will be broadcast
367    * to the child controllers.
368    * @param {KeyboardEvent} event
369    * @returns {String} The action that should be taken, or null if the key
370    * does not match a calendar shortcut.
371    */
372   CalendarCtrl.prototype.getActionFromKeyEvent = function(event) {
373     var keyCode = this.keyCode;
374
375     switch (event.which) {
376       case keyCode.ENTER: return 'select';
377
378       case keyCode.RIGHT_ARROW: return 'move-right';
379       case keyCode.LEFT_ARROW: return 'move-left';
380
381       // TODO(crisbeto): Might want to reconsider using metaKey, because it maps
382       // to the "Windows" key on PC, which opens the start menu or resizes the browser.
383       case keyCode.DOWN_ARROW: return event.metaKey ? 'move-page-down' : 'move-row-down';
384       case keyCode.UP_ARROW: return event.metaKey ? 'move-page-up' : 'move-row-up';
385
386       case keyCode.PAGE_DOWN: return 'move-page-down';
387       case keyCode.PAGE_UP: return 'move-page-up';
388
389       case keyCode.HOME: return 'start';
390       case keyCode.END: return 'end';
391
392       default: return null;
393     }
394   };
395
396   /**
397    * Handles a key event in the calendar with the appropriate action. The action will either
398    * be to select the focused date or to navigate to focus a new date.
399    * @param {KeyboardEvent} event
400    */
401   CalendarCtrl.prototype.handleKeyEvent = function(event) {
402     var self = this;
403
404     this.$scope.$apply(function() {
405       // Capture escape and emit back up so that a wrapping component
406       // (such as a date-picker) can decide to close.
407       if (event.which == self.keyCode.ESCAPE || event.which == self.keyCode.TAB) {
408         self.$scope.$emit('md-calendar-close');
409
410         if (event.which == self.keyCode.TAB) {
411           event.preventDefault();
412         }
413
414         return;
415       }
416
417       // Broadcast the action that any child controllers should take.
418       var action = self.getActionFromKeyEvent(event);
419       if (action) {
420         event.preventDefault();
421         event.stopPropagation();
422         self.$scope.$broadcast('md-calendar-parent-action', action);
423       }
424     });
425   };
426
427   /**
428    * Hides the vertical scrollbar on the calendar scroller of a child controller by
429    * setting the width on the calendar scroller and the `overflow: hidden` wrapper
430    * around the scroller, and then setting a padding-right on the scroller equal
431    * to the width of the browser's scrollbar.
432    *
433    * This will cause a reflow.
434    *
435    * @param {object} childCtrl The child controller whose scrollbar should be hidden.
436    */
437   CalendarCtrl.prototype.hideVerticalScrollbar = function(childCtrl) {
438     var self = this;
439     var element = childCtrl.$element[0];
440     var scrollMask = element.querySelector('.md-calendar-scroll-mask');
441
442     if (self.width > 0) {
443       setWidth();
444     } else {
445       self.$$rAF(function() {
446         var scroller = childCtrl.calendarScroller;
447
448         self.scrollbarWidth = scroller.offsetWidth - scroller.clientWidth;
449         self.width = element.querySelector('table').offsetWidth;
450         setWidth();
451       });
452     }
453
454     function setWidth() {
455       var width = self.width || FALLBACK_WIDTH;
456       var scrollbarWidth = self.scrollbarWidth;
457       var scroller = childCtrl.calendarScroller;
458
459       scrollMask.style.width = width + 'px';
460       scroller.style.width = (width + scrollbarWidth) + 'px';
461       scroller.style.paddingRight = scrollbarWidth + 'px';
462     }
463   };
464
465   /**
466    * Gets an identifier for a date unique to the calendar instance for internal
467    * purposes. Not to be displayed.
468    * @param {Date} date The date for which the id is being generated
469    * @param {string} namespace Namespace for the id. (month, year etc.)
470    * @returns {string}
471    */
472   CalendarCtrl.prototype.getDateId = function(date, namespace) {
473     if (!namespace) {
474       throw new Error('A namespace for the date id has to be specified.');
475     }
476
477     return [
478       'md',
479       this.id,
480       namespace,
481       date.getFullYear(),
482       date.getMonth(),
483       date.getDate()
484     ].join('-');
485   };
486
487   /**
488    * Util to trigger an extra digest on a parent scope, in order to to ensure that
489    * any child virtual repeaters have updated. This is necessary, because the virtual
490    * repeater doesn't update the $index the first time around since the content isn't
491    * in place yet. The case, in which this is an issue, is when the repeater has less
492    * than a page of content (e.g. a month or year view has a min or max date).
493    */
494   CalendarCtrl.prototype.updateVirtualRepeat = function() {
495     var scope = this.$scope;
496     var virtualRepeatResizeListener = scope.$on('$md-resize-enable', function() {
497       if (!scope.$$phase) {
498         scope.$apply();
499       }
500
501       virtualRepeatResizeListener();
502     });
503   };
504 })();
505
506 (function() {
507   'use strict';
508
509   CalendarMonthCtrl['$inject'] = ["$element", "$scope", "$animate", "$q", "$$mdDateUtil", "$mdDateLocale"];
510   angular.module('material.components.datepicker')
511     .directive('mdCalendarMonth', calendarDirective);
512
513   /**
514    * Height of one calendar month tbody. This must be made known to the virtual-repeat and is
515    * subsequently used for scrolling to specific months.
516    */
517   var TBODY_HEIGHT = 265;
518
519   /**
520    * Height of a calendar month with a single row. This is needed to calculate the offset for
521    * rendering an extra month in virtual-repeat that only contains one row.
522    */
523   var TBODY_SINGLE_ROW_HEIGHT = 45;
524
525   /** Private directive that represents a list of months inside the calendar. */
526   function calendarDirective() {
527     return {
528       template:
529         '<table aria-hidden="true" class="md-calendar-day-header"><thead></thead></table>' +
530         '<div class="md-calendar-scroll-mask">' +
531         '<md-virtual-repeat-container class="md-calendar-scroll-container" ' +
532               'md-offset-size="' + (TBODY_SINGLE_ROW_HEIGHT - TBODY_HEIGHT) + '">' +
533             '<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' +
534               '<tbody ' +
535                   'md-calendar-month-body ' +
536                   'role="rowgroup" ' +
537                   'md-virtual-repeat="i in monthCtrl.items" ' +
538                   'md-month-offset="$index" ' +
539                   'class="md-calendar-month" ' +
540                   'md-start-index="monthCtrl.getSelectedMonthIndex()" ' +
541                   'md-item-size="' + TBODY_HEIGHT + '">' +
542
543                 // The <tr> ensures that the <tbody> will always have the
544                 // proper height, even if it's empty. If it's content is
545                 // compiled, the <tr> will be overwritten.
546                 '<tr aria-hidden="true" style="height:' + TBODY_HEIGHT + 'px;"></tr>' +
547               '</tbody>' +
548             '</table>' +
549           '</md-virtual-repeat-container>' +
550         '</div>',
551       require: ['^^mdCalendar', 'mdCalendarMonth'],
552       controller: CalendarMonthCtrl,
553       controllerAs: 'monthCtrl',
554       bindToController: true,
555       link: function(scope, element, attrs, controllers) {
556         var calendarCtrl = controllers[0];
557         var monthCtrl = controllers[1];
558         monthCtrl.initialize(calendarCtrl);
559       }
560     };
561   }
562
563   /**
564    * Controller for the calendar month component.
565    * ngInject @constructor
566    */
567   function CalendarMonthCtrl($element, $scope, $animate, $q,
568     $$mdDateUtil, $mdDateLocale) {
569
570     /** @final {!angular.JQLite} */
571     this.$element = $element;
572
573     /** @final {!angular.Scope} */
574     this.$scope = $scope;
575
576     /** @final {!angular.$animate} */
577     this.$animate = $animate;
578
579     /** @final {!angular.$q} */
580     this.$q = $q;
581
582     /** @final */
583     this.dateUtil = $$mdDateUtil;
584
585     /** @final */
586     this.dateLocale = $mdDateLocale;
587
588     /** @final {HTMLElement} */
589     this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller');
590
591     /** @type {boolean} */
592     this.isInitialized = false;
593
594     /** @type {boolean} */
595     this.isMonthTransitionInProgress = false;
596
597     var self = this;
598
599     /**
600      * Handles a click event on a date cell.
601      * Created here so that every cell can use the same function instance.
602      * @this {HTMLTableCellElement} The cell that was clicked.
603      */
604     this.cellClickHandler = function() {
605       var timestamp = $$mdDateUtil.getTimestampFromNode(this);
606       self.$scope.$apply(function() {
607         self.calendarCtrl.setNgModelValue(timestamp);
608       });
609     };
610
611     /**
612      * Handles click events on the month headers. Switches
613      * the calendar to the year view.
614      * @this {HTMLTableCellElement} The cell that was clicked.
615      */
616     this.headerClickHandler = function() {
617       self.calendarCtrl.setCurrentView('year', $$mdDateUtil.getTimestampFromNode(this));
618     };
619   }
620
621   /*** Initialization ***/
622
623   /**
624    * Initialize the controller by saving a reference to the calendar and
625    * setting up the object that will be iterated by the virtual repeater.
626    */
627   CalendarMonthCtrl.prototype.initialize = function(calendarCtrl) {
628     /**
629      * Dummy array-like object for virtual-repeat to iterate over. The length is the total
630      * number of months that can be viewed. We add 2 months: one to include the current month
631      * and one for the last dummy month.
632      *
633      * This is shorter than ideal because of a (potential) Firefox bug
634      * https://bugzilla.mozilla.org/show_bug.cgi?id=1181658.
635      */
636
637     this.items = {
638       length: this.dateUtil.getMonthDistance(
639         calendarCtrl.firstRenderableDate,
640         calendarCtrl.lastRenderableDate
641       ) + 2
642     };
643
644     this.calendarCtrl = calendarCtrl;
645     this.attachScopeListeners();
646     calendarCtrl.updateVirtualRepeat();
647
648     // Fire the initial render, since we might have missed it the first time it fired.
649     calendarCtrl.ngModelCtrl && calendarCtrl.ngModelCtrl.$render();
650   };
651
652   /**
653    * Gets the "index" of the currently selected date as it would be in the virtual-repeat.
654    * @returns {number}
655    */
656   CalendarMonthCtrl.prototype.getSelectedMonthIndex = function() {
657     var calendarCtrl = this.calendarCtrl;
658
659     return this.dateUtil.getMonthDistance(
660       calendarCtrl.firstRenderableDate,
661       calendarCtrl.displayDate || calendarCtrl.selectedDate || calendarCtrl.today
662     );
663   };
664
665   /**
666    * Change the selected date in the calendar (ngModel value has already been changed).
667    * @param {Date} date
668    */
669   CalendarMonthCtrl.prototype.changeSelectedDate = function(date) {
670     var self = this;
671     var calendarCtrl = self.calendarCtrl;
672     var previousSelectedDate = calendarCtrl.selectedDate;
673     calendarCtrl.selectedDate = date;
674
675     this.changeDisplayDate(date).then(function() {
676       var selectedDateClass = calendarCtrl.SELECTED_DATE_CLASS;
677       var namespace = 'month';
678
679       // Remove the selected class from the previously selected date, if any.
680       if (previousSelectedDate) {
681         var prevDateCell = document.getElementById(calendarCtrl.getDateId(previousSelectedDate, namespace));
682         if (prevDateCell) {
683           prevDateCell.classList.remove(selectedDateClass);
684           prevDateCell.setAttribute('aria-selected', 'false');
685         }
686       }
687
688       // Apply the select class to the new selected date if it is set.
689       if (date) {
690         var dateCell = document.getElementById(calendarCtrl.getDateId(date, namespace));
691         if (dateCell) {
692           dateCell.classList.add(selectedDateClass);
693           dateCell.setAttribute('aria-selected', 'true');
694         }
695       }
696     });
697   };
698
699   /**
700    * Change the date that is being shown in the calendar. If the given date is in a different
701    * month, the displayed month will be transitioned.
702    * @param {Date} date
703    */
704   CalendarMonthCtrl.prototype.changeDisplayDate = function(date) {
705     // Initialization is deferred until this function is called because we want to reflect
706     // the starting value of ngModel.
707     if (!this.isInitialized) {
708       this.buildWeekHeader();
709       this.calendarCtrl.hideVerticalScrollbar(this);
710       this.isInitialized = true;
711       return this.$q.when();
712     }
713
714     // If trying to show an invalid date or a transition is in progress, do nothing.
715     if (!this.dateUtil.isValidDate(date) || this.isMonthTransitionInProgress) {
716       return this.$q.when();
717     }
718
719     this.isMonthTransitionInProgress = true;
720     var animationPromise = this.animateDateChange(date);
721
722     this.calendarCtrl.displayDate = date;
723
724     var self = this;
725     animationPromise.then(function() {
726       self.isMonthTransitionInProgress = false;
727     });
728
729     return animationPromise;
730   };
731
732   /**
733    * Animates the transition from the calendar's current month to the given month.
734    * @param {Date} date
735    * @returns {angular.$q.Promise} The animation promise.
736    */
737   CalendarMonthCtrl.prototype.animateDateChange = function(date) {
738     if (this.dateUtil.isValidDate(date)) {
739       var monthDistance = this.dateUtil.getMonthDistance(this.calendarCtrl.firstRenderableDate, date);
740       this.calendarScroller.scrollTop = monthDistance * TBODY_HEIGHT;
741     }
742
743     return this.$q.when();
744   };
745
746   /**
747    * Builds and appends a day-of-the-week header to the calendar.
748    * This should only need to be called once during initialization.
749    */
750   CalendarMonthCtrl.prototype.buildWeekHeader = function() {
751     var firstDayOfWeek = this.dateLocale.firstDayOfWeek;
752     var shortDays = this.dateLocale.shortDays;
753
754     var row = document.createElement('tr');
755     for (var i = 0; i < 7; i++) {
756       var th = document.createElement('th');
757       th.textContent = shortDays[(i + firstDayOfWeek) % 7];
758       row.appendChild(th);
759     }
760
761     this.$element.find('thead').append(row);
762   };
763
764   /**
765    * Attaches listeners for the scope events that are broadcast by the calendar.
766    */
767   CalendarMonthCtrl.prototype.attachScopeListeners = function() {
768     var self = this;
769
770     self.$scope.$on('md-calendar-parent-changed', function(event, value) {
771       self.changeSelectedDate(value);
772     });
773
774     self.$scope.$on('md-calendar-parent-action', angular.bind(this, this.handleKeyEvent));
775   };
776
777   /**
778    * Handles the month-specific keyboard interactions.
779    * @param {Object} event Scope event object passed by the calendar.
780    * @param {String} action Action, corresponding to the key that was pressed.
781    */
782   CalendarMonthCtrl.prototype.handleKeyEvent = function(event, action) {
783     var calendarCtrl = this.calendarCtrl;
784     var displayDate = calendarCtrl.displayDate;
785
786     if (action === 'select') {
787       calendarCtrl.setNgModelValue(displayDate);
788     } else {
789       var date = null;
790       var dateUtil = this.dateUtil;
791
792       switch (action) {
793         case 'move-right': date = dateUtil.incrementDays(displayDate, 1); break;
794         case 'move-left': date = dateUtil.incrementDays(displayDate, -1); break;
795
796         case 'move-page-down': date = dateUtil.incrementMonths(displayDate, 1); break;
797         case 'move-page-up': date = dateUtil.incrementMonths(displayDate, -1); break;
798
799         case 'move-row-down': date = dateUtil.incrementDays(displayDate, 7); break;
800         case 'move-row-up': date = dateUtil.incrementDays(displayDate, -7); break;
801
802         case 'start': date = dateUtil.getFirstDateOfMonth(displayDate); break;
803         case 'end': date = dateUtil.getLastDateOfMonth(displayDate); break;
804       }
805
806       if (date) {
807         date = this.dateUtil.clampDate(date, calendarCtrl.minDate, calendarCtrl.maxDate);
808
809         this.changeDisplayDate(date).then(function() {
810           calendarCtrl.focus(date);
811         });
812       }
813     }
814   };
815 })();
816
817 (function() {
818   'use strict';
819
820   mdCalendarMonthBodyDirective['$inject'] = ["$compile", "$$mdSvgRegistry"];
821   CalendarMonthBodyCtrl['$inject'] = ["$element", "$$mdDateUtil", "$mdDateLocale"];
822   angular.module('material.components.datepicker')
823       .directive('mdCalendarMonthBody', mdCalendarMonthBodyDirective);
824
825   /**
826    * Private directive consumed by md-calendar-month. Having this directive lets the calender use
827    * md-virtual-repeat and also cleanly separates the month DOM construction functions from
828    * the rest of the calendar controller logic.
829    * ngInject
830    */
831   function mdCalendarMonthBodyDirective($compile, $$mdSvgRegistry) {
832     var ARROW_ICON = $compile('<md-icon md-svg-src="' +
833       $$mdSvgRegistry.mdTabsArrow + '"></md-icon>')({})[0];
834
835     return {
836       require: ['^^mdCalendar', '^^mdCalendarMonth', 'mdCalendarMonthBody'],
837       scope: { offset: '=mdMonthOffset' },
838       controller: CalendarMonthBodyCtrl,
839       controllerAs: 'mdMonthBodyCtrl',
840       bindToController: true,
841       link: function(scope, element, attrs, controllers) {
842         var calendarCtrl = controllers[0];
843         var monthCtrl = controllers[1];
844         var monthBodyCtrl = controllers[2];
845
846         monthBodyCtrl.calendarCtrl = calendarCtrl;
847         monthBodyCtrl.monthCtrl = monthCtrl;
848         monthBodyCtrl.arrowIcon = ARROW_ICON.cloneNode(true);
849
850         // The virtual-repeat re-uses the same DOM elements, so there are only a limited number
851         // of repeated items that are linked, and then those elements have their bindings updated.
852         // Since the months are not generated by bindings, we simply regenerate the entire thing
853         // when the binding (offset) changes.
854         scope.$watch(function() { return monthBodyCtrl.offset; }, function(offset) {
855           if (angular.isNumber(offset)) {
856             monthBodyCtrl.generateContent();
857           }
858         });
859       }
860     };
861   }
862
863   /**
864    * Controller for a single calendar month.
865    * ngInject @constructor
866    */
867   function CalendarMonthBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
868     /** @final {!angular.JQLite} */
869     this.$element = $element;
870
871     /** @final */
872     this.dateUtil = $$mdDateUtil;
873
874     /** @final */
875     this.dateLocale = $mdDateLocale;
876
877     /** @type {Object} Reference to the month view. */
878     this.monthCtrl = null;
879
880     /** @type {Object} Reference to the calendar. */
881     this.calendarCtrl = null;
882
883     /**
884      * Number of months from the start of the month "items" that the currently rendered month
885      * occurs. Set via angular data binding.
886      * @type {number}
887      */
888     this.offset = null;
889
890     /**
891      * Date cell to focus after appending the month to the document.
892      * @type {HTMLElement}
893      */
894     this.focusAfterAppend = null;
895   }
896
897   /** Generate and append the content for this month to the directive element. */
898   CalendarMonthBodyCtrl.prototype.generateContent = function() {
899     var date = this.dateUtil.incrementMonths(this.calendarCtrl.firstRenderableDate, this.offset);
900
901     this.$element
902       .empty()
903       .append(this.buildCalendarForMonth(date));
904
905     if (this.focusAfterAppend) {
906       this.focusAfterAppend.classList.add(this.calendarCtrl.FOCUSED_DATE_CLASS);
907       this.focusAfterAppend.focus();
908       this.focusAfterAppend = null;
909     }
910   };
911
912   /**
913    * Creates a single cell to contain a date in the calendar with all appropriate
914    * attributes and classes added. If a date is given, the cell content will be set
915    * based on the date.
916    * @param {Date=} opt_date
917    * @returns {HTMLElement}
918    */
919   CalendarMonthBodyCtrl.prototype.buildDateCell = function(opt_date) {
920     var monthCtrl = this.monthCtrl;
921     var calendarCtrl = this.calendarCtrl;
922
923     // TODO(jelbourn): cloneNode is likely a faster way of doing this.
924     var cell = document.createElement('td');
925     cell.tabIndex = -1;
926     cell.classList.add('md-calendar-date');
927     cell.setAttribute('role', 'gridcell');
928
929     if (opt_date) {
930       cell.setAttribute('tabindex', '-1');
931       cell.setAttribute('aria-label', this.dateLocale.longDateFormatter(opt_date));
932       cell.id = calendarCtrl.getDateId(opt_date, 'month');
933
934       // Use `data-timestamp` attribute because IE10 does not support the `dataset` property.
935       cell.setAttribute('data-timestamp', opt_date.getTime());
936
937       // TODO(jelourn): Doing these comparisons for class addition during generation might be slow.
938       // It may be better to finish the construction and then query the node and add the class.
939       if (this.dateUtil.isSameDay(opt_date, calendarCtrl.today)) {
940         cell.classList.add(calendarCtrl.TODAY_CLASS);
941       }
942
943       if (this.dateUtil.isValidDate(calendarCtrl.selectedDate) &&
944           this.dateUtil.isSameDay(opt_date, calendarCtrl.selectedDate)) {
945         cell.classList.add(calendarCtrl.SELECTED_DATE_CLASS);
946         cell.setAttribute('aria-selected', 'true');
947       }
948
949       var cellText = this.dateLocale.dates[opt_date.getDate()];
950
951       if (this.isDateEnabled(opt_date)) {
952         // Add a indicator for select, hover, and focus states.
953         var selectionIndicator = document.createElement('span');
954         selectionIndicator.classList.add('md-calendar-date-selection-indicator');
955         selectionIndicator.textContent = cellText;
956         cell.appendChild(selectionIndicator);
957         cell.addEventListener('click', monthCtrl.cellClickHandler);
958
959         if (calendarCtrl.displayDate && this.dateUtil.isSameDay(opt_date, calendarCtrl.displayDate)) {
960           this.focusAfterAppend = cell;
961         }
962       } else {
963         cell.classList.add('md-calendar-date-disabled');
964         cell.textContent = cellText;
965       }
966     }
967
968     return cell;
969   };
970
971   /**
972    * Check whether date is in range and enabled
973    * @param {Date=} opt_date
974    * @return {boolean} Whether the date is enabled.
975    */
976   CalendarMonthBodyCtrl.prototype.isDateEnabled = function(opt_date) {
977     return this.dateUtil.isDateWithinRange(opt_date,
978           this.calendarCtrl.minDate, this.calendarCtrl.maxDate) &&
979           (!angular.isFunction(this.calendarCtrl.dateFilter)
980            || this.calendarCtrl.dateFilter(opt_date));
981   };
982
983   /**
984    * Builds a `tr` element for the calendar grid.
985    * @param rowNumber The week number within the month.
986    * @returns {HTMLElement}
987    */
988   CalendarMonthBodyCtrl.prototype.buildDateRow = function(rowNumber) {
989     var row = document.createElement('tr');
990     row.setAttribute('role', 'row');
991
992     // Because of an NVDA bug (with Firefox), the row needs an aria-label in order
993     // to prevent the entire row being read aloud when the user moves between rows.
994     // See http://community.nvda-project.org/ticket/4643.
995     row.setAttribute('aria-label', this.dateLocale.weekNumberFormatter(rowNumber));
996
997     return row;
998   };
999
1000   /**
1001    * Builds the <tbody> content for the given date's month.
1002    * @param {Date=} opt_dateInMonth
1003    * @returns {DocumentFragment} A document fragment containing the <tr> elements.
1004    */
1005   CalendarMonthBodyCtrl.prototype.buildCalendarForMonth = function(opt_dateInMonth) {
1006     var date = this.dateUtil.isValidDate(opt_dateInMonth) ? opt_dateInMonth : new Date();
1007
1008     var firstDayOfMonth = this.dateUtil.getFirstDateOfMonth(date);
1009     var firstDayOfTheWeek = this.getLocaleDay_(firstDayOfMonth);
1010     var numberOfDaysInMonth = this.dateUtil.getNumberOfDaysInMonth(date);
1011
1012     // Store rows for the month in a document fragment so that we can append them all at once.
1013     var monthBody = document.createDocumentFragment();
1014
1015     var rowNumber = 1;
1016     var row = this.buildDateRow(rowNumber);
1017     monthBody.appendChild(row);
1018
1019     // If this is the final month in the list of items, only the first week should render,
1020     // so we should return immediately after the first row is complete and has been
1021     // attached to the body.
1022     var isFinalMonth = this.offset === this.monthCtrl.items.length - 1;
1023
1024     // Add a label for the month. If the month starts on a Sun/Mon/Tues, the month label
1025     // goes on a row above the first of the month. Otherwise, the month label takes up the first
1026     // two cells of the first row.
1027     var blankCellOffset = 0;
1028     var monthLabelCell = document.createElement('td');
1029     var monthLabelCellContent = document.createElement('span');
1030
1031     monthLabelCellContent.textContent = this.dateLocale.monthHeaderFormatter(date);
1032     monthLabelCell.appendChild(monthLabelCellContent);
1033     monthLabelCell.classList.add('md-calendar-month-label');
1034     // If the entire month is after the max date, render the label as a disabled state.
1035     if (this.calendarCtrl.maxDate && firstDayOfMonth > this.calendarCtrl.maxDate) {
1036       monthLabelCell.classList.add('md-calendar-month-label-disabled');
1037     } else {
1038       monthLabelCell.addEventListener('click', this.monthCtrl.headerClickHandler);
1039       monthLabelCell.setAttribute('data-timestamp', firstDayOfMonth.getTime());
1040       monthLabelCell.setAttribute('aria-label', this.dateLocale.monthFormatter(date));
1041       monthLabelCell.appendChild(this.arrowIcon.cloneNode(true));
1042     }
1043
1044     if (firstDayOfTheWeek <= 2) {
1045       monthLabelCell.setAttribute('colspan', '7');
1046
1047       var monthLabelRow = this.buildDateRow();
1048       monthLabelRow.appendChild(monthLabelCell);
1049       monthBody.insertBefore(monthLabelRow, row);
1050
1051       if (isFinalMonth) {
1052         return monthBody;
1053       }
1054     } else {
1055       blankCellOffset = 3;
1056       monthLabelCell.setAttribute('colspan', '3');
1057       row.appendChild(monthLabelCell);
1058     }
1059
1060     // Add a blank cell for each day of the week that occurs before the first of the month.
1061     // For example, if the first day of the month is a Tuesday, add blank cells for Sun and Mon.
1062     // The blankCellOffset is needed in cases where the first N cells are used by the month label.
1063     for (var i = blankCellOffset; i < firstDayOfTheWeek; i++) {
1064       row.appendChild(this.buildDateCell());
1065     }
1066
1067     // Add a cell for each day of the month, keeping track of the day of the week so that
1068     // we know when to start a new row.
1069     var dayOfWeek = firstDayOfTheWeek;
1070     var iterationDate = firstDayOfMonth;
1071     for (var d = 1; d <= numberOfDaysInMonth; d++) {
1072       // If we've reached the end of the week, start a new row.
1073       if (dayOfWeek === 7) {
1074         // We've finished the first row, so we're done if this is the final month.
1075         if (isFinalMonth) {
1076           return monthBody;
1077         }
1078         dayOfWeek = 0;
1079         rowNumber++;
1080         row = this.buildDateRow(rowNumber);
1081         monthBody.appendChild(row);
1082       }
1083
1084       iterationDate.setDate(d);
1085       var cell = this.buildDateCell(iterationDate);
1086       row.appendChild(cell);
1087
1088       dayOfWeek++;
1089     }
1090
1091     // Ensure that the last row of the month has 7 cells.
1092     while (row.childNodes.length < 7) {
1093       row.appendChild(this.buildDateCell());
1094     }
1095
1096     // Ensure that all months have 6 rows. This is necessary for now because the virtual-repeat
1097     // requires that all items have exactly the same height.
1098     while (monthBody.childNodes.length < 6) {
1099       var whitespaceRow = this.buildDateRow();
1100       for (var j = 0; j < 7; j++) {
1101         whitespaceRow.appendChild(this.buildDateCell());
1102       }
1103       monthBody.appendChild(whitespaceRow);
1104     }
1105
1106     return monthBody;
1107   };
1108
1109   /**
1110    * Gets the day-of-the-week index for a date for the current locale.
1111    * @private
1112    * @param {Date} date
1113    * @returns {number} The column index of the date in the calendar.
1114    */
1115   CalendarMonthBodyCtrl.prototype.getLocaleDay_ = function(date) {
1116     return (date.getDay() + (7 - this.dateLocale.firstDayOfWeek)) % 7;
1117   };
1118 })();
1119
1120 (function() {
1121   'use strict';
1122
1123   CalendarYearCtrl['$inject'] = ["$element", "$scope", "$animate", "$q", "$$mdDateUtil"];
1124   angular.module('material.components.datepicker')
1125     .directive('mdCalendarYear', calendarDirective);
1126
1127   /**
1128    * Height of one calendar year tbody. This must be made known to the virtual-repeat and is
1129    * subsequently used for scrolling to specific years.
1130    */
1131   var TBODY_HEIGHT = 88;
1132
1133   /** Private component, representing a list of years in the calendar. */
1134   function calendarDirective() {
1135     return {
1136       template:
1137         '<div class="md-calendar-scroll-mask">' +
1138           '<md-virtual-repeat-container class="md-calendar-scroll-container">' +
1139             '<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' +
1140               '<tbody ' +
1141                   'md-calendar-year-body ' +
1142                   'role="rowgroup" ' +
1143                   'md-virtual-repeat="i in yearCtrl.items" ' +
1144                   'md-year-offset="$index" class="md-calendar-year" ' +
1145                   'md-start-index="yearCtrl.getFocusedYearIndex()" ' +
1146                   'md-item-size="' + TBODY_HEIGHT + '">' +
1147                 // The <tr> ensures that the <tbody> will have the proper
1148                 // height, even though it may be empty.
1149                 '<tr aria-hidden="true" style="height:' + TBODY_HEIGHT + 'px;"></tr>' +
1150               '</tbody>' +
1151             '</table>' +
1152           '</md-virtual-repeat-container>' +
1153         '</div>',
1154       require: ['^^mdCalendar', 'mdCalendarYear'],
1155       controller: CalendarYearCtrl,
1156       controllerAs: 'yearCtrl',
1157       bindToController: true,
1158       link: function(scope, element, attrs, controllers) {
1159         var calendarCtrl = controllers[0];
1160         var yearCtrl = controllers[1];
1161         yearCtrl.initialize(calendarCtrl);
1162       }
1163     };
1164   }
1165
1166   /**
1167    * Controller for the mdCalendar component.
1168    * ngInject @constructor
1169    */
1170   function CalendarYearCtrl($element, $scope, $animate, $q, $$mdDateUtil) {
1171
1172     /** @final {!angular.JQLite} */
1173     this.$element = $element;
1174
1175     /** @final {!angular.Scope} */
1176     this.$scope = $scope;
1177
1178     /** @final {!angular.$animate} */
1179     this.$animate = $animate;
1180
1181     /** @final {!angular.$q} */
1182     this.$q = $q;
1183
1184     /** @final */
1185     this.dateUtil = $$mdDateUtil;
1186
1187     /** @final {HTMLElement} */
1188     this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller');
1189
1190     /** @type {boolean} */
1191     this.isInitialized = false;
1192
1193     /** @type {boolean} */
1194     this.isMonthTransitionInProgress = false;
1195
1196     var self = this;
1197
1198     /**
1199      * Handles a click event on a date cell.
1200      * Created here so that every cell can use the same function instance.
1201      * @this {HTMLTableCellElement} The cell that was clicked.
1202      */
1203     this.cellClickHandler = function() {
1204       self.calendarCtrl.setCurrentView('month', $$mdDateUtil.getTimestampFromNode(this));
1205     };
1206   }
1207
1208   /**
1209    * Initialize the controller by saving a reference to the calendar and
1210    * setting up the object that will be iterated by the virtual repeater.
1211    */
1212   CalendarYearCtrl.prototype.initialize = function(calendarCtrl) {
1213     /**
1214      * Dummy array-like object for virtual-repeat to iterate over. The length is the total
1215      * number of years that can be viewed. We add 1 extra in order to include the current year.
1216      */
1217     this.items = {
1218       length: this.dateUtil.getYearDistance(
1219         calendarCtrl.firstRenderableDate,
1220         calendarCtrl.lastRenderableDate
1221       ) + 1
1222     };
1223
1224     this.calendarCtrl = calendarCtrl;
1225     this.attachScopeListeners();
1226     calendarCtrl.updateVirtualRepeat();
1227
1228     // Fire the initial render, since we might have missed it the first time it fired.
1229     calendarCtrl.ngModelCtrl && calendarCtrl.ngModelCtrl.$render();
1230   };
1231
1232   /**
1233    * Gets the "index" of the currently selected date as it would be in the virtual-repeat.
1234    * @returns {number}
1235    */
1236   CalendarYearCtrl.prototype.getFocusedYearIndex = function() {
1237     var calendarCtrl = this.calendarCtrl;
1238
1239     return this.dateUtil.getYearDistance(
1240       calendarCtrl.firstRenderableDate,
1241       calendarCtrl.displayDate || calendarCtrl.selectedDate || calendarCtrl.today
1242     );
1243   };
1244
1245   /**
1246    * Change the date that is highlighted in the calendar.
1247    * @param {Date} date
1248    */
1249   CalendarYearCtrl.prototype.changeDate = function(date) {
1250     // Initialization is deferred until this function is called because we want to reflect
1251     // the starting value of ngModel.
1252     if (!this.isInitialized) {
1253       this.calendarCtrl.hideVerticalScrollbar(this);
1254       this.isInitialized = true;
1255       return this.$q.when();
1256     } else if (this.dateUtil.isValidDate(date) && !this.isMonthTransitionInProgress) {
1257       var self = this;
1258       var animationPromise = this.animateDateChange(date);
1259
1260       self.isMonthTransitionInProgress = true;
1261       self.calendarCtrl.displayDate = date;
1262
1263       return animationPromise.then(function() {
1264         self.isMonthTransitionInProgress = false;
1265       });
1266     }
1267   };
1268
1269   /**
1270    * Animates the transition from the calendar's current month to the given month.
1271    * @param {Date} date
1272    * @returns {angular.$q.Promise} The animation promise.
1273    */
1274   CalendarYearCtrl.prototype.animateDateChange = function(date) {
1275     if (this.dateUtil.isValidDate(date)) {
1276       var monthDistance = this.dateUtil.getYearDistance(this.calendarCtrl.firstRenderableDate, date);
1277       this.calendarScroller.scrollTop = monthDistance * TBODY_HEIGHT;
1278     }
1279
1280     return this.$q.when();
1281   };
1282
1283   /**
1284    * Handles the year-view-specific keyboard interactions.
1285    * @param {Object} event Scope event object passed by the calendar.
1286    * @param {String} action Action, corresponding to the key that was pressed.
1287    */
1288   CalendarYearCtrl.prototype.handleKeyEvent = function(event, action) {
1289     var calendarCtrl = this.calendarCtrl;
1290     var displayDate = calendarCtrl.displayDate;
1291
1292     if (action === 'select') {
1293       this.changeDate(displayDate).then(function() {
1294         calendarCtrl.setCurrentView('month', displayDate);
1295         calendarCtrl.focus(displayDate);
1296       });
1297     } else {
1298       var date = null;
1299       var dateUtil = this.dateUtil;
1300
1301       switch (action) {
1302         case 'move-right': date = dateUtil.incrementMonths(displayDate, 1); break;
1303         case 'move-left': date = dateUtil.incrementMonths(displayDate, -1); break;
1304
1305         case 'move-row-down': date = dateUtil.incrementMonths(displayDate, 6); break;
1306         case 'move-row-up': date = dateUtil.incrementMonths(displayDate, -6); break;
1307       }
1308
1309       if (date) {
1310         var min = calendarCtrl.minDate ? dateUtil.getFirstDateOfMonth(calendarCtrl.minDate) : null;
1311         var max = calendarCtrl.maxDate ? dateUtil.getFirstDateOfMonth(calendarCtrl.maxDate) : null;
1312         date = dateUtil.getFirstDateOfMonth(this.dateUtil.clampDate(date, min, max));
1313
1314         this.changeDate(date).then(function() {
1315           calendarCtrl.focus(date);
1316         });
1317       }
1318     }
1319   };
1320
1321   /**
1322    * Attaches listeners for the scope events that are broadcast by the calendar.
1323    */
1324   CalendarYearCtrl.prototype.attachScopeListeners = function() {
1325     var self = this;
1326
1327     self.$scope.$on('md-calendar-parent-changed', function(event, value) {
1328       self.changeDate(value);
1329     });
1330
1331     self.$scope.$on('md-calendar-parent-action', angular.bind(self, self.handleKeyEvent));
1332   };
1333 })();
1334
1335 (function() {
1336   'use strict';
1337
1338   CalendarYearBodyCtrl['$inject'] = ["$element", "$$mdDateUtil", "$mdDateLocale"];
1339   angular.module('material.components.datepicker')
1340       .directive('mdCalendarYearBody', mdCalendarYearDirective);
1341
1342   /**
1343    * Private component, consumed by the md-calendar-year, which separates the DOM construction logic
1344    * and allows for the year view to use md-virtual-repeat.
1345    */
1346   function mdCalendarYearDirective() {
1347     return {
1348       require: ['^^mdCalendar', '^^mdCalendarYear', 'mdCalendarYearBody'],
1349       scope: { offset: '=mdYearOffset' },
1350       controller: CalendarYearBodyCtrl,
1351       controllerAs: 'mdYearBodyCtrl',
1352       bindToController: true,
1353       link: function(scope, element, attrs, controllers) {
1354         var calendarCtrl = controllers[0];
1355         var yearCtrl = controllers[1];
1356         var yearBodyCtrl = controllers[2];
1357
1358         yearBodyCtrl.calendarCtrl = calendarCtrl;
1359         yearBodyCtrl.yearCtrl = yearCtrl;
1360
1361         scope.$watch(function() { return yearBodyCtrl.offset; }, function(offset) {
1362           if (angular.isNumber(offset)) {
1363             yearBodyCtrl.generateContent();
1364           }
1365         });
1366       }
1367     };
1368   }
1369
1370   /**
1371    * Controller for a single year.
1372    * ngInject @constructor
1373    */
1374   function CalendarYearBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
1375     /** @final {!angular.JQLite} */
1376     this.$element = $element;
1377
1378     /** @final */
1379     this.dateUtil = $$mdDateUtil;
1380
1381     /** @final */
1382     this.dateLocale = $mdDateLocale;
1383
1384     /** @type {Object} Reference to the calendar. */
1385     this.calendarCtrl = null;
1386
1387     /** @type {Object} Reference to the year view. */
1388     this.yearCtrl = null;
1389
1390     /**
1391      * Number of months from the start of the month "items" that the currently rendered month
1392      * occurs. Set via angular data binding.
1393      * @type {number}
1394      */
1395     this.offset = null;
1396
1397     /**
1398      * Date cell to focus after appending the month to the document.
1399      * @type {HTMLElement}
1400      */
1401     this.focusAfterAppend = null;
1402   }
1403
1404   /** Generate and append the content for this year to the directive element. */
1405   CalendarYearBodyCtrl.prototype.generateContent = function() {
1406     var date = this.dateUtil.incrementYears(this.calendarCtrl.firstRenderableDate, this.offset);
1407
1408     this.$element
1409       .empty()
1410       .append(this.buildCalendarForYear(date));
1411
1412     if (this.focusAfterAppend) {
1413       this.focusAfterAppend.classList.add(this.calendarCtrl.FOCUSED_DATE_CLASS);
1414       this.focusAfterAppend.focus();
1415       this.focusAfterAppend = null;
1416     }
1417   };
1418
1419   /**
1420    * Creates a single cell to contain a year in the calendar.
1421    * @param {number} opt_year Four-digit year.
1422    * @param {number} opt_month Zero-indexed month.
1423    * @returns {HTMLElement}
1424    */
1425   CalendarYearBodyCtrl.prototype.buildMonthCell = function(year, month) {
1426     var calendarCtrl = this.calendarCtrl;
1427     var yearCtrl = this.yearCtrl;
1428     var cell = this.buildBlankCell();
1429
1430     // Represent this month/year as a date.
1431     var firstOfMonth = new Date(year, month, 1);
1432     cell.setAttribute('aria-label', this.dateLocale.monthFormatter(firstOfMonth));
1433     cell.id = calendarCtrl.getDateId(firstOfMonth, 'year');
1434
1435     // Use `data-timestamp` attribute because IE10 does not support the `dataset` property.
1436     cell.setAttribute('data-timestamp', firstOfMonth.getTime());
1437
1438     if (this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.today)) {
1439       cell.classList.add(calendarCtrl.TODAY_CLASS);
1440     }
1441
1442     if (this.dateUtil.isValidDate(calendarCtrl.selectedDate) &&
1443         this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.selectedDate)) {
1444       cell.classList.add(calendarCtrl.SELECTED_DATE_CLASS);
1445       cell.setAttribute('aria-selected', 'true');
1446     }
1447
1448     var cellText = this.dateLocale.shortMonths[month];
1449
1450     if (this.dateUtil.isMonthWithinRange(firstOfMonth,
1451         calendarCtrl.minDate, calendarCtrl.maxDate)) {
1452       var selectionIndicator = document.createElement('span');
1453       selectionIndicator.classList.add('md-calendar-date-selection-indicator');
1454       selectionIndicator.textContent = cellText;
1455       cell.appendChild(selectionIndicator);
1456       cell.addEventListener('click', yearCtrl.cellClickHandler);
1457
1458       if (calendarCtrl.displayDate && this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.displayDate)) {
1459         this.focusAfterAppend = cell;
1460       }
1461     } else {
1462       cell.classList.add('md-calendar-date-disabled');
1463       cell.textContent = cellText;
1464     }
1465
1466     return cell;
1467   };
1468
1469   /**
1470    * Builds a blank cell.
1471    * @return {HTMLTableCellElement}
1472    */
1473   CalendarYearBodyCtrl.prototype.buildBlankCell = function() {
1474     var cell = document.createElement('td');
1475     cell.tabIndex = -1;
1476     cell.classList.add('md-calendar-date');
1477     cell.setAttribute('role', 'gridcell');
1478
1479     cell.setAttribute('tabindex', '-1');
1480     return cell;
1481   };
1482
1483   /**
1484    * Builds the <tbody> content for the given year.
1485    * @param {Date} date Date for which the content should be built.
1486    * @returns {DocumentFragment} A document fragment containing the months within the year.
1487    */
1488   CalendarYearBodyCtrl.prototype.buildCalendarForYear = function(date) {
1489     // Store rows for the month in a document fragment so that we can append them all at once.
1490     var year = date.getFullYear();
1491     var yearBody = document.createDocumentFragment();
1492
1493     var monthCell, i;
1494     // First row contains label and Jan-Jun.
1495     var firstRow = document.createElement('tr');
1496     var labelCell = document.createElement('td');
1497     labelCell.className = 'md-calendar-month-label';
1498     labelCell.textContent = year;
1499     firstRow.appendChild(labelCell);
1500
1501     for (i = 0; i < 6; i++) {
1502       firstRow.appendChild(this.buildMonthCell(year, i));
1503     }
1504     yearBody.appendChild(firstRow);
1505
1506     // Second row contains a blank cell and Jul-Dec.
1507     var secondRow = document.createElement('tr');
1508     secondRow.appendChild(this.buildBlankCell());
1509     for (i = 6; i < 12; i++) {
1510       secondRow.appendChild(this.buildMonthCell(year, i));
1511     }
1512     yearBody.appendChild(secondRow);
1513
1514     return yearBody;
1515   };
1516 })();
1517
1518 (function() {
1519   'use strict';
1520
1521   /**
1522    * @ngdoc service
1523    * @name $mdDateLocaleProvider
1524    * @module material.components.datepicker
1525    *
1526    * @description
1527    * The `$mdDateLocaleProvider` is the provider that creates the `$mdDateLocale` service.
1528    * This provider that allows the user to specify messages, formatters, and parsers for date
1529    * internationalization. The `$mdDateLocale` service itself is consumed by Angular Material
1530    * components that deal with dates.
1531    *
1532    * @property {(Array<string>)=} months Array of month names (in order).
1533    * @property {(Array<string>)=} shortMonths Array of abbreviated month names.
1534    * @property {(Array<string>)=} days Array of the days of the week (in order).
1535    * @property {(Array<string>)=} shortDays Array of abbreviated dayes of the week.
1536    * @property {(Array<string>)=} dates Array of dates of the month. Only necessary for locales
1537    *     using a numeral system other than [1, 2, 3...].
1538    * @property {(Array<string>)=} firstDayOfWeek The first day of the week. Sunday = 0, Monday = 1,
1539    *    etc.
1540    * @property {(function(string): Date)=} parseDate Function to parse a date object from a string.
1541    * @property {(function(Date, string): string)=} formatDate Function to format a date object to a
1542    *     string. The datepicker directive also provides the time zone, if it was specified.
1543    * @property {(function(Date): string)=} monthHeaderFormatter Function that returns the label for
1544    *     a month given a date.
1545    * @property {(function(Date): string)=} monthFormatter Function that returns the full name of a month
1546    *     for a giben date.
1547    * @property {(function(number): string)=} weekNumberFormatter Function that returns a label for
1548    *     a week given the week number.
1549    * @property {(string)=} msgCalendar Translation of the label "Calendar" for the current locale.
1550    * @property {(string)=} msgOpenCalendar Translation of the button label "Open calendar" for the
1551    *     current locale.
1552    * @property {Date=} firstRenderableDate The date from which the datepicker calendar will begin
1553    * rendering. Note that this will be ignored if a minimum date is set. Defaults to January 1st 1880.
1554    * @property {Date=} lastRenderableDate The last date that will be rendered by the datepicker
1555    * calendar. Note that this will be ignored if a maximum date is set. Defaults to January 1st 2130.
1556    *
1557    * @usage
1558    * <hljs lang="js">
1559    * myAppModule.config(function($mdDateLocaleProvider) {
1560    *
1561    *     // Example of a French localization.
1562    *     $mdDateLocaleProvider.months = ['janvier', 'février', 'mars', ...];
1563    *     $mdDateLocaleProvider.shortMonths = ['janv', 'févr', 'mars', ...];
1564    *     $mdDateLocaleProvider.days = ['dimanche', 'lundi', 'mardi', ...];
1565    *     $mdDateLocaleProvider.shortDays = ['Di', 'Lu', 'Ma', ...];
1566    *
1567    *     // Can change week display to start on Monday.
1568    *     $mdDateLocaleProvider.firstDayOfWeek = 1;
1569    *
1570    *     // Optional.
1571    *     $mdDateLocaleProvider.dates = [1, 2, 3, 4, 5, 6, ...];
1572    *
1573    *     // Example uses moment.js to parse and format dates.
1574    *     $mdDateLocaleProvider.parseDate = function(dateString) {
1575    *       var m = moment(dateString, 'L', true);
1576    *       return m.isValid() ? m.toDate() : new Date(NaN);
1577    *     };
1578    *
1579    *     $mdDateLocaleProvider.formatDate = function(date) {
1580    *       var m = moment(date);
1581    *       return m.isValid() ? m.format('L') : '';
1582    *     };
1583    *
1584    *     $mdDateLocaleProvider.monthHeaderFormatter = function(date) {
1585    *       return myShortMonths[date.getMonth()] + ' ' + date.getFullYear();
1586    *     };
1587    *
1588    *     // In addition to date display, date components also need localized messages
1589    *     // for aria-labels for screen-reader users.
1590    *
1591    *     $mdDateLocaleProvider.weekNumberFormatter = function(weekNumber) {
1592    *       return 'Semaine ' + weekNumber;
1593    *     };
1594    *
1595    *     $mdDateLocaleProvider.msgCalendar = 'Calendrier';
1596    *     $mdDateLocaleProvider.msgOpenCalendar = 'Ouvrir le calendrier';
1597    *
1598    *     // You can also set when your calendar begins and ends.
1599    *     $mdDateLocaleProvider.firstRenderableDate = new Date(1776, 6, 4);
1600    *     $mdDateLocaleProvider.lastRenderableDate = new Date(2012, 11, 21);
1601    * });
1602    * </hljs>
1603    *
1604    */
1605   angular.module('material.components.datepicker').config(["$provide", function($provide) {
1606     // TODO(jelbourn): Assert provided values are correctly formatted. Need assertions.
1607
1608     /** @constructor */
1609     function DateLocaleProvider() {
1610       /** Array of full month names. E.g., ['January', 'Febuary', ...] */
1611       this.months = null;
1612
1613       /** Array of abbreviated month names. E.g., ['Jan', 'Feb', ...] */
1614       this.shortMonths = null;
1615
1616       /** Array of full day of the week names. E.g., ['Monday', 'Tuesday', ...] */
1617       this.days = null;
1618
1619       /** Array of abbreviated dat of the week names. E.g., ['M', 'T', ...] */
1620       this.shortDays = null;
1621
1622       /** Array of dates of a month (1 - 31). Characters might be different in some locales. */
1623       this.dates = null;
1624
1625       /** Index of the first day of the week. 0 = Sunday, 1 = Monday, etc. */
1626       this.firstDayOfWeek = 0;
1627
1628       /**
1629        * Function that converts the date portion of a Date to a string.
1630        * @type {(function(Date): string)}
1631        */
1632       this.formatDate = null;
1633
1634       /**
1635        * Function that converts a date string to a Date object (the date portion)
1636        * @type {function(string): Date}
1637        */
1638       this.parseDate = null;
1639
1640       /**
1641        * Function that formats a Date into a month header string.
1642        * @type {function(Date): string}
1643        */
1644       this.monthHeaderFormatter = null;
1645
1646       /**
1647        * Function that formats a week number into a label for the week.
1648        * @type {function(number): string}
1649        */
1650       this.weekNumberFormatter = null;
1651
1652       /**
1653        * Function that formats a date into a long aria-label that is read
1654        * when the focused date changes.
1655        * @type {function(Date): string}
1656        */
1657       this.longDateFormatter = null;
1658
1659       /**
1660        * ARIA label for the calendar "dialog" used in the datepicker.
1661        * @type {string}
1662        */
1663       this.msgCalendar = '';
1664
1665       /**
1666        * ARIA label for the datepicker's "Open calendar" buttons.
1667        * @type {string}
1668        */
1669       this.msgOpenCalendar = '';
1670     }
1671
1672     /**
1673      * Factory function that returns an instance of the dateLocale service.
1674      * ngInject
1675      * @param $locale
1676      * @returns {DateLocale}
1677      */
1678     DateLocaleProvider.prototype.$get = function($locale, $filter) {
1679       /**
1680        * Default date-to-string formatting function.
1681        * @param {!Date} date
1682        * @param {string=} timezone
1683        * @returns {string}
1684        */
1685       function defaultFormatDate(date, timezone) {
1686         if (!date) {
1687           return '';
1688         }
1689
1690         // All of the dates created through ng-material *should* be set to midnight.
1691         // If we encounter a date where the localeTime shows at 11pm instead of midnight,
1692         // we have run into an issue with DST where we need to increment the hour by one:
1693         // var d = new Date(1992, 9, 8, 0, 0, 0);
1694         // d.toLocaleString(); // == "10/7/1992, 11:00:00 PM"
1695         var localeTime = date.toLocaleTimeString();
1696         var formatDate = date;
1697         if (date.getHours() === 0 &&
1698             (localeTime.indexOf('11:') !== -1 || localeTime.indexOf('23:') !== -1)) {
1699           formatDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 1, 0, 0);
1700         }
1701
1702         return $filter('date')(formatDate, 'M/d/yyyy', timezone);
1703       }
1704
1705       /**
1706        * Default string-to-date parsing function.
1707        * @param {string} dateString
1708        * @returns {!Date}
1709        */
1710       function defaultParseDate(dateString) {
1711         return new Date(dateString);
1712       }
1713
1714       /**
1715        * Default function to determine whether a string makes sense to be
1716        * parsed to a Date object.
1717        *
1718        * This is very permissive and is just a basic sanity check to ensure that
1719        * things like single integers aren't able to be parsed into dates.
1720        * @param {string} dateString
1721        * @returns {boolean}
1722        */
1723       function defaultIsDateComplete(dateString) {
1724         dateString = dateString.trim();
1725
1726         // Looks for three chunks of content (either numbers or text) separated
1727         // by delimiters.
1728         var re = /^(([a-zA-Z]{3,}|[0-9]{1,4})([ \.,]+|[\/\-])){2}([a-zA-Z]{3,}|[0-9]{1,4})$/;
1729         return re.test(dateString);
1730       }
1731
1732       /**
1733        * Default date-to-string formatter to get a month header.
1734        * @param {!Date} date
1735        * @returns {string}
1736        */
1737       function defaultMonthHeaderFormatter(date) {
1738         return service.shortMonths[date.getMonth()] + ' ' + date.getFullYear();
1739       }
1740
1741       /**
1742        * Default formatter for a month.
1743        * @param {!Date} date
1744        * @returns {string}
1745        */
1746       function defaultMonthFormatter(date) {
1747         return service.months[date.getMonth()] + ' ' + date.getFullYear();
1748       }
1749
1750       /**
1751        * Default week number formatter.
1752        * @param number
1753        * @returns {string}
1754        */
1755       function defaultWeekNumberFormatter(number) {
1756         return 'Week ' + number;
1757       }
1758
1759       /**
1760        * Default formatter for date cell aria-labels.
1761        * @param {!Date} date
1762        * @returns {string}
1763        */
1764       function defaultLongDateFormatter(date) {
1765         // Example: 'Thursday June 18 2015'
1766         return [
1767           service.days[date.getDay()],
1768           service.months[date.getMonth()],
1769           service.dates[date.getDate()],
1770           date.getFullYear()
1771         ].join(' ');
1772       }
1773
1774       // The default "short" day strings are the first character of each day,
1775       // e.g., "Monday" => "M".
1776       var defaultShortDays = $locale.DATETIME_FORMATS.SHORTDAY.map(function(day) {
1777         return day.substring(0, 1);
1778       });
1779
1780       // The default dates are simply the numbers 1 through 31.
1781       var defaultDates = Array(32);
1782       for (var i = 1; i <= 31; i++) {
1783         defaultDates[i] = i;
1784       }
1785
1786       // Default ARIA messages are in English (US).
1787       var defaultMsgCalendar = 'Calendar';
1788       var defaultMsgOpenCalendar = 'Open calendar';
1789
1790       // Default start/end dates that are rendered in the calendar.
1791       var defaultFirstRenderableDate = new Date(1880, 0, 1);
1792       var defaultLastRendereableDate = new Date(defaultFirstRenderableDate.getFullYear() + 250, 0, 1);
1793
1794       var service = {
1795         months: this.months || $locale.DATETIME_FORMATS.MONTH,
1796         shortMonths: this.shortMonths || $locale.DATETIME_FORMATS.SHORTMONTH,
1797         days: this.days || $locale.DATETIME_FORMATS.DAY,
1798         shortDays: this.shortDays || defaultShortDays,
1799         dates: this.dates || defaultDates,
1800         firstDayOfWeek: this.firstDayOfWeek || 0,
1801         formatDate: this.formatDate || defaultFormatDate,
1802         parseDate: this.parseDate || defaultParseDate,
1803         isDateComplete: this.isDateComplete || defaultIsDateComplete,
1804         monthHeaderFormatter: this.monthHeaderFormatter || defaultMonthHeaderFormatter,
1805         monthFormatter: this.monthFormatter || defaultMonthFormatter,
1806         weekNumberFormatter: this.weekNumberFormatter || defaultWeekNumberFormatter,
1807         longDateFormatter: this.longDateFormatter || defaultLongDateFormatter,
1808         msgCalendar: this.msgCalendar || defaultMsgCalendar,
1809         msgOpenCalendar: this.msgOpenCalendar || defaultMsgOpenCalendar,
1810         firstRenderableDate: this.firstRenderableDate || defaultFirstRenderableDate,
1811         lastRenderableDate: this.lastRenderableDate || defaultLastRendereableDate
1812       };
1813
1814       return service;
1815     };
1816     DateLocaleProvider.prototype.$get['$inject'] = ["$locale", "$filter"];
1817
1818     $provide.provider('$mdDateLocale', new DateLocaleProvider());
1819   }]);
1820 })();
1821
1822 (function() {
1823   'use strict';
1824
1825   /**
1826    * Utility for performing date calculations to facilitate operation of the calendar and
1827    * datepicker.
1828    */
1829   angular.module('material.components.datepicker').factory('$$mdDateUtil', function() {
1830     return {
1831       getFirstDateOfMonth: getFirstDateOfMonth,
1832       getNumberOfDaysInMonth: getNumberOfDaysInMonth,
1833       getDateInNextMonth: getDateInNextMonth,
1834       getDateInPreviousMonth: getDateInPreviousMonth,
1835       isInNextMonth: isInNextMonth,
1836       isInPreviousMonth: isInPreviousMonth,
1837       getDateMidpoint: getDateMidpoint,
1838       isSameMonthAndYear: isSameMonthAndYear,
1839       getWeekOfMonth: getWeekOfMonth,
1840       incrementDays: incrementDays,
1841       incrementMonths: incrementMonths,
1842       getLastDateOfMonth: getLastDateOfMonth,
1843       isSameDay: isSameDay,
1844       getMonthDistance: getMonthDistance,
1845       isValidDate: isValidDate,
1846       setDateTimeToMidnight: setDateTimeToMidnight,
1847       createDateAtMidnight: createDateAtMidnight,
1848       isDateWithinRange: isDateWithinRange,
1849       incrementYears: incrementYears,
1850       getYearDistance: getYearDistance,
1851       clampDate: clampDate,
1852       getTimestampFromNode: getTimestampFromNode,
1853       isMonthWithinRange: isMonthWithinRange
1854     };
1855
1856     /**
1857      * Gets the first day of the month for the given date's month.
1858      * @param {Date} date
1859      * @returns {Date}
1860      */
1861     function getFirstDateOfMonth(date) {
1862       return new Date(date.getFullYear(), date.getMonth(), 1);
1863     }
1864
1865     /**
1866      * Gets the number of days in the month for the given date's month.
1867      * @param date
1868      * @returns {number}
1869      */
1870     function getNumberOfDaysInMonth(date) {
1871       return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
1872     }
1873
1874     /**
1875      * Get an arbitrary date in the month after the given date's month.
1876      * @param date
1877      * @returns {Date}
1878      */
1879     function getDateInNextMonth(date) {
1880       return new Date(date.getFullYear(), date.getMonth() + 1, 1);
1881     }
1882
1883     /**
1884      * Get an arbitrary date in the month before the given date's month.
1885      * @param date
1886      * @returns {Date}
1887      */
1888     function getDateInPreviousMonth(date) {
1889       return new Date(date.getFullYear(), date.getMonth() - 1, 1);
1890     }
1891
1892     /**
1893      * Gets whether two dates have the same month and year.
1894      * @param {Date} d1
1895      * @param {Date} d2
1896      * @returns {boolean}
1897      */
1898     function isSameMonthAndYear(d1, d2) {
1899       return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth();
1900     }
1901
1902     /**
1903      * Gets whether two dates are the same day (not not necesarily the same time).
1904      * @param {Date} d1
1905      * @param {Date} d2
1906      * @returns {boolean}
1907      */
1908     function isSameDay(d1, d2) {
1909       return d1.getDate() == d2.getDate() && isSameMonthAndYear(d1, d2);
1910     }
1911
1912     /**
1913      * Gets whether a date is in the month immediately after some date.
1914      * @param {Date} startDate The date from which to compare.
1915      * @param {Date} endDate The date to check.
1916      * @returns {boolean}
1917      */
1918     function isInNextMonth(startDate, endDate) {
1919       var nextMonth = getDateInNextMonth(startDate);
1920       return isSameMonthAndYear(nextMonth, endDate);
1921     }
1922
1923     /**
1924      * Gets whether a date is in the month immediately before some date.
1925      * @param {Date} startDate The date from which to compare.
1926      * @param {Date} endDate The date to check.
1927      * @returns {boolean}
1928      */
1929     function isInPreviousMonth(startDate, endDate) {
1930       var previousMonth = getDateInPreviousMonth(startDate);
1931       return isSameMonthAndYear(endDate, previousMonth);
1932     }
1933
1934     /**
1935      * Gets the midpoint between two dates.
1936      * @param {Date} d1
1937      * @param {Date} d2
1938      * @returns {Date}
1939      */
1940     function getDateMidpoint(d1, d2) {
1941       return createDateAtMidnight((d1.getTime() + d2.getTime()) / 2);
1942     }
1943
1944     /**
1945      * Gets the week of the month that a given date occurs in.
1946      * @param {Date} date
1947      * @returns {number} Index of the week of the month (zero-based).
1948      */
1949     function getWeekOfMonth(date) {
1950       var firstDayOfMonth = getFirstDateOfMonth(date);
1951       return Math.floor((firstDayOfMonth.getDay() + date.getDate() - 1) / 7);
1952     }
1953
1954     /**
1955      * Gets a new date incremented by the given number of days. Number of days can be negative.
1956      * @param {Date} date
1957      * @param {number} numberOfDays
1958      * @returns {Date}
1959      */
1960     function incrementDays(date, numberOfDays) {
1961       return new Date(date.getFullYear(), date.getMonth(), date.getDate() + numberOfDays);
1962     }
1963
1964     /**
1965      * Gets a new date incremented by the given number of months. Number of months can be negative.
1966      * If the date of the given month does not match the target month, the date will be set to the
1967      * last day of the month.
1968      * @param {Date} date
1969      * @param {number} numberOfMonths
1970      * @returns {Date}
1971      */
1972     function incrementMonths(date, numberOfMonths) {
1973       // If the same date in the target month does not actually exist, the Date object will
1974       // automatically advance *another* month by the number of missing days.
1975       // For example, if you try to go from Jan. 30 to Feb. 30, you'll end up on March 2.
1976       // So, we check if the month overflowed and go to the last day of the target month instead.
1977       var dateInTargetMonth = new Date(date.getFullYear(), date.getMonth() + numberOfMonths, 1);
1978       var numberOfDaysInMonth = getNumberOfDaysInMonth(dateInTargetMonth);
1979       if (numberOfDaysInMonth < date.getDate()) {
1980         dateInTargetMonth.setDate(numberOfDaysInMonth);
1981       } else {
1982         dateInTargetMonth.setDate(date.getDate());
1983       }
1984
1985       return dateInTargetMonth;
1986     }
1987
1988     /**
1989      * Get the integer distance between two months. This *only* considers the month and year
1990      * portion of the Date instances.
1991      *
1992      * @param {Date} start
1993      * @param {Date} end
1994      * @returns {number} Number of months between `start` and `end`. If `end` is before `start`
1995      *     chronologically, this number will be negative.
1996      */
1997     function getMonthDistance(start, end) {
1998       return (12 * (end.getFullYear() - start.getFullYear())) + (end.getMonth() - start.getMonth());
1999     }
2000
2001     /**
2002      * Gets the last day of the month for the given date.
2003      * @param {Date} date
2004      * @returns {Date}
2005      */
2006     function getLastDateOfMonth(date) {
2007       return new Date(date.getFullYear(), date.getMonth(), getNumberOfDaysInMonth(date));
2008     }
2009
2010     /**
2011      * Checks whether a date is valid.
2012      * @param {Date} date
2013      * @return {boolean} Whether the date is a valid Date.
2014      */
2015     function isValidDate(date) {
2016       return date && date.getTime && !isNaN(date.getTime());
2017     }
2018
2019     /**
2020      * Sets a date's time to midnight.
2021      * @param {Date} date
2022      */
2023     function setDateTimeToMidnight(date) {
2024       if (isValidDate(date)) {
2025         date.setHours(0, 0, 0, 0);
2026       }
2027     }
2028
2029     /**
2030      * Creates a date with the time set to midnight.
2031      * Drop-in replacement for two forms of the Date constructor:
2032      * 1. No argument for Date representing now.
2033      * 2. Single-argument value representing number of seconds since Unix Epoch
2034      * or a Date object.
2035      * @param {number|Date=} opt_value
2036      * @return {Date} New date with time set to midnight.
2037      */
2038     function createDateAtMidnight(opt_value) {
2039       var date;
2040       if (angular.isUndefined(opt_value)) {
2041         date = new Date();
2042       } else {
2043         date = new Date(opt_value);
2044       }
2045       setDateTimeToMidnight(date);
2046       return date;
2047     }
2048
2049      /**
2050       * Checks if a date is within a min and max range, ignoring the time component.
2051       * If minDate or maxDate are not dates, they are ignored.
2052       * @param {Date} date
2053       * @param {Date} minDate
2054       * @param {Date} maxDate
2055       */
2056      function isDateWithinRange(date, minDate, maxDate) {
2057        var dateAtMidnight = createDateAtMidnight(date);
2058        var minDateAtMidnight = isValidDate(minDate) ? createDateAtMidnight(minDate) : null;
2059        var maxDateAtMidnight = isValidDate(maxDate) ? createDateAtMidnight(maxDate) : null;
2060        return (!minDateAtMidnight || minDateAtMidnight <= dateAtMidnight) &&
2061            (!maxDateAtMidnight || maxDateAtMidnight >= dateAtMidnight);
2062      }
2063
2064     /**
2065      * Gets a new date incremented by the given number of years. Number of years can be negative.
2066      * See `incrementMonths` for notes on overflow for specific dates.
2067      * @param {Date} date
2068      * @param {number} numberOfYears
2069      * @returns {Date}
2070      */
2071      function incrementYears(date, numberOfYears) {
2072        return incrementMonths(date, numberOfYears * 12);
2073      }
2074
2075      /**
2076       * Get the integer distance between two years. This *only* considers the year portion of the
2077       * Date instances.
2078       *
2079       * @param {Date} start
2080       * @param {Date} end
2081       * @returns {number} Number of months between `start` and `end`. If `end` is before `start`
2082       *     chronologically, this number will be negative.
2083       */
2084      function getYearDistance(start, end) {
2085        return end.getFullYear() - start.getFullYear();
2086      }
2087
2088      /**
2089       * Clamps a date between a minimum and a maximum date.
2090       * @param {Date} date Date to be clamped
2091       * @param {Date=} minDate Minimum date
2092       * @param {Date=} maxDate Maximum date
2093       * @return {Date}
2094       */
2095      function clampDate(date, minDate, maxDate) {
2096        var boundDate = date;
2097        if (minDate && date < minDate) {
2098          boundDate = new Date(minDate.getTime());
2099        }
2100        if (maxDate && date > maxDate) {
2101          boundDate = new Date(maxDate.getTime());
2102        }
2103        return boundDate;
2104      }
2105
2106      /**
2107       * Extracts and parses the timestamp from a DOM node.
2108       * @param  {HTMLElement} node Node from which the timestamp will be extracted.
2109       * @return {number} Time since epoch.
2110       */
2111      function getTimestampFromNode(node) {
2112        if (node && node.hasAttribute('data-timestamp')) {
2113          return Number(node.getAttribute('data-timestamp'));
2114        }
2115      }
2116
2117      /**
2118       * Checks if a month is within a min and max range, ignoring the date and time components.
2119       * If minDate or maxDate are not dates, they are ignored.
2120       * @param {Date} date
2121       * @param {Date} minDate
2122       * @param {Date} maxDate
2123       */
2124      function isMonthWithinRange(date, minDate, maxDate) {
2125        var month = date.getMonth();
2126        var year = date.getFullYear();
2127
2128        return (!minDate || minDate.getFullYear() < year || minDate.getMonth() <= month) &&
2129         (!maxDate || maxDate.getFullYear() > year || maxDate.getMonth() >= month);
2130      }
2131   });
2132 })();
2133
2134 (function() {
2135   'use strict';
2136
2137   // POST RELEASE
2138   // TODO(jelbourn): Demo that uses moment.js
2139   // TODO(jelbourn): make sure this plays well with validation and ngMessages.
2140   // TODO(jelbourn): calendar pane doesn't open up outside of visible viewport.
2141   // TODO(jelbourn): forward more attributes to the internal input (required, autofocus, etc.)
2142   // TODO(jelbourn): something better for mobile (calendar panel takes up entire screen?)
2143   // TODO(jelbourn): input behavior (masking? auto-complete?)
2144
2145
2146   DatePickerCtrl['$inject'] = ["$scope", "$element", "$attrs", "$window", "$mdConstant", "$mdTheming", "$mdUtil", "$mdDateLocale", "$$mdDateUtil", "$$rAF", "$filter"];
2147   datePickerDirective['$inject'] = ["$$mdSvgRegistry", "$mdUtil", "$mdAria", "inputDirective"];
2148   angular.module('material.components.datepicker')
2149       .directive('mdDatepicker', datePickerDirective);
2150
2151   /**
2152    * @ngdoc directive
2153    * @name mdDatepicker
2154    * @module material.components.datepicker
2155    *
2156    * @param {Date} ng-model The component's model. Expects a JavaScript Date object.
2157    * @param {Object=} ng-model-options Allows tuning of the way in which `ng-model` is being updated. Also allows
2158    * for a timezone to be specified. <a href="https://docs.angularjs.org/api/ng/directive/ngModelOptions#usage">Read more at the ngModelOptions docs.</a>
2159    * @param {expression=} ng-change Expression evaluated when the model value changes.
2160    * @param {expression=} ng-focus Expression evaluated when the input is focused or the calendar is opened.
2161    * @param {expression=} ng-blur Expression evaluated when focus is removed from the input or the calendar is closed.
2162    * @param {boolean=} ng-disabled Whether the datepicker is disabled.
2163    * @param {boolean=} ng-required Whether a value is required for the datepicker.
2164    * @param {Date=} md-min-date Expression representing a min date (inclusive).
2165    * @param {Date=} md-max-date Expression representing a max date (inclusive).
2166    * @param {(function(Date): boolean)=} md-date-filter Function expecting a date and returning a boolean whether it can be selected or not.
2167    * @param {String=} md-placeholder The date input placeholder value.
2168    * @param {String=} md-open-on-focus When present, the calendar will be opened when the input is focused.
2169    * @param {Boolean=} md-is-open Expression that can be used to open the datepicker's calendar on-demand.
2170    * @param {String=} md-current-view Default open view of the calendar pane. Can be either "month" or "year".
2171    * @param {String=} md-hide-icons Determines which datepicker icons should be hidden. Note that this may cause the
2172    * datepicker to not align properly with other components. **Use at your own risk.** Possible values are:
2173    * * `"all"` - Hides all icons.
2174    * * `"calendar"` - Only hides the calendar icon.
2175    * * `"triangle"` - Only hides the triangle icon.
2176    * @param {Object=} md-date-locale Allows for the values from the `$mdDateLocaleProvider` to be
2177    * ovewritten on a per-element basis (e.g. `msgOpenCalendar` can be overwritten with
2178    * `md-date-locale="{ msgOpenCalendar: 'Open a special calendar' }"`).
2179    *
2180    * @description
2181    * `<md-datepicker>` is a component used to select a single date.
2182    * For information on how to configure internationalization for the date picker,
2183    * see `$mdDateLocaleProvider`.
2184    *
2185    * This component supports [ngMessages](https://docs.angularjs.org/api/ngMessages/directive/ngMessages).
2186    * Supported attributes are:
2187    * * `required`: whether a required date is not set.
2188    * * `mindate`: whether the selected date is before the minimum allowed date.
2189    * * `maxdate`: whether the selected date is after the maximum allowed date.
2190    * * `debounceInterval`: ms to delay input processing (since last debounce reset); default value 500ms
2191    *
2192    * @usage
2193    * <hljs lang="html">
2194    *   <md-datepicker ng-model="birthday"></md-datepicker>
2195    * </hljs>
2196    *
2197    */
2198
2199   function datePickerDirective($$mdSvgRegistry, $mdUtil, $mdAria, inputDirective) {
2200     return {
2201       template: function(tElement, tAttrs) {
2202         // Buttons are not in the tab order because users can open the calendar via keyboard
2203         // interaction on the text input, and multiple tab stops for one component (picker)
2204         // may be confusing.
2205         var hiddenIcons = tAttrs.mdHideIcons;
2206         var ariaLabelValue = tAttrs.ariaLabel || tAttrs.mdPlaceholder;
2207
2208         var calendarButton = (hiddenIcons === 'all' || hiddenIcons === 'calendar') ? '' :
2209           '<md-button class="md-datepicker-button md-icon-button" type="button" ' +
2210               'tabindex="-1" aria-hidden="true" ' +
2211               'ng-click="ctrl.openCalendarPane($event)">' +
2212             '<md-icon class="md-datepicker-calendar-icon" aria-label="md-calendar" ' +
2213                      'md-svg-src="' + $$mdSvgRegistry.mdCalendar + '"></md-icon>' +
2214           '</md-button>';
2215
2216         var triangleButton = '';
2217
2218         if (hiddenIcons !== 'all' && hiddenIcons !== 'triangle') {
2219           triangleButton = '' +
2220             '<md-button type="button" md-no-ink ' +
2221               'class="md-datepicker-triangle-button md-icon-button" ' +
2222               'ng-click="ctrl.openCalendarPane($event)" ' +
2223               'aria-label="{{::ctrl.locale.msgOpenCalendar}}">' +
2224             '<div class="md-datepicker-expand-triangle"></div>' +
2225           '</md-button>';
2226
2227           tElement.addClass(HAS_TRIANGLE_ICON_CLASS);
2228         }
2229
2230         return calendarButton +
2231         '<div class="md-datepicker-input-container" ng-class="{\'md-datepicker-focused\': ctrl.isFocused}">' +
2232           '<input ' +
2233             (ariaLabelValue ? 'aria-label="' + ariaLabelValue + '" ' : '') +
2234             'class="md-datepicker-input" ' +
2235             'aria-haspopup="true" ' +
2236             'aria-expanded="{{ctrl.isCalendarOpen}}" ' +
2237             'ng-focus="ctrl.setFocused(true)" ' +
2238             'ng-blur="ctrl.setFocused(false)"> ' +
2239             triangleButton +
2240         '</div>' +
2241
2242         // This pane will be detached from here and re-attached to the document body.
2243         '<div class="md-datepicker-calendar-pane md-whiteframe-z1" id="{{::ctrl.calendarPaneId}}">' +
2244           '<div class="md-datepicker-input-mask">' +
2245             '<div class="md-datepicker-input-mask-opaque"></div>' +
2246           '</div>' +
2247           '<div class="md-datepicker-calendar">' +
2248             '<md-calendar role="dialog" aria-label="{{::ctrl.locale.msgCalendar}}" ' +
2249                 'md-current-view="{{::ctrl.currentView}}"' +
2250                 'md-min-date="ctrl.minDate"' +
2251                 'md-max-date="ctrl.maxDate"' +
2252                 'md-date-filter="ctrl.dateFilter"' +
2253                 'ng-model="ctrl.date" ng-if="ctrl.isCalendarOpen">' +
2254             '</md-calendar>' +
2255           '</div>' +
2256         '</div>';
2257       },
2258       require: ['ngModel', 'mdDatepicker', '?^mdInputContainer', '?^form'],
2259       scope: {
2260         minDate: '=mdMinDate',
2261         maxDate: '=mdMaxDate',
2262         placeholder: '@mdPlaceholder',
2263         currentView: '@mdCurrentView',
2264         dateFilter: '=mdDateFilter',
2265         isOpen: '=?mdIsOpen',
2266         debounceInterval: '=mdDebounceInterval',
2267         dateLocale: '=mdDateLocale'
2268       },
2269       controller: DatePickerCtrl,
2270       controllerAs: 'ctrl',
2271       bindToController: true,
2272       link: function(scope, element, attr, controllers) {
2273         var ngModelCtrl = controllers[0];
2274         var mdDatePickerCtrl = controllers[1];
2275         var mdInputContainer = controllers[2];
2276         var parentForm = controllers[3];
2277         var mdNoAsterisk = $mdUtil.parseAttributeBoolean(attr.mdNoAsterisk);
2278
2279         mdDatePickerCtrl.configureNgModel(ngModelCtrl, mdInputContainer, inputDirective);
2280
2281         if (mdInputContainer) {
2282           // We need to move the spacer after the datepicker itself,
2283           // because md-input-container adds it after the
2284           // md-datepicker-input by default. The spacer gets wrapped in a
2285           // div, because it floats and gets aligned next to the datepicker.
2286           // There are easier ways of working around this with CSS (making the
2287           // datepicker 100% wide, change the `display` etc.), however they
2288           // break the alignment with any other form controls.
2289           var spacer = element[0].querySelector('.md-errors-spacer');
2290
2291           if (spacer) {
2292             element.after(angular.element('<div>').append(spacer));
2293           }
2294
2295           mdInputContainer.setHasPlaceholder(attr.mdPlaceholder);
2296           mdInputContainer.input = element;
2297           mdInputContainer.element
2298             .addClass(INPUT_CONTAINER_CLASS)
2299             .toggleClass(HAS_CALENDAR_ICON_CLASS, attr.mdHideIcons !== 'calendar' && attr.mdHideIcons !== 'all');
2300
2301           if (!mdInputContainer.label) {
2302             $mdAria.expect(element, 'aria-label', attr.mdPlaceholder);
2303           } else if(!mdNoAsterisk) {
2304             attr.$observe('required', function(value) {
2305               mdInputContainer.label.toggleClass('md-required', !!value);
2306             });
2307           }
2308
2309           scope.$watch(mdInputContainer.isErrorGetter || function() {
2310             return ngModelCtrl.$invalid && (ngModelCtrl.$touched || (parentForm && parentForm.$submitted));
2311           }, mdInputContainer.setInvalid);
2312         } else if (parentForm) {
2313           // If invalid, highlights the input when the parent form is submitted.
2314           var parentSubmittedWatcher = scope.$watch(function() {
2315             return parentForm.$submitted;
2316           }, function(isSubmitted) {
2317             if (isSubmitted) {
2318               mdDatePickerCtrl.updateErrorState();
2319               parentSubmittedWatcher();
2320             }
2321           });
2322         }
2323       }
2324     };
2325   }
2326
2327   /** Additional offset for the input's `size` attribute, which is updated based on its content. */
2328   var EXTRA_INPUT_SIZE = 3;
2329
2330   /** Class applied to the container if the date is invalid. */
2331   var INVALID_CLASS = 'md-datepicker-invalid';
2332
2333   /** Class applied to the datepicker when it's open. */
2334   var OPEN_CLASS = 'md-datepicker-open';
2335
2336   /** Class applied to the md-input-container, if a datepicker is placed inside it */
2337   var INPUT_CONTAINER_CLASS = '_md-datepicker-floating-label';
2338
2339   /** Class to be applied when the calendar icon is enabled. */
2340   var HAS_CALENDAR_ICON_CLASS = '_md-datepicker-has-calendar-icon';
2341
2342   /** Class to be applied when the triangle icon is enabled. */
2343   var HAS_TRIANGLE_ICON_CLASS = '_md-datepicker-has-triangle-icon';
2344
2345   /** Default time in ms to debounce input event by. */
2346   var DEFAULT_DEBOUNCE_INTERVAL = 500;
2347
2348   /**
2349    * Height of the calendar pane used to check if the pane is going outside the boundary of
2350    * the viewport. See calendar.scss for how $md-calendar-height is computed; an extra 20px is
2351    * also added to space the pane away from the exact edge of the screen.
2352    *
2353    *  This is computed statically now, but can be changed to be measured if the circumstances
2354    *  of calendar sizing are changed.
2355    */
2356   var CALENDAR_PANE_HEIGHT = 368;
2357
2358   /**
2359    * Width of the calendar pane used to check if the pane is going outside the boundary of
2360    * the viewport. See calendar.scss for how $md-calendar-width is computed; an extra 20px is
2361    * also added to space the pane away from the exact edge of the screen.
2362    *
2363    *  This is computed statically now, but can be changed to be measured if the circumstances
2364    *  of calendar sizing are changed.
2365    */
2366   var CALENDAR_PANE_WIDTH = 360;
2367
2368   /** Used for checking whether the current user agent is on iOS or Android. */
2369   var IS_MOBILE_REGEX = /ipad|iphone|ipod|android/i;
2370
2371   /**
2372    * Controller for md-datepicker.
2373    *
2374    * ngInject @constructor
2375    */
2376   function DatePickerCtrl($scope, $element, $attrs, $window, $mdConstant,
2377     $mdTheming, $mdUtil, $mdDateLocale, $$mdDateUtil, $$rAF, $filter) {
2378
2379     /** @final */
2380     this.$window = $window;
2381
2382     /** @final */
2383     this.dateUtil = $$mdDateUtil;
2384
2385     /** @final */
2386     this.$mdConstant = $mdConstant;
2387
2388     /* @final */
2389     this.$mdUtil = $mdUtil;
2390
2391     /** @final */
2392     this.$$rAF = $$rAF;
2393
2394     /** @final */
2395     this.$mdDateLocale = $mdDateLocale;
2396
2397     /**
2398      * The root document element. This is used for attaching a top-level click handler to
2399      * close the calendar panel when a click outside said panel occurs. We use `documentElement`
2400      * instead of body because, when scrolling is disabled, some browsers consider the body element
2401      * to be completely off the screen and propagate events directly to the html element.
2402      * @type {!angular.JQLite}
2403      */
2404     this.documentElement = angular.element(document.documentElement);
2405
2406     /** @type {!angular.NgModelController} */
2407     this.ngModelCtrl = null;
2408
2409     /** @type {HTMLInputElement} */
2410     this.inputElement = $element[0].querySelector('input');
2411
2412     /** @final {!angular.JQLite} */
2413     this.ngInputElement = angular.element(this.inputElement);
2414
2415     /** @type {HTMLElement} */
2416     this.inputContainer = $element[0].querySelector('.md-datepicker-input-container');
2417
2418     /** @type {HTMLElement} Floating calendar pane. */
2419     this.calendarPane = $element[0].querySelector('.md-datepicker-calendar-pane');
2420
2421     /** @type {HTMLElement} Calendar icon button. */
2422     this.calendarButton = $element[0].querySelector('.md-datepicker-button');
2423
2424     /**
2425      * Element covering everything but the input in the top of the floating calendar pane.
2426      * @type {!angular.JQLite}
2427      */
2428     this.inputMask = angular.element($element[0].querySelector('.md-datepicker-input-mask-opaque'));
2429
2430     /** @final {!angular.JQLite} */
2431     this.$element = $element;
2432
2433     /** @final {!angular.Attributes} */
2434     this.$attrs = $attrs;
2435
2436     /** @final {!angular.Scope} */
2437     this.$scope = $scope;
2438
2439     /** @type {Date} */
2440     this.date = null;
2441
2442     /** @type {boolean} */
2443     this.isFocused = false;
2444
2445     /** @type {boolean} */
2446     this.isDisabled;
2447     this.setDisabled($element[0].disabled || angular.isString($attrs.disabled));
2448
2449     /** @type {boolean} Whether the date-picker's calendar pane is open. */
2450     this.isCalendarOpen = false;
2451
2452     /** @type {boolean} Whether the calendar should open when the input is focused. */
2453     this.openOnFocus = $attrs.hasOwnProperty('mdOpenOnFocus');
2454
2455     /** @final */
2456     this.mdInputContainer = null;
2457
2458     /**
2459      * Element from which the calendar pane was opened. Keep track of this so that we can return
2460      * focus to it when the pane is closed.
2461      * @type {HTMLElement}
2462      */
2463     this.calendarPaneOpenedFrom = null;
2464
2465     /** @type {String} Unique id for the calendar pane. */
2466     this.calendarPaneId = 'md-date-pane-' + $mdUtil.nextUid();
2467
2468     /** Pre-bound click handler is saved so that the event listener can be removed. */
2469     this.bodyClickHandler = angular.bind(this, this.handleBodyClick);
2470
2471     /**
2472      * Name of the event that will trigger a close. Necessary to sniff the browser, because
2473      * the resize event doesn't make sense on mobile and can have a negative impact since it
2474      * triggers whenever the browser zooms in on a focused input.
2475      */
2476     this.windowEventName = IS_MOBILE_REGEX.test(
2477       navigator.userAgent || navigator.vendor || window.opera
2478     ) ? 'orientationchange' : 'resize';
2479
2480     /** Pre-bound close handler so that the event listener can be removed. */
2481     this.windowEventHandler = $mdUtil.debounce(angular.bind(this, this.closeCalendarPane), 100);
2482
2483     /** Pre-bound handler for the window blur event. Allows for it to be removed later. */
2484     this.windowBlurHandler = angular.bind(this, this.handleWindowBlur);
2485
2486     /** The built-in Angular date filter. */
2487     this.ngDateFilter = $filter('date');
2488
2489     /** @type {Number} Extra margin for the left side of the floating calendar pane. */
2490     this.leftMargin = 20;
2491
2492     /** @type {Number} Extra margin for the top of the floating calendar. Gets determined on the first open. */
2493     this.topMargin = null;
2494
2495     // Unless the user specifies so, the datepicker should not be a tab stop.
2496     // This is necessary because ngAria might add a tabindex to anything with an ng-model
2497     // (based on whether or not the user has turned that particular feature on/off).
2498     if ($attrs.tabindex) {
2499       this.ngInputElement.attr('tabindex', $attrs.tabindex);
2500       $attrs.$set('tabindex', null);
2501     } else {
2502       $attrs.$set('tabindex', '-1');
2503     }
2504
2505     $attrs.$set('aria-owns', this.calendarPaneId);
2506
2507     $mdTheming($element);
2508     $mdTheming(angular.element(this.calendarPane));
2509
2510     var self = this;
2511
2512     $scope.$on('$destroy', function() {
2513       self.detachCalendarPane();
2514     });
2515
2516     if ($attrs.mdIsOpen) {
2517       $scope.$watch('ctrl.isOpen', function(shouldBeOpen) {
2518         if (shouldBeOpen) {
2519           self.openCalendarPane({
2520             target: self.inputElement
2521           });
2522         } else {
2523           self.closeCalendarPane();
2524         }
2525       });
2526     }
2527
2528     // For Angular 1.4 and older, where there are no lifecycle hooks but bindings are pre-assigned,
2529     // manually call the $onInit hook.
2530     if (angular.version.major === 1 && angular.version.minor <= 4) {
2531       this.$onInit();
2532     }
2533
2534   }
2535
2536   /**
2537    * Angular Lifecycle hook for newer Angular versions.
2538    * Bindings are not guaranteed to have been assigned in the controller, but they are in the $onInit hook.
2539    */
2540   DatePickerCtrl.prototype.$onInit = function() {
2541
2542     /**
2543      * Holds locale-specific formatters, parsers, labels etc. Allows
2544      * the user to override specific ones from the $mdDateLocale provider.
2545      * @type {!Object}
2546      */
2547     this.locale = this.dateLocale ? angular.extend({}, this.$mdDateLocale, this.dateLocale) : this.$mdDateLocale;
2548
2549     this.installPropertyInterceptors();
2550     this.attachChangeListeners();
2551     this.attachInteractionListeners();
2552   };
2553
2554   /**
2555    * Sets up the controller's reference to ngModelController and
2556    * applies Angular's `input[type="date"]` directive.
2557    * @param {!angular.NgModelController} ngModelCtrl Instance of the ngModel controller.
2558    * @param {Object} mdInputContainer Instance of the mdInputContainer controller.
2559    * @param {Object} inputDirective Config for Angular's `input` directive.
2560    */
2561   DatePickerCtrl.prototype.configureNgModel = function(ngModelCtrl, mdInputContainer, inputDirective) {
2562     this.ngModelCtrl = ngModelCtrl;
2563     this.mdInputContainer = mdInputContainer;
2564
2565     // The input needs to be [type="date"] in order to be picked up by Angular.
2566     this.$attrs.$set('type', 'date');
2567
2568     // Invoke the `input` directive link function, adding a stub for the element.
2569     // This allows us to re-use Angular's logic for setting the timezone via ng-model-options.
2570     // It works by calling the link function directly which then adds the proper `$parsers` and
2571     // `$formatters` to the ngModel controller.
2572     inputDirective[0].link.pre(this.$scope, {
2573       on: angular.noop,
2574       val: angular.noop,
2575       0: {}
2576     }, this.$attrs, [ngModelCtrl]);
2577
2578     var self = this;
2579
2580     // Responds to external changes to the model value.
2581     self.ngModelCtrl.$formatters.push(function(value) {
2582       if (value && !(value instanceof Date)) {
2583         throw Error('The ng-model for md-datepicker must be a Date instance. ' +
2584             'Currently the model is a: ' + (typeof value));
2585       }
2586
2587       self.onExternalChange(value);
2588
2589       return value;
2590     });
2591
2592     // Responds to external error state changes (e.g. ng-required based on another input).
2593     ngModelCtrl.$viewChangeListeners.unshift(angular.bind(this, this.updateErrorState));
2594
2595     // Forwards any events from the input to the root element. This is necessary to get `updateOn`
2596     // working for events that don't bubble (e.g. 'blur') since Angular binds the handlers to
2597     // the `<md-datepicker>`.
2598     var updateOn = self.$mdUtil.getModelOption(ngModelCtrl, 'updateOn');
2599
2600     if (updateOn) {
2601       this.ngInputElement.on(
2602         updateOn,
2603         angular.bind(this.$element, this.$element.triggerHandler, updateOn)
2604       );
2605     }
2606   };
2607
2608   /**
2609    * Attach event listeners for both the text input and the md-calendar.
2610    * Events are used instead of ng-model so that updates don't infinitely update the other
2611    * on a change. This should also be more performant than using a $watch.
2612    */
2613   DatePickerCtrl.prototype.attachChangeListeners = function() {
2614     var self = this;
2615
2616     self.$scope.$on('md-calendar-change', function(event, date) {
2617       self.setModelValue(date);
2618       self.onExternalChange(date);
2619       self.closeCalendarPane();
2620     });
2621
2622     self.ngInputElement.on('input', angular.bind(self, self.resizeInputElement));
2623
2624     var debounceInterval = angular.isDefined(this.debounceInterval) ?
2625         this.debounceInterval : DEFAULT_DEBOUNCE_INTERVAL;
2626     self.ngInputElement.on('input', self.$mdUtil.debounce(self.handleInputEvent,
2627         debounceInterval, self));
2628   };
2629
2630   /** Attach event listeners for user interaction. */
2631   DatePickerCtrl.prototype.attachInteractionListeners = function() {
2632     var self = this;
2633     var $scope = this.$scope;
2634     var keyCodes = this.$mdConstant.KEY_CODE;
2635
2636     // Add event listener through angular so that we can triggerHandler in unit tests.
2637     self.ngInputElement.on('keydown', function(event) {
2638       if (event.altKey && event.keyCode == keyCodes.DOWN_ARROW) {
2639         self.openCalendarPane(event);
2640         $scope.$digest();
2641       }
2642     });
2643
2644     if (self.openOnFocus) {
2645       self.ngInputElement.on('focus', angular.bind(self, self.openCalendarPane));
2646       angular.element(self.$window).on('blur', self.windowBlurHandler);
2647
2648       $scope.$on('$destroy', function() {
2649         angular.element(self.$window).off('blur', self.windowBlurHandler);
2650       });
2651     }
2652
2653     $scope.$on('md-calendar-close', function() {
2654       self.closeCalendarPane();
2655     });
2656   };
2657
2658   /**
2659    * Capture properties set to the date-picker and imperitively handle internal changes.
2660    * This is done to avoid setting up additional $watches.
2661    */
2662   DatePickerCtrl.prototype.installPropertyInterceptors = function() {
2663     var self = this;
2664
2665     if (this.$attrs.ngDisabled) {
2666       // The expression is to be evaluated against the directive element's scope and not
2667       // the directive's isolate scope.
2668       var scope = this.$scope.$parent;
2669
2670       if (scope) {
2671         scope.$watch(this.$attrs.ngDisabled, function(isDisabled) {
2672           self.setDisabled(isDisabled);
2673         });
2674       }
2675     }
2676
2677     Object.defineProperty(this, 'placeholder', {
2678       get: function() { return self.inputElement.placeholder; },
2679       set: function(value) { self.inputElement.placeholder = value || ''; }
2680     });
2681   };
2682
2683   /**
2684    * Sets whether the date-picker is disabled.
2685    * @param {boolean} isDisabled
2686    */
2687   DatePickerCtrl.prototype.setDisabled = function(isDisabled) {
2688     this.isDisabled = isDisabled;
2689     this.inputElement.disabled = isDisabled;
2690
2691     if (this.calendarButton) {
2692       this.calendarButton.disabled = isDisabled;
2693     }
2694   };
2695
2696   /**
2697    * Sets the custom ngModel.$error flags to be consumed by ngMessages. Flags are:
2698    *   - mindate: whether the selected date is before the minimum date.
2699    *   - maxdate: whether the selected flag is after the maximum date.
2700    *   - filtered: whether the selected date is allowed by the custom filtering function.
2701    *   - valid: whether the entered text input is a valid date
2702    *
2703    * The 'required' flag is handled automatically by ngModel.
2704    *
2705    * @param {Date=} opt_date Date to check. If not given, defaults to the datepicker's model value.
2706    */
2707   DatePickerCtrl.prototype.updateErrorState = function(opt_date) {
2708     var date = opt_date || this.date;
2709
2710     // Clear any existing errors to get rid of anything that's no longer relevant.
2711     this.clearErrorState();
2712
2713     if (this.dateUtil.isValidDate(date)) {
2714       // Force all dates to midnight in order to ignore the time portion.
2715       date = this.dateUtil.createDateAtMidnight(date);
2716
2717       if (this.dateUtil.isValidDate(this.minDate)) {
2718         var minDate = this.dateUtil.createDateAtMidnight(this.minDate);
2719         this.ngModelCtrl.$setValidity('mindate', date >= minDate);
2720       }
2721
2722       if (this.dateUtil.isValidDate(this.maxDate)) {
2723         var maxDate = this.dateUtil.createDateAtMidnight(this.maxDate);
2724         this.ngModelCtrl.$setValidity('maxdate', date <= maxDate);
2725       }
2726
2727       if (angular.isFunction(this.dateFilter)) {
2728         this.ngModelCtrl.$setValidity('filtered', this.dateFilter(date));
2729       }
2730     } else {
2731       // The date is seen as "not a valid date" if there is *something* set
2732       // (i.e.., not null or undefined), but that something isn't a valid date.
2733       this.ngModelCtrl.$setValidity('valid', date == null);
2734     }
2735
2736     angular.element(this.inputContainer).toggleClass(INVALID_CLASS, !this.ngModelCtrl.$valid);
2737   };
2738
2739   /** Clears any error flags set by `updateErrorState`. */
2740   DatePickerCtrl.prototype.clearErrorState = function() {
2741     this.inputContainer.classList.remove(INVALID_CLASS);
2742     ['mindate', 'maxdate', 'filtered', 'valid'].forEach(function(field) {
2743       this.ngModelCtrl.$setValidity(field, true);
2744     }, this);
2745   };
2746
2747   /** Resizes the input element based on the size of its content. */
2748   DatePickerCtrl.prototype.resizeInputElement = function() {
2749     this.inputElement.size = this.inputElement.value.length + EXTRA_INPUT_SIZE;
2750   };
2751
2752   /**
2753    * Sets the model value if the user input is a valid date.
2754    * Adds an invalid class to the input element if not.
2755    */
2756   DatePickerCtrl.prototype.handleInputEvent = function() {
2757     var inputString = this.inputElement.value;
2758     var parsedDate = inputString ? this.locale.parseDate(inputString) : null;
2759     this.dateUtil.setDateTimeToMidnight(parsedDate);
2760
2761     // An input string is valid if it is either empty (representing no date)
2762     // or if it parses to a valid date that the user is allowed to select.
2763     var isValidInput = inputString == '' || (
2764       this.dateUtil.isValidDate(parsedDate) &&
2765       this.locale.isDateComplete(inputString) &&
2766       this.isDateEnabled(parsedDate)
2767     );
2768
2769     // The datepicker's model is only updated when there is a valid input.
2770     if (isValidInput) {
2771       this.setModelValue(parsedDate);
2772       this.date = parsedDate;
2773     }
2774
2775     this.updateErrorState(parsedDate);
2776   };
2777
2778   /**
2779    * Check whether date is in range and enabled
2780    * @param {Date=} opt_date
2781    * @return {boolean} Whether the date is enabled.
2782    */
2783   DatePickerCtrl.prototype.isDateEnabled = function(opt_date) {
2784     return this.dateUtil.isDateWithinRange(opt_date, this.minDate, this.maxDate) &&
2785           (!angular.isFunction(this.dateFilter) || this.dateFilter(opt_date));
2786   };
2787
2788   /** Position and attach the floating calendar to the document. */
2789   DatePickerCtrl.prototype.attachCalendarPane = function() {
2790     var calendarPane = this.calendarPane;
2791     var body = document.body;
2792
2793     calendarPane.style.transform = '';
2794     this.$element.addClass(OPEN_CLASS);
2795     this.mdInputContainer && this.mdInputContainer.element.addClass(OPEN_CLASS);
2796     angular.element(body).addClass('md-datepicker-is-showing');
2797
2798     var elementRect = this.inputContainer.getBoundingClientRect();
2799     var bodyRect = body.getBoundingClientRect();
2800
2801     if (!this.topMargin || this.topMargin < 0) {
2802       this.topMargin = (this.inputMask.parent().prop('clientHeight') - this.ngInputElement.prop('clientHeight')) / 2;
2803     }
2804
2805     // Check to see if the calendar pane would go off the screen. If so, adjust position
2806     // accordingly to keep it within the viewport.
2807     var paneTop = elementRect.top - bodyRect.top - this.topMargin;
2808     var paneLeft = elementRect.left - bodyRect.left - this.leftMargin;
2809
2810     // If ng-material has disabled body scrolling (for example, if a dialog is open),
2811     // then it's possible that the already-scrolled body has a negative top/left. In this case,
2812     // we want to treat the "real" top as (0 - bodyRect.top). In a normal scrolling situation,
2813     // though, the top of the viewport should just be the body's scroll position.
2814     var viewportTop = (bodyRect.top < 0 && document.body.scrollTop == 0) ?
2815         -bodyRect.top :
2816         document.body.scrollTop;
2817
2818     var viewportLeft = (bodyRect.left < 0 && document.body.scrollLeft == 0) ?
2819         -bodyRect.left :
2820         document.body.scrollLeft;
2821
2822     var viewportBottom = viewportTop + this.$window.innerHeight;
2823     var viewportRight = viewportLeft + this.$window.innerWidth;
2824
2825     // Creates an overlay with a hole the same size as element. We remove a pixel or two
2826     // on each end to make it overlap slightly. The overlay's background is added in
2827     // the theme in the form of a box-shadow with a huge spread.
2828     this.inputMask.css({
2829       position: 'absolute',
2830       left: this.leftMargin + 'px',
2831       top: this.topMargin + 'px',
2832       width: (elementRect.width - 1) + 'px',
2833       height: (elementRect.height - 2) + 'px'
2834     });
2835
2836     // If the right edge of the pane would be off the screen and shifting it left by the
2837     // difference would not go past the left edge of the screen. If the calendar pane is too
2838     // big to fit on the screen at all, move it to the left of the screen and scale the entire
2839     // element down to fit.
2840     if (paneLeft + CALENDAR_PANE_WIDTH > viewportRight) {
2841       if (viewportRight - CALENDAR_PANE_WIDTH > 0) {
2842         paneLeft = viewportRight - CALENDAR_PANE_WIDTH;
2843       } else {
2844         paneLeft = viewportLeft;
2845         var scale = this.$window.innerWidth / CALENDAR_PANE_WIDTH;
2846         calendarPane.style.transform = 'scale(' + scale + ')';
2847       }
2848
2849       calendarPane.classList.add('md-datepicker-pos-adjusted');
2850     }
2851
2852     // If the bottom edge of the pane would be off the screen and shifting it up by the
2853     // difference would not go past the top edge of the screen.
2854     if (paneTop + CALENDAR_PANE_HEIGHT > viewportBottom &&
2855         viewportBottom - CALENDAR_PANE_HEIGHT > viewportTop) {
2856       paneTop = viewportBottom - CALENDAR_PANE_HEIGHT;
2857       calendarPane.classList.add('md-datepicker-pos-adjusted');
2858     }
2859
2860     calendarPane.style.left = paneLeft + 'px';
2861     calendarPane.style.top = paneTop + 'px';
2862     document.body.appendChild(calendarPane);
2863
2864     // Add CSS class after one frame to trigger open animation.
2865     this.$$rAF(function() {
2866       calendarPane.classList.add('md-pane-open');
2867     });
2868   };
2869
2870   /** Detach the floating calendar pane from the document. */
2871   DatePickerCtrl.prototype.detachCalendarPane = function() {
2872     this.$element.removeClass(OPEN_CLASS);
2873     this.mdInputContainer && this.mdInputContainer.element.removeClass(OPEN_CLASS);
2874     angular.element(document.body).removeClass('md-datepicker-is-showing');
2875     this.calendarPane.classList.remove('md-pane-open');
2876     this.calendarPane.classList.remove('md-datepicker-pos-adjusted');
2877
2878     if (this.isCalendarOpen) {
2879       this.$mdUtil.enableScrolling();
2880     }
2881
2882     if (this.calendarPane.parentNode) {
2883       // Use native DOM removal because we do not want any of the
2884       // angular state of this element to be disposed.
2885       this.calendarPane.parentNode.removeChild(this.calendarPane);
2886     }
2887   };
2888
2889   /**
2890    * Open the floating calendar pane.
2891    * @param {Event} event
2892    */
2893   DatePickerCtrl.prototype.openCalendarPane = function(event) {
2894     if (!this.isCalendarOpen && !this.isDisabled && !this.inputFocusedOnWindowBlur) {
2895       this.isCalendarOpen = this.isOpen = true;
2896       this.calendarPaneOpenedFrom = event.target;
2897
2898       // Because the calendar pane is attached directly to the body, it is possible that the
2899       // rest of the component (input, etc) is in a different scrolling container, such as
2900       // an md-content. This means that, if the container is scrolled, the pane would remain
2901       // stationary. To remedy this, we disable scrolling while the calendar pane is open, which
2902       // also matches the native behavior for things like `<select>` on Mac and Windows.
2903       this.$mdUtil.disableScrollAround(this.calendarPane);
2904
2905       this.attachCalendarPane();
2906       this.focusCalendar();
2907       this.evalAttr('ngFocus');
2908
2909       // Attach click listener inside of a timeout because, if this open call was triggered by a
2910       // click, we don't want it to be immediately propogated up to the body and handled.
2911       var self = this;
2912       this.$mdUtil.nextTick(function() {
2913         // Use 'touchstart` in addition to click in order to work on iOS Safari, where click
2914         // events aren't propogated under most circumstances.
2915         // See http://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
2916         self.documentElement.on('click touchstart', self.bodyClickHandler);
2917       }, false);
2918
2919       window.addEventListener(this.windowEventName, this.windowEventHandler);
2920     }
2921   };
2922
2923   /** Close the floating calendar pane. */
2924   DatePickerCtrl.prototype.closeCalendarPane = function() {
2925     if (this.isCalendarOpen) {
2926       var self = this;
2927
2928       self.detachCalendarPane();
2929       self.ngModelCtrl.$setTouched();
2930       self.evalAttr('ngBlur');
2931
2932       self.documentElement.off('click touchstart', self.bodyClickHandler);
2933       window.removeEventListener(self.windowEventName, self.windowEventHandler);
2934
2935       self.calendarPaneOpenedFrom.focus();
2936       self.calendarPaneOpenedFrom = null;
2937
2938       if (self.openOnFocus) {
2939         // Ensures that all focus events have fired before resetting
2940         // the calendar. Prevents the calendar from reopening immediately
2941         // in IE when md-open-on-focus is set. Also it needs to trigger
2942         // a digest, in order to prevent issues where the calendar wasn't
2943         // showing up on the next open.
2944         self.$mdUtil.nextTick(reset);
2945       } else {
2946         reset();
2947       }
2948     }
2949
2950     function reset(){
2951       self.isCalendarOpen = self.isOpen = false;
2952     }
2953   };
2954
2955   /** Gets the controller instance for the calendar in the floating pane. */
2956   DatePickerCtrl.prototype.getCalendarCtrl = function() {
2957     return angular.element(this.calendarPane.querySelector('md-calendar')).controller('mdCalendar');
2958   };
2959
2960   /** Focus the calendar in the floating pane. */
2961   DatePickerCtrl.prototype.focusCalendar = function() {
2962     // Use a timeout in order to allow the calendar to be rendered, as it is gated behind an ng-if.
2963     var self = this;
2964     this.$mdUtil.nextTick(function() {
2965       self.getCalendarCtrl().focus();
2966     }, false);
2967   };
2968
2969   /**
2970    * Sets whether the input is currently focused.
2971    * @param {boolean} isFocused
2972    */
2973   DatePickerCtrl.prototype.setFocused = function(isFocused) {
2974     if (!isFocused) {
2975       this.ngModelCtrl.$setTouched();
2976     }
2977
2978     // The ng* expressions shouldn't be evaluated when mdOpenOnFocus is on,
2979     // because they also get called when the calendar is opened/closed.
2980     if (!this.openOnFocus) {
2981       this.evalAttr(isFocused ? 'ngFocus' : 'ngBlur');
2982     }
2983
2984     this.isFocused = isFocused;
2985   };
2986
2987   /**
2988    * Handles a click on the document body when the floating calendar pane is open.
2989    * Closes the floating calendar pane if the click is not inside of it.
2990    * @param {MouseEvent} event
2991    */
2992   DatePickerCtrl.prototype.handleBodyClick = function(event) {
2993     if (this.isCalendarOpen) {
2994       var isInCalendar = this.$mdUtil.getClosest(event.target, 'md-calendar');
2995
2996       if (!isInCalendar) {
2997         this.closeCalendarPane();
2998       }
2999
3000       this.$scope.$digest();
3001     }
3002   };
3003
3004   /**
3005    * Handles the event when the user navigates away from the current tab. Keeps track of
3006    * whether the input was focused when the event happened, in order to prevent the calendar
3007    * from re-opening.
3008    */
3009   DatePickerCtrl.prototype.handleWindowBlur = function() {
3010     this.inputFocusedOnWindowBlur = document.activeElement === this.inputElement;
3011   };
3012
3013   /**
3014    * Evaluates an attribute expression against the parent scope.
3015    * @param {String} attr Name of the attribute to be evaluated.
3016    */
3017   DatePickerCtrl.prototype.evalAttr = function(attr) {
3018     if (this.$attrs[attr]) {
3019       this.$scope.$parent.$eval(this.$attrs[attr]);
3020     }
3021   };
3022
3023   /**
3024    * Sets the ng-model value by first converting the date object into a strng. Converting it
3025    * is necessary, in order to pass Angular's `input[type="date"]` validations. Angular turns
3026    * the value into a Date object afterwards, before setting it on the model.
3027    * @param {Date=} value Date to be set as the model value.
3028    */
3029   DatePickerCtrl.prototype.setModelValue = function(value) {
3030     var timezone = this.$mdUtil.getModelOption(this.ngModelCtrl, 'timezone');
3031     this.ngModelCtrl.$setViewValue(this.ngDateFilter(value, 'yyyy-MM-dd', timezone));
3032   };
3033
3034   /**
3035    * Updates the datepicker when a model change occurred externally.
3036    * @param {Date=} value Value that was set to the model.
3037    */
3038   DatePickerCtrl.prototype.onExternalChange = function(value) {
3039     var timezone = this.$mdUtil.getModelOption(this.ngModelCtrl, 'timezone');
3040
3041     this.date = value;
3042     this.inputElement.value = this.locale.formatDate(value, timezone);
3043     this.mdInputContainer && this.mdInputContainer.setHasValue(!!value);
3044     this.resizeInputElement();
3045     this.updateErrorState();
3046   };
3047 })();
3048
3049 ngmaterial.components.datepicker = angular.module("material.components.datepicker");