$(document).ready(function() {

	$('select.date_selector_month').change(
		function() {
			var selected_month = $(this).val();
			var date_selector_day = $(this).next();
			var selected_day = date_selector_day.val();
			var selected_year = date_selector_day.next().val();
			date_selector_day.html(setDateSelectorDays(selected_month, selected_day, selected_year,
				date_selector_day.hasClass('blank_top_entry')));
		}
	);

	$('select.date_selector_year').change(
		function() {
			var selected_year = $(this).val();
			var date_selector_day = $(this).prev();
			var selected_day = date_selector_day.val();
			var selected_month = date_selector_day.prev().val() ;
			date_selector_day.html(setDateSelectorDays(selected_month, selected_day, selected_year,
				date_selector_day.hasClass('blank_top_entry')));
		}
	);

	function setDateSelectorDays(selected_month, selected_day, selected_year, blank_top_entry) {

		// Handle blank entries.
		if (!selected_month.match(/[0-9]{1,2}/)) {
			selected_month = new Date().getMonth() + 1;
		}
		if (!selected_year.match(/[0-9]{4}/)) {
			selected_year = new Date().getFullYear();
		}

		var day_count = 31;
		if (selected_month == 2) {
			if (isLeapYear(selected_year)) {
				day_count = 29;
			} else {
				day_count = 28;
			}
		} else if (selected_month == 4) {
			day_count = 30;
		} else if (selected_month == 6) {
			day_count = 30;
		} else if (selected_month == 9) {
			day_count = 30;
		} else if (selected_month == 11) {
			day_count = 30;
		}

		var html = '';
		if (blank_top_entry) {
			html += '<option value="">---</option>';
		}
		for (var i = 1; i <= day_count; i++) {
			var temp = '<option ';
			if (i == selected_day) {
				temp += 'selected="true" ';
			}
			temp += 'value="' + i + '">' + i + '</option>\n';
			html += temp;
		}
		return html;
	}

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

	$('select.date_selector_month').change();

});
