var currentImage = 0;
var pe = null;
var imageContainer = null;
var caption = null;
var frameWidth = 600;
var frameHeight = 450;

function getImage(i) {
	return $('project_image_'+i);
}
function getThumb(i) {
	return $('project_thumb_'+i);
}

function showImage(i) {
	if (i == currentImage)
		return;

	var comingThumb = getThumb(i);
	var goingThumb = getThumb(currentImage);
	if (comingThumb != null)
		comingThumb.addClassName('current');
  if (goingThumb != null)
		goingThumb.removeClassName('current');
	
	var coming = getImage(i);
	var going = getImage(currentImage);

	if (coming != null) {
		var dim = coming.getDimensions();
		coming.setStyle({
			zIndex: 4,
			top: Math.round((frameHeight-dim.height)*0.5)+'px',
			left: Math.round((frameWidth-dim.width)*0.5)+'px'
		});
	}
	if (going != null)
		going.setStyle({zIndex: 5});

	if (coming != null)
		coming.appear({duration: 0.4});
	if (going != null)
		going.fade({duration: 0.5});
	
	if (coming.alt != '') {
		caption.show();
		caption.update(coming.alt);
	}
	else {
		caption.hide();
	}

	currentImage = i;
}

function showImageAndStop(i) {
	if (pe != null)
		pe.stop();
		
	showImage(i);
}

function nextImage() {
	var nextImage = currentImage + 1;
	if (getImage(nextImage) == null)
		nextImage = 1;
		
	showImage(nextImage);
}

function init() {
	imageContainer = $('project_images');
	caption = new Element('div',{id: 'project_caption'});
	caption.setOpacity(0.7);
	caption.hide();
	imageContainer.appendChild(caption);
	
	if (startImage == null) startImage = 1;

	showImage(startImage);
	if (getImage(currentImage) != null)
		pe = new PeriodicalExecuter(nextImage,5);
}

Event.observe(window,'load',init);
