/**

	Image Rotator
	By: Leland Cope
	Copyright 2011: Leland Cope. Must get permission to use.
	Version: 2.0
	
	options
	{
		speed:(default: 0.75 sec) Speed in seconds of the transition
		delay:(default: 5 sec) Delay between transitions in seconds
		navholder:(Optional) The ID of the navigation holder
		callback:(Optional) A function to callback when everything is finished.
	}

**/

(function($)
{
	$.fn.imagerotator = function(options)
	{
		var defaults = {
						speed:0.75,
						delay:5,
						navholder:null,
						callback:null
		}
		
		var options = $.extend(defaults, options);
		
		return this.each(function()
		{
			var obj = $(this);
			var $nav = null;
			var navchildren = null;
			var i = 0;
			var total = obj.children().length;
			var curCount = 0;
			var children = obj.children();
			var sto;
			
			if(options.navholder != null) $nav = $("#"+options.navholder);
			
			obj.addClass("ir-parent");
			
			
			obj.children().each(function()
			{
				var $tmp = $(this);
				
				if(i == 0) $tmp.addClass("ir-selected");
				else $tmp.css("display", "none");
				
				$tmp.css({position:"absolute", top:0, left:0}).addClass("ir-child");
				
				i++;
			});
			
			
			if($nav != null)
			{
				var l = 0;
			
				$nav.children().each(function()
				{
					var $tmp = $(this);
					
					if(l == 0) $tmp.addClass("ir-nav-selected");
					
					$tmp.attr("data-i", l).click(jumptoimage);
					
					l++;
				});
				
				navchildren = $nav.children();
			}
			
			function jumptoimage(e)
			{
				clearTimeout(sto);
			
				hidecurrent();
				curCount = $(e.currentTarget).attr("data-i");
				showcurrent();
				
				sto = setTimeout(nextimage, ((options.delay*1000)+(options.speed*1000)));
			}
			
			function nextimage()
			{
				clearTimeout(sto);
			
				hidecurrent();
				curCount++;
				showcurrent();
				
				sto = setTimeout(nextimage, ((options.delay*1000)+(options.speed*1000)));
			}
			
			function hidecurrent()
			{
				$(".ir-selected").removeClass("ir-selected").fadeOut((options.speed*1000));
				if($nav != null) $(".ir-nav-selected").removeClass("ir-nav-selected");
			}
			
			function showcurrent()
			{
				$(children[curCount%total]).addClass("ir-selected").fadeIn((options.speed*1000));
				if($nav != null && navchildren[curCount%total] != undefined) $(navchildren[curCount%total]).addClass("ir-nav-selected");
			}
			
			
			sto = setTimeout(nextimage, (options.delay*1000));
			
			if(options.callback != null) 
			{
				options.callback();
				
				options.callback = null;
			}
			
		});
	}
	
})(jQuery);
