/** Mini month calendar */
var calendarTimeout = null;
var calendarInit = false;

$(document).ready(function() {
    $('#date-selector').hide();
})

function togglePeriodSelection() {
    ds = $('#date-selector');
    ds.toggle();
    if (ds.css('display') == 'block') {
        fillCalendar();
    }
    return false;
}

function fillCalendar() {
    months = ['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli',
        'Augustus', 'September', 'Oktober', 'November', 'December'];

    first = endDate;
    
    // Todo: display selection range.
    // Todo: enable selecting ranges.
    // Todo: Lots of CSS

    for (mon=3;mon>0;mon--) {
        first.setFullYear(first.getFullYear(), first.getMonth(), 1)
        max_days = days_in_month(first.getFullYear(), first.getMonth())
        offset_days = first.getDay();

        cur_day = (offset_days - 2) * -1;
        now = new Date();
        today = now.getDate();

        if (first.getMonth() == 0) {
            t_year = first.getFullYear() - 1;
            t_month = 11;
        }
        else {
            t_year = first.getFullYear();
            t_month = first.getMonth() - 1;
        }

        max_days_prev = days_in_month(t_year, t_month);
        new_first = new Date(t_year, t_month, 1);
        
        $('.month-'+mon+' caption').html(months[first.getMonth()])

        for (i = 0; i < 6; i++) {
            for (j = 0; j < 7; j++) {
                if (cur_day < 1) {
                    t_month = first.getMonth() - 1;
                    t_day = max_days_prev + cur_day;
                    t_class = "other_month";
                }
                else if (cur_day > max_days) {
                    t_month = first.getMonth() + 1;
                    t_day = cur_day - max_days;
                    t_class = "other_month";
                }
                else {
                    t_month = first.getMonth();
                    t_day = cur_day;
                    t_class = "";
                }
                t_html = t_day;

                cell = $('.month-'+ mon +' .r'+ i +'c' + j);
                cell.html(t_html);
                cell.removeClass('other_month');
                cell.addClass(t_class);
    
                cur_day++;
            }
        }
        first = new_first;
    }
}

function days_in_month(year, month) {
	return 32 - new Date(year, month, 32).getDate();
}

function onDayClick(trigger) {
    // Check which date is selected (start or end)

    // Set date (input-box)
}

function setPeriodSelection(trigger) {
    // Submit the 2 values
}
