/*
 * Fabtabulous! Simple tabs using Prototype
 * http://tetlaw.id.au/view/blog/fabtabulous-simple-tabs-using-prototype/
 * Andrew Tetlaw
 * version 1.1 2006-05-06
 * http://creativecommons.org/licenses/by-sa/2.5/
 */
var Fabtabs = Class.create();

Fabtabs.prototype = {
	initialize : function(element) {
    /*
     * Updated the tab pattern to recognize a leading underscore after
     * the anchor marker so IE won't scroll down the page. Also consolidated
     * the numerous instances of the pattern into one place.
     */
    Fabtabs.pattern = /#[_]?(\w.+)/;
		this.element = $(element);
		this.options = Object.extend({
      onActivate: function() {}
    }, arguments[1] || {});
		this.menu = $A(this.element.getElementsByTagName('a'));
		this.show(this.getInitialTab());
		this.menu.each(this.setupTab.bind(this));
	},
	setupTab : function(elm) {
		Event.observe(elm,'click',this.activate.bindAsEventListener(this),false)
	},
	activate :  function(ev) {
		var elm = $(Event.findElement(ev, "a"));
		Event.stop(ev);
    document.location.href = elm.href;
    
		this.show(elm);
		this.menu.without(elm).each(this.hide.bind(this));
    return false;
	},
	hide : function(elm) {
    elm = $(elm);
		$(elm.parentNode).removeClassName('active_button');
    $(this.tabID(elm)).hide();
	},
	show : function(elm) {
    elm = $(elm);
		$(elm.parentNode).addClassName('active_button');
    elm.blur();
    $(this.tabID(elm)).show();
    this.options.onActivate(this.tabID(elm));
	},
	tabID : function(elm) {
		return elm.href.match(Fabtabs.pattern)[1];
	},
	getInitialTab : function() {
		if(document.location.href.match(Fabtabs.pattern)) {
			var loc = RegExp.$1;
			var elm = this.menu.find(function(value) { return value.href.match(Fabtabs.pattern)[1] == loc; });
			return elm || this.menu.first();
		} else {
			return this.menu.first();
		}
	}
}