/*	CODE BY: SAM SACCONE	SAM@SAMSACCONE.COM	-	5.05.11 V1.2 */

(function($){
	$.fn.tinySlideshow = function(options)
	{
		var targeted = $(this);
		if(options.showNav){make_nav();}
		if(options.keyNav){bind_keys();}
		
		
		init();
		
		
		function init()
		{
			$('img',targeted).each(function(index,target){index === 0 ? $(target).attr('index',index).addClass('active_image') : $(target).attr('index',index).css({'display':'none'});});
			$('img',targeted).click(function(e){move_to('forward')});
			$(window).load(function(){set_caption();});
		}
	
		function make_nav()
		{
			targeted.append('<div class="gallery_nav"><div class="nav left"><div></div></div><div class="nav right"><div></div></div><div id="caption"><div id="location"></div><div id="caption_inner"></div></div>');
			

			$('.nav','.gallery_nav').click(function(e){
				$(e.currentTarget).hasClass('right') ? move_to("forward") : move_to("back");
				$('div',e.currentTarget).show();	
				e.stopImmediatePropagation();
			});
			
			$('.gallery_nav',targeted).click(function(e){move_to("forward");});
			
			$('.nav','.gallery_nav').hover(function(e){if(!$(e.currentTarget).find('div').is(':animated')){$(e.currentTarget).find('div').fadeIn();}},function(e){$(e.currentTarget).find('div').fadeOut();});
		}
		
		function set_caption()
		{
			
			var to_move_top		=	parseInt($('.active_image').css('margin-top'),10)+parseInt($('.active_image').height(),10)+'px';
			var current_index	=	parseInt($('.active_image').index(),10)+1;
			var total_length	=	$('img','#right').length;
						
			$('#location').html(current_index+"/"+total_length);
			$('#caption_inner').html($('.active_image').attr('alt'));
			
			$('#caption').css({'margin-left':$('.active_image').css('margin-left')});
			$('#caption').css({'margin-top':to_move_top});
			
		}
		function move_to(direction)
		{
			var target		=	$('.active_image','#right');
			var spot		=	direction === "back" ? make_pos(((parseInt(target.attr('index'),10)-1))%$('img',targeted).length) : make_pos(((parseInt(target.attr('index'),10)+1))%$('img',targeted).length);
			//STRAIGHT CUT target.removeClass('active_image').fadeOut('fast',function(){$('img[index="'+spot+'"]',targeted).addClass('active_image').fadeIn('fast')});
			
			//CROSS FADE
			target.removeClass('active_image').fadeOut(700);
			$('img[index="'+spot+'"]',targeted).addClass('active_image').fadeIn(700);
			set_caption();
		}
		
		function make_pos(num)
		{
			return num<0 ? $('img',targeted).length-1 : num; 
		}
		
		function bind_keys()
		{
			$(document).keydown(function(e){ if(e.which === 37){ move_to("back");}if(e.which === 39){move_to('forward');}});
		}
		
		return this.each(function(){});
	};
})(jQuery);
