var CosMooTabs = new Class({
	Implements: [Options],
	

	version: '0.3',
 
	options: {
		startTitle: '',
		titleSelector: 'li',
		panelSelector: '.morphtabs_panel'
	},
 
	
	initialize: function(element, options) {
		
		this.setOptions(options);
		this.el = $(element);
		this.elid = element;
		 
		this.titles = $$(this.options.titleSelector);
		this.panels = $(element).getElements(this.options.panelSelector);
		
		this.activePanel = null;
		
		this.attach(this.titles);
				
		var title = $(''+this.options.startTitle);
		if(this.options.startTitle=='' || !title)
			this.activate(this.titles[0]);
		else
			this.activate(title);
	},
	
	attach: function(titles)
	{
		var obj = this;
		titles.each(function(el){
			el.addEvent('click', function(){obj.activate(el);});
		});
	},
	
	detach: function(titles)
	{
		var obj = this;
		titles.each(function(el){
			el.removeEvents('click');
		});
	},
	
	activate: function(title)
	{
		var obj = this;
		obj.detach(obj.titles);
		var id = title.get("title");
		var panel = $(id);
		this.activePanel = panel;
		this.panels.each(function(el){
			var fade = el.retrieve('fade');
			if (!fade) {
				fade = new Fx.Tween(el, {'property':'opacity', 'duration':200});
				el.store('fade', fade);
			}
			fade.set(0);
			el.setStyle('height', 0);
		});
		panel.setStyle('height','');
		panel.retrieve('fade').start(1).chain(function(){obj.setHeight(panel); obj.attach(obj.titles);});
		this.titles.each(function(el){el.removeClass('active');});
		title.addClass('active');
		
	},
	
	setHeight: function(panel)
	{
		var height = panel.getCoordinates().height;
		if (parseInt(panel.getStyle('top'))) height+=parseInt(panel.getStyle('top'));
		if (parseInt(panel.getStyle('margin-top'))) height+=parseInt(panel.getStyle('margin-top'));
		this.el.setStyle('height', height);
	}
});
