(function( $ ){
	var methods = 
	{
		init : function( options ) 
		{
			if (!$.fn.rotator.inited)
			{
				//Global Plug-in Initialisation
				$.fn.rotator.inited = true;
				$("body").append("<div id='fnPortfolioLoaders' style='position:absolute;left:-10000px;top:-10000px;'></div><div id='rotator' style='position:absolute;left:-10000px;top:-10000px;'></div>");
				$("#rotator_cover").data("owner", $(this));
			}
			$.fn.rotator.currentOpen = this;
			
			return this.each(function()
			{
				var _images = options.images;
				var images = [];
				for (var i = 0; i < _images.length; i++)
					images[images.length] = {src:_images[i], loaded:false};
				$(this).data({"images":images, "index":10000});
				var loadersHTML = '';
				var toLoadCount = 0;
				for (var i = 0; i < images.length; i++)
					if (!images[i].loaded)
						loadersHTML+="<img alt='"+i+"'>";
				$("#fnPortfolioLoaders").html(loadersHTML);
				var i = 0;
				$("#fnPortfolioLoaders img").data("owner", $(this)).each(function()
				{
					$(this).load(function()
					{
						$(this).data("owner").rotator("imageLoaded", $(this).attr("alt"));
					});
					$(this).attr("src", images[i].src);
					i++;
				});
		
			});
		},
		"imageLoaded":function(index)
		{
			var images = $(this).data("images");
			images[index].loaded = true;
			if (index == 0)
				$(this).rotator("rotate");
		},
		"rotate":function()
		{
			var images = $(this).data("images");
			var index  = $(this).data("index");
			index++;
			if (index >= images.length)
				index = 0;
			if (images[index].loaded)
			{
				$(this).data("index", index);
				$("#rotator_cover").css({"opacity":"0", "background-image":"url("+images[index].src+")"}).animate({opacity:1}, 1000, "easeInOutQuad", function()
				{
					$("#rotator").css("background-image", $(this).css("background-image"));
					$(this).css("opacity", "0");
					var $elem = $(this).data("owner");
					setTimeout(function()
					{
						$elem.rotator("rotate");
					}, 3000);
				});
			}
			else
			{
				var $elem = $(this);
				setTimeout(function()
				{
					$elem.rotator("rotate");
				}, 500);
			}
		}
		
	};
	$.fn.rotator = 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.rotator' );
		}    

	};
	


})( jQuery );


$(document).ready(function()
{
	$("#rotator").rotator({images:["/opener2/01.jpg", "/opener2/02.jpg", "/opener2/03.jpg", "/opener2/04.jpg", "/opener2/05.jpg"]});
});

