jQuery(function(){

// image slideshow

var photoContainer = jQuery('#photoContainer');
var caption = jQuery('#captionWrapper');
var previousPhoto = jQuery('#previousPhoto');
var nextPhoto = jQuery('#nextPhoto');
var currentIndex;
var slideshowInterval;

// add photos for preload
for (var i = 0; i < photoList.length; i++) {
	var p = photoList[i], img = new Image(), lnk = document.createElement("a");
	img.setAttribute('alt', p.Title);
	img.src = p.SRC;
	photoList[i]['Image'] = img;
	lnk.setAttribute('href', p.Link);
	photoList[i]['Link'] =  lnk;
}
//console.dir(photoList);

function showImage(i) {
	if (i == currentIndex) return;
	photoContainer.html('');
	caption.html(photoList[i]['Description']);
	currentIndex = i;
	photoContainer.append(photoList[i]['Image']);
	//photoContainer.html('<img src="' + photoList[i]['SRC'] + '" alt="' + photoList[i]['Title'] + '">');
	// display immediately if loaded
	if (photoList[i]['Image'].complete) {
		photoContainer.append(photoList[i]['Image']);
		// add link to the image
		jQuery('#photoContainer img').wrap(photoList[i]['Link']);
	}
	// otherwise, set an onload event and display later
	else {
		photoList[i]['Image'].onload = function(){
			photoContainer.append(photoList[i]['Image']);			
			// add link to the image
			jQuery('#photoContainer img').wrap(photoList[i]['Link']);
		};
	}
}

previousPhoto.click(function(){
	if (slideshowInterval) {
		window.clearInterval(slideshowInterval);
		slideshowInterval = false;
	}
	showImage(currentIndex == 0 ? photoList.length - 1 : currentIndex - 1);
	return false;
});

nextPhoto.click(function(){
	if (slideshowInterval) {
		window.clearInterval(slideshowInterval);
		slideshowInterval = false;
	}
	showImage(currentIndex == photoList.length - 1 ? 0 : currentIndex + 1);
	return false;
});

slideshowInterval = window.setInterval(function(){
	showImage(currentIndex == photoList.length - 1 ? 0 : currentIndex + 1);
}, loopInterval);

showImage(0);

});