/*
TO IMPROVE: 
	- show/hide instead of positioning
	- provide transition effects
*/
var TabSwitcher = Class.create({
	initialize: function(links, items, options) {
		this.options = Object.extend({
			initialTabIndex: 0, // int index | string tab id.
			tabOnClassName: 'selected',
			tabOffClassName: null,
			bodyOnStyles: {display:'block'},
			bodyOffStyles: {display: 'none'}
			
			//bodyOnStyles: {position:'static'},
			//bodyOffStyles: {top: '-50001px', position: 'absolute'}
			
		}, options || {});	
		// get dom references for tab and body elements
		this.links = (Object.isString(links)) ? $$(links) : links;
		this.items = (Object.isString(items)) ? $$(items) : items;
		if (this.items.length == 0 || this.links.length == 0) {return;}
		
		// attach event handlers
		this.links.invoke('observe', 'click', this._linkClick.bindAsEventListener(this));

		if(Object.isNumber(this.options.initialTabIndex)){
			this.setItem(this.links[this.options.initialTabIndex]);
		} else{
			this.setItem(this.options.initialTabIndex);
		}
	},
	
	_linkClick: function(e) {
		Event.stop(e);  // stop event
		var link = Event.findElement(e, 'a');
		this.setItem(link); // show item
	},
	
	// Sets the current item (tab and item). Allows a tab link reference, or a string id.
	setItem: function(elLnk) {
		// add/remove selected class on parent LI (tab elements)
		var tabOffClassName = this.options.tabOffClassName;
		var tabOnClassName = this.options.tabOnClassName;
		elLnk = this._getLink(elLnk);

		this.links.each(function(lnk){
			if(elLnk === lnk){
				lnk.up('li').addClassName(tabOnClassName);
				if(tabOffClassName != null){
					lnk.up('li').removeClassName(tabOffClassName);
				}
			}
			else{
				lnk.up('li').removeClassName(tabOnClassName);
				if(tabOffClassName != null){
					lnk.up('li').addClassName(tabOffClassName);
				}				
			}
		});
		
		// show/hide items (body elements)
		var attHref = elLnk.readAttribute("href").replace(/.*#+/, '');
		this.items.each(function(elBody){
			if(elBody.id == attHref){
				elBody.setStyle(this.options.bodyOnStyles);
			}
			else{
				elBody.setStyle(this.options.bodyOffStyles);
			}
		}.bind(this));
	},
	
	// Parses a string, integer, or element reference into an associated link element.
	_getLink: function(arg){
		var elLink;
		if(Object.isElement(arg)){
			elLink = arg;
		} else if(Object.isNumber(arg)){
			elLink = this.links[arg];
		} else {
			elLink = this.links.find(function(lnk){
				return (arg === lnk.readAttribute("href")) || (arg === lnk.readAttribute("href").replace(/^#/, ''));
			});
		}
		return elLink;		
	}
});
/*
document.observe("dom:loaded", function(){
	var ts = new TabSwitcher("ul#tabs li a", "div.tab_content div");

});
*/

