(function($){
	
	$.fn.imagefader = function(options) {
		var obj = this;
		var defaults = {
			fadeSpeed: 3000,
			displayTime: 6000,
			callBackFade: function(){}
		};
		var settings = $.extend(defaults, options);
		
		var selectedIndex = 0;
		var nextIndex = 1;
		var total = 0;
		var interval;
		
		init();
		
		function init(){
			var counter = 0;
			
			total = settings.imgArr.length;
			
			obj.html("<ul></ul>");
			for(var i = 0; i < settings.imgArr.length; i++){
				var img = new Image();
				obj.children("ul").append("<li class='slide-"+i+"'><img class='"+settings.imgArr[i][1]+"' src=''></li>");
			}
			
			
			obj.find("li").each(function(){
				$(this).children("img").load(function () {
					$(this).parent().addClass("img-loaded")
				})
				.error(function () { // if there was an error loading the image, react accordingly
					// notify the user that the image could not be loaded
				})
				.attr('src', settings.imgArr[counter][0]); // set the src attribute of the new image to our image
				
				counter++;
			});
			
			obj.find("li:eq("+selectedIndex+")").css("display","block" ).css("z-index","2");
						
			if(total>1){
				interval = setInterval(function(){slideImages();}, settings.displayTime);
			}
		}
		
		function slideImages(){
			var currentSlide = obj.find("li:eq("+selectedIndex+")");
			
			var nextSlide = obj.find("li:eq("+nextIndex+")");
			if(nextSlide.hasClass("img-loaded")){
				
				currentSlide.css("display","block" ).css("z-index","2");
				nextSlide.css("display","block" ).css("display","block" ).css("z-index","1");
				currentSlide.fadeOut(settings.fadeSpeed);
				
				settings.callBackFade(nextIndex, nextSlide.children("img").attr("class"));
				
				slideCounter();
			}
		}
		
		
		function slideCounter()
		{
			if(nextIndex < (total -1))
			{
				
				nextIndex++;
			}
			else
			{
				nextIndex = 0;
			}
			if(selectedIndex < (total-1))
			{
				
				selectedIndex++;
			}
			else
			{
				selectedIndex = 0;
			}
		}
};
})(jQuery);
