
//**************************************************
// Widget that controls a date field combination
// Days in month depend on the month and year selected.
// This adjusts the day field based on the other two.
//***************************************************


//Get the number of days in the selected month,year
function daysInMonth(month, year){
  var days = (month == 3 || month == 5 || month == 8 || month == 10)?30:31;
  if(month==1) {
  	days = ((year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0))) ?29:28;
  }
  return days;
}


/**
  * Update the select lists to deal with a different 
  * month not having the same number of days .
  *
  * call this when the month or year select changes (Leap issue)
  * @return void
  * @called Internally or from an onChange handler
  */
function setDayOptions(dayDomId,monthDomId,yearDomId){

	var dayField = document.getElementById(dayDomId);
	var monthField = document.getElementById(monthDomId);
	var yearField = document.getElementById(yearDomId);
	
	var month = monthField.selectedIndex -normalizeMonth(monthField);
  	var year = yearField[yearField.selectedIndex].value;
	var days = daysInMonth(month,year);
	var dayOffset = normalizeDay(dayField)
	var currentOptions = dayField.length;
	var currentDays = currentOptions-dayOffset;
	
	if(currentDays > days) {
		for (i=0; i<currentDays-days; i++)
    		dayField.options[dayField.options.length - 1] = null;
	}
	else if(days > currentDays) {
		for (i=0; i<(days-currentDays); i++)
    		dayField.options[dayField.options.length]=new Option(dayField.options.length + 1 -dayOffset,dayField.options.length + 1 -dayOffset);
    }   
    if(dayField.selectedIndex < 0)
    	dayField.selectedIndex = parseInt(1 + dayOffset);
}


/**
 * Determine the index of the select list that corresponds to January
 */
function normalizeMonth(monthField){
	for(var i = 0; i < monthField.options.length;i++){
		if(monthField.options[i].value==0 || monthField.options[i].value.toLowerCase()=="jan" || monthField.options[i].value.toLowerCase()=="january") 
			return i;
	}
}

/**
 * Determine the index of the select list that corresponds to January
 */
function normalizeDay(dayField){
	for(var i = 0; i < dayField.options.length;i++){
		if(dayField.options[i].value==1) 
			return i;
	}
}

/**
 * Used to initialize the month and year hidden fields for
 * the flight finder with today's current month/year.
 */
function setMonthYear(monthDomId, dayDomId, yearDomId, dateDomId) {
	var monthField = document.getElementById(monthDomId);
	var dayField = document.getElementById(dayDomId);
	var yearField = document.getElementById(yearDomId);
	var dateField = document.getElementById(dateDomId);

	var now = new Date();
	var m = now.getMonth();
	var d = now.getDate();
	var y = now.getFullYear();
	monthField.value = m+1; 
	dayField.value = d;
	yearField.value = y;
	dateField.value = getFormattedDateBefore(m, d + 1, y);
}

