
var ssContainer;
var ssFrame = null;
var ssSize, ssDim;
var ssNextPhoto;
var debug=false;
var ssTimeout=0;
var ssIsPaused;
var ssIsInitialized=false;

function ssInit(containerId)
{
	if (ssIsInitialized) {
		ssPlay();
		return;
	}
	
	ssSize = 'large';
	ssDim  = '800px';
	ssFrame = new Array(2);
	ssIsInitialized = true;
	
	// Add image object to the photos array
	for (var i=0;i<ssPhotos.length;++i)
	{
		ssPhotos[i] = Object.extend({
			img: $(new Image()),
			ready: false
		}, ssPhotos[i] );
	}
	
	// Preload images
	ssPhotos.each( function(p) {
		p.img.onload = function() {p.ready=true;}
		p.img.src = mpPhotoUrl( p.id, ssSize );
	});
	
	// Setup the container
	ssContainer = $(containerId);
	ssContainer.setStyle({'position':'relative','height':ssDim});
	
	if (debug)
	{
		ssContainer.appendChild(Builder.node('div',{id:'debug-output'}));
	}
	
	for (var i=0;i<2;++i)
	{
		ssFrame[i] = Builder.node( 'img' );
		ssFrame[i].setStyle({'opacity':0,'position':'absolute',top:0,left:0});
		ssContainer.appendChild(ssFrame[i]);
	}
		
	ssNextPhoto = 0;
	
	ssPlay();
}

function debugDisplay(text){
	if (!debug)
		return;
	$('debug-output').innerHTML += text
}

function ssPause()
{
	clearTimeout( ssTimeout );
	ssTimeout = 0;
	ssIsPaused = true;
}

function ssPlay()
{
	ssIsPaused = false;
	ssGotoNext();
}

function ssGotoNext()
{
	if (ssIsPaused)
		return;
		
	debugDisplay('Checking photo ' + ssNextPhoto + ': ');
	
	// Is the next photo ready to be displayed?
	if (ssPhotos[ssNextPhoto].ready)
	{
		debugDisplay('Ready<br/>');
		fadeOut( ssFrame[0], {duration:.2,
			afterFinish:function() {
				ssFrame[0].src = ssPhotos[ssNextPhoto].img.src;
				ssNextPhoto = (ssNextPhoto+1)%ssPhotos.length;
				if (!ssIsPaused)
				{
					fadeIn( ssFrame[0], {duration:1} );
					ssTimeout = setTimeout( ssGotoNext, 5000 );
				}
			}
		});
	} else {
		// check again in .5 seconds
		debugDisplay('NOT READY; checking in .5 seconds...<br/>');
		ssTimeout = setTimeout(ssGotoNext, 500);
	}
}