﻿Tactica.Slideshow = function()
{
	this.fadeTime = 500; // ms
	this.slideArray = new Array();
	this.slideIndex = -1;
	this.swapTime = 5000 // ms;
	this.timer = null;
}

// creates a new slideshow in the specified element
Tactica.Slideshow.create = function(id)
{
	var target = $("#" + id);
	
	if (target.length > 0)
	{
		var slideshow = new Tactica.Slideshow();
		var w = target.width(), h = target.height();
		
		for (var i = 1; i < arguments.length; i++)
		{
			var slide = target.append(document.createElement("DIV"));
			var slideImage = Tactica.basePath + arguments[i];
			
			slide.addClass("slide");
			slide.css({backgroundImage:"url('" + slideImage + "')", left:"0px", overflow:"hidden", position:"absolute", top: "0px"});
			slide.height(h);
			slide.width(w);
			
			if (i > 1)
				slide.css("zIndex", 1).fadeTo(0, 0);
			else
				slide.css("zIndex", 2);
			
			slideshow.slideArray.push(slide);
		}
		
		slideshow.slideIndex = 0;
		slideshow.start();
		
		return slideshow;
	}
	
	return null;
}

// creates a new slideshow from an existing unordered list
Tactica.Slideshow.createFromList = function(id)
{
	var slides = $("#" + id + " > LI");
	
	if (slides.length > 1)
	{
		var slideshow = new Tactica.Slideshow();
		
		for (var i = 0; i < slides.length; i++)
		{
			var slide = slides.eq(i);
			
			if (i > 0)
				slide.css("zIndex", 1).fadeTo(0, 0);
			else
				slide.css("zIndex", 2);
			
			slideshow.slideArray.push(slide);
		}
		
		slideshow.slideIndex = 0;
		slideshow.start();
		
		return slideshow;
	}
	return null;
}

// shows the next slide
Tactica.Slideshow.prototype.nextSlide = function()
{
	var me = this;
	
	me.showSlide(me.slideIndex + 1);
}

// shows the previous slide
Tactica.Slideshow.prototype.previousSlide = function()
{
	var me = this;
	
	me.showSlide(me.slideIndex - 1);
}


// shows a specific slide and stops the slideshow
Tactica.Slideshow.prototype.showSlide = function(index, stop)
{	
	var me = this;
	if (index < 0)
	{
		index = me.slideArray.length - Math.abs(index) % me.slideArray.length;
	}	
	var i1 = me.slideIndex;
	var i2 = me.slideArray.length > 0 ? index % me.slideArray.length : 0;
	
	me.slideArray[i1].css("zIndex", 1).fadeTo(me.fadeTime, 0.0);
	me.slideArray[i2].css("zIndex", 2).fadeTo(me.fadeTime, 1.0);
	me.slideIndex = i2;
	
	if (stop)
	{
		me.stop();
	}
	
}

// starts the slideshow
Tactica.Slideshow.prototype.start = function()
{
	var me = this;

	if (typeof(me.timer) != "undefined")
	{
		window.clearInterval(me.timer);
	}
	
	me.timer = window.setInterval(function(){me.nextSlide()}, me.fadeTime + me.swapTime);
}

// stops the slideshow
Tactica.Slideshow.prototype.stop = function()
{
	var me = this;
	
	if (typeof(me.timer) != "undefined")
	{
		window.clearInterval(me.timer);
	}

	me.timer = null;
}

