/* Functions to handle date selection boxes (eg. Day Month Year) */

function trim(str) {
  // Strip leading/trailing whitespace from a string
  return str.replace(/^\s+|\s+$/g, '');
}

function updateDays(dayInput, monthInput, yearInput) {
  // Change the number of days in a the dayInput select box, based on the selections
	// in the monthInput and yearInput select boxes.

  var y = document.getElementById(yearInput).options[document.getElementById(yearInput).selectedIndex].value;
  var m = document.getElementById(monthInput).options[document.getElementById(monthInput).selectedIndex].value;
  var d;
	if ( (m == 4) || (m == 6) || (m == 9) || (m == 11) ) {days = 30;}
	else if (m == 2) {
		if ( (Math.floor(y/4) == (y/4)) && ((Math.floor(y/100) != (y/100)) || (Math.floor(y/400) == (y/400))) )
			days = 29;
		else
			days = 28;
	}
	else {days = 31;}
	if(document.getElementById(monthInput).length > 12){
		if ((days + 1) > document.getElementById(dayInput).length) {
			for (i = document.getElementById(dayInput).length; i < (days + 1); i++) {
				document.getElementById(dayInput).length = (days + 1);
				document.getElementById(dayInput).options[i].text = i;
				document.getElementById(dayInput).options[i].value = i;
			}
		} else if ((days + 1) < document.getElementById(dayInput).length) {
			var selectedDay = document.getElementById(dayInput).selectedIndex;
			document.getElementById(dayInput).length = (days + 1);
			if (selectedDay > days) 
				document.getElementById(dayInput).selectedIndex = days;
		}
	}else{
		if (days > document.getElementById(dayInput).length) {
			for (i = document.getElementById(dayInput).length; i < days; i++) {
				document.getElementById(dayInput).length = days;
				document.getElementById(dayInput).options[i].text = i + 1;
				document.getElementById(dayInput).options[i].value = i + 1;
			}
		} else if (days < document.getElementById(dayInput).length) {
			var selectedDay = document.getElementById(dayInput).selectedIndex;
			document.getElementById(dayInput).length = days;
			if (selectedDay > days - 1) 
				document.getElementById(dayInput).selectedIndex = days - 1;
		}
	}

}

function copyDate(fromDayInput, fromMonthInput, fromYearInput, toDayInput, toMonthInput, toYearInput) {
  // Copy date values from one group of select boxes to another.

  document.getElementById(toMonthInput).selectedIndex = document.getElementById(fromMonthInput).selectedIndex;
  document.getElementById(toYearInput).selectedIndex = document.getElementById(fromYearInput).selectedIndex;
	updateDays(toDayInput, toMonthInput, toYearInput);
  document.getElementById(toDayInput).selectedIndex = document.getElementById(fromDayInput).selectedIndex;
}
