//angular.module('datePicker1', []).controller('DatePicker1', ['$scope', function ($scope) {}]);


/**
 * copied from http://plnkr.co/edit/rp4Q1ydwENCJG0vkQgxP?p=preview
 */
angular.module('datePicker1', ['ngAnimate', 'ui.bootstrap.met']).controller('DatePicker1', ['$scope', function ($scope) {
    $scope.today = function () {
      $scope.dt = new Date(new Date().setYear(new Date().getYear() - 60));
    };
    $scope.today();

    $scope.clear = function () {
      $scope.dt = null;
    };

    // Disable weekend selection
    $scope.disabled = function (date, mode) {
      var disable = false;
      // uncomment the line below to disable selection of weekend days
      //disable = ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) );

      return disable;
    };

    $scope.toggleMin = function () {
      $scope.maxDate = $scope.maxDate ? null : new Date("January 1, 2200");
      $scope.minDate = $scope.minDate ? null : new Date("January 1, 1900");
    };
    $scope.toggleMin();

    $scope.open = function ($event) {
      $event.preventDefault();
      $event.stopPropagation();
      if (!$scope.status.opened)
        $scope.status.opened = true;
      else
        $scope.status.opened = false;
    };

    $scope.dateOptions = {
      startingDay: 1,
      format: 'dd-MM-yyyy',
      yearFormat: "'yyyy'",
      //yearRange: 100,		// Re-implemented in the widget
      //yearRows: 3,			// Re-implemented in the widget
      //yearColumns: 3,		// Re-implemented in the widget
      datepickerMode: 'year',
      showWeeks: false,
    };

    $scope.showWeeks = $scope.dateOptions.showWeeks;

    $scope.formats = ['dd-MM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
    $scope.format = $scope.formats[0];

    $scope.status = {
      opened: false
    };

    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    var afterTomorrow = new Date();
    afterTomorrow.setDate(tomorrow.getDate() + 2);
    $scope.events =
      [
        {
          date: tomorrow,
          status: 'full'
        },
        {
          date: afterTomorrow,
          status: 'partially'
        }
      ];

    $scope.getDayClass = function (date, mode) {
      if (mode === 'day') {
        var dayToCheck = new Date(date).setHours(0, 0, 0, 0);

        for (var i = 0; i < $scope.events.length; i++) {
          var currentDay = new Date($scope.events[i].date).setHours(0, 0, 0, 0);

          if (dayToCheck === currentDay) {
            return $scope.events[i].status;
          }
        }
      }

      return '';
    };
  }]).config(['datepickerConfigMet', 'datepickerPopupConfigMet', function (datepickerConfigMet, datepickerPopupConfigMet) {
    datepickerConfigMet.datepickerMode = 'year';
    datepickerPopupConfigMet.datepickerPopup = 'dd-MM-yyyy';
    //datepickerPopupConfigMet.datepickerPopup = 'dd/MM/yyyy';
  }]);


/*
 * MET adapted bootstrap library
 */

/*
 * angular-ui-bootstrap
 * http://angular-ui.github.io/bootstrap/
 
 * Version: 0.12.1 - 2015-02-20
 * License: MIT
 */
angular.module("ui.bootstrap.met", ["ui.bootstrap.tpls.met", "ui.bootstrap.datepicker.met"]);
angular.module("ui.bootstrap.tpls.met", ["template/datepicker/datepicker-met.html", "template/datepicker/day-met.html", "template/datepicker/month-met.html", "template/datepicker/popup-met.html", "template/datepicker/year-met.html"]);
angular.module('ui.bootstrap.transition.met', [])

//angular.module('ui.bootstrap.datepicker.met', ['ui.bootstrap.position', 'ui.bootstrap.dateparser'])
angular.module('ui.bootstrap.datepicker.met', ['ui.bootstrap.dateparser'])

  .constant('datepickerConfigMet', {
    formatDay: 'dd',
    formatMonth: 'MMMM',
    formatYear: 'yyyy',
    formatDayHeader: 'EEE',
    formatDayTitle: 'MMMM yyyy',
    formatMonthTitle: 'yyyy',
    datepickerMode: 'day',
    minMode: 'day',
    maxMode: 'year',
    showWeeks: true,
    startingDay: 0,
    // INFO: modified the widget to accept rows and columns params as directive attrs
    //yearRange: 20,
    yearColumns: 5,
    yearRows: 4,
    // INFO: added a date hour offset to avoid problems with european timezone (at the suggestion of RINA team) - TODO as a new feature eventually
    // INFO: Backwards of forwards widget date
    timeArrow: 'forward',
    minDate: null,
    maxDate: null
  })

  .controller('DatepickerControllerMet', ['$scope', '$attrs', '$parse', '$interpolate', '$log', 'dateFilter', 'datepickerConfigMet', function ($scope, $attrs, $parse, $interpolate, $log, dateFilter, datepickerConfigMet) {
      var self = this,
        ngModelCtrl = {$setViewValue: angular.noop}; // nullModelCtrl;

      // Modes chain
      this.modes = ['day', 'month', 'year'];

      // Configuration attributes
      angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle',
        'minMode', 'maxMode', 'showWeeks', 'startingDay', 'yearRows', 'yearColumns', 'timeArrow'], function (key, index) {
        self[key] = angular.isDefined($attrs[key]) ? (index < 8 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfigMet[key];

      });

      // Watchable date attributes
      angular.forEach(['minDate', 'maxDate'], function (key) {
        if ($attrs[key]) {
          $scope.$parent.$watch($parse($attrs[key]), function (value) {
            self[key] = value ? new Date(value) : null;
            self.refreshView();
          });
        } else {
          self[key] = datepickerConfigMet[key] ? new Date(datepickerConfigMet[key]) : null;
        }
      });

      //INFO: modified the widget to accept rows and columns params as directive attrs
      angular.forEach(['yearRows', 'yearColumns'], function (key) {
        if ($attrs[key]) {
          $scope.$parent.$watch($parse($attrs[key]), function (value) {
            if (value)
              self[key] = new Number(value);
            else
            {
              if (key == 'yearRows')
                self[key] = datepickerConfigMet.yearRows;
              if (key == 'yearColumns')
                self[key] = datepickerConfigMet.yearColumns;
            }
            self.refreshView();
          });
        } else {
          self[key] = datepickerConfigMet[key] ? new Number(datepickerConfigMet[key]) : null;
        }
      });

      //INFO: modified the widget to accept forward or backward date display
      angular.forEach(['timeArrow'], function (key) {
        if ($attrs[key]) {
          $scope.$parent.$watch($parse($attrs[key]), function (value) {
            if (value)
              self[key] = value;
            else
              self[key] = datepickerConfigMet.timeArrow;
            self.refreshView();
          });
        } else {
          self[key] = datepickerConfigMet[key] ? datepickerConfigMet[key] : null;
        }
      });

      $scope.datepickerMode = $scope.datepickerMode || datepickerConfigMet.datepickerMode;
      $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000);
      this.activeDate = angular.isDefined($attrs.initDate) ? $scope.$parent.$eval($attrs.initDate) : new Date();

      $scope.isActive = function (dateObject) {
        if (self.compare(dateObject.date, self.activeDate) === 0) {
          $scope.activeDateId = dateObject.uid;
          return true;
        }
        return false;
      };

      this.init = function (ngModelCtrl_) {
        ngModelCtrl = ngModelCtrl_;

        ngModelCtrl.$render = function () {
          self.render();
        };
      };

      this.render = function () {

        if (ngModelCtrl.$modelValue) {

          var date = new Date(ngModelCtrl.$modelValue),
            isValid = !isNaN(date);

          if (isValid) {
            this.activeDate = date;
          } else {
            $log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
          }
          ngModelCtrl.$setValidity('date', isValid);
        }
        this.refreshView();
      };

      this.refreshView = function () {
        if (this.element) {
          this._refreshView();

          var date = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : null;
          ngModelCtrl.$setValidity('date-disabled', !date || (this.element && !this.isDisabled(date)));
        }
      };

      this.createDateObject = function (date, format) {

        // UTC issue - commenting RINA suggested hack
        // INFO: added a date hour offset to avoid problems with european timezone (at the suggestion of RINA team)
//      if(ngModelCtrl.$modelValue)
//    	ngModelCtrl.$modelValue.setHours(12);

        var model = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : null;
        return {
          date: date,
          label: dateFilter(date, format),
          selected: model && this.compare(date, model) === 0,
          disabled: this.isDisabled(date),
          current: this.compare(date, new Date()) === 0
        };
      };

      this.isDisabled = function (date) {
        return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode})));
      };

      // Split array into smaller arrays
      this.split = function (arr, size) {
        var arrays = [];
        while (arr.length > 0) {
          arrays.push(arr.splice(0, size));
        }
        return arrays;
      };

      $scope.select = function (date) {
        if ($scope.datepickerMode === self.minMode) {
          var dt = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : new Date(0, 0, 0, 0, 0, 0, 0);
          dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
          ngModelCtrl.$setViewValue(dt);
          ngModelCtrl.$render();
        } else {
          self.activeDate = date;
          $scope.datepickerMode = self.modes[ self.modes.indexOf($scope.datepickerMode) - 1 ];
        }
      };

      $scope.move = function (direction) {
        var year = self.activeDate.getFullYear() + direction * (self.step.years || 0),
          month = self.activeDate.getMonth() + direction * (self.step.months || 0);
        self.activeDate.setFullYear(year, month, 1);
        self.refreshView();
      };

      $scope.toggleMode = function (direction) {
        direction = direction || 1;

        if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) {
          return;
        }

        $scope.datepickerMode = self.modes[ self.modes.indexOf($scope.datepickerMode) + direction ];
      };

      // Key event mapper
      $scope.keys = {13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down'};

      var focusElement = function () {
        self.element[0].focus();
      };

      // Listen for focus requests from popup directive
      $scope.$on('datepicker.focus', focusElement);

      $scope.keydown = function (evt) {
        var key = $scope.keys[evt.which];

        if (!key || evt.shiftKey || evt.altKey) {
          return;
        }

        evt.preventDefault();
        evt.stopPropagation();

        if (key === 'enter' || key === 'space') {
          if (self.isDisabled(self.activeDate)) {
            return; // do nothing
          }
          $scope.select(self.activeDate);
          focusElement();
        } else if (evt.ctrlKey && (key === 'up' || key === 'down')) {
          $scope.toggleMode(key === 'up' ? 1 : -1);
          focusElement();
        } else {
          self.handleKeyDown(key, evt);
          self.refreshView();
        }
      };
    }])

  .directive('datepickerMet', function () {
    return {
      restrict: 'EA',
      replace: true,
      templateUrl: 'template/datepicker/datepicker-met.html',
      scope: {
        datepickerMode: '=?',
        dateDisabled: '&'
      },
      require: ['datepickerMet', '?^ngModel'],
      controller: 'DatepickerControllerMet',
      link: function (scope, element, attrs, ctrls) {
        var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];

        if (ngModelCtrl) {
          datepickerCtrl.init(ngModelCtrl);
        }
      }
    };
  })

  .directive('daypickerMet', ['dateFilter', function (dateFilter) {
      return {
        restrict: 'EA',
        replace: true,
        templateUrl: 'template/datepicker/day-met.html',
        require: '^datepickerMet',
        link: function (scope, element, attrs, ctrl) {
          scope.showWeeks = ctrl.showWeeks;

          ctrl.step = {months: 1};
          ctrl.element = element;

          var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
          function getDaysInMonth(year, month) {
            return ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0))) ? 29 : DAYS_IN_MONTH[month];
          }

          function getDates(startDate, n) {
            var dates = new Array(n), current = new Date(startDate), i = 0;
            current.setHours(12); // Prevent repeated dates because of timezone bug
            while (i < n) {
              dates[i++] = new Date(current);
              current.setDate(current.getDate() + 1);
            }
            return dates;
          }

          ctrl._refreshView = function () {
            var year = ctrl.activeDate.getFullYear(),
              month = ctrl.activeDate.getMonth(),
              firstDayOfMonth = new Date(year, month, 1),
              difference = ctrl.startingDay - firstDayOfMonth.getDay(),
              numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : -difference,
              firstDate = new Date(firstDayOfMonth);

            if (numDisplayedFromPreviousMonth > 0) {
              firstDate.setDate(-numDisplayedFromPreviousMonth + 1);
            }

            // 42 is the number of days on a six-month calendar
            var days = getDates(firstDate, 42);
            for (var i = 0; i < 42; i++) {
              days[i] = angular.extend(ctrl.createDateObject(days[i], ctrl.formatDay), {
                secondary: days[i].getMonth() !== month,
                uid: scope.uniqueId + '-' + i
              });
            }

            scope.labels = new Array(7);
            for (var j = 0; j < 7; j++) {
              scope.labels[j] = {
                abbr: dateFilter(days[j].date, ctrl.formatDayHeader),
                full: dateFilter(days[j].date, 'EEEE')
              };
            }

            scope.title = dateFilter(ctrl.activeDate, ctrl.formatDayTitle);
            scope.rows = ctrl.split(days, 7);

            if (scope.showWeeks) {
              scope.weekNumbers = [];
              var weekNumber = getISO8601WeekNumber(scope.rows[0][0].date),
                numWeeks = scope.rows.length;
              while (scope.weekNumbers.push(weekNumber++) < numWeeks) {
              }
            }
          };

          ctrl.compare = function (date1, date2) {
            return (new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()));
          };

          function getISO8601WeekNumber(date) {
            var checkDate = new Date(date);
            checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday
            var time = checkDate.getTime();
            checkDate.setMonth(0); // Compare with Jan 1
            checkDate.setDate(1);
            return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
          }

          ctrl.handleKeyDown = function (key, evt) {
            var date = ctrl.activeDate.getDate();

            if (key === 'left') {
              date = date - 1;   // up
            } else if (key === 'up') {
              date = date - 7;   // down
            } else if (key === 'right') {
              date = date + 1;   // down
            } else if (key === 'down') {
              date = date + 7;
            } else if (key === 'pageup' || key === 'pagedown') {
              var month = ctrl.activeDate.getMonth() + (key === 'pageup' ? -1 : 1);
              ctrl.activeDate.setMonth(month, 1);
              date = Math.min(getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth()), date);
            } else if (key === 'home') {
              date = 1;
            } else if (key === 'end') {
              date = getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth());
            }
            ctrl.activeDate.setDate(date);
          };

          ctrl.refreshView();
        }
      };
    }])

  .directive('monthpickerMet', ['dateFilter', function (dateFilter) {
      return {
        restrict: 'EA',
        replace: true,
        templateUrl: 'template/datepicker/month-met.html',
        require: '^datepickerMet',
        link: function (scope, element, attrs, ctrl) {
          ctrl.step = {years: 1};
          ctrl.element = element;

          ctrl._refreshView = function () {
            var months = new Array(12),
              year = ctrl.activeDate.getFullYear();

            for (var i = 0; i < 12; i++) {
              months[i] = angular.extend(ctrl.createDateObject(new Date(year, i, 1), ctrl.formatMonth), {
                uid: scope.uniqueId + '-' + i
              });
            }

            scope.title = dateFilter(ctrl.activeDate, ctrl.formatMonthTitle);
            scope.rows = ctrl.split(months, 3);
          };

          ctrl.compare = function (date1, date2) {
            return new Date(date1.getFullYear(), date1.getMonth()) - new Date(date2.getFullYear(), date2.getMonth());
          };

          ctrl.handleKeyDown = function (key, evt) {
            var date = ctrl.activeDate.getMonth();

            if (key === 'left') {
              date = date - 1;   // up
            } else if (key === 'up') {
              date = date - 3;   // down
            } else if (key === 'right') {
              date = date + 1;   // down
            } else if (key === 'down') {
              date = date + 3;
            } else if (key === 'pageup' || key === 'pagedown') {
              var year = ctrl.activeDate.getFullYear() + (key === 'pageup' ? -1 : 1);
              ctrl.activeDate.setFullYear(year);
            } else if (key === 'home') {
              date = 0;
            } else if (key === 'end') {
              date = 11;
            }
            ctrl.activeDate.setMonth(date);
          };

          ctrl.refreshView();
        }
      };
    }])

  .directive('yearpickerMet', ['dateFilter', function (dateFilter) {
      return {
        restrict: 'EA',
        replace: true,
        templateUrl: 'template/datepicker/year-met.html',
        require: '^datepickerMet',
        link: function (scope, element, attrs, ctrl) {
          // INFO: modified the widget to accept rows and columns params as directive attrs
          //var range = ctrl.yearRange;

          var columns, range;
          columns = ctrl.yearColumns;
          range = ctrl.yearRows * columns;

          ctrl.step = {years: range};
          ctrl.element = element;

          function getStartingYear(year) {
            // INFO: Modified to start the widget with the current year
            //return parseInt((year - 1) / range, 10) * range + 1;

            // INFO: modified to start with currentYear - range
            if (ctrl.timeArrow === 'backward')
              year = year - range + 1;
            return parseInt(year, 10);
          }

          ctrl._refreshView = function () {
            var years = new Array(range);

            for (var i = 0, start = getStartingYear(ctrl.activeDate.getFullYear()); i < range; i++) {
              years[i] = angular.extend(ctrl.createDateObject(new Date(start + i, 0, 1), ctrl.formatYear), {
                uid: scope.uniqueId + '-' + i
              });
            }

            scope.title = [years[0].label, years[range - 1].label].join(' - ');
            scope.rows = ctrl.split(years, columns);
            scope.columns = columns;
          };

          ctrl.compare = function (date1, date2) {
            return date1.getFullYear() - date2.getFullYear();
          };

          ctrl.handleKeyDown = function (key, evt) {
            var date = ctrl.activeDate.getFullYear();

            if (key === 'left') {
              date = date - 1;   // up
            } else if (key === 'up') {
              date = date - columns;   // down
            } else if (key === 'right') {
              date = date + 1;   // down
            } else if (key === 'down') {
              date = date + columns;
            } else if (key === 'pageup' || key === 'pagedown') {
              date += (key === 'pageup' ? -1 : 1) * ctrl.step.years;
            } else if (key === 'home') {
              date = getStartingYear(ctrl.activeDate.getFullYear());
            } else if (key === 'end') {
              date = getStartingYear(ctrl.activeDate.getFullYear()) + range - 1;
            }
            ctrl.activeDate.setFullYear(date);
          };

          ctrl.refreshView();
        }
      };
    }])

  .constant('datepickerPopupConfigMet', {
    datepickerPopup: 'yyyy-MM-dd',
    currentText: 'Today',
    clearText: 'Clear',
    closeText: 'Done',
    closeOnDateSelection: true,
    appendToBody: false,
    showButtonBar: true
  })

  .directive('datepickerPopupMet', ['$compile', '$parse', '$document', '$position', 'dateFilter', 'dateParser', 'datepickerPopupConfigMet', '$timeout',
    function ($compile, $parse, $document, $position, dateFilter, dateParser, datepickerPopupConfigMet, $timeout) {
      return {
        restrict: 'EA',
        require: 'ngModel',
        scope: {
          isOpen: '=?',
          currentText: '@',
          clearText: '@',
          closeText: '@',
          dateDisabled: '&'
        },
        link: function (scope, element, attrs, ngModel) {
          var dateFormat,
            closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? scope.$parent.$eval(attrs.closeOnDateSelection) : datepickerPopupConfigMet.closeOnDateSelection,
            appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? scope.$parent.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfigMet.appendToBody;

          scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? scope.$parent.$eval(attrs.showButtonBar) : datepickerPopupConfigMet.showButtonBar;

          scope.getText = function (key) {
            return scope[key + 'Text'] || datepickerPopupConfigMet[key + 'Text'];
          };

          attrs.$observe('datepickerPopupMet', function (value) {
            dateFormat = value || datepickerPopupConfigMet.datepickerPopup;
            ngModel.$render();
          });

          // popup element used to display calendar
          var popupEl = angular.element('<div datepicker-popup-wrap-met><div datepicker-met></div></div>');
          popupEl.attr({
            'ng-model': 'date',
            'ng-change': 'dateSelection(date)'
          });

          function cameltoDash(string) {
            return string.replace(/([A-Z])/g, function ($1) {
              return '-' + $1.toLowerCase();
            });
          }

          // datepicker element
          var datepickerEl = angular.element(popupEl.children()[0]);
          if (attrs.datepickerOptions) {
            angular.forEach(scope.$parent.$eval(attrs.datepickerOptions), function (value, option) {
              datepickerEl.attr(cameltoDash(option), value);
            });
          }

          scope.watchData = {};
          // INFO: modified the widget to accept rows and columns params as directive attrs and date forward/backward display
          angular.forEach(['minDate', 'maxDate', 'datepickerMode', 'yearRows', 'yearColumns', 'timeArrow'], function (key) {
            if (attrs[key]) {
              var getAttribute = $parse(attrs[key]);
              scope.$parent.$watch(getAttribute, function (value) {
                if (key === 'timeArrow')
                  value = attrs[key];
                scope.watchData[key] = value;
              });
              datepickerEl.attr(cameltoDash(key), 'watchData.' + key);

              // Propagate changes from datepicker to outside
              if (key === 'datepickerMode') {
                var setAttribute = getAttribute.assign;
                scope.$watch('watchData.' + key, function (value, oldvalue) {
                  if (value !== oldvalue) {
                    setAttribute(scope.$parent, value);
                  }
                });
              }
            }
          });
          if (attrs.dateDisabled) {
            datepickerEl.attr('date-disabled', 'dateDisabled({ date: date, mode: mode })');
          }

          function parseDate(viewValue) {
            if (!viewValue) {
              ngModel.$setValidity('date', true);
              return null;
            } else if (angular.isDate(viewValue) && !isNaN(viewValue)) {
              ngModel.$setValidity('date', true);
              return viewValue;
            } else if (angular.isString(viewValue)) {
              // Verify if it contains two -
              var parts = viewValue.split("-");
              if (parts.length != 3) {
                ngModel.$setValidity('date', false);
                return undefined;
              }
              // The year needs to be full
              if (parts[2].length != 4) {
                ngModel.$setValidity('date', false);
                return undefined;
              }
              // Also the year needs not to start with 0
              if (parts[2][0] == '0') {
                ngModel.$setValidity('date', false);
                return undefined;
              }
              // If the month or the day is a single digit, modify it to have two digits
              if (parts[0].length == 1)
                parts[0] = "0" + parts[0];
              if (parts[1].length == 1)
                parts[1] = "0" + parts[1];

              viewValue = parts[0] + "-" + parts[1] + "-" + parts[2];
              var date = dateParser.parse(viewValue, dateFormat) || new Date(viewValue);
              if (isNaN(date)) {
                ngModel.$setValidity('date', false);
                return undefined;
              } else {
                ngModel.$setValidity('date', true);
                return date;
              }
            } else {
              ngModel.$setValidity('date', false);
              return undefined;
            }
          }
          ngModel.$parsers.unshift(parseDate);

          // Inner change
          scope.dateSelection = function (dt) {
            if (angular.isDefined(dt)) {
              scope.date = dt;
            }
            ngModel.$setViewValue(scope.date);
            ngModel.$render();

            if (closeOnDateSelection) {
              scope.isOpen = false;
              element[0].focus();
            }
          };

          element.bind('input change keyup', function () {
            scope.$apply(function () {
              scope.date = ngModel.$modelValue;
            });
          });

          // Outter change
          ngModel.$render = function () {
            // UTC issue - when using setFormData() with a JSON object and thus receiving for the binded control an actual Date object
            // (this could be achieved via sed_angular_commons.js getFormData()/setFormData()), the ngModel.$viewValue comes already 
            // as a full ISO string and this string will be shown ignoring :-( the datePicker1's specified format. We have to correct 
            // it via this hack
            if (typeof ngModel.$viewValue === "string" && Utils.getClassName(ngModel.$modelValue) === "Date")
              ngModel.$viewValue = parseDate(ngModel.$modelValue);

            var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
            element.val(date);
            scope.date = parseDate(ngModel.$modelValue);

          };

          var documentClickBind = function (event) {
            if (scope.isOpen && event.target !== element[0]) {
              scope.$apply(function () {
                scope.isOpen = false;
              });
            }
          };

          var inputKeydownBind = function (evt) {
            if (evt.which === 27 && scope.isOpen) {
              evt.preventDefault();
              evt.stopPropagation();
              scope.$apply(function () {
                scope.isOpen = false;
              });
              element[0].focus();
            } else if (evt.which === 40 && !scope.isOpen) {
              evt.preventDefault();
              evt.stopPropagation();
              scope.$apply(function () {
                scope.isOpen = true;
              });
            }
          };
          element.bind('keydown', inputKeydownBind);

          scope.keydown = function (evt) {
            if (evt.which === 27) {
              scope.isOpen = false;
              element[0].focus();
            }
          };

          scope.$watch('isOpen', function (value) {
            if (value) {
              scope.position = appendToBody ? $position.offset(element) : $position.position(element);
              scope.position.top = scope.position.top + element.prop('offsetHeight');

              $document.bind('click', documentClickBind);

              $timeout(function () {
                scope.$broadcast('datepicker.focus');
              }, 0, false);
            } else {
              $document.unbind('click', documentClickBind);
            }
          });

          scope.select = function (date) {
            if (date === 'today') {
              var today = new Date();
              if (angular.isDate(ngModel.$modelValue)) {
                date = new Date(ngModel.$modelValue);
                date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate());
              } else {
                date = new Date(today.setHours(0, 0, 0, 0));
              }
            }
            scope.dateSelection(date);
          };

          scope.close = function () {
            scope.isOpen = false;
            element[0].focus();
          };

          var $popup = $compile(popupEl)(scope);
          // Prevent jQuery cache memory leak (template is now redundant after linking)
          popupEl.remove();

          if (appendToBody) {
            $document.find('body').append($popup);
          } else {
            element.after($popup);
          }

          scope.$on('$destroy', function () {
            if (scope.isOpen === true) {
              scope.$apply(function () {
                scope.isOpen = false;
              });
            }

            $popup.remove();

            element.unbind('keydown', inputKeydownBind);
            $document.unbind('click', documentClickBind);
          });
        }
      };
    }])

  .directive('datepickerPopupWrapMet', function () {
    return {
      restrict: 'EA',
      replace: true,
      transclude: true,
      templateUrl: 'template/datepicker/popup-met.html',
    };
  });

