var Featured_Controller = new Class({
    options: {
		id: null,
		container: null,
		autoplay: false,
		fx_duration: 250,
		transition_interval: 5000
    },

    initialize: function(options) {
		this.setOptions(options);
		
		this.interval = null;
		this.container = $(this.options.container);

		this.featured_items = this.container.getElements("div.featured-item");
		
		this.count = this.featured_items.length;
		this.current_featured = 0;

		var controller = this;

		this.links = $("featured-links").getElements("a");
		$each(this.links, function(link, index) {
			link.addEvent("click", function() {
				controller.clear_interval();
				controller.do_featured(index);
			});
		});
		
		//Cufon.replace("div.featured-content h2,div#featured-links a");
		
		if (this.options.autoplay === true) { this.play(); }
	},
	
	transition: function(from, to) {		
		var f = new Fx.Tween(from, { property: "opacity", duration: this.options.fx_duration, onComplete:function(elem) { elem.style.display = "none"; } });
		var t = new Fx.Tween(to, { property: "opacity", duration: this.options.fx_duration });
		
		f.start(1, 0).chain(
			function() {
				$(to).setStyles({ opacity: 0, display:"block" });
				t.start(0, 1);
			}
		);
	},
	
	do_featured: function(which) {
		if (this.current_featured !== which) {
			if (Browser.Engine.trident) {
				var movie = $("flash" + this.current_featured);
				if ($chk(movie)) { movie.sendEvent("PLAY", false); }
			}

			this.transition(this.featured_items[this.current_featured], this.featured_items[which]);
			this.links[this.current_featured].removeClass("selected");
			this.links[which].addClass("selected");
			
			this.current_featured = which;
		}
	},

	next: function() {
		if ($defined(this.interval)) { // reset the timer
			this.clear_interval();
			this.set_interval() 
		}
		
		if (this.current_featured == (this.count - 1)) {
			this.clear_interval(); // quick hack so it only plays through once
			this.do_featured(0);
		} else {
			this.do_featured(this.current_featured + 1);
		}
	},
	
	previous: function() {
		if ($defined(this.interval)) { // reset the timer
			this.clear_interval();
			this.set_interval() 
		}
		
		if (this.current_featured == 0) {
			this.do_featured(this.count - 1);
		} else {
			this.do_featured(this.current_featured - 1);
		}
	},
	
	play: function() {
		if (this.paused === true) { 
			this.next();
			this.paused = false;
		}
		this.set_interval();
	},
	
	pause: function() {
		this.clear_interval();
		this.paused = true;
	},
	
	set_interval: function () {
		this.interval = setInterval(this.options.id + ".next()", this.options.transition_interval);
	},
	
	clear_interval: function() {
		clearInterval(this.interval);
		this.interval = null;
	}
});

Featured_Controller.implement(new Options);

