if(!Nibynic) {
	var Nibynic = { };
}

Nibynic.Events = {
	datesIndex: 0,
	initialized: false,
	
	init: function() {
		if(this.initialized) {
			return;
		}
		
		this.initialized = true;
		
		this.container = $('events');
		
		var showEventId = Nibynic.LocationHash.getParam('event');
		if(showEventId) {
			showEventId = 'event_' + showEventId;
		}
		
		this.events = [ ];
		this.container.select('.event').each(function(event) {
			var eventObject = new Nibynic.Event(event);
			this.events[this.events.length] = eventObject;
			if(showEventId && event.id == showEventId)  {
				eventObject.show();
			}
		}.bind(this));
		
		if(!showEventId && this.events.length > 0) {
			// this.events[0].show();
		}
	},
	
	addDate: function(link) {
		var date = link.up('tr');
		
		new Ajax.Request('/kalendarium/date-form/index:' + this.datesIndex, {
			onSuccess: function(transport) {
				this.insert({ after: transport.responseText })
			}.bind(date)
		});
		
		this.datesIndex++;
	},
	
	removeDate: function(link) {
		var date = link.up('tr');
		var idField = date.down('input[type="hidden"]');
		
		if(idField && idField.value) {
			date.up('form').down('input[name="dates_to_remove"]').value += idField.value + ',';
		}
		
		date.remove();
	}
}

Nibynic.Event = Class.create({
	initialize: function(element) {
		this.element = $(element);
		
		this.header = this.element.down('.header');
		this.body = this.element.down('.body');

		this.header.observe('click', function(event) {
			this.toggle();
		}.bind(this));
		
		this.header.observe('mouseover', function(event) {
			this.element.addClassName('hover');
		}.bind(this));
		
		this.header.observe('mouseout', function(event) {
			this.element.removeClassName('hover');
		}.bind(this));
		
		this.ajaxContext = new Nibynic.AjaxContext(this.element, { mode: 'update' });
	},
	
	hide: function() {
		this.element.addClassName('hidden');
	},
	
	show: function() {
		Nibynic.Events.events.each(function(event) {
			event.hide();
		})
		this.element.removeClassName('hidden');

		if(matches = this.element.id.match(/^event_([0-9]+)$/)) {
			Nibynic.LocationHash.setParam('event', matches[1]);
		}
	},
	
	toggle: function() {
		if(this.element.hasClassName('hidden')) {
			this.show();
		} else {
			this.hide();
		}
	}
});

document.observe('dom:loaded', function() {
	Nibynic.Events.init();
});
