
var Featured = new Class({
	Implements: [Options, Events, Chain],
	Titulos : ["","","","","",""],
	initialize: function(options){
		this.setOptions(options);
		if(!$('featured')) return;
		
		this.navigation = $$('.featured_display')[0].getChildren();
		this.navigation.each(function(el, i){
            this.Titulos[i] = this.navigation[i].getElement('img').get('title');
            var arr = this.Titulos[i].split('::');
            this.navigation[i].getElement('img').set('title', arr[0]);
			el.addEvent('click', function(e){
				e.stop();
				this.switchto(i);
			}.bind(this));
		}.bind(this));
		
		$$('.featured_left')[0].addEvent('click', function(){ this.prev(); }.bind(this));
		$$('.featured_right')[0].addEvent('click', function(){ this.next(); }.bind(this));
		
		this.set(0);
		this.loading = false;
	},

	set: function(i, chg_img){
		this.active = i;
		chg_img = (chg_img===false?false:true);
		this.navigation.each(function(el){ el.removeClass('active'); });
		this.navigation[i].addClass('active');
		
		var arr = this.Titulos[i].split('::');
		$('featured_title').set('html', '<a href="'+ arr[1] +'" title="'+ arr[0] +'">'+ arr[0] +'</a>');
		$('featured_comments').set('html', '<a href="'+ arr[1] +'#comment" title="'+ arr[0] +'">'+ arr[2] +'</a>');
		$('featured_category').set('html', arr[3]);
		if (!chg_img) return;
		$('featured').getElements('div[id^=featured_img_]').each(function(el){ el.removeClass('active'); });
		$('featured_img_'+i).addClass('active');
	},

	switchto: function(i){
		if(this.loading || this.active == i) return;
		this.loading = true;
		var old = this.active;
		var cords = $('featured_img_'+this.active).getCoordinates();
		this.fxOld = new Fx.Tween($('featured_img_'+old), {duration: 500});
		this.fxNew = new Fx.Tween($('featured_img_'+i), {duration: 500});
		
		this.set(i, false);
		$('featured_img_'+i).set('opacity', 0);
		$('featured_img_'+i).setStyles({
			'position': 'absolute',
			'top': cords.top,
			'left': cords.left
		});
		$('featured_img_'+i).addClass('active');
		this.fxOld.start('opacity', 0).chain(function(){
			$('featured_img_'+old).removeClass('active');
		}.bind(this));
		this.fxNew.start('opacity', 1).chain(function(){
			$('featured_img_'+i).removeProperty('style');
			this.loading = false;
		}.bind(this));
	},

	prev: function(){
		var i = this.active - 1;
		if(i < 0) i = this.navigation.length - 1;
		this.switchto(i);
	},

	next: function(){
		var i = this.active + 1;
		if(i >= this.navigation.length) i = 0;
		this.switchto(i);
	}
});

window.addEvent('domready', function(){ new Featured(); });
