$( document ).ready( function() {
	
	$( '.photos' ).each( function() {
		//ecopodStartStop( this );
	} );
	
	$( '.photos' ).each( function() {
		ecopodFadeThrough( $( this ).find( '.photo' ) );
	} );
	
	$( '.ecopodStart' ).live( 'click', function() {
		ecopodFadeThrough( $( this ).closest( '.photos' ).find( '.photo' ) );		
	} );
	
	$( '.ecopodStop' ).live( 'click', function() {
		$( this ).closest( '.photos' ).addClass( 'stop' ).removeClass( 'running' );
		ecopodStartStop( parent );
	} );

	
} );

function ecopodFadeThrough( elems, key ) {

	parent = $( elems ).first().closest( '.photos' );

	if ( $( parent ).hasClass( 'stop' ) ) {
		$( parent ).removeClass( 'stop' );
		ecopodStartStop( parent );
		return false;
	
	} else {
		$( parent ).addClass( 'running' );
	
	}
	
	ecopodStartStop( parent );

	if ( typeof( key ) == 'undefined' ) {
		key = 0;
	}
	
	setTimeout( function() {
	
		if ( $( elems ).eq( key + 1 ).size() ) {
		
			$( elems ).eq( key ).fadeOut( 'slow', function() {
				ecopodFadeThrough( elems, key + 1 );
			} );
			
			$( elems ).eq( key + 1 ).fadeIn( 'slow' )
		
		} else {
			
			$( elems ).eq( 0 ).fadeIn( 'slow' );
			$( elems ).eq( key ).fadeOut( 'slow', function() {
				ecopodFadeThrough( elems );
			} );
		
		}
	}, 3000 );
	
}

function ecopodStartStop( elem ) {

	$( elem ).find( '.ecopodStop, .ecopodStart' ).remove();
	
	if ( $( elem ).hasClass( 'running' ) ) {
		$( elem ).append( '<a class="ecopodStop">Stop</a>' );
	} else {
		$( elem ).append( '<a class="ecopodStart">Start</a>' );
	}
	
}
