window.addEventListener?window.addEventListener("load",so_init,false):window.attachEvent("onload",so_init);

var d=document, 
	zoomfactor = 0.5,
	opacity_step = .01,
	imgs = new Array(),
	first_run = true,
	zInterval = null,
    container_width = 0,
	container_height = 0,
	current=0, 
	nIndex=0, 
	pause=false, 
	interval_xfade=50, 
	interval_pause=3000,
	interval_zoom=50;

function so_init() {

	if(!d.getElementById || !d.createElement)
		return;
	
	imgs = d.getElementById("imageContainer").getElementsByTagName("img");
	
	if (imgs == null)
		return;
		
	container_width = d.getElementById("imageContainer").clientWidth;
	container_height = d.getElementById("imageContainer").clientHeight;

	for (i = 1; i < imgs.length; i++) {
		imgs[i].xOpacity = 0;
	}
	
	interval_size_chk = interval_xfade/opacity_step;
	
	if (0 in imgs) {
		imgs[0].style.display = "block";
		imgs[0].xOpacity = .99;
		xFade();
	}
	
}

function xFade() {

	nIndex = imgs[current+1]?current+1:0;	
	cOpacity = imgs[current].xOpacity;
	nOpacity = imgs[nIndex].xOpacity;

	/* if (first_run)
		zoomPic();
	*/
		
	// first_run = false;

	cOpacity-=opacity_step; 
	nOpacity+=opacity_step;
	
	imgs[nIndex].style.display = "block";
	imgs[current].xOpacity = cOpacity;
	imgs[nIndex].xOpacity = nOpacity;
	
	setOpacity(imgs[current]); 
	setOpacity(imgs[nIndex]);
	
	if (cOpacity <= 0) {
	
		imgs[current].style.display = "none";
		current = nIndex;
		nIndex = imgs[current + 1] ? current + 1 : 0;
		setTimeout(xFade, interval_pause);
	// zoomPic();
	}
	else {
	
		setTimeout(xFade, interval_xfade);
		
	}


	function setOpacity(obj) {

		if(obj.xOpacity>.99) {
			obj.xOpacity = .99;
			return;
		}

		obj.style.opacity = obj.xOpacity;
		obj.style.MozOpacity = obj.xOpacity;
		obj.style.filter = "alpha(opacity=" + (obj.xOpacity*100) + ")";
	}

}

function zoomPic() {

	if ((imgs[current].width - container_width > 0) && (imgs[current].height - container_height) > 0)
		cprefix = -1;
	else
		cprefix = 1;
	
	if ((imgs[nIndex].width - container_width > 0) && (imgs[nIndex].height - container_height) > 0)
		nprefix = -1;
	else
		nprefix = 1;

	setZoom(current, cprefix);
	setZoom(nIndex, nprefix);
}

function setZoom(num, prefix) {

	if (imgs[num].style.display != 'none' && 
		((imgs[num].width - container_width) > 0 && (imgs[num].height - container_height) > 0)) {
	
		console.debug(num+", "+zoomfactor*prefix);

		imgs[num].width += zoomfactor*prefix;
		imgs[num].height += zoomfactor*prefix;
	
		setTimeout(function(){setZoom(num, prefix)}, interval_zoom);
	} 
}

