window.addEventListener?window.addEventListener("load",init,false):window.attachEvent("onload",init);

var currentOpacity = 1.00;
var currentBackground = "";
var newBackground = "";
var switchInterval = 10000;
var backgroundPath = "templates/default/images/backgrounds/";
var backgrounds = new Array("01.jpg", "02.jpg", "03.jpg" , "04.jpg", "05.jpg", 
						"06.jpg", "07.jpg");

function init(){
	preload_images();
	currentBackground = document.getElementById("background").style.backgroundImage;
	if(currentOpacity > 0){
		setTimeout(fadeOut, switchInterval);
	} else {
		do {
			newBackground = getRandomImage();
		} while(newBackground == currentBackground);
		currentBackground = newBackground;
		document.getElementById("background").style.backgroundImage = currentBackground
		fadeIn();
	}
}

function fadeOut(){
	currentOpacity -= 0.05;
	fade(document.getElementById("background"));
	if(currentOpacity > 0){
		setTimeout(fadeOut,5);
	} else {
		setTimeout(init,5);
	}
}

function fadeIn(){
	currentOpacity += 0.05;
	fade(document.getElementById("background"));
	if(currentOpacity < 1){
		setTimeout(fadeIn,5);
	} else {
		setTimeout(init,5);
	}
}

function fade(obj){
	obj.style.MozOpacity = currentOpacity;
	obj.style.Opacity = currentOpacity;
	obj.style.filter = "alpha(opacity=" + (currentOpacity * 100) + ")";
}


function getRandomImage(){
	var randomIndex = Math.floor( Math.random() * backgrounds.length );
	return "url("+ backgroundPath + backgrounds[randomIndex] +")";
}

function preload_images(){
   for (var i = 0; i < backgrounds.length; i++) {
         (new Image()).src = backgrounds[i];
   }
}