dojo.require('dijit._Calendar');
dojo.require('ion.date');

var AgendaFrontendClass = function() {
	this.cal = [];
	this.initStatus = true;
};

AgendaFrontendClass.prototype.init = function(node) {
	var t = this;
	if (typeof node == 'undefined')
		node = dojo.body();
	if (!dojo.isArray(node)) {
		node = [node];
	}
	dojo.forEach(node, function(n) {
		dojo.forEach(dojo.query('.AgendaCalendar',n), function(c) {	
			t.cal.push(new dijit._Calendar({
				hasEvents: {},
				init: true,
				value: new Date(),
				onChange: function(date) {
					t.filter(dojo.query('.result',this.domNode.parentNode.parentNode.parentNode)[0],this.domNode.parentNode.parentNode.action,{dtdate:date});
				},
				getClassForDate: function(date) {
					var t = this;
					var year = date.getFullYear();
					var month = date.getMonth()+1;
					var day = date.getDate();
					if (typeof t.hasEvents[year] == 'undefined')	
						this.hasEvents[year] = {};
					if (typeof t.hasEvents[year][month] == 'undefined') {
						dojo.xhrPost({
							url: dojo.attr(c,'title'),
							content: {
								year: year,
								month: month
							},
							load: function(days) {
								t.hasEvents[year][month] = days;
							},
							handleAs: 'json',
							sync: true
						});
					}
					for (var i=0; i<t.hasEvents[year][month].length; i++) {
						if (day == t.hasEvents[year][month][i][0])
							return 'hasEvent e'+t.hasEvents[year][month][i][1].join(' e');
					};
				}
			},c));
		});
		dojo.forEach(dojo.query('.agendaFilter',n), function(f) {
			dojo.connect(f, 'onsubmit', function(e) {
				dojo.stopEvent(e);
				t.filter(dojo.query('.result',this.parentNode)[0], this.action, dojo.formToObject(this));
			});
		});
	});
}

AgendaFrontendClass.prototype.filter = function(resultNode, url, filter) {
	var t = this;
	if (typeof filter.dtdate !== 'undefined') {
		filter.dtdate = ion.date.toDatabase(filter.dtdate);
	}
	filter.initStatus = t.initStatus;
	t.initStatus = false;
	dojo.empty(resultNode);
	resultNode.innerHTML = '<img src="/app/views/layouts/cooperations/loading.gif" alt="loading..." />';
	dojo.xhrPost({
		url: url,
		content: filter,
		load: function(data) {
			resultNode.innerHTML = data;
		}
	});
}

AgendaFrontendClass.prototype.showDetails = function(resultNode, url) {
	dojo.empty(resultNode);
	resultNode.innerHTML = '<img src="/app/views/layouts/cooperations/loading.gif" alt="loading..." />';
	dojo.xhrGet({
		url: url,
		load: function(data) {
			dojo.empty(resultNode);
			resultNode.innerHTML = data;
		}
	});
}