$(function() {
	
	$('table.calendar tr.calendar-navi a.calendar-prev').live('click', function() {
		var table = $(this).closest('table');
		var date = table.attr('id').replace('date_', '').split('/');		
		var month = parseInt(date[0]) - 1;
		var year = date[1];
		
		if(month < 1) {
			year--;
			month = 12;
		}
		
		table.updateCalendar(month, year);
		return false;			
	});
	
	$('table.calendar tr.calendar-navi a.calendar-next').live('click', function() {		
		var table = $(this).closest('table');
		var date = table.attr('id').replace('date_', '').split('/');		
		var month = parseInt(date[0]) + 1;
		var year = date[1];	
		
		if(month > 12) {
			year++;
			month = 1;
		}
		
		table.updateCalendar(month, year);
		return false;			
	});
	
	var calendar_tooltip_visible = false;
	var $tooltip = false;
	
	$('table.calendar tr td .calendar-has-events').live('mousemove', function(e) {
		
		if(!calendar_tooltip_visible) {
			$tooltip = $(document.createElement('div')).addClass('calendar-tooltip');
			
			$tooltip.hide().html($(this).next('ul').clone().show());
			
			
			$(this).closest('table').after($tooltip);
			calendar_tooltip_visible = true;
		}
		else {
			$tooltip.fadeIn(100).css({
				left: e.pageX + 20 - $tooltip.parent().offset().left,
				top: e.pageY + 20
			});
		}
	});
	
	$('table.calendar tr td .calendar-has-events').live('mouseout', function() {
		
		$('div.calendar-tooltip').fadeOut(100, function() {
			$(this).remove();
		});;
		calendar_tooltip_visible = false;
	});
});

jQuery.fn.updateCalendar = function(month, year) {
	
	var table = $(this);
	
	$.ajax({
		type: 'GET',
		data: 'month='+month+'&year='+year,
		url: 'eventcalendar.php',
		success: function(r) {
			table.replaceWith(r);
		}
	});
	
}
