/*
	Image Crossfader, with random display order
	By Ryan Conway

	Based on original:
		Image Cross Fade Redux, Version 1.0, Last revision: 02.15.200 by steve@slayeroffice.com
*/

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

var d=document, imgs = new Array(), zInterval = null, current=0, pause=false, nextImg=1, pastA=1, pastB=1, pastC=1, pastD=1, pastE=1, pastF=1, pastG=1;

function so_init()
{
	if(!d.getElementById || !d.createElement)return;

	css = d.createElement('link');
	css.setAttribute('href','http://mindcandy.com/wp-includes/js/recruitment/slideshow.css');
	css.setAttribute('rel','stylesheet');
	css.setAttribute('type','text/css');
	d.getElementsByTagName('head')[0].appendChild(css);

	imgs = d.getElementById('recruitment_slides').getElementsByTagName('img');
	//imgs.sort(function() {return 0.5 - Math.random();});
	for(i=1;i<imgs.length;i++) imgs[i].xOpacity = 0;
	imgs[0].style.display = 'block';
	imgs[0].xOpacity = .99;

	//setTimeout(so_xfade,2000);
	setTimeout(prepNextImg,2000);
}

function prepNextImg()
{
	// Randomly selects the next image to fade into, keeps reselecting if the random number is the same as the current or last 7 images, for more variety.
	nextImg = current;
	while((nextImg==current) || (nextImg==pastA) || (nextImg==pastB) || (nextImg==pastC) || (nextImg==pastD) || (nextImg==pastE) || (nextImg==pastF) || (nextImg==pastG))
	{
		nextImg = Math.floor(15*Math.random());	
	}
	setTimeout(so_xfade,1);
}

function so_xfade()
{
	cOpacity = imgs[current].xOpacity;
	//nIndex = imgs[current+1]?current+1:0;
	nIndex = nextImg;
	//nIndex = Math.floor(14*Math.random())
	nOpacity = imgs[nIndex].xOpacity;

	cOpacity-=.05;
	nOpacity+=.05;

	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';
		
		// Keeps track of the past 7 images that were used, to avoid too much repetition in the random images.
		pastG = pastF;
		pastF = pastE;
		pastE = pastD;
		pastD = pastC;
		pastC = pastB;
		pastB = pastA;
		pastA = current;

		current = nIndex;

		//setTimeout(so_xfade,2000);
		setTimeout(prepNextImg,2000);

	}
	else
	{
		setTimeout(so_xfade,50);
	}

	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) + ')';
	}
}
