//List of artists and their associated pieces
var slideshowList;

//Document finished loading. Set up the slideshow
$(document).ready(function () {
	var jsonURL = "/cgi-bin/homeslideshow.cgi";
	$.getJSON(jsonURL, function(data) {
		data = decodeJSONStrings(data);
		if(data[0] !== null){ //On load
			console.log('Error creating slideshow');
			return;
		}
		var obj = data[1];
		//Flatten the list
		slideshowList = $.map(obj, function(artist, i) {
			return $.map(artist.art, function(piece, j){
				return {
					artistName:	artist.name,
					artistID:	artist.id,
					pieceName:	piece.name,
					pieceID:	piece.id,
					order: Math.random() //used for shuffling
				};
			});
		});
		//shuffle
		slideshowList.sort(function(a,b) { return a.order - b.order;} );
		
		startSlideShow();
	});
});


//Take a JSON object returned by an AJAX request and recursively URI decode its
//keys and values (recursively)
function decodeJSONStrings(data) {
	if(data === null) return null; //null is a special case
	
	var outData;
	
	if($.isArray(data)) {
		outData = []; //array
	} else {
		outData = {}; //object
	}
	
	$.each(data, function(k, v) {
		//If key is a string, decode it
		if('string' === typeof k) {
			k = decodeURIComponent(k);
		}
		
		//Handle different types differently
		switch(typeof v) {
			case 'string':
				v = decodeURIComponent(v); //decode the string
				break;
			case 'object':
				v = decodeJSONStrings(v); //recurse
				break;
		}
		//Save to output object
		outData[k] = v;
	});
	return outData;
}

function startSlideShow() {
	//Set up the next slide
	setupNextSlide();
}

//Set up the next slide so that it will fade once it loads
//The slide is shifted from the beginning of the slideshow list, and pushed back to the end.
function setupNextSlide() {
	if(!slideshowList.length) return; //no slides to show
	//Get the next slide data
	var slideData = slideshowList.shift();
	//Push the data back to the end of the list
	slideshowList.push(slideData);
	
	var slideWidth = $("#SlideshowCell").width();
	var slideHeight = $("#SlideshowCell").height();
	
	//Create the next slide
	$("#SlideshowCell").append(
		'<div id = "SSNextSlide" style = "' +
			'position:absolute; ' +
			'background-color:#FFFFFF;">' +
			'<a href = "cgi-bin/artist.cgi?id=' + slideData.artistID + '#' + slideData.pieceID + '">' +
			'<img src = "image.php?w=600&h=600&f=artists/' + 
				slideData.artistID + '/art/' + slideData.pieceID + '/image.jpg' +
			'" + alt = "' + slideData.artistName + ': ' + slideData.pieceName + '"' +
			'" + title = "' + slideData.artistName + ': ' + slideData.pieceName + '"' +
			'border = "0"></a></div>');
	
	var nextSlide = $("#SSNextSlide");
	//Add the caption
	nextSlide.append("<div class=\"SSCaption\">" + slideData.artistName + "</div>");
	var caption = $("#SSNextSlide > .SSCaption");
	caption.width('100%');
	caption.css("position", "absolute");
	caption.css("text-align", 'center');
	caption.css("font-family", "Verdana");
	caption.css("font-size", "10px");
	caption.css("font-weight", "bold");
	//Center the caption
	//caption.css("left", (slideWidth - caption.width())/2);
	caption.css("bottom", 0);

	
	var img = $("#SSNextSlide img");
	
	img.hide();
	//When the slide loads:
	img.bind('load', function () {
		setTimeout(function() { //delay slightly; workaround for cached image bug in Chrome
			//Fade in the slide
			$("#SSNextSlide").fadeIn(1000, slideFadeFinished);
			
			//Resize the image
			var w, h;
			w = img.width();
			h = img.height();
			var scale = Math.min(slideWidth/w, (slideHeight - 20)/h);
			
			w *= scale;
			h *= scale;
			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();
		}, 1);
	});

	$("#SSNextSlide").css("display","none");
	$("#SSNextSlide").css("z-index","1");
	nextSlide.width(slideWidth);
	nextSlide.height(slideHeight);
	
}

//Callback for when the current slide finishes fading in
function slideFadeFinished() {
	//Remove the current slide
	$("#SSCurrentSlide").remove();
	//Make the next slide the current slide
	$("#SSNextSlide").attr("id", "SSCurrentSlide");
	//Move the current slide backward
	$("#SSCurrentSlide").css("z-index", "0");
	
	setTimeout(setupNextSlide, 3000);
}
