/* -*- coding: utf-8 -*- */

var monthNames = {
    1: 'Januar',
    2: 'Februar',
    3: 'März',
    4: 'April',
    5: 'Mai',
    6: 'Juni',
    7: 'Juli',
    8: 'August',
    9: 'September',
    10: 'Oktober',
    11: 'November',
    12: 'Dezember'
};

var today = new Date();
var currentYear = today.getFullYear();
var nextYear = currentYear + 1;
var currentMonth = today.getMonth() + 1;

var nextTwelveMonths = [];
for (var m = currentMonth; m <= 12; m++) nextTwelveMonths.push(currentYear + '-' + m);
for (m = 1; m <= currentMonth; m++) nextTwelveMonths.push(nextYear + '-' + m);

var displayMonth = nextTwelveMonths[0];

function updateDisplayMonth(direction) {
    if (direction < 0) {
        if (displayMonth == nextTwelveMonths[0]) return; // already at earliest month
        displayMonth = nextTwelveMonths[nextTwelveMonths.indexOf(displayMonth) - 1];
    }
    if (direction > 0) {
        if (displayMonth == nextTwelveMonths[12]) return; // already at last month
        displayMonth = nextTwelveMonths[nextTwelveMonths.indexOf(displayMonth) + 1];
    }

    // set frame source
    new Request.HTML({
      'url': '/wikitext/display',
      'data': {'document': 'events-' + displayMonth},
      'update': $('events-frame')
    }).send();

    // set heading
    $('events-month').set('text', monthNames[displayMonth.split('-')[1]]);
    if (currentYear < displayMonth.split('-')[0].toInt()) {
        $('events-year').set('text', displayMonth.split('-')[0]);
    } else {
        $('events-year').set('text', '');
    }

    // hide or show prev /next links
    $('events-prevmonth').setStyle('display', (displayMonth == nextTwelveMonths[0])
        ? 'none' : 'inline');
    $('events-nextmonth').setStyle('display', (displayMonth == nextTwelveMonths[12])
        ? 'none' : 'inline');

    // set month names in prev/ next links
    var i = nextTwelveMonths.indexOf(displayMonth) - 1;
    if (0 <= i) { // When first calling this function from the domready event, there
                  // is no previous month. Subsequent calls are protected by the
                  // initial direction switch.
        var prevMonth = nextTwelveMonths[i];
        $('events-prevmonth').getElement('span').set('text',
            monthNames[prevMonth.split('-')[1].toInt()]
            + ' '
            + prevMonth.split('-')[0]
        );
    }
    var nextMonth = nextTwelveMonths[nextTwelveMonths.indexOf(displayMonth) + 1];
    $('events-nextmonth').getElement('span').set('text',
        monthNames[nextMonth.split('-')[1].toInt()]
        + ' '
        + nextMonth.split('-')[0]
    );
}


window.addEvent('domready', function() {

    updateDisplayMonth();

    $('events-prevmonth').addEvent('click', function(event) {
        event.stop();
        updateDisplayMonth(-1);
    });
    $('events-nextmonth').addEvent('click', function(event) {
        event.stop();
        updateDisplayMonth(+1);
    });
});

