var ssBorderColor = "#66CCCC";
var ssThumbBarWidth = 120;
var ssThumbsBarTop = 50;
var ssThumbsPerPage = 5;
var ssIsPlaying = true;
var ssCurIndex = -1;

//Set up, if there are pieces to show in the slide show
$(document).ready(function() {
	if(pieceList.length === 0) return; //no slide show if no pieces
	decodePieceStrings();
	
	var ssdiv = $("#SlideShowDiv");
	var titleDiv = $('<div id = "SSTitleDiv"></div>');
	var infoDiv = $('<div id = "SSInfoDiv"></div>');
	ssdiv.width(700);
	ssdiv.height(600);
	ssdiv.css({
		position:'relative',
		border: '1px solid ' + ssBorderColor,
		'text-align': 'left',
		'margin-top': 20
	});
	
	//Insert the title and info divs
	ssdiv.append(titleDiv);
	ssdiv.append(infoDiv);

	
	titleDiv.width(ssdiv.width() - ssThumbBarWidth);
	titleDiv.height(25);
	
	infoDiv.width(titleDiv.width());
	infoDiv.height(titleDiv.height());
	
	//Set up the title and info divs
	$.each([titleDiv, infoDiv], function() {
		this.css({
			position: 'absolute',
			left: 120,
			border: '1px solid ' + ssBorderColor,
			'border-right-style': 'none',
			'border-bottom-style': 'none',
			color: '#333333',
			'font-family': 'Arial, san-serif',
			'text-align': 'left'
		})
		this.append('<div class="SSText"></div>')
	});
	
	titleDiv.css({bottom: infoDiv.height()})
	infoDiv.css({bottom: 0 });
	
	
	$('.SSText', titleDiv).css({
		'padding-left': 21,
		'padding-top': 6,
		'font-size': 12,
		'font-weight': 'bold'
	});
	
	$('.SSText', infoDiv).css({
		'padding-left': 21,
		'padding-top': 7,
		'font-size': 11
	});
	
	//Create thumbnail paging buttons
	var prevButton = $('<div id="SSPrev"></div>');
	var nextButton = $('<div id="SSNext"></div>');
	$.each([prevButton, nextButton], function() {
		this.append('<img>');
		this.css({
			position:'absolute',
			bottom: 15
		});
		ssdiv.append(this);
	});
	prevButton.css({left: 16});
	nextButton.css({left: 86});
	
	//Create thumbnail page number display
	var pageNumView = $('<div id="SSPageNum"></div>');
	pageNumView.css({
		position: 'absolute',
		left: 32,
		bottom: 15,
		color: '#333333',
		'font-family': 'Arial, san-serif',
		'font-size': 12,
		'font-weight': 'bold',
		'text-align': 'center'
	});
	pageNumView.width(56);
	ssdiv.append(pageNumView);
	
	//Create the slide container
	var slideContainer = $('<div id="SlideContainer"></div>');
	slideContainer.css({
		position: 'absolute',
		top: 20,
		right: 20
	});
	
	slideContainer.width(540);
	slideContainer.height(510);
	
	ssdiv.append(slideContainer);
	
	//Show first page of thumbnails
	showThumbsPage(0);
	
	goURLPieceIfNeeded();
	
	//Run the slide show
	runSlideshow();
});

//URI decode string members of pieces
function decodePieceStrings(){
	$.each(pieceList, function(){
		this.name = decodeURIComponent(this.name);
		this.info = decodeURIComponent(this.info);
	});
}

//Proportionally scale an image so to some maximum width and height
function setMaxSize(img, maxWidth, maxHeight) {
	var w, h;
	w = img.width();
	h = img.height();
	var scale = Math.min(maxWidth/w, maxHeight/h);
	
	w = Math.ceil(scale*w);
	h = Math.ceil(scale*h);
	img.width(w);
	img.height(h);
}

function runSlideshow() {
	if(!ssIsPlaying) return;
	ssCurIndex++;
	if(ssCurIndex >= pieceList.length) ssCurIndex = 0;
	showSlide(pieceList[ssCurIndex]);
}

//Show a given page of thumbnails in the side bar
function showThumbsPage(pageNum) {
	var newThumbPage = $('<div></div>');
	var pagePieces = pieceList.slice(pageNum*5, pageNum*5 + 5);
	$.each(pagePieces, function() {
		newThumbPage.append(makeThumb(this));
		newThumbPage.append('<br>');
	});
	newThumbPage.css({
		position: 'absolute',
		left: 0,
		top: ssThumbsBarTop,
		'line-height': 0
	});
	newThumbPage.width(ssThumbBarWidth);
	newThumbPage.height(500);
	$('#SlideShowDiv').append(newThumbPage);
	
	var pageCount = Math.ceil(pieceList.length/5);
	
	//Set the nav button images
	var prevButton = $('#SSPrev > img');
	var nextButton = $('#SSNext > img');
	$.each([prevButton, nextButton], function() { this.unbind('click'); });
	if(pageNum > 0) {
		prevButton.prop('src', 'ssPrevEnabled.png');
		prevButton.click(function() {
			newThumbPage.remove();
			showThumbsPage(pageNum - 1);
		});
	} else {
		prevButton.prop('src', 'ssPrevDisabled.png');
	}
	
	if(pageNum+1 < pageCount) {
		nextButton.prop('src', 'ssNextEnabled.png');
		nextButton.click(function() {
			newThumbPage.remove();
			showThumbsPage(pageNum + 1);
		});
	} else {
		nextButton.prop('src', 'ssNextDisabled.png');
	}
	
	//Set the page number
	$("#SSPageNum").text((pageNum + 1) + ' of ' + pageCount);
}

