/** Code Taken from the book "MooTools Essentials" by Aaron Newton **/

var Tabs = new Class({
	
	Implements: [Options, Events], 
	
	options: {
		selectedTabCssClass : 'selected',
		selectedSectionCssClass : 'selected',
		firstShow : 0
		/*
		 * onShow: $empty,
		 * onHide: $empty
		 */
	},
	
	tabs: [],
	
	initialize: function(containers, tabs, options) {
		this.setOptions(options);
		$$(tabs).each(function(tab, index) {
			this.addSection(tab, $$(containers)[index]);
		}, this);
		this.show(this.options.firstShow);
	},
	
	addSection: function(tab, container) {
		this.tabs.include(tab);
		tab.store('container', container);
		this.attach(tab);
	},
	
	attach: function(tab) {
		tab.addEvent('click', function(event) {
			event.preventDefault();
			this.show(this.tabs.indexOf(tab));
		}.bind(this));
	},

	show: function(index) {
		if(this.current === index) return;
		this.tabs.each(function(tab, i) {
			var container = tab.retrieve('container');
			if(index === i) {
				tab.addClass(this.options.selectedTabCssClass);
				container.addClass(this.options.selectedSectionCssClass);
				container.setStyle('display', 'block');
				this.fireEvent('onShow', [i, tab, container]);
			} else {
				tab.removeClass(this.options.selectedTabCssClass);
				container.removeClass(this.options.selectedSectionCssClass);
				container.setStyle('display', 'none');
				if(this.current === i || $chk(this.current)) {
					this.fireEvent('onHide', [i, tab, container]);
				}
			}
		}, this);
		this.current = index;
	}

});

var AjaxTabs = new Class({
	
	Extends: Tabs,
	options: {
		cache: true,
		urls: [],
		requestOptions: {}
	},

	show: function(index, force) {
		var tab = this.tabs[index];
		var url = this.options.urls[index] || tab.get('href');
		if(!url || force || (this.options.cache && tab.retrieve('loaded'))) {
			this.parent(index);
		} else {
			this.fetchTabContent(index, url);
		}
	},
	
	fetchTabContent: function(index, url) {
		var tab = this.tabs[index];
		var container = tab.retrieve('container');
		var request = tab.retrieve('tabAjax');
		if(!request) {
			request = new Request.HTML(
				$merge(this.options.requestOptions, {
					update: container,
					url: url
				})
			).addEvent('onSuccess', function() {
				tab.store('loaded', true);
				this.show(index, true);
			}.bind(this));
			tab.store('tabAjax', request);
			
		}
		request.send();
	}
	
});
