// tabbar.js -- Dudeplace Tab Bar component
// Written by Oo+
// require MooTools to be function

var TabBar = new Class({
	options: {
		manual: false,
		onactive: null
	},

	initialize: function(container, tabIndex, options) {
		this.setOptions(options);
		this.container = $(container);
		this.tabs = this.container.getElements('li');
		this.tabs.each(function(tab, index) {
			tab.addEvent(this.options.manual ? 'click' : 'mouseenter', function(event) {
				event.stop();
				this.setIndex(index);
			}.bind(this));
		}.bind(this));
		this.tabIndex = -1;
		this.setIndex(tabIndex);
	},

	setIndex: function(tabIndex) {
		var oldIndex = this.tabIndex;
		if (this.tabIndex >= 0)
			this.tabs[this.tabIndex].removeClass('active');
		this.tabIndex = tabIndex;
		if (this.tabIndex >= 0)
			this.tabs[this.tabIndex].addClass('active');
		if (this.options.onactive)
			this.options.onactive(this.tabIndex, oldIndex);
	}
});

TabBar.implement(new Options);
TabBar.implement(new Events);

var TabPages = new Class({
	initialize: function(container, pageIndex) {
		var self = this;
		this.container = $(container);
		this.displays = new Array();
		this.height = 0;
		this.pages = this.container.getElements('.tabpage');
		this.pages.each(function(page, index) {
			var height = page.getStyle('height').toInt();
			if (self.height < height)
				self.height = height;
			page.addClass('collapsed');
		}.bind(this));
		this.container.setStyle('height', this.height);
		this.pageIndex = -1;
		this.setIndex(pageIndex);
	},

	setIndex: function(pageIndex) {
		if (this.pageIndex >= 0)
			this.pages[this.pageIndex].addClass('collapsed')
		this.pageIndex = pageIndex;
		if (this.pageIndex >= 0)
			this.pages[this.pageIndex].removeClass('collapsed');
	}
});


var TabbedPages = new Class({
	initialize: function(tabs, pages, manual, tabIndex) {
		this.pages = new TabPages(pages, tabIndex);
		this.tabs = new TabBar(tabs, tabIndex, {
			'manual': manual,
			onactive: function(newIndex, oldIndex) { this.pages.setIndex(newIndex); }.bind(this)
		});
	}
});