function makeThumb(piece) {
	var thumbImg = $('<img>');
	thumbImg.prop('src', 'image.php?w=90&h=80&f=artists/' + artistID + '/art/' + piece.id + '/image.jpg');
	thumbImg.hide();
	thumbImg.css({
		'outline-style': 'solid',
		'outline-color': '#000000',
		'outline-width': 5
	});
	$('body').append(thumbImg);
	thumbImg.load(function() { setTimeout(function() {
		setMaxSize(thumbImg, 90, 80);
		var vMargin = 100 - thumbImg.height();
		thumbImg.css({
			'margin-top': vMargin/2,
			'margin-bottom': vMargin/2,
			'margin-left': (ssThumbBarWidth - thumbImg.width())/2
		})
		thumbImg.show();
	}, 1)});
	triggerLoadIfComplete(thumbImg);
	
	thumbImg.detach();
	
	thumbImg.hover(
	function() {
		if(!thumbImg.hasClass('selectedThumb')) {
			thumbImg.css({'outline-color': '#666666'});
		}
	}, function(){
		if(!thumbImg.hasClass('selectedThumb')) {
			thumbImg.css({'outline-color': '#000000'});
		}
	});
	
	thumbImg.click(function() {
		ssIsPlaying = false; //stop running the slideshow
		var oldSelectedThumb = $('.selectedThumb');
		oldSelectedThumb.css({'outline-color': '#000000'});
		oldSelectedThumb.removeClass('selectedThumb');
		
		thumbImg.addClass('selectedThumb');
		thumbImg.css({'outline-color': '#AAAAAA'});
		showSlide(piece);
		
		//Make the new url
		var loc = window.location.href;
		
		var poundIndex = loc.indexOf('#');
		//Remove any existing pound parameter
		if(poundIndex != -1) {
			loc = loc.slice(0,poundIndex);
		}
		//add the new pound parameter
		loc += "#" + piece.id;
		//Set the new window location
		window.location.href = loc;
	});
	
	return thumbImg;
}

//Set up the next slide so that it will fade in once it loads (fading out any current slide)

function showSlide(piece) {
	
	var slideContainer = $("#SlideContainer");
	
	var slideWidth = slideContainer.width();
	var slideHeight = slideContainer.height();

	var imageURL = 'image.php?w=540&h=510&f=artists/' + artistID + '/art/' + piece.id + '/image.jpg';
	
	var nextSlide = $('<div></div>');
	nextSlide.css({
		position: 'absolute',
		'background-color': '#FFFFFF'
	});
	
	nextSlide.append('<img src = "' + imageURL +' ">');
	
	//Create the next slide
	slideContainer.append(nextSlide);
	
	var img = $("img", nextSlide);
	
	img.hide();
	//When the slide loads:
	img.load(function () {
		setTimeout(function() { //delay slightly; workaround for cached image bug in Chrome
			//Fade in the slide
			nextSlide.fadeIn(1000, function() {
				$(".SSCurrentSlide").remove();
				//Move the slide backward
				nextSlide.css("z-index", "0");
				//Make the slide current
				nextSlide.addClass('SSCurrentSlide');
				setTimeout(function() {
					runSlideshow();
				}, 5000);
			});
			
			//Resize the image
			var w, h;
			w = img.width();
			h = img.height();
			var scale = Math.min(slideWidth/w, (slideHeight - 20)/h);
			
			w = Math.ceil(scale*w);
			h = Math.ceil(scale*h);
			img.width(w);
			img.height(h);
			
			//Center the image
			img.css("position", "absolute");
			img.css("left", (slideWidth - w)/2);
			img.css("top", (slideHeight - h - 10)/2);
			img.show();
			
			$('#SSTitleDiv > .SSText').text(piece.name);
			$('#SSInfoDiv > .SSText').text(piece.info);
		}, 1);
	});
	triggerLoadIfComplete(img);
	nextSlide.css("display","none");
	nextSlide.css("z-index","1");
	nextSlide.width(slideWidth);
	nextSlide.height(slideHeight);
	
}

//If a jquery image is complete, trigger its 'load' handlers
//	shouldUnbind: if true (default), unbind the load event handlers after firing
function triggerLoadIfComplete(img, shouldUnbind) {
	if(shouldUnbind == null) shouldUnbind = true;
	if(img.prop('complete')) {
		img.trigger('load');
		if(shouldUnbind) {
			img.unbind('load');
		}
	}
}

//If there's a piece in the URL return it, otherwise return -1
function getPieceIDFromURL(aURL) {
	var poundIndex = aURL.indexOf('#');
	if(poundIndex == -1) return -1;
	
	//If # sign found, return the ID (no checks for validity)
	return aURL.slice(poundIndex+1);
	
}

function goURLPieceIfNeeded() {
	//Check if there is a piece ID in the URL
	pieceID = getPieceIDFromURL(window.location.href);
	if(pieceID == -1) return; //no URL piece
	var piece;
	$.each(pieceList, function(){
		if(this.id == pieceID) {
			piece = this;
			return false; //done
		}
		return true;
	});
	if(piece) {
		ssIsPlaying = false; //stop running slide show
		showSlide(piece);
	}
}

