
var PHOTO_DELAY = 7; // in seconds
var FADE_DELAY = 1000; // milliseconds (1000 per second; 500 is a half-second, etc.)
var photos = [];
var currentPhoto = 0;
var clockInterval = -1;
var seconds = 0;
var playing = true;

var hiding = false;
var hidingTimer = null;

function clock() {
	if( playing ) {
		seconds++;
	}
	if( seconds == PHOTO_DELAY ) {
		seconds = 0;
		nextPhoto();
	}
}

function showPhoto( n ) {
	// make sure the current photo is at z 10
	$(photos[currentPhoto]).css( "z-index", 10 );
	// bring new photo to "next" slot (just behind current photo)
	$(photos[n]).css( "z-index", 9 );
	$(photos[n]).show();
	// fade out the current photo to reveal the next one
	$(photos[currentPhoto]).fadeOut( FADE_DELAY, function () {
		// when fade finishes, pu tthis one behind
		$(photos[currentPhoto]).css( "z-index", 9 );
	} );
	currentPhoto = n;
}

function nextPhoto() {
	var n = currentPhoto + 1;
	if( n == photos.length ) {
		n = 0;
	}
	showPhoto( n );
}

function previousPhoto() {
	var n = currentPhoto - 1;
	if( n < 0 ) {
		n = photos.length - 1;
	}
	showPhoto( n );
}

function cancelHiding() {
	if( hidingTimer ) {
		clearTimeout( hidingTimer );
	}
	hiding = false;
}

function setupControls() {
	$( "#vcr" + ( playing ? "Playing" : "Paused" ) ).show();
	$( "#vcr" + ( !playing ? "Playing" : "Paused" ) ).hide();
	cancelHiding();
}

function play() {
	playing = true;
}

function stop() {
	playing = false;
}

$(document).ready( function () {

	// timer prevents the controls from flickering because of header mouseout when entering controls
	$(".vcrControls").mouseover( function () {
		cancelHiding();
	} );

	// gather the photos in the header
	$(".rotateMe").each( function ( img ) {
		photos.push( this );
		$(this).mouseover( function () {
			$( "#vcr" + ( playing ? "Playing" : "Paused" ) ).fadeIn( 250 );
			$( "#vcr" + ( !playing ? "Playing" : "Paused" ) ).hide();
			cancelHiding();
		} );
		$(this).mouseout( function () {
			if( !hiding ) {
				hiding = true;
				hidingTimer = setTimeout( function () {
					hiding = false;
					$( "#vcr" + ( playing ? "Playing" : "Paused" ) ).fadeOut( 250 );
					$( "#vcr" + ( !playing ? "Playing" : "Paused" ) ).hide();
				}, 500 );
			}
		} );
	} );

	// start the rotation
	clockInterval = setInterval( clock, 1000 );

} );
