/**
* @author Ryan Johnson <ryan@livepipe.net>
* @copyright 2007 LivePipe LLC
* @package Control.Tabs
* @license MIT
* @url http://livepipe.net/projects/control_tabs/
*/

if(typeof(document.getElementsByAttribute) == "undefined"){
	document.getElementsByAttribute = function(attribute,parent) {
		return $A(($(parent) || document.body).getElementsByTagName('*')).inject([],function(elements,child){
			return (child.getAttribute(attribute)) ? (elements.push(Element.extend(child)),elements) : elements;
		});
	}
}

if(typeof(Control) == "undefined")
	var Control = {};
Control.Tabs = Class.create();
Object.extend(Control.Tabs.prototype,{
	options: $H({
		beforeChange: Prototype.emptyFunction,
		afterChange: Prototype.emptyFunction,
		linkSelector: 'li a',
		activeClassName: 'active'
	}),
	activeContainer: false,
	initialize: function(tab_set,options){
		tab_set = $(tab_set);
		this.options.merge(options || {});
		this.containers = $H({});
		this.links = (typeof(this.options.linkSelector) == "string"
			? tab_set.getElementsBySelector(this.options.linkSelector)
			: this.options.linkSelector(tab_set)
		);
		this.links.each(function(link){
			link.key = link.href.replace(/[^#]+#/,'');
			this.containers[link.key] = document.getElementsByAttribute('name').findAll(function(e){return (e.getAttribute('name') == link.key);})[0];
			link.onclick = function(link){
				this.setActiveTab(link);
				return false;
			}.bind(this,link);
		}.bind(this));
		this.setActiveTab(this.links.first());
		target_regexp = /#(.+)$/;
		targets = target_regexp.exec(window.location);
		if(targets && targets[1]){
			$A(targets[1].split(',')).each(function(target){
				this.links.each(function(target,link){
					if(link.key == target){
						this.setActiveTab(link);
						throw $break;
					}
				}.bind(this,target));
			}.bind(this));
		}
	},
	setActiveTab: function(link){
		if(typeof(link) == "string"){
			this.links.each(function(link){
				if(link.key == name){
					this.setActiveTab(link);
					throw $break;
				}
			});
		}else{
			this.containers.each(function(item){
				item[1].hide();
			});
			this.links.each(function(l){
				l.removeClassName(this.options.activeClassName);
			}.bind(this));
			link.addClassName(this.options.activeClassName);
			this.options.beforeChange(this,this.activeContainer);
			this.activeContainer = this.containers[link.key];
			this.containers[link.key].show();
			this.options.afterChange(this.containers[link.key]);
		}
	}
});
