/*
 * A Simple slide show with fading transitions
 * Justin Longbottom
 * <justin@giantgoat.com>
 * Dec 16, 2010
 */

var current = 0;
var num;
var delay = 5000; //how long between slides
var fade = 1000; //how long the fade transition will take
var text = 'alt text';
var t;

$(document).ready(function() {
	num = $('.slides img').length-1; //how many slides there are
	$('.slides img:gt(0)').hide(); //hide all but the first one
	
	var width = $('.slides img').width();
	var height = $('.slides img').height();
	$('#gallery').css({width:width});
	$('.slides').css({height:height});
	$('#slide_info').css({height:height-20, padding:'10px'});
	$('.slides').after('<div id="controls" style="float:right;"></div>');
	$('#controls').append('<a href="#_" id="prev" style="float:left;padding:2px 5px;" onclick="skip(-1); return false;"><<</a>');
	$('#controls').append('<a href="#_" id="next" style="float:right;padding:2px 5px;" onclick="skip(1); return false;">>></a>');
	
	//give each image an ID, the necessary CSS, and a button to skip to it
	$('.slides img').each(function(index) {
		$(this).attr('id',index);
		$(this).css({position:'absolute',left:0,top:0});
		$('#controls').append('<a href="#_" id="control'+index+'" style="float:left;padding:2px 5px;" onclick="skipTo('+index+'); return false;">'+(index+1)+'</a>');
	});
	
	$('#control'+current).addClass('active');
	
	updateText();
	
	t = setTimeout(function(){
			skip(1)
		}, delay);
});

//grab alt text of current image and put in #slide_info DIV
function updateText() {
	text = $('#'+current).attr('alt');
	$('#slide_info').html(text);
}

//skip forwards or back
function skip(direction) {
	t = clearTimeout(t);
	$('#'+current).fadeOut(fade);
	$('#control'+current).removeClass('active');
	
	if(direction == 1) { // 1 = skip ahead
		current++;
		if(current > num) current = 0;
	} else {
		current--;
		if(current < 0) current = num;
	}
	
	$('#control'+current).addClass('active');
	$('#'+current).fadeIn(fade);
	updateText();
	t = setTimeout(function(){
			skip(1)
		}, delay);
}

//skip to a particular image
function skipTo(image) {    
	$('#'+current).fadeOut(fade);
	$('#control'+current).removeClass('active');
	current = image;
	$('#control'+current).addClass('active');
	$('#'+image).fadeIn(fade);
	updateText();
	t = setTimeout(function(){
			skip(1)
		}, delay);
	return false;
}
