$(document).ready(function() {
    var curMonth = 0;
    var numMonths = $('.availMonth').size();

    $('.ag_next a').bind('click dblclick', function () {
        if (curMonth + 4 >= numMonths)
            return false;

        $('#month-'+(curMonth+0)+', #month-'+(curMonth+1)).hide();
        curMonth += 2;
        $('#month-'+(curMonth+2)+', #month-'+(curMonth+3)).show();

        $('.ag_prev').show();
        if (curMonth + 4 >= numMonths)
            $('.ag_next').hide();

        return false;
    })

    $('.ag_prev a').bind('click dblclick', function () {
        if (curMonth <= 0)
            return false;

        $('#month-'+(curMonth+2)+', #month-'+(curMonth+3)).hide();
        curMonth -= 2;
        $('#month-'+(curMonth+0)+', #month-'+(curMonth+1)).show();

        $('.ag_next').show();
        if (curMonth <= 0)
            $('.ag_prev').hide();

        return false;
    })

    $('#month-0, #month-1, #month-2, #month-3').show();

    $('#scboArrivalDate').bind('focus', function() { this.blur(); })
    $('.availMonth a').bind('click', function() {
        $('#scboArrivalDate').val(this.href.substring(this.href.length-10));
        $('#scboArrivalDate').trigger('change');
        this.blur();
        return false;
    })
    $('#scboArrivalDate, #scboLengthOfStay').bind('change', function() {
        $('.availMonth td')
            .removeClass('selected')
            .removeClass('selectin')
            .removeClass('selectout')
            .removeClass('conflict');
        var matcher = $('.availMonth a[href$=#'+$('#scboArrivalDate').val()+']');
        if (!matcher.size())
            return false;
        var start_id = matcher.parent().attr('id').substring(4)*1;
        var end_id = start_id + 1*$('#scboLengthOfStay').val();
        for (x=start_id; x<=end_id; x++) {
            $('#day-'+x).addClass('selected');
        }
        $('#day-'+start_id).addClass('selectin');
        $('#day-'+end_id).addClass('selectout');
        var conflicts = $('.selected.unavailable, .selected.checkin, .selected.checkout')
            .not('.selectin.checkin, .selectout.checkout');
        if (conflicts.size()) {
            conflicts.addClass('conflict');
            $('#conflictWarn').show();
            $('#reserveSubmit').attr('disabled', 'disabled');
        } else {
            $('#conflictWarn').hide();
            $('#reserveSubmit').removeAttr('disabled');
        }
    })
    $('#scboArrivalDate').trigger('change');
})

