$(function()
{
	// Get JSON data of images
	$.get('/carousel', function(data) {

		if (! data.length) {
			return;
		}

		// Shuffle them
		data.sort(function() {
			return 0.5 - Math.random()
		});

		// Remove default image
		$('#image-carousel img').remove();

		// Load images
		for(var i=0;i<data.length;i++) {
			$('#image-carousel div').append(
				getHtml(data[i])
			);
		}

		// Start cycle
		$('#image-carousel div').cycle({
			timeout: 7000,
			speed: 800
		});
	}, 'json');
});

function getHtml(item)
{
	var img = '<img src="/assets/carousel/' +
		item.image + '" alt="' +
		item.caption + '" title="' +
		item.caption + '" width="620" height="250" />';

	if (item.url !== null && item.url.length) {
		img = '<a href="' + item.url + '">' + img + '</a>';
	}
	
	return img;
};
