$(function() {
	var first_load = false;
	
	var pad = function (number, length) {
		var str = '' + number;

		while (str.length < length) {
			str = '0' + str;
		}
	
		return str;
	}
	
	var regexDateValidator = function (month, day, year) {
		return (pad(month, 2) + "/" + pad(day, 2) + "/" + pad(year, 2)).match(/(0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])[\- \/.]((?:19|20)+\d{2})/);
	}

	if ($("#scal_m").length > 0 && first_load == false){ 
		first_load = true;
		var result, check, month, day, year;
		result = regexDateValidator(month = $('#scal_m').val(), day = 1, year = $('#scal_y').val());
		
		if ( Boolean(result) ) {
			// at this point, $1 holds the year, $2 the month and $3 the day of the date entered
			if ( result[2] == 31 && (result[1] == 4 || result[1] == 6 || result[1] == 9 || result[1] == 11) ) {
				check = false; // 31st of a month with 30 days
			} else if (result[2] >= 30 && result[1] == 2) {
				check = false; // February 30th or 31st
			} else if ( (result[1] == 2) && (result[2] == 29) && ( !(result[3] % 4 == 0 && (result[3] % 100 != 0 || result[3] % 400 == 0)) ) ) {
				check = false; // February 29th outside a leap year
			} else {
				check = true; // valid date
			}
		}
		
		if ( check ) {
			// valid date
			$('#cal_month').val(month);
			$('#cal_year').val(year);
			$("a[id='cal_set']").html("click to change").attr("href", "?cal_y=" + parseInt(year) + "&cal_m=" + parseInt(month) + "&cal_d=" + parseInt(day));
		}
	}

	$("select[id*='cal_']").change(function () {
		var result = false, check = false, month = null, day = null, year = null;
		result = regexDateValidator(month = $('#cal_month').val(), day = 1, year = $('#cal_year').val());
		
		if ( Boolean(result) ) {
			// at this point, $1 holds the year, $2 the month and $3 the day of the date entered
			if ( result[2] == 31 && (result[1] == 4 || result[1] == 6 || result[1] == 9 || result[1] == 11) ) {
				check = false; // 31st of a month with 30 days
			} else if (result[2] >= 30 && result[1] == 2) {
				check = false; // February 30th or 31st
			} else if ( (result[1] == 2) && (result[2] == 29) && ( !(result[3] % 4 == 0 && (result[3] % 100 != 0 || result[3] % 400 == 0)) ) ) {
				check = false; // February 29th outside a leap year
			} else {
				check = true; // valid date
			}
		} else {
			check = false; // invalid date
		}
		
		if ( !check ) {
			$("a[id='cal_set']").html("invalid date").attr("href", "#");
		} else {
			$("a[id='cal_set']").html("click to change").attr("href", "?cal_y=" + parseInt(year) + "&cal_m=" + parseInt(month) + "&cal_d=" + parseInt(day));
		}
	});
});
