// JavaScript Document

function init_events() {
	
	
	$("li:hasEvent > a").hover(
		function() {
			var li = $(this).parent()
			var info = li.find("div.eventDescr");
			if (!info.visible) {
				info.css($(this).offset());
				info.show();
				
				var yOffset = li.height();
				var xOffset = info.width()/2 - li.width()/2 + parseInt(info.css("padding-left"));
				
				
				info.css({
						 top:info.position().top - yOffset + "px",
						 left:info.position().left - xOffset + "px"
				});
			}
		},
		
		function() {
			var info = $(this).parent().find("div.eventDescr");
			info.hide();
		}
	);
};


$(document).ready(function() {
	// Initialize the global date
	var d = new Date();				
	var currentYear = d.getFullYear();
	var currentMonth = d.getMonth()+1; // PHP is 1-12, but javascript is 0-11

	//var currentMonth = 4; // Force it to April
  currentYear = 2011;
  currentMonth = 10;

	// Initialize the prev and next months
	var nextYear = currentYear;
	var prevYear = currentYear;			
	var nextMonth = currentMonth+1;
	var prevMonth = currentMonth-1;

	// Update the year if the month goes into another year than the current
	if (nextMonth == 13) {
		nextMonth = 1;
		nextYear = currentYear + 1;
		
	}

	if (prevMonth == 0) {
		prevMonth = 12;
		prevYear = currentYear - 1;
	}
	
	// Called after a month change in ajax
	function resetNextPrevMonth() {
		
		// Setup the previous and next months (and years)
		nextYear = currentYear;
		prevYear = currentYear;
		
		nextMonth = currentMonth+1;
		prevMonth = currentMonth-1;
		
		// Update the year if the month goes into another year than the current
		if (nextMonth == 13 ) {
			nextMonth = 1;
			nextYear = currentYear + 1;
			
		}
	
		if (prevMonth == 0 ) {
			prevMonth = 12;
			prevYear = currentYear - 1;
		}
	}
	
	$.ajax({
		  url: "__calendar-generator.php",      
		  type: "GET",
		  dataType: "html",
		  success: function(html){
			$("div#event-calendar").html(html);	
			init_events();					
		  }
	   }
	);
	
	$("a#prev-month").click(function() {
		$.ajax({
			  url: "__calendar-generator.php",      
			  type: "GET",
			  data: ({calyear:prevYear, 
					  calmonth:prevMonth}),
			  dataType: "html",
			  success: function(html){
				$("div#event-calendar").html(html);
				currentYear = prevYear;
				currentMonth = prevMonth;
				resetNextPrevMonth();
				init_events();
			  }
		   }
		);	
	});
		
					
	$("a#next-month").click(function() {
		$.ajax({
			  url: "__calendar-generator.php",      
			  type: "GET",
			  data: ({calyear:nextYear, 
					  calmonth:nextMonth}),
			  dataType: "html",
			  success: function(html){
				$("div#event-calendar").html(html);
				currentYear = nextYear;
				currentMonth = nextMonth;
				resetNextPrevMonth();
				init_events();
			  }
		   }
		);
	});
		
});

