var Miyos = {
	
	timer: null,
	
	muted: false,
	default_volume: 40,
	
	init: function ( ) {
		
		// we only run on the main page, so see if there is a slideshow
		if ( $('#slideshow').length == 0 ) {
			return;
		}
		
		// hook the controls
		$('#play').click( Miyos.play );
		$('#mute').click( Miyos.mute );
		
		// they're all hidden, show the first image immediately
		$('#slideshow ul li:first').show();
		
		Miyos.reset_timer();
		
	},
	
	rotate: function ( ) {
		
		$('#slideshow ul li').each( function () {
			
			if ( $(this).css('display') != 'none' ) {
				$(this).fadeOut( 1000, function () {
					
					// if this is the last item in the list
					if ( $(this).next().length == 0 ) {
						// go back to the first
						$(this).siblings().first().fadeIn( 1000 );
					}
					else {
						// otherwise, do the next one
						$(this).next().fadeIn( 1000 );
					}
					
				} );
			}
			
		} );
		
		Miyos.reset_timer();
		
	},
	
	reset_timer: function ( ) {
		
		this.timer = setTimeout( Miyos.rotate, 4000 );
		
	},
	
	stop: function ( ) {
		
		// cancel the rotating timer
		clearTimeout( Miyos.timer );
		
		Miyos.timer = null;
		
		// stop the music
		AudioPlayer.close('audio');
		
		$('#play').addClass('paused');
		
	},
	
	start: function ( ) {
		
		// start the rotating timer
		Miyos.reset_timer();
		
		// start the music
		AudioPlayer.open('audio');
		
		$('#play').removeClass('paused');
		
	},
	
	play: function ( ) {
		
		if ( Miyos.timer == null ) {
			// we are stopped, play
			Miyos.start();
		}
		else {
			Miyos.stop();
		}
		
	},
	
	mute: function ( ) {
		
		if ( Miyos.muted ) {
			// it is muted, unmute it
			AudioPlayer.getPlayer('audio').setVolume( Miyos.default_volume );
			
			Miyos.muted = false;
			
			$('#mute').removeClass('muted');
		}
		else {
			// it is not muted, mute it
			AudioPlayer.getPlayer('audio').setVolume( 0 );
			
			Miyos.muted = true;
			
			$('#mute').addClass('muted');
		}
		
	}
	
};

$(document).ready( function () {
	Miyos.init();
} );
