﻿var ImageRotator = function()
{
	var index = 0;
	var images = [];
	var imageElement = null;
	var textElement = null;
	var loadingElement = null;
	var buttonClicked = false;
	
	var navigationElement = null;
	
	var initialize = function()
	{
		imageElement = document.getElementById("slideImage");
		textElement = document.getElementById("slideText");
		loadingElement = document.getElementById("slideLoading");
		
		navigationElement = document.getElementById("slideshowNavigation");
		window.setTimeout(function() { fadeIn(15); }, 500);
		
		document.getElementById("previous").onclick = gotoPrevious;
		document.getElementById("next").onclick = gotoNext;
	};
	
	var fadeIn = function(i)
	{
		navigationElement.style.marginTop = (401- 2 * i) + "px";

		navigationElement.style.opacity = 0.7 * (1 - i / 15);
		navigationElement.style.filter = "alpha(opacity=" + (70 * (1 - i / 15)) + ")";	
		
		if(i > 0)
			window.setTimeout(function() { fadeIn(i-1) }, 25);
		else
			window.setTimeout(function() { bounce(2); }, 6000);
	};
	
	var bounce = function(repeat)
	{
		if(buttonClicked)
			return;
	
		var positions = [];
		
		var a = 12 // 6 + 2 * repeat // The number of frames
		var	b = 25 // 8 * repeat; // The height
		
		for(var i=0; i<=a; i++)
		{
			positions[i] = - ((4 * b)/(a * a)) * i * (i - a);
		}
	
		var frame = 0;
		
		var gotoNextFrame = function()
		{
			frame++;

			navigationElement.style.marginTop = (401 - positions[frame]) + "px";
			
			if(frame < a)
				window.setTimeout(gotoNextFrame, 25);
			else if(repeat > 0)
				window.setTimeout(function() { bounce(repeat-1); }, 0);
			else
				window.setTimeout(function() { bounce(2); }, 20000);
		};
		
		gotoNextFrame();
	};
	
	var addImage = function(imageUrl, left, top, width, imageText)
	{
		var image = new Image();
		image.src = imageUrl;
		
		images.push({
			image : image,
			url : imageUrl,
			left : left,
			top : top,
			width : width,
			text : imageText
		});
		
		if(imageElement == null)
			initialize();
	};

	var gotoPrevious = function()
	{
		buttonClicked = true;
		index = (index == 0 ? images.length - 1 : index - 1);
		showImage();
	};
	
	var gotoNext = function()
	{
		buttonClicked = true;
		index = (index == images.length - 1 ? 0 : index + 1);
		showImage();
	};
	
	var showImage = function()
	{
		imageElement.onload = function()
		{
			textElement.innerHTML = images[index].text;
			loadingElement.style.display = "none";
		};

		loadingElement.style.display = "block";
		imageElement.src = images[index].url;
	};

	var pub = {
		addImage : addImage
	};

	return pub;
}();