//## The DynAmbiente plugin to scroll through the images
jQuery.dynambiente = function(options) { 
	var defaults = {
		databank: ".ambiente-data",
		box: ".ambiente-box",
		changer: ".ambiente-changer",
		lineup: 1,
		duration: 3000,
		effect: "fade"
	};
	
	//## Get the plugin options
	var plugin = $.extend({}, defaults, options);
	plugin.restart = function(){
		$.dynambiente({
			databank: plugin.databank,
			box: plugin.box,
			changer: plugin.changer,
			lineup: plugin.lineup,
			duration: plugin.duration,
			effect: plugin.effect
		});
	};
	
	//## Set the private variables
	var amount = $(plugin.databank + " img").length;;
	var current = "";
	var next = "";

	
	//## Check the current image and the next for effects
	$(plugin.databank + " img").each(function(){
		if($(this).attr("alt") == plugin.lineup)
		{
			current = $(this).attr("src");
		}
		
		nextCounter = plugin.lineup+1 > amount ? 1 : plugin.lineup+1;
		if($(this).attr("alt") == nextCounter)
		{
			next = $(this).attr("src");
		}
	});
	
	
	//## Perform the show actions
	$(plugin.changer).css("background-image", "url("+current+")").show(0, function(){
		$(plugin.box).css("background-image", "url("+next+")")
	}).delay(plugin.duration);
	
	
	//## Check wich effect to perform
	var effectNumber = 5;
	
	if(plugin.effect == "random")
	{
		effectNumber = Math.floor(Math.random()*5);
	} else if(plugin.effect == "slideup") {
		effectNumber = 1;
	} else if(plugin.effect == "crop") {
		effectNumber = 2;
	} else if(plugin.effect == "slideleft") {
		effectNumber = 3;
	} else {
		effectNumber = 4;
	}
	
	switch(effectNumber) {
		case 1:	
			$(plugin.changer).slideUp(plugin.duration/2, function(){
				//## Re-run the script after showing the image
				plugin.restart();
			});
			break;
		case 2:
			$(plugin.changer).hide(plugin.duration/2, function(){
				//## Re-run the script after showing the image
				plugin.restart();
			});
			break;
		case 3:
			$(plugin.changer).animate({
				"width": "0"
			},plugin.duration/2, function(){
				//## Re-set the changer values
				$(plugin.changer).hide(0, function(){
					$(this).css("width", "100%");
				});
				
				//## Re-run the script after showing the image
				plugin.restart();
			});
			break;
		default:
			$(plugin.changer).fadeOut(plugin.duration/2, function(){
				//## Re-run the script after showing the image
				plugin.restart();
			});
			break;
	}
	
	
	//## Re-set the line-up
	plugin.lineup = plugin.lineup == amount ? 1 : plugin.lineup+1;
}
