var imageCount = 0;
var zIndexBase = 100;
var currentIndex = 1;
var galleryElementWidth = 0;
var waitTime = 5000;
var rotateTimeout;
var firstSrc;
var lastSrc;


$(document).ready(function() {
	imageCount = $('#homeImages span').length;
    $('#homeImages span').each(function(i) {
        if(i == 0) {
            $(this).css({'z-index' : i+2});
        } else {
            $(this).css({'z-index' : i+2, 'opacity' : 0});
        }
        if(i == imageCount-1) {
        	firstSrc = $('#homeImages span:eq(0)').children('img').attr('src');
        	firstTitle = $('#homeImages span:eq(0)').children('div').children('strong').html();
        	lastSrc = $('#homeImages span:eq('+(imageCount-1)+')').children('img').attr('src');
        	lastTitle = $('#homeImages span:eq('+(imageCount-1)+')').children('div').children('strong').html();
        }
    });
    $('#homeImages').prepend("<span><img alt='' src='"+lastSrc+"'/><div class='title-image'><strong>"+lastTitle+"</strong></div></span>");
    $('#homeImages').append("<span><img alt='' src='"+firstSrc+"'/><div class='title-image'><strong>"+firstTitle+"</strong></div></span>");
    $('#homeImages span:eq('+(imageCount+1)+')').css({'z-index' : (imageCount + 2), opacity: 0});
    $('#homeImages span:eq(0)').css({'z-index' : 1, opacity: 0});
    initGallery(currentIndex);
    
});

function initGallery(currentIndex) {
	rotateTimeout = setTimeout(function() {
		animateNextImage(currentIndex);
	}, waitTime);
};

function animateNextImage(index) {
    index++;
    currentIndex = index;
    $('#homeImages span').stop(true, true);
    $('#homeImages span:eq('+index+')').animate({'opacity' : 1}, {
        duration:1000, 
        queue:false, 
        easing:"swing",
        complete: function() {
            if(index-1 == imageCount) {
                $('#homeImages span:eq('+(imageCount)+')').css({opacity : 0});
                $('#homeImages span:eq('+(imageCount+1)+')').css({opacity : 0});
                $('#homeImages span:eq(1)').css({opacity : 1});
                currentIndex = 1;
            } else {
                $('#homeImages span:eq('+(index-1)+')').css({opacity : 0});
                $('#homeImages span:eq('+(index)+')').css({opacity : 1});
            }
        }
    });
    rotateTimeout = setTimeout(function() {
		animateNextImage(currentIndex);
	}, waitTime);
}
