var images = new Array();
var active = new Array();
var switching = new Array();
var interval = new Array();
var imageWidth = 800;

$(document).ready(function() {
		
	//Resize container
	var container = $('.homeGallery ul');
	container.css('margin-left', 0);
	container.css('width', (container.find('li').length * 790))

	container.each(function(key, thisContainer) {
	
		var id = thisContainer.id;	
		active[id] = 0;
		switching[id] = false;
		
		//Images
		images[id] = $(thisContainer).find('li');
		if(images[id].length == 0)
			return false;
		
		//Auto scroll
		interval[id] = setInterval("showNext('"+id+"')", 4000)

		//Create navigation buttons
		var gallery = $(thisContainer).parent();
		var height = gallery.height();
	
		var next = document.createElement('div');
		next.className = 'next nav';
		
		var prev = document.createElement('div');
		prev.className = 'prev nav';
		
		gallery.append(prev);
		gallery.append(next);
		
		$(next).fadeTo(0, 0);
		$(prev).fadeTo(0, 0);
	
		$(gallery).bind('mouseover', function(e) {
			$(this).find('.nav').fadeTo(0, 0.5);
			clearInterval(interval[id])
		})
		$(gallery).bind('mouseout', function(e) {
			$(this).find('.nav').fadeTo(0, 0);
			interval[id] = setInterval("showNext('"+id+"')", 4000)
		})
		
		$(next).css('height', height);
		$(prev).css('height', height);
		$(next).css('margin-top', -height);
		$(prev).css('margin-top', -height);
		
		$(next).bind('click', function() { showNext(id) } )
		$(prev).bind('click', function() { showPrev(id) } )
		
		var width = gallery.width()
		$(next).css('margin-left', (width-$(next).width()))
		
	})

})

function showNext(id) {
	show(1, id)
}

function showPrev(id) {
	show(-1, id)
}

function show(step, id) {

	if(switching[id])
		return false;
	
	switching[id] = true;

	//Calculate next image
	newActive = active[id] + step;

	if(newActive < 0)
		newActive = images[id].length-1;
	else if(newActive > (images[id].length-1))
		newActive = 0;
		
	//Switch!
	if((newActive == 0 && step > 0) || (step < 0 && active[id] == 0))
		speed = 800;
	else
		speed = 300	
	
	$('#'+id).animate({'left' : (-newActive*imageWidth) }, speed);	
	
	active[id] = newActive;
	
	switching[id] = false;

}
