if (typeof Effect == 'undefined')
	throw("tabswapper.js requires including script.aculo.us' effects.js library!");

var tabSwapper = Class.create();

tabSwapper.prototype = {
	tabs: [],
	panels: [],
	currentIndex: null,

	initialize: function( container, panels, links, options) {
		this.container = container;
		this.links = links;
		this.panels = panels;

		this.options = Object.extend({
			activeClassName:'current',
			onEvent:  'click',
			cookieName: '',
			effects:  false
		}, options || {} );

		tabList = new Element('ul').addClassName('tabs');
		this.container.insert( {'top':tabList} );

		this.links.each(function(link,index){
			var tab = new Element('li');

			// copy text from panel headings into list element
			tab.insert( {'top': new Element('span').update(link.innerHTML) } );
			tabList.insert( {'bottom':tab} );

			Event.observe(tab, this.options.onEvent, this.activate.bind(this, index), false);
			this.tabs.push(tab);
		}.bind(this));
		
		this.links.invoke('hide');
		this.panels.invoke('hide');
		
 		if(this.options.cookieName && this.getCookie()) 
 			this.activate( parseInt(this.getCookie()) );
 		else 
 			this.activate(0)

		
	},

	setCookie: function(index) {
		document.cookie = this.options.cookieName + "=" +escape(index) ;
	},
	
	getCookie: function(){
		// regexp from Carlos Reche (http://gorondowtl.sourceforge.net/wiki/Cookie)
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(this.options.cookieName) + '=([^;\\s]*)'));
		return (cookie ? unescape(cookie[2]) : null);
	},

	activate: function(index) {
		if (index === this.currentIndex) return false;
		if (index >= this.tabs.length) index = 0;

		if (this.currentIndex != null) {
			if (this.options.effects) {
				new Effect.Fade(this.panels[this.currentIndex], {queue: 'front'});
			} else {
				this.panels[this.currentIndex].hide();
			}
			this.tabs[this.currentIndex].removeClassName(this.options.activeClassName);
		}
		this.currentIndex = index ;
		if (this.options.effects) {
			new Effect.Appear(this.panels[this.currentIndex], {queue: 'end'});
		} else {
			this.panels[this.currentIndex].show();
		}
		this.tabs[this.currentIndex].addClassName(this.options.activeClassName);
		if(this.options.cookieName) this.setCookie(index);
	} ,

	autoActivate: function(value) {
		// value can be index, id or object
		var el = null ;
		if (Object.isElement(value))
			el = value	
		else if (Object.isNumber(value))
			if (value>=0 && value<this.panels.length) el = this.panels[value];
		else if (Object.isString(value)) 
			el = $(value);
		if (!el) return ;			
		this.panels.each(function(panel,index){
			if (panel.id==el.id) this.activate(index)
		}.bind(this));
	}
}