// Usage note: the div that contains the rotation should be IDed 'rotator'

// Global variables
var duration = 3000; // How long each image is displayed before moving to the next
var fade = 3000;
var img_loc = 'http://clients.tierratechnology.com/spin/wp-content/themes/spin/images/homepage/'; // Prefix path to images
// List of homepage images
var images = [
	'auto_show.jpg',
	'alcatraz.jpg',
	'motorcycle.jpg'
];
var img_num = 0;

// ==================================================================

// These functions control the guts of the image rotation

function display_image(prev, next) {
	prev.get('tween', {property: 'opacity', duration: fade}).start(0);
	next.get('tween', {property: 'opacity', duration: fade}).start(1).chain(function() {
		rotate_images.delay(duration);
	});
}

function rotate_images() {
	var prev = $('img-' + img_num);
	img_num++;
	if (img_num == images.length) {
		img_num = 0;
	}
	if ($('img-' + img_num)) {
		// Already exists
		display_image(prev, $('img-' + img_num));
	} else {
		var new_image = new Asset.image(img_loc + images[img_num], {
			id: 'img-' + img_num,
			onload: function() {
				new_image.setStyle('opacity', 0).inject($('rotator'));
				display_image(prev, new_image);
			}
		});
	}
}

// ==================================================================

window.addEvent('domready', function() {
	// Stick whichever image ended up first into the placeholder
	$('rotator').getElement('.placeholder').destroy();
	$('rotator').grab(new Element('img', {
		id: 'img-0',
		src: img_loc + images[0],
		alt: ''
	}));
	rotate_images.delay(duration);
});