// JavaScript Document

var playing = false;
var interval;
var currentIndex = 0;
var dateDisplay = getElement('dateDisplay');
var seriesImage = getElement('series_image');
var playElement = getElement('play');
var largeImage = getElement('view_large');

var images; // should be populated by enclosing code

function TSImage(image_path, large_image_path, date_formatted_long, date_formatted_nav) {
	this.image_path = image_path;
	this.large_image_path = large_image_path;
	this.date_formatted_long = date_formatted_long;
	this.date_formatted_nav = date_formatted_nav;
	this.image = new Image();
}

function play() {
	// so we don't launch multiple play threads
	if (playing === false) {
		playing = true;
		interval = window.setInterval(playNextImage,1000);
		// switch play button image to pause
		playElement.innerHTML = "pause";
	} else {
		// since the play button has been hit again, pause the looping
		stop();
	}
}

// a wrapper around nextImage for "playing"
// this will ensure that the current image has loaded before
// proceeding to the next image so that any lag is dealt with.
function playNextImage() {
	if (images[currentIndex].image.complete) {
		if (currentIndex+1 >= images.length) {
			currentIndex = 0;
		} else {
			currentIndex += 1;
		}
		
		showImage(currentIndex);
	}
}

function stop() {
	if (playing === true) {
		playing = false;
		window.clearInterval(interval);
		playElement.innerHTML = "play";
	}
}

function showImage(index) {
	dateDisplay.innerHTML = images[index].date_formatted_long;
	
	// assign the path to the image object
	images[index].image.src = images[index].image_path;
	
	// this is the line that actually tells the image to display
	seriesImage.src = images[index].image.src;
	
	// if there is a large image for this image, link it
	if (images[index].large_image_path != '') {
		largeImage.innerHTML = "<span class=\"separator-margin\">&middot;</span><a href='"+ images[index].large_image_path +"'>view large</a>";
	} else {
		largeImage.innerHTML = "";	
	}

	// make the current link black, all others should not be black
	for (var i = 0; i < images.length; i++) {
		if (i == index) {
			getElement("link_"+i).className = "black";
		} else {
			getElement("link_"+i).className = "none";
		}
	}
}

// this is for selecting a specific image from the navigation
function selectImage(index) {
	stop();
	currentIndex = index;
	showImage(index);
}
