/*
---
description: A Class that provides cross-browser tabs

license: 

authors:
- Roy Teusink

requires:
- Mootools core/1.3: [Object,Class,Class.Extras,Element,Element.Event,Element.Style,HashListener]

provides: [Tabs]

*/
var Tabs = new Class({
	Implements: [Events, Options],
	
	initialize: function(tabs) {
		if(!tabs) return;
		this.tabs_container = tabs;
		this.tabs = tabs.getElements('a');
		
		this.pages_container = document.id(tabs.get('data-link')) || 0;
		if(!this.pages_container) return;
		
		this.pages = this.pages_container.getChildren('li');
		this.attach();
	},
	attach: function() {
		var app = this;
		
		this.hash = new HashListener();
		this.hash.addEvent('hashChanged', this.hashchange.bind(this));
		this.hash.start();
		
		this.tabs.addEvent('click', function(e) {
			var name = app.strip_hash(this.get('href'));
			app.goto(name, this, e);
			app.fireEvent('click', [e, this, name]);
		});
	},
	goto: function(tabname, tab, e) {
		
		this.pages.addClass('hidden');
		var href = '.tab_' + tabname;
		var active_pages = this.pages_container.getElements(href);
		active_pages.each(function(item){
			item.removeClass('hidden');
		});
		
		this.tabs.removeClass('active');
		if(tab) {
			tab.addClass('active');
		} else {
			this.tabs_container.getElement('a[href=#'+tabname+']').addClass('active');
		}
		
		
		this.hash.updateHash(tabname);
		this.fireEvent('click', [e, tab, tabname]);
		
	},
	strip_hash: function(input) {
		return input.replace('#', '');
	},
	first: function(e) {
		if(e) e.stop();
		var next = this.strip_hash(this.tabs[0].get('href'));
		this.goto(next);
	},
	next: function(e) {
		if(e) e.stop();
		var next = null, active = null, app = this;
		
		this.tabs.each(function(item) {
			if(active != null && next == null) next = app.strip_hash(item.get('href'));
			if(item.hasClass('active')) active = item;
		});
		if(next != null) {
			this.goto(next);
		}
	},
	previous: function(e) {
		if(e) e.stop();
		var prev = null, active = null, app = this;
		
		this.tabs.each(function(item) {
			if(active == null && !item.hasClass('active')) prev = app.strip_hash(item.get('href'));
			if(item.hasClass('active')) active = item;
		});
		if(prev != null) {
			this.goto(prev);
		}
	},
	hashchange: function(value) {
		if(value == '') {
			this.first();
			return;
		}
		this.goto(value);
	}	
	
});
