//===========================================================================================
// This script crates the day selection box with the correct ammound of days for each month.
//===========================================================================================
var monthLength = [31,28,31,30,31,30,31,31,30,31,30,31];

// returns true if a year is a leap year
function checkIfLeapYear(year) {
	return (((year % 400) == "0") ? true
	: (((year % 100) == "0") ? false
	: (((year % 4) == "0") ? true
	: false)));
}

// clear options of a select box
function clearSelectBox (id) {
	while (document.getElementById(id).options.length > 0) {
		var last = document.getElementById(id).lastChild;
		document.getElementById(id).removeChild(last);
	}
}

// create an option of a select box
function appendOption(selectBoxId, value, text, isSelected) {
	if(!document.getElementById(selectBoxId)) 
		return;
	
	var element = document.createElement("option");
	element.setAttribute("value", value);
	element.innerHTML = text;
	if (isSelected) 
		element.setAttribute("selected", "selected");
	document.getElementById(selectBoxId).appendChild(element);
	return true;
}

// create the options of the day select box
function createDayOptions () {
	var selectedDay = parseInt(document.getElementById('dateDay').value,10);
	var year = document.getElementById('dateYearMonth').value.substring(0,4);
	var month = document.getElementById('dateYearMonth').value.substring(4);
	
	// clear options 
	clearSelectBox ('dateDay');
	
	// february has 29 days in leap years
	var range = month == '02' && checkIfLeapYear (year) ? (monthLength[parseInt(month,10)-1] + 1)  : monthLength[parseInt(month,10)-1];
	
	// create options
	for (var i=1; i<=range; i++) {
		var day = (i < 10) ? '0'+i : i; 
		if (i == selectedDay) 
			appendOption('dateDay', day, day, true);
		else 
			appendOption('dateDay', day, day, false);
	}	
}

			
