/**
 * Featured Content Selector
 * Made with blood, sweat and bacon
 * 
 * Luke Wilde - luke.wilde@clock.co.uk
 * 10 May 2010
 */
FeaturedContentSelector = Class.create();
FeaturedContentSelector.prototype = {
	
	initialize: function(featureContainer, snippetContainer, options) {
		this.featureContainer = $(featureContainer);
		this.snippetContainer = $(snippetContainer);
		
		this.options = {
			timerDuration: 1.5,
			pausableTimerArea: null,
			selectedFeatureClass: "inactive-feature",
			selectedSnippetClass: "active",
			featureIdPrepend: "article-",
			snippetIdPrepend: "snippet-",
			snippetClass: "snippet",
			featureClass: "featured-content"
		};
		
		Object.extend(this.options, options || { });
		
		if (this.options.pausableTimerArea != null) {
			this.pausableTimerArea = $(this.options.pausableTimerArea);
			new PeriodicalExecuter(this.onTick.bind(this), this.options.timerDuration);
			this.pausableTimerArea.onmouseover = this.onMouseOverFeatureArea.bind(this);
			this.pausableTimerArea.onmouseout  = this.onMouseOutFeatureArea.bind(this);
		}
		
		this.snippets = this.snippetContainer.select("." + this.options.snippetClass);
		this.features = this.featureContainer.select("." + this.options.featureClass);
		
		id = 0;
		this.snippets.each((function(snippet) {
			snippet.onclick = this.updateDisplay.bindAsEventListener(this, id);
			Element.extend(snippet);
			id++;
		}).bind(this));
		
		// Manually set the first
		this.snippets[0].toggleClassName(this.options.selectedSnippetClass);
		this.currentActiveSnippet = this.snippets[0];
		this.currentActiveFeature = this.features[0];
		this.currentIndex = 0;
	},
	
	onMouseOverFeatureArea: function() {
		this.mouseOverFeature = true;
	},
	
	onMouseOutFeatureArea: function() {
		this.mouseOverFeature = false;
	},
	
	onTick: function() {
		
		if (this.currentIndex + 1 == this.snippets.length) {
			this.currentIndex = -1;
		}
		
		if (!this.mouseOverFeature) {
			this.updateDisplay(null, this.currentIndex + 1);
		}
	},
	
	updateDisplay: function(event, id) {
		this.changeActiveSnippet(id);
		this.changeFeature(id);
		this.currentIndex = id;
	},
	
	changeActiveSnippet: function(id) {
		if (this.currentActiveSnippet != null) {
			this.currentActiveSnippet.toggleClassName(this.options.selectedSnippetClass);
		}
		
		this.snippets[id].toggleClassName(this.options.selectedSnippetClass);
		this.currentActiveSnippet = this.snippets[id];
	},
	
	changeFeature: function(id) {
		this.currentActiveFeature.toggleClassName(this.options.selectedFeatureClass);
		this.currentActiveFeature = this.features[id];
		this.currentActiveFeature.toggleClassName(this.options.selectedFeatureClass);
	}
}