﻿
function dropDownDatePicker(dayDropdown, monthDropdown, yearDropdown) {
    var _self = this;
    var _dayDropdown = dayDropdown;
    var _monthDropdown = monthDropdown;
    var _yearDropdown = yearDropdown;

    this.getDate = function () {
        return new Date(_self.getFullYear(), _self.getMonth() - 1, _self.getDay());
    }

    this.setDate = function (d) {        
        _self.setDay(d.getDate());
        _self.setMonth(d.getMonth() + 1);
        _self.setYear(d.getFullYear());
    }

    this.getDay = function () {
        return dayDropdown.val();
    }

    this.setDay = function (d) {
        dayDropdown.val(d);
    }

    this.getMonth = function () {
        return monthDropdown.val();
    }

    this.setMonth = function (m) {
        monthDropdown.val(m)
    }

    this.getFullYear = function () {
        return yearDropdown.val();
    }

    this.setYear = function (y) {
        yearDropdown.val(y)
    }

    this.getDaysInMonth = function (d) {
        return [31, (_self.isLeapYear(d.getFullYear()) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][d.getMonth()];
    }

    this.isLeapYear = function (y) {
        return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
    }

    this.populateDays = function (selectedDay) {
        var newDate = new Date(_self.getFullYear(), _self.getMonth() - 1, 1, 0, 0, 0, 0);
        var daysInMonth = _self.getDaysInMonth(newDate);

        if (selectedDay > daysInMonth) selectedDay == 1;

        dayDropdown.empty();

        for (var i = 1; i <= daysInMonth; i++) {
            var option = $("<option>").attr("value", i).text(i)
            if (i == selectedDay) option.attr("selected", "selected");
            option.appendTo(dayDropdown);
        };
    }

    this.update = function () {
        var selectedDay = _self.getDay();
        _self.populateDays(selectedDay);
    }

    yearDropdown.bind('change', this.update);
    yearDropdown.bind('keyup', this.update);
    monthDropdown.bind('change', this.update);
    monthDropdown.bind('keyup', this.update);
}
