(function( $ ){
	var methods = 
	{
		init : function( options ) 
		{	
			return $(this).each(function()
			{
				$.fn.jrotator.timeout = 2000;
				var id = $(this).attr("id");
				var images = [];
				for (var i = 0; i < options.images.length; i++)
					images[images.length] = options.images[i];
				$(this).addClass("jrotator_loading").after("<div id='"+id+"_cover' style='width:"+$(this).width()+"px;height:"+$(this).height()+"px;margin-top:-"+$(this).height()+"px;'></div><img id='"+id+"_loader' class='jrotator_loader' />").data({loadedIndex:0, images:images, rotindex:0, loader:$("#"+id+"_loader"), cover:$("#"+id+"_cover")});
				$("#"+id+"_cover").data("owner", $(this)).css("opacity", 0);
				$("#"+id+"_loader").data("owner", $(this)).load(function()
				{
					$(this).data("owner").jrotator("onloadimage");
				}).attr("src", images[0]);
				
			});
		},
		"onloadimage":function()
		{
			var loadedIndex = $(this).data("loadedIndex");
			var images = $(this).data("images");

			if (loadedIndex == 0)
			{
				$(this).removeClass("jrotator_loading");
				$(this).css("background-image", "url("+images[loadedIndex]+")");
				var $that = $(this);
				setTimeout(function()
				{
					$that.jrotator("rotate");
				}, $.fn.jrotator.timeout);
			}
			
			loadedIndex++;
			$(this).data("loadedIndex", loadedIndex);
			$(this).data("loader").attr("src", images[loadedIndex]);
		},
		"rotate":function()
		{
			var loadedIndex = $(this).data("loadedIndex");
			var images = $(this).data("images");
			var rotindex = $(this).data("rotindex");
			rotindex++;
			if (rotindex == images.length)
				rotindex = 0;
			if (rotindex < loadedIndex)
			{
				$(this).data("cover").css("background-image","url("+images[rotindex]+")").animate({opacity:1}, 500, "easeInOutQuad", function()
				{
					$(this).data("owner").css("background-image", $(this).css("background-image"));
					var $that2 = $(this);
					setTimeout(function()
					{
						$that2.css("opacity", 0);
					}, 500);
					var $that = $(this).data("owner");
					setTimeout(function()
					{
						$that.jrotator("rotate");
					}, $.fn.jrotator.timeout);
				});
				$(this).data("rotindex", rotindex);
			}
		}
	};

	$.fn.jrotator = function( method ) 
	{

		if ( methods[method] ) 
		{
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} 
		else if ( method instanceof Object || ! method ) 
		{
			return methods.init.apply( this, arguments );
		} 
		else 
		{
			$.error( 'Method ' +  method + ' does not exist on jQuery.jlentaitem' );
		}    

	};

})( jQuery );

