var num = 0;
var preloads = new Array();

var bg_imgArr = [
	"/img/bg/hero_gs450h.jpg",
	"/img/bg/2012-01-20.jpg",
	"/img/bg/hero_wallabies.jpg",
	"/img/bg/is350.jpg"
];

var bg_linkArr = [
	"/hybrid/index.htm",
	"/content/Document/Demonstrator-Showcase-Event.pdf",
	"http://www.lexus.com.au/lexus/sponsorships/#0",
	"/page/Models/Luxury_Sedans/IS/IS350/"
];

function show() {
	var old_num = num;
	num++;
	if(num > bg_imgArr.length-1) {
		num = 0;
	}

	tDiv = "div"+old_num;
	vDiv = "div"+num;

	if($(tDiv).fx){$(tDiv).fx.stop();}
	if($(vDiv).fx){$(vDiv).fx.stop();}
	$(tDiv).fx = $(tDiv).effect('opacity', {duration: 1000}).start(0);
	$(vDiv).fx = $(vDiv).effect('opacity', {duration: 1000}).start(1);
	$(vDiv).fx.fireEvent('onStart', switchLayer(), 10);
}

function switchLayer() {
	i = 0;
	while (document.getElementById("div" + i)) {
		if (num == i) {
			document.getElementById("div" + i).style.zIndex = 2;
		} else {
			document.getElementById("div" + i).style.zIndex = 1;
		}
		i++;
	}
}

function preloadImages() {
	preloads = new Array();

	var i;
	for (i = 0; i < bg_imgArr.length; i++) {
		preloads[i] = new Image();
		preloads[i].src = bg_imgArr[i];
	}
}

function insertDivs() {
	document.getElementById("hero").innerHTML = "";

	var i;
	for (i = 0; i < bg_imgArr.length; i++) {
		// Make external links and PDFs open in new windows
		var target = (bg_linkArr[i].indexOf('http://') > -1 || bg_linkArr[i].indexOf('.pdf') > -1) ? '_blank' : '_self';

		document.getElementById("hero").innerHTML +=
			'<div id="div'+i+'" style="position:absolute; opacity: 0; filter:alpha(opacity = 0); z-index:1;">'+
				'<a href="'+bg_linkArr[i]+'" target="'+target+'">'+
					'<img id="image'+(i+1)+'" src="'+bg_imgArr[i]+'" border="0" />'+
				'</a>'+
			'</div>';
	}
}

function rotate() {
	setTimeout(rotate, 7000);
	show();
}

function start() {
	document.getElementById("hero").style.left = "50%";
	document.getElementById("hero").style.marginLeft = "-500px";
	document.getElementById("hero").style.width = "1000px";
	document.getElementById("hero").style.height = "100%";
	document.getElementById("hero").style.zIndex = "0";
	document.getElementById("hero").style.position = "absolute";

	preloadImages();
	insertDivs();
	rotate();
}
