$(document).ready(function() {
	initCalendar();
});

function getCalendar() {
	var blockId = getBlockId($(".agenda-box"));
	var env = $("body").attr('class');
	var locale = jQuery('html').attr('xml:lang').replace('-', '_');
	var parameters = 'calendarMonth=' + $('#calendarMonth').val() + '&calendarYear=' + $("#calendarYear").val() + '&block=' + blockId + '&environment=' + env;
	parameters += '&uilanguage=' + locale;
	getAjaxContent(parameters, 'updateCalendar', {url: '/block/get/format/json'});
}

// Récupére le block id dans la classe de l'element
function updateCalendar(jsonres) {
	if(jsonres.block) {
		$('.agenda-box').replaceWith(jsonres.block);
	}
	initCalendar();
}

function initCalendar() {
	if ($("#calendarMonth").length) {
		$("#calendarMonth").change(getCalendar);
	}
	if ($("#calendarYear").length) {
		$("#calendarYear").change(getCalendar);
	}
	initCalendarTooltip();
}

function initCalendarTooltip() {
	$('.agenda-box td.on a').each(function() {
		if($(this).attr('title') != "") {
			var cloneLink = $(this);
            var eventsList = $(this).attr('title').split('|');
			var titleList = eventsList[0].split(', ');
			var title = '';
			for(index in titleList) {
				if (titleList[index] != "") {
					if(index != 0) {
						title += titleList[index] + '<br />';
					} else {
						title += '<strong>' + titleList[index] + '</strong><br />';
					}
				}
			}
            var secondEvent = '';
            if(eventsList.length > 1) {
                var title2List = eventsList[1].split(', ');
                secondEvent = '<a class="second-event" href="' + title2List[1] + '">' + title2List[0] + '</a>';
            }
			$(this).parents('td').append('<span style="display:none" class="tooltip"><a href="' + $(this).attr('href') + '">' + title + '</a>' + secondEvent + '</span>');
			$(this).attr('title','');
		}
	});
	$('.agenda-box td.on').mouseover(function() {
		$(this).children('.tooltip').show();
	});
	$('.agenda-box td.on').mouseout(function() {
		$(this).children('.tooltip').hide();
	});

}

