var auto_rotate_num = 1;
var auto_rotate_max = 1;
var file_name = "";
var file_ext = ".jpg";
var obj;

$.fn.auto_rotate = function(arg_max_num){
	auto_rotate_max = arg_max_num;

	return this.each(function(){
		var temp_file_name = $(this).attr("src");
		file_name = temp_file_name.substring(0, temp_file_name.lastIndexOf(".")-1);
		file_ext = temp_file_name.substring(temp_file_name.lastIndexOf("."), temp_file_name.length);
		obj = this;
		
		$(this).wrap('<div id="auto_rotate_wrapper" />');
		
		
		setTimeout("auto_rotate_fade(this)", 3000);
	});
	
};

function auto_rotate_fade(arg_obj){
	auto_rotate_num++;
	if(auto_rotate_num > auto_rotate_max){
		auto_rotate_num = 1;
	}
	$("#auto_rotate_wrapper").find("img").animate({opacity:0}, 500, auto_rotate_set);		
}
		
function auto_rotate_set(){
	
	//$(obj).attr("src", file_name + auto_rotate_num + file_ext);
	load_image(file_name + auto_rotate_num + file_ext);
	
	//$(obj).animate({opacity:1}, 1000);	
	setTimeout(auto_rotate_fade, 3000);
}


function load_image(arg_image){
	var img = new Image();
	$(img).load(function () {
		$("#auto_rotate_wrapper img").remove();
      	$(this).hide();
		$("#auto_rotate_wrapper").prepend(this);
		//$(loading).fadeOut();
		$(this).fadeIn();
	})
	.error(function () {
		// notify the user that the image could not be loaded
    }).attr('src', arg_image);;
}

