$(function(){

/**
 * initialize
 */
initialize();

$.datepicker.setDefaults({
    showOn: 'both',
    showAnim: 'fadeIn',
    buttonImageOnly: true,
    buttonImage: '/image/calendar/calendar_button.gif',
    buttonText: 'カレンダーから選ぶ',
    mandatory: true
});

/**
 * chkin
 */
$('#chkin_date').datepicker({
    minDate: new Date(2009, 1 - 1, 1),
    maxDate: new Date(2010, 12 - 1, 31),
    beforeShow: readLinkedChkin,
    onSelect: updateLinkedChkin
});

// Prepare to show a date picker linked to three select controls
function readLinkedChkin(){
    $('#chkin_date').val(
        $('#chkin_yy').val() + '/' +
        $('#chkin_mm').val() + '/' +
        $('#chkin_dd').val()
    );
    return {};
}

// Update three select controls to match a date picker selection
function updateLinkedChkin(date){
    $('#chkin_yy').val(date.substring(0, 4));
    $('#chkin_mm').val(date.substring(5, 7));
    $('#chkin_dd').val(date.substring(8, 10));
    
    var chkinDate = new Date($('#chkin_yy').val(), $('#chkin_mm').val() - 1, $('#chkin_dd').val());
    var chkoutDate = new Date(chkinDate.getTime() + (1000 * 60 * 60 * 24));

    var y = chkoutDate.getFullYear();
    var m = chkoutDate.getMonth();
    var d = chkoutDate.getDate();

    updateChkout(y, m, d);
}

$('#chkin_yy, #chkin_mm, #chkin_dd').change(linkedChkout);

function linkedChkout(){
    var chkinDate = new Date($('#chkin_yy').val(), $('#chkin_mm').val() - 1, $('#chkin_dd').val());
    var chkoutDate = new Date(chkinDate.getTime() + (1000 * 60 * 60 * 24));

    var y = chkoutDate.getFullYear();
    var m = chkoutDate.getMonth();
    var d = chkoutDate.getDate();

    updateChkout(y, m, d);
}

/**
 * chkout
 */
$('#chkout_date').datepicker({
    minDate: new Date(2009, 1 - 1, 1),
    maxDate: new Date(2010, 12 - 1, 31),
    beforeShow: readLinkedChkout,
    onSelect: updateLinkedChkout
});

// Prepare to show a date picker linked to three select controls
function readLinkedChkout(){
    $('#chkout_date').val(
        $('#chkout_yy').val() + '/' +
        $('#chkout_mm').val() + '/' +
        $('#chkout_dd').val()
    );
    return {};
}

// Update three select controls to match a date picker selection
function updateLinkedChkout(date){
    $('#chkout_yy').val(date.substring(0, 4));
    $('#chkout_mm').val(date.substring(5, 7));
    $('#chkout_dd').val(date.substring(8, 10));
}

function initialize(){
    /**
     * chkin
     */
    var cd = new Date();
    $('#chkin_yy').val(cd.getFullYear());
    $('#chkin_mm').val(cd.getMonth() + 1);
    $('#chkin_dd').val(cd.getDate());

    /**
     * chkout
     */
    var nd = new Date(cd.getTime() + (1000 * 60 * 60 * 24));
    $('#chkout_yy').val(nd.getFullYear());
    $('#chkout_mm').val(nd.getMonth() + 1);
    $('#chkout_dd').val(nd.getDate());
}

function updateChkout(y, m, d){
    $('#chkout_yy').val(y);
    $('#chkout_mm').val(m + 1);
    $('#chkout_dd').val(d);
}

});


