var images = [];
var imageelements = [];

$(document).ready (function ()  {

	$.post ('/homeajax.php', { request : "homeimages" }, function (json) {
		json = eval ('(' + json + ')');
		images = json.images;
		loadImages ();
	});

});

function loadImages()
{
	img = new Image ();


	img.onload = function ()
	{

		// Create an empty div, and stick it into the gallery
		var carouseldiv = document.createElement ('div');
		carouseldiv.id = 'carouseldiv';
		$(carouseldiv).appendTo ('#gallery');

		$(this).addClass ('active').click(function () {
			window.location =  this.title;
		}).appendTo ('#carouseldiv').css ('cursor', 'pointer');

		for (i = 0; i < images.length; i++)
		{
			var img = new Image ();
			img.src = '/gallery/'+images[i].src;
			$(img).css ('cursor', 'pointer').attr ({
				title : images[i].title
			}).click (function () {
				window.location = this.title;
			}).appendTo('#carouseldiv');
		}

		setInterval ("nextSlide()", 4000);
	}

	$(img).attr ( {
		src : '/gallery/'+images[0].src,
		title : images[0].title
		
	});
	
	$('#gallery p').html(images[0].title);
	
}

function nextSlide () {



	var active = $('#carouseldiv img.active');
	
	if (active.length == 0) active = $('#carouseldiv img:last');


	var next = active.next ().length ? active.next() : $('#carouseldiv img:first');
	 var p = $('#gallery p');

	active.addClass ('last-active');
	
	next.css ({opacity : 0.0 })
		.addClass ('active')
		
		.animate ({ opacity : 1.0 }, 2000, function () {
			active.removeClass ('active last-active');
			
			
		});
		
		p.html(next.attr('title'));
		p.css ({opacity : 0.0 })
		
		.animate ({ opacity : 1.0 }, 2000, function () {
			//active.removeClass ('active last-active');
			
			
		});

}