angular.module("template/datepicker/datepicker-met.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("template/datepicker/datepicker-met.html",
      "<div ng-switch=\"datepickerMode\" role=\"application\" ng-keydown=\"keydown($event)\">\n" +
      "  <daypicker-met ng-switch-when=\"day\" tabindex=\"0\"></daypicker-met>\n" +
      "  <monthpicker-met ng-switch-when=\"month\" tabindex=\"0\"></monthpicker-met>\n" +
      "  <yearpicker-met ng-switch-when=\"year\" tabindex=\"0\"></yearpicker-met>\n" +
      "</div>");
  }]);

angular.module("template/datepicker/day-met.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("template/datepicker/day-met.html",
      "<table role=\"grid\" aria-labelledby=\"{{::uniqueId}}-title\" aria-activedescendant=\"{{::activeDateId}}\">\n" +
      "  <thead>\n" +
      "    <tr>\n" +
      "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" +
      "      <th colspan=\"{{::5 + showWeeks}}\"><button id=\"{{::uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" tabindex=\"-1\" style=\"width:100%;\"><strong>{{title}}</strong></button></th>\n" +
      "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" +
      "    </tr>\n" +
      "    <tr>\n" +
      "      <th ng-show=\"showWeeks\" class=\"text-center\"></th>\n" +
      "      <th ng-repeat=\"label in ::labels track by $index\" class=\"text-center\"><small aria-label=\"{{::label.full}}\">{{::label.abbr}}</small></th>\n" +
      "    </tr>\n" +
      "  </thead>\n" +
      "  <tbody>\n" +
      "    <tr ng-repeat=\"row in rows track by $index\">\n" +
      "      <td ng-show=\"showWeeks\" class=\"text-center h6\"><em>{{ weekNumbers[$index] }}</em></td>\n" +
      "      <td ng-repeat=\"dt in row track by dt.date\" class=\"text-center\" role=\"gridcell\" id=\"{{::dt.uid}}\" aria-disabled=\"{{::!!dt.disabled}}\">\n" +
      "        <button type=\"button\" style=\"width:100%;\" class=\"btn btn-default btn-sm\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"::dt.disabled\" tabindex=\"-1\"><span ng-class=\"::{'text-muted': dt.secondary, 'text-info': dt.current}\">{{::dt.label}}</span></button>\n" +
      "      </td>\n" +
      "    </tr>\n" +
      "  </tbody>\n" +
      "</table>\n" +
      "");
  }]);

