$(document).ready(function() {
	$('#cal_mini_dates span.has_event').bind('click', function() {
		$('#d').val($(this).text());
		$("form[name='cal_mini']").submit();
	});
	
	$('#cal_mini_jump span.month').bind('click', function() {
		$('#d').val('');
		$("form[name='cal_mini']").submit();
	});
	
	$('#cal_mini #category_select').bind('change', function() {
		
		$('#category_id').val($('#category_select').val());
		document.forms.cal_mini.submit();
	});
});

var days_in_month = new Array('', '31', '28', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31');

/**
 * Check day is valid in newly selected month
 * if not set day to last day of new month
 * 
 * @param new_month_index
 */
function check_day_in_range() {
	month_index = $('#m').val();
 	// determine leap year
 	var year = $('#y').val();
 	if (year % 400 == 0) {
 		days_in_month[2] = 29;
 	} else if (year % 100 == 0) {
 		days_in_month[2] = 28;
 	} else if (year % 4 == 0) {
 		days_in_month[2] = 29;
 	} else {
 		days_in_month[2] = 28;
 	}
 	
 	// check day isn't out of range for new month
 	var selected_day = $('#d').val();
 	// +1 offsets index to actual month number
 	if (selected_day > days_in_month[month_index]) {
 		$('#d').val(days_in_month[month_index]);
 	}
 }

function prev_month() {
 	// if current month is january, prev_month
	// will also mean prev_year
 	if ($('#m').val() == '1') {
 		
 		// month to december
 		$('#m').val('12');
 		
 		// if selected year is first in list
 		// we can't go back without adding a 
 		// new option first
 		if ($('#y').selectedIndex == 0) {
 			var selected_year = $('#y option:selected').text();
 			var new_year = selected_year - 1;
 			$('#y').prepend('<option value="'+ new_year + '">' + new_year + '</option>');
 		} 

 		// now we can go back a year safely
 		$('#y').val(parseInt($('#y').val()) - 1);
 	// safe to change month only
 	} else {
 		// go back a month
 		$('#m').val(parseInt($('#m').val()) - 1);
 	}
 	
 	
 	//check_day_in_range();
 	$('#d').val('');
 }

function next_month() {
 	// if current month is december, next_month
	// will mean next year
 	if ($('#m').val() == '12') {
 		// month to january
 		$('#m').val('1');
 		
 		// if selected_year is last in list
 		// we can't go forward without adding
 		// a new option first
 		if (($('#y').selectedIndex + 1) == $('#y').length) {
 			var new_year = parseInt($('#y option:selected').text()) + 1;
 			$('#y').append('<option value="' + new_year + '">' + new_year + '</option>');
 		}
 		
 		// now we can go forward a year safely
 		$('#y').val(parseInt($('#y').val()) + 1);
 	// safe to change month only
 	} else {
 		$('#m').val(parseInt($('#m').val()) + 1);
 	}
 			
 	//check_day_in_range();
 	$('#d').val('');
}	 
