// Events array
var events = new Array();

// Called when the document is loaded (body.onload).
$(function()
{
    /**
     * Fonction callback pour le rendering des dates du calendrier
     * @param {Object Element} $td
     * @param {Object Date} thisDate
     * @param {String} month
     * @param {String} year
     */
    var calCallback = function($td, thisDate, month, year)
    {
        if (isEvent(thisDate))
        {
            var dateStr = formatYMD(thisDate, '/');
            var sectionPath = section.length > 0 ? '/' + section : '';
            var link = eventBaseUrl + '/' + dateStr + sectionPath + '/events.html';

            $td.addClass('event').addClass('disabled');
            $td.bind(
                'click',
                function()
                {
                    // Load the events html doc and inject the div.events into the div of id 'agenda_txt'
                    $('#agenda_txt').load(link + ' .events');
                }
            );

        }
        else
        {
            $td.addClass('disabled');
        }
    }

    // Inline, multiple dates selectable, with a custom render callback, without year navigation, starting at 01/01/2000.
    $('#agenda').datePicker({
        inline:true,
        selectMultiple:true,
        renderCallback:calCallback,
        showYearNavigation:false,
        startDate:'01/01/2000'
    }).bind(
		'dpMonthChanged',
		function(e, month, year)
		{
			// To avoid the calendar layout breaking on IE when the month is changed.
			$('table.jCalendar').attr('cellspacing', 0);
		}
	);
});

/**
 * Format a date like 2008-08-24, with the given separator.
 * @param {Object Date} date
 * @param {String} separator
 */
function formatYMD(date, separator)
{
    return date.getFullYear() + separator + zeroPad(date.getMonth() + 1) + separator + zeroPad(date.getDate());
}

function addEvent(date)
{
	if (!isEvent(date))
	{
		events.push(date);
	}
}

/**
 * Test if there's an event or news at the given date.
 * @param {Object Date} date
 */
function isEvent(date)
{
    for (var i = 0; i < events.length; i++)
    {
        var dateStr = (typeof date == 'object') ? formatYMD(date, '-') : date;
        if (dateStr == events[i])
        {
            return true;
        }
    }
    return false;
}

/**
 * Make the number (between 1 and 99) a two-digit string, padding with a '0' if needed. 
 * @param {Integer} num
 */
function zeroPad(num)
{
    var s = '0' + num;
    return s.substring(s.length - 2);
}
