var photoCacheSrc = [];
var photoCacheImg = [];

var photoDelay = 5000;
var photoShown = 1;
var photoSrc;

function transitionOut () {
	photoImg2.src = photoSrc;
	photoImg2.show();
	photoShown = 0;
	if(typeof(photoLoading) !== 'undefined') photoLoading.style.visibility = 'hidden';
	new Effect.Opacity(photoImg1, {from: 0.999, to: 0, duration: 2.0});
	window.setTimeout(photoRotation,photoDelay);
}
function transitionIn () {
	photoImg1.src = photoSrc;
	photoImg1.show();
	photoShown = 1;
	if(typeof(photoLoading) !== 'undefined') photoLoading.style.visibility = 'hidden';
	new Effect.Opacity(photoImg1, {from: 0, to: 0.999, duration: 2.0});
	window.setTimeout(photoRotation,photoDelay);
}

photoRotation = function () {

	if (photoShown) {

		photoSrc = photoImg1.src.replace(/https?:\/\/[^/]+?\//,'/');
		var photoIndex = photos.indexOf(photoSrc);

		// On the first loop, the first image will already be cached. Push the src so we don't duplicate
		if ( photoIndex == 0 && photoCacheSrc.indexOf(photoSrc) == -1 )
			photoCacheSrc.push(photoImg1.src);
	
		photoSrc = photoImg1.src.replace(/(https?:\/\/[^/]+?)\/.*/,'$1');

		if(photos.length > photoIndex+1)
			photoSrc = photoSrc + photos[photoIndex+1];
		else
//			photoShown = 0;
			photoSrc = photoSrc + photos[0];


		var photoCacheIndex = photoCacheSrc.indexOf(photoSrc);

		if(photoCacheIndex == -1) {

			photoCacheSrc.push(photoSrc);

			if(typeof(photoLoading) !== 'undefined') photoLoading.style.visibility = '';

			photoCacheImg.push(new Image());
			photoCacheImg[photoCacheImg.length-1].onload = transitionOut;
			photoCacheImg[photoCacheImg.length-1].src = photoSrc;

		} else {
			transitionOut();
		}


	} else {

		photoSrc = photoImg2.src.replace(/https?:\/\/[^/]+?\//,'/');
		var photoIndex = photos.indexOf(photoSrc);

		photoSrc = photoImg2.src.replace(/(https?:\/\/[^/]+?)\/.*/,'$1');

		if(photos.length > photoIndex+1)
			photoSrc = photoSrc + photos[photoIndex+1];
		else
//			photoShown = 0;
			photoSrc = photoSrc + photos[0];


		var photoCacheIndex = photoCacheSrc.indexOf(photoSrc);

		if(photoCacheIndex == -1) {

			photoCacheSrc.push(photoSrc);

			if(typeof(photoLoading) !== 'undefined') photoLoading.style.visibility = '';
			photoCacheImg.push(new Image());
			photoCacheImg[photoCacheImg.length-1].onload = transitionIn;
			photoCacheImg[photoCacheImg.length-1].src = photoSrc;

		} else {
			transitionIn();
		}

	}
}

Event.observe(window, 'load', photoRotation );

