(function($) {
	$(document).ready( function() {

		setActive = function( showIndex, nextIndex, prevSlide ) {
			console.log( "setActive: " + showIndex + ", " + nextIndex );

			$('.slide-show-wrapper').each( function( index ) {
				var keep = $(this).hasClass("keep");
				console.log(keep);
				if( index == showIndex ) {
					$(this).find('.slide img').each( function( sIndex ) {
						if( sIndex == nextIndex ) {
							$(this).fadeIn('slow');
							$(this).addClass("active");
						} else {
							$(this).fadeOut('slow');
							$(this).removeClass("active");
						}
					});
				}
			});
		}

		$('.left-arrow').click( function(event) {
			var cTotal = $(this).parent().children('p').children('.current').text();
			if( cTotal != '1' ) {
				cTotal--;
				setActive( $(this).parents('.slide-show-wrapper').children('.show-index').html(), cTotal-1 );
				$(this).parent().children('p').children('.current').text( cTotal );
			} else if( cTotal == 1 ) {
				cTotal = $(this).parents('.slide-show-wrapper').children('.total-slides').html();
				setActive( $(this).parents('.slide-show-wrapper').children('.show-index').html(), cTotal-1 );
				$(this).parent().children('p').children('.current').html( $(this).parents('.slide-show-wrapper').children('.total-slides').html() );
			}
		});

		$('.right-arrow').click( function(event) {
			var cTotal = $(this).parent().children('p').children('.current').html();
			if( cTotal != $(this).parents('.slide-show-wrapper').children('.total-slides').html() ) {
				cTotal++;
				setActive( $(this).parents('.slide-show-wrapper').children('.show-index').html(), cTotal-1 );
				$(this).parent().children('p').children('.current').html( cTotal );
			} else if( cTotal == $(this).parents('.slide-show-wrapper').children('.total-slides').html() ) {
				cTotal = 0;
				setActive( $(this).parents('.slide-show-wrapper').children('.show-index').html(), 0 );
				$(this).parent().children('p').children('.current').html( '1' );
			}
		});

		$('.slide-show-wrapper').each( function(index) { 
			var length = $(this).find('.slide').length;
			$(this).find('.total-slides').html( length );
			$(this).find('.total').text( length );
			
			$(this).find('.show-index').html( index );
			setActive( index, 0 );
		});

	});
})(jQuery);
