/* Handles birthday control functions */
function milosBirthday(){}

// Reacts to changing month
milosBirthday.monthChanges = function(month, day, year)
{
    milosBirthday.daysMustChange(month, day, year);
}

// Reacts to changing day
milosBirthday.dayChanges = function(month, day, year)
{
    // Nothing to do
}

// Reacts to changing year
milosBirthday.yearChanges = function(month, day, year)
{
    milosBirthday.daysMustChange(month, day, year);
}

// Reacts to changing month or year
milosBirthday.daysMustChange = function(month, day, year)
{
    var monthValue = month.value;
    var dayValue = day.value;
    var yearValue = year.value;

    if (monthValue == 1 || monthValue == 3  || monthValue == 5 || monthValue == 7 || monthValue == 8 || monthValue == 10 || monthValue == 12)
        milosBirthday.populateDays(day, 31, dayValue);
    if (monthValue == 4 || monthValue == 6  || monthValue == 9 || monthValue == 11)
        milosBirthday.populateDays(day, 30, dayValue);
    if (monthValue == 2)
    {
        if (milosBirthday.isLeapYear(yearValue))
            milosBirthday.populateDays(day, 29, dayValue);
        else
            milosBirthday.populateDays(day, 28, dayValue);
    }    
}

/* Populate the days drop down */
milosBirthday.populateDays = function(days, totalDays, selectedDay)
{
    var firstCaption = days.options[0].text;
    var selectedIndex = days.selectedIndex;
    while (days.options.length > totalDays + 1)
        days.options.remove(days.options.length - 1);
    while (totalDays + 1 > days.options.length)
    {
        var newOption = document.createElement('option');
        newOption.text = days.options.length;
        newOption.value = days.options.length;
        days.options.add(newOption);
    }
    if (selectedIndex > days.options.length - 1)
        days.selectedIndex = days.options.length - 1;
}

/* Leap year calculation */
milosBirthday.isLeapYear = function(year)
{
    if (year == 0) return false;
    if (year % 400 == 0) return true;
    if (year % 100 == 0) return false;
    if (year % 4 == 0) return true;
    return false;
}