var header1, header2, finv=.02, opv=1, doFade=true, nextImg=0, imDone="d";

function fade(){
	if(doFade){
		opv -= finv;
		header2.style.opacity = opv;
		header2.style.filter = 'alpha(opacity=' + opv*100 + ')';
		if(opv <= 0){ opv=1; doFade=false; ChangeCSSBgImg(); }
		setTimeout("fade()", 30);
	}
}

function ChangeCSSBgImg() {
	if (!document.getElementById) return false;
	
	var MyElement1 = "header1"; //The ID of the element you want to change
	var MyElement2 = "header2";
	var ImgPath = "images/"; //The file path to your images
	
	if (!document.getElementById(MyElement1)) return false;
	
	var random_images = new Array ();
	random_images[0] = "header_home.jpg"; // Don't forget to increase the array number each time
	random_images[1] = "header_home2.jpg";
	random_images[2] = "header_home3.jpg";
	random_images[3] = "header_home4.jpg";

	header2 = document.getElementById(MyElement2);
	header1 = document.getElementById(MyElement1);
	header2.style.backgroundImage = header1.style.backgroundImage;
	header2.style.opacity = 1;
	header2.style.filter = 'alpha(opacity=' + 100 + ')';
	var $backgroundurl = header1.style.backgroundImage;
	var ImgURL = "url(" + ImgPath + random_images[nextImg] + ")";
	
	if ($backgroundurl != ImgURL) {
		header1.style.backgroundImage = ImgURL;
	}
	
	
	setTimeout("doFade=true; fade()", 5000);

	last = nextImg;
	while(nextImg == last) nextImg = rand(random_images.length);
	if(!imDone.match("" + nextImg)){
		pre = new Image();
		pre.src = ImgPath + random_images[nextImg];
		imDone += " " + nextImg + " ";
	}
}

/* random number generator */
function rand(n) {
  return ( Math.floor ( Math.random ( ) * n ) );
}

/* Custom onload function */
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
/* trigger onload */
addLoadEvent(ChangeCSSBgImg);
