$(function()
{

// initialise the "Select date" link
$('.pageAccueil #date-pick')
        .datePicker(
                // associate the link with a date picker
                {
                        createButton:false,
                        startDate:'12/08/2011',
                        endDate:'31/12/2016'
                }
        ).bind(
                // when the link is clicked display the date picker
                'click',
                function()
                {
                        updateSelects($(this).dpGetSelected()[0]);
                        $(this).dpDisplay();
                        return false;
                }
        ).bind(
                // when a date is selected update the SELECTs
                'dateSelected',
                function(e, selectedDate, $td, state)
                {
                        updateSelects(selectedDate);
                }
        ).bind(
                'dpClosed',
                function(e, selected)
                {
                        updateSelects(selected[0]);
                }
        );

var updateSelects = function (selectedDate)
{
//déselection de tous les éléments
$('#fday option').each(function() {$(this).removeAttr('selected');});
$('#fmonth option').each(function() {$(this).removeAttr('selected');});
$('#fyear option').each(function() {$(this).removeAttr('selected');});

//mise à jour de la date
var selectedDate = new Date(selectedDate);
$('#fday option[value=' + selectedDate.getDate() + ']').attr('selected', 'selected');
$('#fmonth option[value=' + (selectedDate.getMonth()+1) + ']').attr('selected', 'selected');
$('#fyear option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');

var txtMonth = $('#fmonth option[value=' + (selectedDate.getMonth()+1) + ']').text();

$('#fday-button span.ui-selectmenu-status').text(selectedDate.getDate());
$('#fmonth-button span.ui-selectmenu-status').text(txtMonth);
$('#fyear-button span.ui-selectmenu-status').text(selectedDate.getFullYear());

}

// listen for when the selects are changed and update the picker
$('#fday, #fmonth, #fyear')
        .bind(
                'change',
                function()
                {
                        var d = new Date(
                                                $('#fyear').val(),
                                                $('#fmonth').val()-1,
                                                $('#fday').val()
                                        );
                        $('#date-pick').dpSetSelected(d.asString());
                }
        );

// default the position of the selects to today
var today = new Date();
updateSelects(today.getTime());

// and update the datePicker to reflect it...
$('#fday').trigger('change');
});
