var EventCalendarList = Class.create({
	/** デフォルト オプション */
	defaultOptions : {
		useWrap:true,
		containerId : 'calenderList',
		eventItemUnitId : 'event-calendar-item-unit'
	},
	/** 初期化 */
	initialize : function() {
		this.options = Object.extend(this.defaultOptions, {});
		this.container = $(this.options.containerId);

		if(!this.container)
			return;
		this.unitTpl = Conf.getApplicationParts(this.options.eventItemUnitId);
	},
	createUnit : function(event) {
		// イベント表示の雛形を取得
		var unit = this.unitTpl.cloneNode(true);
		for(var key in event) {
			var value = event[key];
			$(unit).select('.' + key).each(function(node) {
				if(value == null) {
					$(node).hide(); // null のばあいは非表示
				}
				else {
					switch(node.tagName) {
						case 'IMG': node.src  = value; break;
						case 'A':
							if(node.href.match(/@@@/)) {
								node.href = node.href.replace(/@@@/, value);
							}
							else {
								node.href = value;
							}
							break;
						default:
							if(node.className.match(/@@@/)) {
								node.className = node.className.replace(/@@@/, value);
							}
							else {
								node.update(value);
							}
					}
				}
			});
		}
		return unit;
	},
	reflesh: function(events) {
		if(!this.container) return;

		this.events = events;
		while(this.container.firstChild) {
			this.container.removeChild(this.container.firstChild);
		}
		// イベント情報を表示
		this.units = [];
		this.highlighted = null;
		for(var i = 0; i < events.length; i++) {
			var event = events[i];
			var unit = this.createUnit(event);
			this.container.appendChild(unit);
			this.units.push(unit);
		}
	},
	showWrap : function(msg) {
		if(!this.options.useWrap) return;
		if(!this.wrap) {
			this.wrap = new Wrap(this.container.parentNode, {opacity:0.9});
			this.wrap.setImage(Conf._p(Conf.images.loading.url));
		}
		this.wrap.setMessage(msg);
		this.wrap.show();
	},
	hideWrap : function() {
		if(!this.options.useWrap) return;
		this.wrap.hide();
	}
});

var EventCalendar = Class.create(Calendar, {
	/** コンストラクタ */
	initialize : function($super, element, defaultDate, options) {
		var eventList = new EventCalendarList();
		if(eventList.container) {
			this.eventList = eventList;
		}
		$super(element, defaultDate, options);
	},
	/** 表示を更新 */
	update : function($super) {
		var dt = this.getDate();
		var y  = dt.getFullYear();
		var m  = dt.getMonth() + 1;

		if(!this.options.eventListUri) {
			this.options.eventListUri = EventCalendar.eventListUri;
		}
		if(!this.options.dateLink) {
			this.options.dateLink = EventCalendar.dateLink;
		}
		this.eventData = {};

		var parameters = { year:y, month:m };
		if(this.eventList) {
			parameters.eventList = 1;
			this.eventList.showWrap('読み込み中');
			this.eventList.container.setOpacity(0.1);
		}
		new Ajax.Request(this.options.eventListUri, {
			parameters: parameters,
			onSuccess: (function(res, eventData) {
				try {
					this.eventData = eventData;
					$super();
					if(this.eventList) {
						var events = res.responseJSON;
						if(events) {
							this.eventList.reflesh(events);
							new Effect.Opacity(this.eventList.container, { from: 0.1, to: 1.0, duration: 0.5 });
						}
						this.eventList.hideWrap();
					}
				}catch (e){
					//this.debugOut(res.responseText.replace(/}/, "}\n"));
					alert("eventCalender:" + e.message);
				}
			}).bind(this),
			onFailure: function(res)    {
				$super(); alert('読み込みに失敗しました');
			},
			onException: function (res) {
				$super(); alert('読み込み中にエラーが発生しました');
			}
		});
	},
	debugOut : function(text) {
		var w = window.open('', 'debugconsole',
			'width=400, height=300, menubar=no, toolbar=no, scrollbars=yes, resizable=yes');
		w.document.open();
		w.document.write('<html><head><title>debug console</title></head><body><pre>');
		w.document.write(text);
		w.document.write('</pre></body></html>');
		w.document.close();
		w.focus();
	},
	/** 表示セルを更新 */
	updateCell : function($super, cell, y, m, d) {
		//$super(cell, y, m, d);
		var dNum = cell.down('.calendarDayNum');
		var eCnt = cell.down('.calendarEventCount');
		if(!y) {
			dNum.update('');
			eCnt.update('');
			cell.title = '';
		}
		else {
			if(this.eventData && this.eventData[d] > 0) {
				var href = this.options.dateLink + '?y=' + y + '&m=' + m + '&d=' + d;
				var node = $(Conf.getApplicationParts('event-calendar-cell'));

				var dNumA = node.down('.calendarDayNum').down('a');
				dNumA.href = href;
				dNumA.update(d);
				dNum.update(dNumA);

				var eCntA = node.down('.calendarEventCount').down('a');
				eCntA.href = href;
				eCntA.down('span').update(this.eventData[d]);
				eCnt.update(eCntA);

				cell.title = y + '-' + m + '-' + d;
			}
			else {
				dNum.update(d);
				eCnt.update('&nbsp;');
				cell.title = y + '-' + m + '-' + d;
			}
		}
	}
});
EventCalendar.eventListUri = document.URL.replace(/#.+$/, '').replace(/\?.+$/, '');
EventCalendar.dateLink     = document.URL.replace(/#.+$/, '').replace(/\?.+$/, '');

document.observe('dom:loaded', function () {
	new EventCalendar('eventCalendar', null, {
		curMSelector        : ".curr-month",
		nextMSelector       : ".monthlyNaviNext",
		prevMSelector       : ".monthlyNaviPrev",
		dispYSelector       : ".dispY",
		dispMSelector       : ".dispM",
		calendarCellSelector: ".calenderTableDay",
		eventListUri : '../EventCalendar.php',
		dateLink : '../event/index.php',
		keepDt:true
	});
});



