var Showcase = {
	activePanel: 1,
	
	init: function( el ) {
		this.showcase = el;
		this.panels = el.getElements('.showcasePanel');
		
		if ( this.panels.length <= 1 ) return;
		
		this.slider = el.getElements('.showcaseSlider')[0];
		this.navlinks = el.getElements('.showcaseNav a');
		
		this.slider.setStyles({
			width: el.getSize().x * this.panels.length,
			display: 'block'
		});
		
		this.initNav();
		this.loadImages();
	},
	
	initNav: function() {
		var self = this;
		this.navlinks.addEvent('click', function(e) {
			new Event(e).stop();
			self.stopTimer();
			self.activatePanel(this);
		});
		this.selectNav(this.navlinks[0].id);
	},
	
	selectNav: function(id) {
		this.navlinks.removeClass('active');
		$(id).addClass('active');
	},
	
	activatePanel: function(el) {
		var panel = el.href.split('#').pop();
		var panelIndex = parseInt(panel.split('-').pop(), 10);
		
		this.activePanel = panelIndex;
		this.slideTo($(panel));
		this.selectNav(el.id);
	},
	
	slideTo: function(panel) {
		if (this.tween != null) { this.tween.cancel(); }
		
		var pos = panel.getPosition(this.slider).x;
		
		this.tween = new Fx.Morph(this.slider, {
			duration: 1200,
			transition: Fx.Transitions.Cubic.easeOut
		}).start({'left': -pos});
	},
	
	slideNext: function() {
		var panelIndex = this.activePanel + 1;
		if ( panelIndex > this.panels.length ) {
			panelIndex = 1;
		}
		this.activatePanel($('showcase-nav' + panelIndex));
	},
	
	startTimer: function() {
		this.interval = this.slideNext.periodical(5000, this);
	},
	
	stopTimer: function() {
		// stop the animation
		this.interval = $clear(this.interval);
		
		// restart the animation after 10 seconds
		this.timeout = $clear(this.timeout);
		this.startTimer.delay(8000, this);
	},
	
	loadImages: function() {
		var self = this;
		var images = this.showcase.getElements('img');
		images.each(function(img, i){
			images[i] = img.src;
		});
		var loader = new Asset.images(images, {
			onComplete: function() {
				self.startTimer();
			}
		});
	}
};

