
if (!mayaFish.modules.eventCalendar)
mayaFish.modules.eventCalendar = (function () {
	
	var _drawDays = function (res, cid) {
		var htmlo = mayaFish.$id('calendar_content_' + cid);
		var hasEvents = false;
		htmlo.innerHTML = '';
		for (i in res.events) {
			if (res.events[i] && res.events[i].id) {
				var title = document.createElement('h3');
				if (res.isAdmin) {
					var edit = document.createElement('a');
					var eimg = document.createElement('img');
					edit.setAttribute('href', '/eventCalendar/editEvent/' + res.events[i].id);
					eimg.setAttribute('src', mayaFish.consts.ACTUAL_TEMPLATE_URL + '/images/common/edit.19x19.gif');
					eimg.setAttribute('alt', 'edit');
					edit.appendChild(eimg);
					title.appendChild(edit);
				}
				title.appendChild(document.createTextNode(res.events[i].title + ' (' + res.events[i].type_label + ')'));
				htmlo.appendChild(title);
				title.style.color = '#' + _createForeColor(res.events[i].type_color);
				title.style.backgroundColor = '#' + res.events[i].type_color;
				
				var duration = document.createElement('div');
				duration.setAttribute('class', 'duration');
				duration.appendChild(document.createTextNode(
					res.events[i].start_date_formatted + ' ' + res.events[i].start_time + ' ' +
					String.fromCharCode(187) + ' ' + res.events[i].end_date_formatted + ' ' + res.events[i].end_time
				));
				htmlo.appendChild(duration);
				
				var description = document.createElement('div');
				description.setAttribute('class', 'description');
				description.innerHTML = res.events[i].descr;
				htmlo.appendChild(description);
				hasEvents = true;
			}
		}
		if (!hasEvents)
			htmlo.innerHTML = mayaFish.translations('eventCalendar', 'No events');
	};
	
	var _createForeColor = function (colorCode) {
		var color = new mayaFish.color.Rgb(
			parseInt(colorCode.substr(0, 2), 16) / 255.0,
			parseInt(colorCode.substr(2, 2), 16) / 255.0,
			parseInt(colorCode.substr(4, 2), 16) / 255.0
		);
		color = color.toHsl();
		if (color.l < 0.5)
			return 'ffffff';
		else
			return '000000';
	};
	
	var _setAppendedDay = function (td, res, cid, year, month, day) {
		var d = document.createElement('div');
		d.setAttribute('class', 'dayTitle');
		d.setAttribute('className', 'dayTitle');
		d.appendChild(document.createTextNode(day));
		td.appendChild(d);
		
		for (i in res.events) {
			if (res.events[i] && res.events[i].id) {
				if (res.events[i].start_day == day) {
					var e = document.createElement('div');
					e.setAttribute('class', 'event');
					e.setAttribute('className', 'event');
					var eTitle = document.createElement('div');
					eTitle.setAttribute('class', 'title');
					eTitle.setAttribute('className', 'title');
					var eBody = document.createElement('div');
					eBody.setAttribute('class', 'body');
					eBody.setAttribute('className', 'body');
					eTitle.appendChild(document.createTextNode(res.events[i].title +
						' (' + res.events[i].type_label + ')'));
					eBody.innerHTML = (res.events[i].start_date_formatted + ' ' +
						res.events[i].start_time + ' ' + String.fromCharCode(187) + ' ' +
						res.events[i].end_date_formatted + ' ' + res.events[i].end_time) +
						'<br />' + res.events[i].descr;
					e.appendChild(eTitle);
					e.appendChild(eBody);
					td.appendChild(e);
					eTitle.style.background = '#' + res.events[i].type_color;
					eTitle.style.color = '#' + _createForeColor(res.events[i].type_color);
				}
			}
		}
	};
	
	var _appendedElement = null;
	var _drawAppended = function (res, cid, year, month, toElement) {
		var htmlo = toElement;
		if (!htmlo) {
			var s = mayaFish.getAbsolutePosition(mayaFish.$id('calendar_content_' + cid));
			var w = mayaFish.windowSize();
			htmlo = document.createElement('div');
			htmlo.setAttribute('class', 'calendarBoxAppendedContainer');
			htmlo.setAttribute('className', 'calendarBoxAppendedContainer');
			mayaFish.$tag('body').appendChild(htmlo);
			htmlo.style.background = '#ffffff';
			htmlo.style.position = 'fixed';
			htmlo.style.top = (s.top - w.top) + 'px';
			htmlo.style.left = (s.left - w.left) + 'px';
			htmlo.style.width = s.width + 'px';
			htmlo.style.height = s.height + 'px';
			htmlo.style.zIndex = '1000';
			mayaFish.animate.props({
				'node': htmlo,
				'duration': 1000,
				'easing': 'expoOut',
				'props': {
					'top': parseInt(w.height / 6),
					'left': parseInt(w.width / 6),
					'width': parseInt(w.width / 1.5),
					'height': parseInt(w.height / 1.5)
				}
			});
			_appendedElement = htmlo;
		} else {
			htmlo.innerHTML = '';
		}
		var header = document.createElement('div');
		header.setAttribute('class', 'header');
		header.setAttribute('className', 'header');
		var headerPrev = document.createElement('a');
		headerPrev.setAttribute('href', '#');
		headerPrev.setAttribute('class', 'prev');
		headerPrev.setAttribute('className', 'prev');
		var headerTitle = document.createElement('a');
		headerTitle.setAttribute('href', '#');
		headerTitle.setAttribute('class', 'title');
		headerTitle.setAttribute('className', 'title');
		var headerNext = document.createElement('a');
		headerNext.setAttribute('href', '#');
		headerNext.setAttribute('class', 'next');
		headerNext.setAttribute('className', 'next');
		var headerClose = document.createElement('a');
		headerClose.setAttribute('href', '#');
		headerClose.setAttribute('class', 'close');
		headerClose.setAttribute('className', 'close');
		
		headerPrev.appendChild(document.createTextNode('«'));
		headerNext.appendChild(document.createTextNode('»'));
		headerTitle.appendChild(document.createTextNode(res.title));
		headerClose.appendChild(document.createTextNode('[x]'));
		
		header.appendChild(headerClose);
		header.appendChild(headerPrev);
		header.appendChild(headerTitle);
		header.appendChild(headerNext);
		
		headerPrev.onclick = function () {
			htmlo.innerHTML = '...';
			mayaFish.jsonRpc.call({
				'method': 'eventCalendarView::getEvents',
				'params': {
					'date': res.prev
				},
				'onSuccess': function (result) {
					var y = result.month.split('-')[0], m = result.month.split('-')[1];
					_drawAppended(result, cid, y, m, _appendedElement);
				}
			});
			return false;
		}
		
		headerNext.onclick = function () {
			htmlo.innerHTML = '...';
			mayaFish.jsonRpc.call({
				'method': 'eventCalendarView::getEvents',
				'params': {
					'date': res.next
				},
				'onSuccess': function (result) {
					var y = result.month.split('-')[0], m = result.month.split('-')[1];
					_drawAppended(result, cid, y, m, _appendedElement);
				}
			});
			return false;
		}
		
		headerTitle.onclick =
		headerClose.onclick = function () {
			mayaFish.$tag('body').removeChild(htmlo);
			_appendedElement = null;
			return false;
		}
		
		var table = document.createElement('table');
		table.setAttribute('class', 'calendarBoxAppended');
		table.setAttribute('className', 'calendarBoxAppended');
		var week = res.spec.firstWeek;
		var tr = null;
		var td = null;
		
		tr = document.createElement('tr');
		td = document.createElement('td');
		tr.appendChild(td);
		for (var i = 0; i < 7; i++) {
			td = document.createElement('td');
			td.appendChild(document.createTextNode(res.spec.dayNames[i]));
			tr.appendChild(td);
		}
		table.appendChild(tr);
		
		tr = document.createElement('tr');
		
		if (res.spec.firstDayInWeek > 0) {
			td = document.createElement('td');
			td.appendChild(document.createTextNode(week));
			tr.appendChild(td);
			for (var i = 0; i < res.spec.firstDayInWeek; i++) {
				td = document.createElement('td');
				td.setAttribute('class', 'empty');
				td.setAttribute('className', 'empty');
				tr.appendChild(td);
			}
		} else {
			week--;
		}
		
		var col = res.spec.firstDayInWeek;
		var today = new Date();
		today = {
			'year': today.getFullYear(),
			'month': today.getMonth() + 1,
			'day': today.getDate()
		}
		for (var i = 1; i <= res.spec.lastDay; i++) {
			if (col % 7 == 0) {
				week++;
				if (month == 1 && week > 50) week = 1;
				td = document.createElement('td');
				td.appendChild(document.createTextNode('' + week));
				tr.appendChild(td);
			}
			
			td = document.createElement('td');
			if (today.year == year && today.month == month && today.day == i) {
				td.setAttribute('class', 'std today');
				td.setAttribute('className', 'std today');
			} else {
				td.setAttribute('class', 'std');
				td.setAttribute('className', 'std');
			}
			_setAppendedDay(td, res, cid, year, month, i);
			tr.appendChild(td);
			
			if (col % 7 == 6) {
				table.appendChild(tr);
				tr = document.createElement('tr');
			}
			col++;
		}
		if (col % 7 > 0) {
			while (col % 7 != 0) {
				td = document.createElement('td');
				td.setAttribute('class', 'empty');
				td.setAttribute('className', 'empty');
				tr.appendChild(td);
				col++;
			}
			table.appendChild(tr);
		}
		
		htmlo.appendChild(header);
		htmlo.appendChild(table);
	}
	
	var _setDay = function (td, res, cid, year, month, day) {
		var link = document.createElement('a');
		var title = [];
		var linkId = '';
		
		var dayStr = '' + year + '-' + month + '-' + (day < 10 ? '0' + day : day);
		var hasEvents = 0;
		var evtColor = '';
		var evtPrio = 0;
		
		var p  = function (str, pn, pc) {
			str = "" + str; pc = "" + pc;
			while (str.length < pn) str = "0" + str;
			return str;
		}
		var curDate = p(year, 4) + "-" + p(month, 2) + "-" + p(day, 2);
		for (i in res.events) {
			if (res.events[i] && res.events[i].id) {
				if ((res.events[i].start_date <= curDate) && (res.events[i].valid_end_date >= curDate)) {
					hasEvents++;
					if (evtPrio <= parseInt(res.events[i].priority)) {
						evtPrio = parseInt(res.events[i].priority);
						evtColor = res.events[i].type_color;
					}
					title.push({
						'prio': parseInt(res.events[i].priority),
						'text': '<span style="background: #' + res.events[i].type_color +
							';">&nbsp;&nbsp;&nbsp;&nbsp;</span> ' + res.events[i].title +
							' (' + res.events[i].type_label + ')'
					});
				}
			}
		}
		if (hasEvents) {
			link.setAttribute('href',
				'javascript:mayaFish.modules.eventCalendar.draw("' +
				cid + '", "' + dayStr + '")');
			link.setAttribute('id', linkId = mayaFish.generateId());
		}
		link.appendChild(document.createTextNode('' + day));
		td.appendChild(link);
		if (hasEvents) {
			link.style.color = '#' + _createForeColor(evtColor);
			td.style.backgroundColor = '#' + evtColor;
			setTimeout(function () {
				var link = mayaFish.$id(linkId);
				var t = '';
				title.sort(function (a, b) { return b.prio - a.prio; });
				mayaFish.forEach(title, function (k, v) { t += (t ? "<br />\n" : '') + v.text; });
				mayaFish.ui.createToolTip(link, t);
				link['onclick'] = function () { this.blur(); return true; };
			}, 100);
		}
	};
	
	var _drawMonth = function (res, cid, year, month) {
		var htmlo = mayaFish.$id('calendar_content_' + cid);
		htmlo.innerHTML = '';
		var table = document.createElement('table');
		table.setAttribute('class', 'calendarBox events');
		table.setAttribute('className', 'calendarBox events');
		var week = res.spec.firstWeek;
		var tr = null;
		var td = null;
		
		tr = document.createElement('tr');
		td = document.createElement('td');
		/*
		var append = document.createElement('a');
		append.setAttribute('href', '#');
		append.appendChild(document.createTextNode('+'));
		td.appendChild(append);
		*/
		tr.appendChild(td);
		for (var i = 0; i < 7; i++) {
			td = document.createElement('td');
			td.appendChild(document.createTextNode(res.spec.dayNames[i]));
			tr.appendChild(td);
		}
		table.appendChild(tr);
		
		tr = document.createElement('tr');
		
		if (res.spec.firstDayInWeek > 0) {
			td = document.createElement('td');
			td.appendChild(document.createTextNode(week));
			tr.appendChild(td);
			for (var i = 0; i < res.spec.firstDayInWeek; i++) {
				td = document.createElement('td');
				td.setAttribute('class', 'empty');
				td.setAttribute('className', 'empty');
				tr.appendChild(td);
			}
		} else {
			week--;
		}
		
		var col = res.spec.firstDayInWeek;
		var today = new Date();
		today = {
			'year': today.getFullYear(),
			'month': today.getMonth() + 1,
			'day': today.getDate()
		}
		for (var i = 1; i <= res.spec.lastDay; i++) {
			if (col % 7 == 0) {
				week++;
				if (month == 1 && week > 50) week = 1;
				td = document.createElement('td');
				td.appendChild(document.createTextNode('' + week));
				tr.appendChild(td);
			}
			
			td = document.createElement('td');
			if (today.year == year && today.month == month && today.day == i) {
				td.setAttribute('class', 'std today');
				td.setAttribute('className', 'std today');
			} else {
				td.setAttribute('class', 'std');
				td.setAttribute('className', 'std');
			}
			_setDay(td, res, cid, year, month, i);
			tr.appendChild(td);
			
			if (col % 7 == 6) {
				table.appendChild(tr);
				tr = document.createElement('tr');
			}
			col++;
		}
		if (col % 7 > 0) {
			while (col % 7 != 0) {
				td = document.createElement('td');
				td.setAttribute('class', 'empty');
				td.setAttribute('className', 'empty');
				tr.appendChild(td);
				col++;
			}
			table.appendChild(tr);
		}
		if ((typeof table.outerHTML != "undefined") && table.outerHTML)
			htmlo.innerHTML = table.outerHTML;
		else
			htmlo.appendChild(table);
		/*
		append.onclick = function () {
			mayaFish.domDir(this);
			_drawAppended(res, cid, year, month, null);
			return false;
		}
		*/
	};
	
	return {
		'make': function (cid, result) {
			var html_calendar = mayaFish.$id('calendar_' + cid);
			var html_title = mayaFish.$id('calendar_title_' + cid);
			var html_content = mayaFish.$id('calendar_content_' + cid);
			var html_nextlink = mayaFish.$id('calendar_nextlink_' + cid);
			var html_prevlink = mayaFish.$id('calendar_prevlink_' + cid);
			html_title.innerHTML = result.title;
			html_nextlink['onclick'] = function () {
				mayaFish.modules.eventCalendar.draw(cid, result.next);
			};
			html_prevlink['onclick'] = function () {
				mayaFish.modules.eventCalendar.draw(cid, result.prev);
			};
			
			if (result.type) {
				html_title['onclick'] = function () {
					mayaFish.modules.eventCalendar.draw(cid, result.month);
				};
				if (result.type == 'day') {
					_drawDays(result, cid);
				} else {
					var typ = result.month.split('-');
					_drawMonth(result, cid, typ[0], typ[1]);
				}
			} else {
				mayaFish.ui.alert('Parse error (eventCalendar)',
					mayaFish.translations('common', 'Error'),
					null, null, mayaFish.ui.icons.WARNING);
				mayaFish.debug(result);
			}
			mayaFish.removeClass(html_calendar, 'loading');
		},
		'draw': function (cid, dat) {
			var html_calendar = mayaFish.$id('calendar_' + cid);
			mayaFish.addClass(html_calendar, 'loading');
			mayaFish.jsonRpc.call({
				'method': 'eventCalendarView::getEvents',
				'params': {
					'date': dat
				},
				'onSuccess': function (result) {
					mayaFish.modules.eventCalendar.make(cid, result);
				}
			});
		}
	};
})();
