/*
 * File: apme.calendar.js
 * Author: Jo�o Fonseca (j.fonseca@netcabo.pt)
 */
var apme = apme || {};

apme.calendar = {
	month : new Date().getMonth(),
	year : new Date().getFullYear(),
	day : 1,
	monthNames : [
			[ 'Janeiro', 'Fevereiro', 'Mar&ccedil;o', 'Abril', 'Maio', 'Junho',
					'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro',
					'Dezembro' ], [], [] ],
	eventdays : [],
	update : function() {
		var that = this;
		$("#cal_titulo span").html(
				that.monthNames[apme.content.language - 1][that.month] + ' '
						+ that.year);


		$.getJSON('cal.php?action=eventdays&m='+(that.month+1)+'&y='+that.year, function(data) {
			that.eventdays = data;
			var today = new Date();
			var firstDay = new Date(that.year, that.month, 1);

			for (i = 7; i < 49; i++) {
				j = i - firstDay.getDay() - 6;
				testDate = new Date(that.year, that.month, j);

				istoday = today.getDate() == j
						&& today.getMonth() == firstDay.getMonth()
						&& today.getFullYear() == firstDay.getFullYear();

				if (testDate.getDate() == j) {
					$($("#cal_table td").get(i)).html(j).attr(
							'class',
							(istoday ? 'today' : '')
									+ (that.eventdays.exists(j) ? ' event' : ''))
							.click(function() {
								that.day = parseInt($(this).text());
								that.open();
								$(window).scrollTop(100);
							});
				} else {
					$($("#cal_table td").get(i)).html('&nbsp;').attr('class',
							'disabled')
				}

			}
		});

	},
	open : function() {
		var that = this;
		apme.content.section = 8;
		$('#right_container').load(
				'cal.php?d=' + that.day + '&m=' + that.month + '&y='
						+ that.year, function() {
					$('#calendar2').html($("#calendar").html());
				});
		this.update();
	},
	move : function(offset) {
		this.month += offset;

		while (this.month > 11) {
			this.month -= 12;
			this.year++;
		}
		while (this.month < 0) {
			this.month += 12;
			this.year--;
		}
		this.update();
	},
	init : function() {
		var that = this;
		$('#calPrevious').live('click', function() {
			that.move(-1);
			return false;
		});
		$('#calNext').live('click', function() {
			that.move(+1);
			return false;
		});

		$('.prevDay').live('click', function() {
			testDate = new Date(that.year, that.month, that.day - 1);
			that.year = testDate.getFullYear();
			that.month = testDate.getMonth();
			that.day = testDate.getDate();
			that.open();
			return false;
		});

		$('.nextDay').live('click', function() {
			testDate = new Date(that.year, that.month, that.day + 1);
			that.year = testDate.getFullYear();
			that.month = testDate.getMonth();
			that.day = testDate.getDate();
			that.open();
			return false;
		});

		this.update();
	}
};
