$(function() {    
    if ($('#carousel').length) {        
        carouselTimeout = window.setTimeout(carouselRandom, 5000);
    }
});


function carouselNext() {
    var carousel = $('#carousel');
    var visibleImage = carousel.find('img:visible');
    var nextImage = visibleImage.next('img');
	
	if (!nextImage.length) {
		nextImage = $("#pic1");
	}
    
    visibleImage.fadeTo(800, 0, function() {
        visibleImage.hide().css('opacity', '1'); // If opacity is not set to 1, the next fadein will fail.
    });
    
    nextImage.fadeIn(800, 0, function() {
        nextImage.show();
    });
    
    carouselTimeout = window.setTimeout(carouselNext, 5000);
}


function carouselRandom() {
    var carousel = $('#carousel');
    var imageCount = carousel.find('img').length;
    var visibleImage = carousel.find('img:visible');
    var visibleIndex = parseInt(visibleImage.attr('id').substr(3,1));
    var nextIndex = visibleIndex;
    
    while (nextIndex == visibleIndex) {
        nextIndex = Math.round(Math.random() * imageCount);     
        if (nextIndex == 0) nextIndex = visibleIndex; // Rolled an non-existing zero index, force reroll.
    }

    var nextImage = carousel.find('img:nth-child(' + nextIndex + ')');
    
    visibleImage.fadeTo(800, 0, function() {
        visibleImage.hide().css('opacity', '1'); // If opacity is not set to 1, the next fadein will fail.
    });
    
    nextImage.fadeIn(800, 0, function() {
        nextImage.show();
    });
    
    carouselTimeout = window.setTimeout(carouselRandom, 5000);
}
