(function($){

var mod_calendar_id = 'mod_calendar_render';


function refreshTipsys(year, month) {
	$.ajax({
		type: "GET",
		url: AYA_absPath+"/calendar/events/"+year+"/"+month,
		dataType: "xml",
		success: parseEventsXML
	});
}

var currentYear;
var currentMonth;


function parseEventsXML(xml) {
	var theDateLinks = $('#' + mod_calendar_id + ' .ui-datepicker-calendar a');

	$(xml).find("event").each( function() {
		if (
			$(this).attr("year") == currentYear &&
			$(this).attr("month") == currentMonth
		   )
		{
			var day = $(this).attr("day");
			var date = $(this).find("date").text();
			var time = $(this).find("time").text();
			if ( time != 0 )
				time = ", "+time;
			var title = $(this).find("title").text();
			var descr = $(this).find("descr").text();

			var text = "<i>"+date+time+"</i><br/><h4 style='font-size: 1.2em;'>"+title+"</h4><p>"+descr+"</p>";

			theDateLinks.eq(day-1)		// select the right link
				.attr('original-title', text)	// set the text
				.css('color', 'red')
				.css('cursor', 'pointer')
				.tipsy({trigger: 'manual', html: true});   // init the tipsy, set your properties.
		}
	});
}


// Because the the event `onChangeMonthYear` get's called before updating 
// the items, we'll add our code after the elements get rebuilt. We will hook 
// to the `_updateDatepicker` method in the `Datepicker`.
// Saves the original function.
var _updateDatepicker_o = $.datepicker._updateDatepicker;

// Replaces the function.
$.datepicker._updateDatepicker = function(inst) {

	// First we call the original function from the appropiate context.
	_updateDatepicker_o.apply(this, [inst]);

	if ( inst.id == mod_calendar_id ) {
		// No we can update the Tipsys.
		refreshTipsys(inst.drawYear, inst.drawMonth+1);
		currentYear = inst.drawYear;
		currentMonth = inst.drawMonth+1;
	}
};


// Because all calendar gets re-rendered after each date select we need to make
// all dates unselectable
// Saves the original function
var _selectDay_o = $.datepicker._selectDay;

// Replaces the function
$.datepicker._selectDay = function(id, month, year, td) {
	if ( id == '#'+mod_calendar_id ) {
		return;
	}

	_selectDay_o.apply(this, [id,month,year,td]);
}


// Finally the calendar initializer.
$(function(){
	// Creates the date picker, with your options.
//	$.datepicker.setDefaults( $.datepicker.regional[ "" ] );
	$( "#"+mod_calendar_id ).datepicker( $.datepicker.regional[ "lt" ] );
	$('#' + mod_calendar_id + ' .ui-datepicker-calendar a').css( 'cursor', 'default' );

	currentDate = $( '#'+mod_calendar_id).datepicker('getDate');
	currentYear = currentDate.getFullYear();
	currentMonth = currentDate.getMonth()+1;
});


})(jQuery);

