/*
	A simple, but cool, slider. you know.
	
	Federico Quagliotto <f.quagliotto@mandarinoadv.com>
	
*/

$(function() {
	var slider = 0;
	$('.slider').each(function() {
		
		var questoId = 'slider_identify_' + ++slider;
		
		/*if(!$("#status").html())
			$('body').append('<div id="status">Caricamento Immagini</div>');
		
		$(this).fadeTo(0, 0.2);*/
		
		// Prendo il numero di fotografie e instanzio un oggetto contenente l'attuale
		var thiss = $(this);
		var foto = $(this).find('img').length;
		var attuale = 0;
		
		// Creo un wrapper, molto più grande.
		$(this).attr("id", questoId).attr('foto', foto).css({
			overflow: 'hidden',
			width: $(this).width()
		});
		
		$(this).wrapInner('<div style="width: '+(1000*foto)+'px" />');
		
		// Aspetto che tutte le immagini siano cariche
		$(this).find('img').load(function() {
			attuale++;
			if(attuale == foto) {
				$("#status").fadeOut().remove();
				$(thiss).fadeTo(1000, 1);
			}
		}); // Tutte le immagini sono state caricate.
		
		// C'è da creare gli slider.
		$(this).after('<div class="controller" vId="'+questoId+'"><a href="javascript:;" class="left" sId="'+questoId+'"><img src="/static/media/images/left.png" border="0" /></a><a href="javascript:;" sId="'+questoId+'" class="right"><img src="/static/media/images/right.png" border="0" /></a></div>');
		
	});
	
	$(".controller .left").live('click', function() {
		
		var larghezza = $("#" + $(this).attr("sId")).width();
		var left = -1 * parseInt($("#" + $(this).attr("sId")).find('div').css('margin-left'));
		var spostamenti = $("#" + $(this).attr("sId")).attr('foto') - 2;
		
		if(left > 0) {
			$("#" + $(this).attr("sId")).find('div').animate({
				marginLeft: "+=" + larghezza + "px"
			});
		} else {
			$("#" + $(this).attr("sId")).find('div').animate({
				marginLeft: (-1*larghezza * spostamenti) + "px"
			});
		}
		
	});
	
	$(".controller .right").live('click', function() {
		
		var larghezza = $("#" + $(this).attr("sId")).width();
		
		var left = -1 * parseInt($("#" + $(this).attr("sId")).find('div').css('margin-left'));
		var spostamenti = $("#" + $(this).attr("sId")).attr('foto') - 2;
		
		if(left/larghezza <= spostamenti) {
		
			$("#" + $(this).attr("sId")).find('div').animate({
				marginLeft: "-=" + larghezza + "px"
			});
		
		} else {
			
			$("#" + $(this).attr("sId")).find('div').animate({
				marginLeft: "0px"
			});
			
		}
		
	});
	
});
