var has_trudev_framework = typeof( trudev ) === 'object';

// if not available, just create the namespace
if ( !has_trudev_framework )
{
	var trudev = {};
}

trudev.SlideShowManager = {

	slideshows:[],

	init: function()
	{
		var slideshows = $$( 'div.slideshow' ),
			i = slideshows.length;
		
		while ( i-- )
		{
			this.add( new trudev.SlideShow( slideshows[ i ] ) );
		}
	},

	add: function( slideShowObj )
	{
		this.slideshows[ this.slideshows.length ] = slideShowObj;
	},
	
	get: function( id )
	{
		var i = this.slideshows.length;

		while ( i-- )
		{
			var cur = this.slideshows[ i ];

			if ( cur.id === id )
				return cur;
		}

		return false;
	}
};

trudev.SlideShow = Class.create();
trudev.SlideShow.prototype = {

	htmlObj: null,
	id: '',
	slides: [],
	slideCount: 0,
	numbers: [],
	effectDuration: 0.3,
	index: 0,
	swapDelay: 5,
	swapTimeout: null,

	initialize: function( htmlObj )
	{
		this.id = 'slideShow' + ( Math.random().toString().split( '.' )[ 1 ] );
		this.htmlObj = htmlObj;
		this.htmlObj.id = this.id;
		this.initSlides();
		this.initNumberDisplay();
		
		this.createSwapTimeout();
	},

	initSlides: function()
	{
		this.slides = this.htmlObj.select( 'li' );
		this.slideCount = this.slides.length;
	},

	initNumberDisplay: function()
	{
		if ( this.slideCount <= 1 )
			return;

		var item_html = [];

		for  ( var i = 1; i <= this.slideCount; ++i )
			item_html[ i-1 ] = '<li><a href="javascript:trudev.SlideShowManager.get(\'' + this.id + '\').switchTo(' + ( i - 1 ) + ')">' + i + '</a></li>';

		this.htmlObj.insert( '<ul class="numberDisplay">' + item_html.join( '' ) + '</ul>' );
		this.numbers = this.htmlObj.select( '.numberDisplay a' );
		this.numbers[ 0 ].className = 'active';
	},

	switchTo: function( newIndex )
	{
		if ( this.index == newIndex || newIndex < 0 || newIndex >= this.slideCount )
			return;

		this.numbers[ this.index ].className = '';
		this.numbers[ newIndex ].className = 'active';
		this.numbers[ newIndex ].blur();

		if ( navigator.userAgent.indexOf( 'IE 6' ) == -1 )
		{
			new Effect.Fade( this.slides[ this.index ], { duration: this.effectDuration } );
			new Effect.Appear( this.slides[ newIndex ], { duration: this.effectDuration } );
		}
		else
		{
			this.slides[ newIndex ].setOpacity( 1 );
			this.slides[ this.index ].setOpacity( 0 );
		}

		this.index = newIndex;
		
		this.createSwapTimeout();
	},
	
	createSwapTimeout: function()
	{
		if ( this.slideCount <= 1 )
			return;

		clearTimeout( this.swapTimeout );
		this.swapTimeout = setTimeout( this.swap.bind( this ), this.swapDelay * 1000 );
	},
	
	swap: function()
	{
		var next_index = this.index + 1;
		this.switchTo( next_index >= this.slideCount ? 0 : next_index );
	}
};

if ( has_trudev_framework )
{
	trudev.Application.addComponent( trudev.SlideShowManager );
}