angular.module("template/datepicker/month-met.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("template/datepicker/month-met.html",
      "<table role=\"grid\" aria-labelledby=\"{{::uniqueId}}-title\" aria-activedescendant=\"{{::activeDateId}}\">\n" +
      "  <thead>\n" +
      "    <tr>\n" +
      "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" +
      "      <th><button id=\"{{::uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" tabindex=\"-1\" style=\"width:100%;\"><strong>{{title}}</strong></button></th>\n" +
      "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" +
      "    </tr>\n" +
      "  </thead>\n" +
      "  <tbody>\n" +
      "    <tr ng-repeat=\"row in rows track by $index\">\n" +
      "      <td ng-repeat=\"dt in row track by dt.date\" class=\"text-center\" role=\"gridcell\" id=\"{{::dt.uid}}\" aria-disabled=\"{{::!!dt.disabled}}\">\n" +
      "        <button type=\"button\" style=\"width:100%;\" class=\"btn btn-default\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"::dt.disabled\" tabindex=\"-1\"><span ng-class=\"::{'text-info': dt.current}\">{{::dt.label}}</span></button>\n" +
      "      </td>\n" +
      "    </tr>\n" +
      "  </tbody>\n" +
      "</table>\n" +
      "");
  }]);

angular.module("template/datepicker/popup-met.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("template/datepicker/popup-met.html",
      "<ul class=\"dropdown-menu\" ng-if=\"isOpen\" style=\"display: block\" ng-style=\"{top: position.top+'px', left: position.left+'px'}\" ng-keydown=\"keydown($event)\" ng-click=\"$event.stopPropagation()\">\n" +
      "	<li ng-transclude></li>\n" +
      "	<li ng-if=\"showButtonBar\" style=\"padding:10px 9px 2px\">\n" +
      "		<span class=\"btn-group pull-left\">\n" +
      "			<button type=\"button\" class=\"btn btn-sm btn-link\" style=\"color:#0088CC\" ng-click=\"select('today')\">{{ getText('current') }}</button>\n" +
      "			<button type=\"button\" class=\"btn btn-sm btn-link\" style=\"color:#0088CC\" ng-click=\"select(null)\">{{ getText('clear') }}</button>\n" +
      "		</span>\n" +
      "		<button type=\"button\" class=\"btn btn-sm btn-link pull-right\" style=\"color:#0088CC\" ng-click=\"close()\">{{ getText('close') }}</button>\n" +
      "	</li>\n" +
      "</ul>\n" +
      "");
  }]);

