/** date_dropdown.js
 *  Author: Bradley Hovinga
 *  Date: 2/20/06
 * 
 *  
 */

// Do on page load
function date_dropdown_init(day, month, year) {

    // Load the forms
    var day_node = document.getElementById(day); 
    var month_node = document.getElementById(month);
    var year_node = document.getElementById(year);
    
    // Get the last couple day nodes
    var extra_days = new Array(3);
    for (var i = 0; i < 3; i++) {
        extra_days[i] = day_node[i + 28].cloneNode(true);
    }
    
    // Set it so it runs and runs whatever is already in onchange
    if (month_node.onchange != null) {
	    	var month_node_onchange = month_node.onchange;
    		month_node.onchange = function() { month_node_onchange(); date_dropdown_days_in_month(day_node, month_node, year_node, extra_days); };
    } else {
	    month_node.onchange = function() { date_dropdown_days_in_month(day_node, month_node, year_node, extra_days); };
    }
    if (year_node.onchange != null) {
	    var year_node_onchange = year_node.onchange;
	    year_node.onchange = function() { year_node_onchange(); date_dropdown_days_in_month(day_node, month_node, year_node, extra_days); };
    } else {
        year_node.onchange = function() { date_dropdown_days_in_month(day_node, month_node, year_node, extra_days); };
    }
    
    // And run once
    date_dropdown_days_in_month(day_node, month_node, year_node, extra_days);
}

// This function determines the number of days to display for each month
function date_dropdown_days_in_month(day_node, month_node, year_node, extra_days) {
    
    var days;
    month = month_node.value;
    year = year_node.value;

    // How many days in the month
    switch (month) {
        case "1":
        case "3":
        case "5":
        case "7":
        case "8":
        case "10":
        case "12":
            days = 31;
            break;
        case "4":
        case "6":
        case "9":
        case "11":
            days = 30;
            break;
        case "2":
            // Check for leap year
            if (year / 4 == Math.floor(year / 4)) {
                days = 29;
            } else {
                days = 28;
            }
            break;
        default:
            alert("DATE ERROR")
            break;
    }
    
    // Set the form
    if (days <= day_node.length) {
        // If there are too many days, set the number of days
        day_node.length = days;
    } else {
        // If there aren't enough days, add some in
        for (var i = day_node.length - 28; i < days - 28; i++) {
            day_node.appendChild(extra_days[i].cloneNode(true));
        }
    }
}

