
// define Array.shuffle()
Array.prototype.shuffle = function() {
	var len = this.length;
	for (var i=0; i < len; i++) {
        var rand = Math.floor(Math.random()*len);
		//swap current index with a random one
		var temp = this[i];
		this[i] = this[rand];
		this[rand] = temp;
	}
}

var gHeaderCarouselImageNames = [
	'img1.jpg', 
	'img2.jpg', 
	'img3.jpg',
	'img4.jpg',
	'img5.jpg',
];

// shuffle the array so we always can start at 0 and know to start pre-loading from the beginning of the array
gHeaderCarouselImageNames.shuffle();

// instantiating Image objects here defines the preloads them from the server
var gHeaderCarouselImages = [];
gHeaderCarouselImageNames.each(function(name) {
	var img = new Image(1, 1);
	img.src = 'themes/shared/header-carousel/images/' + name;
	
	gHeaderCarouselImages.push(img);
});


var gHeaderCarouselDivs = [];

var gHeaderCarouselIndex = 0;

function next_carousel_slide()
{
	var oldEl = gHeaderCarouselDivs[gHeaderCarouselIndex];
	gHeaderCarouselIndex = (gHeaderCarouselIndex + 1) % gHeaderCarouselDivs.length;
	var newEl = gHeaderCarouselDivs[gHeaderCarouselIndex];
	

	Effect.Fade(oldEl, {duration: .5 });
	Effect.Appear(newEl, { duration: .5 });

	// schedule next transition
	next_carousel_slide.delay(7);
}

function init_header_carousel()
{
	var w = $('container').getWidth();
	var h = $('header').getHeight();

	// write in the style and content for the header carousel
	// NOTE: this is fetching values set by the theme
	$('header-carousel').setStyle({
		width: w + 'px',
		height: h + 'px'
	});

	// write in the slides
	gHeaderCarouselImages.each(function(img, index) {
		$('header-carousel').insert('<div class="slide" style="display: none; width: ' + w + 'px; height: ' + h + 'px; background: url(' + img.src + ') no-repeat right;"></div>');
	});


	// save an array of all the slides we created
	$('header-carousel').select('.slide').each(function(el) {
		gHeaderCarouselDivs.push(el);
	});

	// start the rotation
	next_carousel_slide();
}

