var Panels = new Class({

	Implements: Options,

	options: {
		mode: 'horizontal',
		transition: 'back:out',
		duration: 900,
		defaultPanel: 'intro'
	},
	
	holder: null,
	panels: null,
	fx: null,
	nav: null,
	links: null,
	
	initialize: function(holder, nav, options) {
		this.setOptions(options);
		this.holder = $(holder);
		this.nav = $(nav);
	
		/* Hide overflow and create fx */
		this.holder.setStyle('overflow-x', 'hidden');
		this.fx = new Fx.Scroll(this.holder, {
			transition: this.options.transition,
			duration: this.options.duration,
			link: 'cancel'
		});
		this.holder.set('tween', {
			duration: this.options.duration - 100,
			link: 'cancel'
		});
		
		/* Add panels to hash and erase id to prevent nav on location hash update */
		var panels = this.holder.getElements('div.panel');
		this.panels = $H();
		panels.each(function(panel) {
			if (this.options.mode == 'vertical') {
				panel.setStyle('float', 'none');
			}
			this.panels.set(panel.get('id'), panel);
			panel.erase('id');
		}, this);
		if (this.options.mode == 'vertical') {
			this.holder.getElementById('panels-inner').setStyles({
				'width': 'auto',
				'padding-bottom': 1
			});
		}
		
		/* Add tab events */
		this.links = this.nav.getElements('a');
		this.links.each(function(link) {
		
			/* Get target id */
			var href = link.get('href');
			var id = href.substr(href.indexOf('#') + 1);
			
			/* Add event */
			link.addEvent('click', this.onTabClick.bindWithEvent(this, [link, id]));
		}, this);
		
		/* Mark current section active */
		this.gotoCurrent();
	},
	
	onTabClick: function(event, link, id) {
		link.blur();

		/* Smooth scroll to new panel */
		var panel = this.panels.get(id);
		this.holder.tween('height', panel.getHeight());
		this.fx.toElement(panel);

		/* Mark tab active */
		this.links.removeClass('current');
		link.addClass('current');
	
		/* Update location hash */
		location.hash = id;
	
		if ($defined(event)) {
			event.stop();
		}
	},
	
	gotoCurrent: function() {
	
		/* Mark current link based on location hash */
		var id = location.hash.substr(1) || this.options.defaultPanel;
		
		var link = this.nav.getElement('li.'+id+' a');
		if (link) {
			var panel = this.panels.get(id);
			var position = panel.getPosition(this.holder);
			this.holder.setStyle('height', panel.getHeight());
			this.holder.scrollTo(position.x, position.y);
			this.links.removeClass('current');
			link.addClass('current');
		}
	
	}
	
});
