var Qrotator = 
{
	initialize: function(id)
	{
		this.duration = 1;
		this.el = $(id);
		this.images = $$('#' + this.el.id + ' img');
		this.list = $$('#' + this.el.id + ' li');
		var switchImage = this.switchImage.bind(this);
		this.list.invoke('observe', 'click', switchImage);
		this.index = 0;
		this.delay = 4;
		var navigateToTitle = this.navigateToTitle.bind(this);
		
		// this.images.invoke('observe', 'click', navigateToTitle);
		
		/*
		This is a special case due to the rounded corners image being on top of all the other images
		*/
		var navigate = this.navigate.bind(this);
		$('main_image_corners').observe('click', navigate);
		/*
		END
		*/
		
		this.effect = false;
		this.next = 1;
		
		if(this.images.size() > 1)
			this.startRotate();
	},
	
	/*
	This is a special case due to the rounded corners image being on top of all the other images
	*/
	navigate: function(e)
	{
		window.location.href = this.images[this.index].title;
	},
	/*
	END
	*/
	
	navigateToTitle: function(e)
	{
		window.location.href = this.title;
	},
	
	switchImage: function(e)
	{
		var el = Event.element(e);
		if(el.hasClassName('selected'))
			return;
		this.pe.stop();
		
		if(this.effect)
		{
			this.cancelEffect();
		}
		
		var value = 0;
		var fade = false;
		this.images.each(function(e)
		{
			if(e.getOpacity() > value && e.visible())
			{
				value = e.getOpacity();
				fade = e;
			}
			else
			{
				e.setStyle({ opacity: 0, display: 'none' });
			}
		});
		
		
		this.next = parseInt(el.innerHTML) - 1;
		
		var next = this.next;
		
		this.setSelected(this.list[next]);
		
		var _this = this;
		
		this.effect = new Effect.Parallel(
		[
			new Effect.Fade(fade, { sync: true }),
			new Effect.Appear(this.images[next], { sync: true })
		], { afterFinish: function(e) { _this.effect = false; _this.startRotate(); _this.index = next; }, duration: _this.duration });
	},
	
	setSelected: function(el)
	{
		this.list.invoke('removeClassName','selected');
		el.addClassName('selected');
	},
	
	cancelEffect: function()
	{
		this.effect.cancel();
		this.effect = false;		
	},
	
	startRotate: function()
	{
		var crossFade = this.crossFade.bind(this);
		this.pe = new PeriodicalExecuter(crossFade, this.delay);
	},
	
	crossFade: function()
	{
		
		this.next = this.getNext();
		
		next = this.next;
		
		var selectTarget = this.getNext();
		
		this.setSelected(this.list[selectTarget]);
		
		var _this = this;

		this.effect = new Effect.Parallel(
		[
			new Effect.Fade(this.images[this.index], { sync: true }),
			new Effect.Appear(this.images[next], { sync: true })
		], { afterFinish: function(e) { _this.effect = false; _this.index = next; }, duration: _this.duration });	
	},
	
	getNext: function()
	{
		if(this.index < this.images.size() - 1)
		{
			return this.index + 1;
		}
		else
		{
			return 0;
		}
	}
}

