(function($){
	$(document).ready(function(){
		$('.js-images').each(function(){
			var $images = $(this);
			var $items = $images.find('li');
			var $next = $(this).find('li:first');
			var $visible = $(this).find('li:last');
			var $controlpane = $images.find('.js-controls').removeClass('full-hidden').hide();
			var $controls = $controlpane.find('a').css('opacity','0');
			var $play =  $controlpane.find('a.js-play').data('state','play');
			var $bw = $controlpane.find('a.js-bw');
			var $fw = $controlpane.find('a.js-fw');
			var t = null;
			var loop = true;
			var speed = 1000;
			
			var next = function(){
				if(loop){
					speed = 1000;
				}
				$next = $images.find('li:first');
				$next.insertAfter($visible).fadeIn(speed,function(){
					$visible.hide();
					$visible = $images.find('li:last');
					$next = $images.find('li:first');
					if(loop){
						play();
					}
				});
			}
			
			var prev = function(){
				$next = $images.find('li:last').prev().show();
				$visible.fadeOut(speed,function(){
					$visible.prependTo($images.find('ul'));
					$visible = $next;
				});
			}
			
			var play = function(){
				t = setTimeout(next,4000);
			};
			
			var stop = function(){
				loop = false;
				speed = 200;
				clearTimeout(t);
				$next.stop(true,true);
				$play.removeClass('pause').addClass('play').data('state','pause');
			};
			
			var showControls = function(){
				$controlpane.show();
				$controls.stop(true,true).fadeTo(200,0.75);
			};
			
			var hideControls = function(){
				$controls.stop(true,true).fadeTo(200,0,function(){
					$controlpane.hide();
				});
			};
			
			if($items.length > 1){
				$items.hide();
				$visible.show();
				$images.hover(showControls,hideControls);
				
				$controls.hover(
					function(e){
						$(this).hoverFlow(e.type,{opacity:1},200);
					},
					function(e){
						$(this).hoverFlow(e.type,{opacity:0.75},200);
					}
				);
				
				$play.click(function(e){
					e.preventDefault();
					if($(this).data('state') == 'play'){
						stop();
					}else{
						stop();
						hideControls();
						$(this).removeClass('play').addClass('pause');
						$(this).data('state','play');
						loop = true;
						next();
					}
				});
				
				$fw.click(function(e){
					e.preventDefault();
					stop();
					loop = false;
					next();
				});
				
				$bw.click(function(e){
					e.preventDefault();
					stop();
					loop = false;
					prev();
				});
				
				play();
			}
		});
	});
})(jQuery);