jQuery( function( $ ) {

	$( '.polaroid-container > .polaroid' ).css( 'position', 'absolute' );

	$( '.polaroid-container' ).each( function() {

		$( this ).data( 'count', $( this ).children( '.polaroid' ).length ).data( 'current', 1 );

		if ( $( this ).data( 'count' ) > 1 ) {

			start_animation( $( this ) );

			$( this ).children( '.polaroid, .polaroid-date, .polaroid-frame' ).click(
				function( e ) {
					stop_animation( $( e.target ).parents( '.polaroid-container' ) );
				}
			).hover(
				function() {
					stop_animation( $( this ).parents( '.polaroid-container' ) );
				},
				function() {
					stop_animation( $( this ).parents( '.polaroid-container' ) );
					start_animation( $( this ).parents( '.polaroid-container' ) );
				}
			);

		}

	} );

	function do_animation( o ) {

		$( '.polaroid-' + o.data( 'current' ) ).fadeOut( 999 ).removeClass( 'visible-polaroid' );

		if ( o.data( 'current' ) == o.data( 'count' ) )
			o.data( 'current', 1 );
		else
			o.data( 'current', o.data( 'current' ) + 1 );

		$( '.polaroid-' + o.data( 'current' ) ).addClass( 'visible-polaroid' ).fadeIn( 999 );

	}

	function start_animation( o ) {

		o.data( 'interval', setInterval( function() { do_animation( o ) }, 7299 ) );

	}

	function stop_animation( o ) {

		clearInterval( o.data( 'interval' ) );

	}

} );