angular.module("template/datepicker/year-met.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("template/datepicker/year-met.html",
      "<table role=\"grid\" aria-labelledby=\"{{::uniqueId}}-title\" aria-activedescendant=\"{{::activeDateId}}\">\n" +
      "  <thead>\n" +
      "    <tr>\n" +
      "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-left\"></i></button></th>\n" +
      "      <th colspan=\"{{::columns-2}}\"><button id=\"{{::uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" tabindex=\"-1\" style=\"width:100%;\"><strong>{{title}}</strong></button></th>\n" +
      "      <th><button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"><i class=\"glyphicon glyphicon-chevron-right\"></i></button></th>\n" +
      "    </tr>\n" +
      "  </thead>\n" +
      "  <tbody>\n" +
      "    <tr ng-repeat=\"row in rows track by $index\">\n" +
      "      <td ng-repeat=\"dt in row track by dt.date\" class=\"text-center\" role=\"gridcell\" id=\"{{::dt.uid}}\" aria-disabled=\"{{::!!dt.disabled}}\">\n" +
      "        <button type=\"button\" style=\"width:100%;\" class=\"btn btn-default\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"::dt.disabled\" tabindex=\"-1\"><span ng-class=\"::{'text-info': dt.current}\">{{::dt.label}}</span></button>\n" +
      "      </td>\n" +
      "    </tr>\n" +
      "  </tbody>\n" +
      "</table>\n" +
      "");
  }]);
















