/*
 * Fabtabulous! Simple tabs using Prototype
 * http://tetlaw.id.au/view/blog/fabtabulous-simple-tabs-using-prototype/
 * Andrew Tetlaw
 * version 2 2008-08-10
 * http://creativecommons.org/licenses/by-sa/2.5/
 */
var Fabtabs = Class.create({
	initialize : function(element,options) {
		var parent = this.element = $(element);
		var opt = Object.extend({
		  hover: true,
		  remotehover: true
		}, options || {});
		this.menu = this.element.select('a');
		this.hrefs = this.menu.map(function(elm){
		  return elm.href.match(/#(\w.+)/) ? RegExp.$1 : null;
		}).compact();
		this.show(this.getInitialTab());
		var activate = function(event) {
  		var elm = event.findElement("a");
  		this.activate(elm);
  	};
  	var remoteActivate = function(event) {
	    var trig = event.findElement("a");
	    var elm = this.element.select('a[href="#'+ this.tabID(trig) +'"]')[0];
    	this.activate(elm);
	  }
		this.element.observe('click', activate.bindAsEventListener(this));
		if(opt.hover) {
		  this.menu.each(function(elm){elm.observe('mouseover', activate.bindAsEventListener(this))}.bind(this));
		}
		var triggers = []; 
		this.hrefs.each(function(id){
		  $$('a[href="#' + id + '"]').reject(function(elm){
		    return elm.descendantOf(parent)
		  }).each(function(trig){
		    triggers.push(trig);
		  });
		})
		triggers.each(function(elm){
		  elm.observe('click', remoteActivate.bindAsEventListener(this));
		  if(opt.remotehover) {
  		  elm.observe('mouseover', remoteActivate.bindAsEventListener(this));
  		}
		}.bind(this));
	},
	activate: function(elm) {
	  this.show(elm);
		this.menu.without(elm).each(this.hide.bind(this));
	},
	hide: function(elm) {
		$(elm).removeClassName('active-tab');
		$(this.tabID(elm)).removeClassName('active-tab-body');
	},
	show: function(elm) {
		$(elm).addClassName('active-tab');
		$(this.tabID(elm)).addClassName('active-tab-body');
	},
	tabID: function(elm) {
		return elm.href.match(/#(\w.+)/)[1];
	},
	getInitialTab: function() {
			return document.location.href.match(/#(\w.+)/) ? 
			    this.element.select('a[href="#'+ RegExp.$1 +'"]')[0] : 
			    this.menu.first();
	}
});

document.observe("dom:loaded", function(){ new Fabtabs('tabs'); });