var interval, gap = 3000,  container;

function rotateImages(container) {

    var current = $('#bg img.current'),
        next = $(current).next();

    if (next.length == 0) next = $('#bg img:first');

    $(current).addClass('previous').removeClass('current');

    $(next)
        .addClass('current')
        .css({ opacity: 0 })
        .animate({ opacity: 1 }, 1500, function() {
            $(current).removeClass('previous');
        });

}

function newRotation(){
	  var images = [
			"images/backgrounds/1a.jpg",
			"images/backgrounds/2a.jpg",
			"images/backgrounds/3a.jpg",
			"images/backgrounds/4a.jpg",
			"images/backgrounds/5a.jpg",
	      		"images/backgrounds/6a.jpg",
			"images/backgrounds/7a.jpg"
        ];
        //Preload
        $(images).each(function(){
           $('<img/>')[0].src = this; 
        });
       
        var index = 0;
        
        $.backstretch(images[index], {speed: 500});
        
		//Chain and animate
        setInterval(function() {
            index = (index >= images.length - 1) ? 0 : index + 1;
            $.backstretch(images[index]);
        }, 5000);
	}
function startAnimation() {

    stopAnimation();

   
	
	newRotation();

}

function stopAnimation() {

    $("#bg").find("img").stop(true,true);

    clearInterval(interval);

}

$(document).ready(function() {

    container = $("#bg");

    // create the home page animation
    if ($(container).find("img").length) startAnimation();
	
	newRotation();

});
