var pos = 0;
var count = 0;
var intervalID = 0;
var animating = false;
var interval = 4000;
var animation = 1000;

$(document).ready(function() {

	$('#gallery img').each(function(i)
	{
	this.id="galleryimage" + i;
	$('#gallerylinks ul').append("<li class='gallerylinkwrapper'><a href='#' class='gallerylink' id='gallerylink" + i + "'>" + (i+1) + "</a></li>");
	count++;
	}
	).hide();

	$('#gallerylink' + pos).html("[" + (pos+1) + "]");
	
	$('a.gallerylink').click(function() {
	clearInterval(intervalID);
	var nextpos = $(this).html() - 1;
	if(nextpos == -1)
		return false;
	moveNext(nextpos-pos);
	return false;
	});
	
$("#galleryprev").click(function() {
	clearInterval(intervalID);
	moveNext(-1);
	return false;
   });
$("#gallerynext").click(function() {
	clearInterval(intervalID);
	moveNext(1);
	return false;
   });


	$('#gallery img').not('#galleryimage' + pos).hide();
	$('#galleryimage' + pos).show();
	
	intervalID = setInterval(function(){moveNext(1);}, interval);
	
});

function moveNext(step)
{
	if(animating)
		return false;
	var current = $('#galleryimage' + pos);
	$('#gallerylink' + pos).html((pos+1));
	pos = pos + step;
	if(pos == count)
		pos = 0;
	if(pos < 0)
		pos = count-1;
	$('#gallerylink' + pos).html("[" + (pos+1) + "]");
	var next = $('#galleryimage' + pos);
	updateImages(current,next);
}

function updateImages(current,next)
{
	animating = true;

	current.css({'z-index':'1'});
	next.css({'z-index':'2'});
	next.fadeIn(animation, function(){current.hide();animating=false;});
}
