// JavaScript Document

var short_months = new Array(4,6,9,11);

month_names = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

function set_up_date_change() {
	//test for browser capabiities
	if (!document.getElementsByTagName) return false;
	if (!document.getElementById) return false;
	if (document.getElementById("date_select")) {
		var selects = document.getElementById("date_select").getElementsByTagName("select");
	}
	selects[1].onchange = function() {
		change_dates();
	}
	selects[2].onchange = function() {
		change_dates();
	}
	
}

addLoadEvent(set_up_date_change);

function change_dates() {

	//var last_birthday = new Date(9,14,1992);
	
	var selects = document.getElementById("date_select").getElementsByTagName("select");
	
	year = selects[2].options[selects[2].selectedIndex].value;
	month = selects[1].options[selects[1].selectedIndex].value;
	
	var months = selects[1].options;
	var days = selects[0].options;
	
	//30 day months
	//alert(days.length);
	short_month = false;
	for (var i=0;i<short_months.length;i++) {
		if (short_months[i] == month) {
			if (days.length == 32) {
				selects[0].removeChild(days[31]);
			} else { //changing from Feb
				while (days.length < 31) {
					var new_option = create_option(days.length,days.length);
					insertAfter(new_option,days[days.length-1]);
				}				
			}
			short_month = true;
			break;
		}
	}

	//feb
	if  (month == 2) {
		//alert(days.length);
		//leap year adjustments
		if (year%400 ==0 || (year%100 != 0 && year%4 == 0)) {
			var day_target = 30;
			//alert(year + " is a leap year");
			
		} else {
			var day_target = 29;
		}
		while (days.length > day_target) {
			selects[0].removeChild(days[days.length-1]);
		}
		while (days.length < day_target) {
			var new_option = create_option(days.length,days.length);
			insertAfter(new_option,days[days.length-1]);
		}
		//short_month = true;
		//break;
	}
	
	
	if ((!short_month && month != 2) && days.length < 32 ) {
		while (days.length < 32) {
			var new_option = create_option(days.length,days.length);
			insertAfter(new_option,days[days.length-1]);
		}
	}
	
	
	
	//removes months before age limit
	if(year == first_year) {
		
		for(var i=1;i<months.length;i++) {
			//alert(months[i].value);
			if (parseInt(months[i].value)  > first_month) {
				selects[1].removeChild(months[i]);
				i--;
			}
		}
	} else {
		while (months.length < 13) {
			var new_option = create_option(months.length,month_names[months.length-1]);
			insertAfter(new_option,months[months.length-1]);
		}		
	}
	
	//removes days before age limit
	if (year == first_year && month == first_month) {
		
		
		for(var i=1;i<days.length;i++) {
			//alert(days[i].value);
			if (parseInt(days[i].value) > first_day) {
				selects[0].removeChild(days[i]);
				i--;
			}
		}	
	}

}

