function isLeapYear(year) {
	if (year%4!=0) {
		return false;
	} else {
		if (year%100!=0) {
			return true;
		} else {
			if (year%400!=0) {
				return false;
			} else {
				return true;
			}
		}
	}
}

function daysInMonth(year, month) {
	if (isLeapYear(year) && month == 1) {
		return 29;
	} else if (month == 1) {
		return 28;
	} else if (month==3 || month==5 || month==8 || month==10) {
		return 30;
	} else {
		return 31;
	}
}

function updateDays(parentDivJQ) {
	month = parentDivJQ.children('.monthPick').get(0).value;
	year = parentDivJQ.children('.yearPick').get(0).value;
	day = parentDivJQ.children('.dayPick').get(0).value;
	numDays = daysInMonth(year, month);
	parentDivJQ.children('.dayPick').children().remove();
	for (i=1; i<=numDays; i++) {
		parentDivJQ.children('.dayPick').append('<option value="'+i+'">'+i+'</option>');
	}
	if (day <= numDays) {
		parentDivJQ.children('.dayPick').get(0).selectedIndex = day-1;
	} else {
		parentDivJQ.children('.dayPick').get(0).selectedIndex = numDays-1;
	}
}

function updateDateSelects() {
	$('#useFromDate, #useToDate').each(function(){
		if (this.checked) {
			$(this).parent().children(".yearPick, .monthPick, .dayPick").removeAttr('disabled');
		} else {
			$(this).parent().children(".yearPick, .monthPick, .dayPick").attr('disabled', 'true');
		}
	});
}

$(document).ready(function(){
	$('.yearPick, .monthPick').change(function(ev) {
		updateDays($(ev.target).parent());
	});

	$('#useFromDate, #useToDate').bind("click", (function(ev) {
		box = $(ev.target);
		if (ev.target.checked) {
			box.parent().children(".yearPick, .monthPick, .dayPick").removeAttr('disabled');
		} else {
			box.parent().children(".yearPick, .monthPick, .dayPick").attr('disabled', 'true');
		}
		return true;
	}));

	updateDateSelects();

});
