/**
 * Slideshow class
 * © 2011 Daniel Eneström (daniel [at] enestrom [dot] com)
 */
var Slideshow=$.Class.create({

	options: undefined,
	items: undefined,
	paging: undefined,
	delay: 5,
	currentSlide: null,
	currentIndex: -1,
	running: false,
	usepaging: false,

	/**
	 * Constructor
	 */
	initialize: function(options) {
		trace("Slideshow init");
		this.options = options;
		if (options.delay) this.delay = options.delay;
		
		if (options == undefined) {
			alert('The slideshow has options missing.');
			return false;
		}
		if (options.container == undefined) {
			alert('The slideshow container parameter is missing.');
			return false;
		}
		this.items = options.container.children();
		this.items.css('display','none');
		
		if (options.paging_container)
		{
			this.usepaging = true;
			var scope = this;
			this.items.each(function(index)
			{
				var code = '<li class="'+scope.options.paging_class+'" index="'+index+'"><a href="javascript:;" index="'+index+'">Image '+(index+1)+'</a></li>';
				scope.options.paging_container.append(code);
			});
			this.paging = options.paging_container.children();
			this.paging.click(function(){
				clearTimeout(scope.timeout);
				var index = $(this).attr('index');
				scope.showSlide(index);
				scope.timeout = setTimeout(function(){
					var thescope = scope;
					thescope.nextSlide();
				},10000);
			});
		}
		
		// Start the slideshow
		this.start();
	},
	
	start: function() {
		trace("Slideshow start");
		this.running = true;
		this.nextSlide();
	},
	
	stop: function() {
		this.running = false;
	},
	
	nextSlide: function() {
		trace("Slideshow nextSlide");
		if (this.running)
		{
			// Calculate next slide
			var nextIndex = this.currentIndex + 1;
			if (nextIndex > this.items.length -1)
			{
				nextIndex = 0;
			}
			if (nextIndex != this.currentIndex)
			{
				this.showSlide(nextIndex);
				
				// Call this function again
				var scope = this;
				scope.timeout = setTimeout(function(){
					var thescope = scope;
					thescope.nextSlide();
				},this.delay*1000);
			}
		}
	},
	
	showSlide: function(index) {
		trace("Slideshow showSlide("+index+")");
		
		// Hide current slide
		if (this.currentSlide)
		{
			this.currentSlide.fadeOut();
		}
		// Show new slide
		var nextSlide = this.items.eq(index);
		nextSlide.fadeIn(600);
		this.currentSlide = nextSlide;
		this.currentIndex = index;
		
		// Set paging item active
		if (this.usepaging)
		{
			this.paging.removeClass('active');
			var pageItem = this.paging.eq(index);
			pageItem.addClass('active');
		}
	}
	
});

function trace(str)
{
	if (console)
	{
		console.log(str);
	}
}
	
