function PadDigits(n, totalDigits) 
    { 
        n = n.toString(); 
        var pd = ''; 
        if (totalDigits > n.length) 
        { 
            for (i=0; i < (totalDigits-n.length); i++) 
            { 
                pd += '0'; 
            } 
        } 
        return pd + n.toString(); 
    } 
    
$(function() {
	
	var num_webcams = 8;
	
	$("#btn_next").click(function() {
		
		// Nasconndo pulsanti avanti / indietro
		$("#btn_next").hide();
	    $("#btn_prev").hide();
	    
		var nome = $("#img_webcam img").attr('src');
		var attuale = nome.substr(7,2);
		var next  = parseInt(attuale,10) + 1;
		
		if (next == (num_webcams+1))
			next = 1;
			
		if (next == 10)
			next = 11;
			
		next = PadDigits(next,2);
		
		var image1 = $('<img />').attr('src', 'images/indicator.gif').css("padding-top", "170px");
		// Insert preloaded image into the DOM tree
		$('#img_webcam').html(image1);
		
		var timestamp = new Date().getTime();
		
		var immagine = 'images/' + next + '.jpg';    
			$('<img />')
		    .attr('src', immagine+'?'+timestamp)
		    .height(425).width(985)
	    	.load(function(){
	        	$('#img_webcam').html( $(this));
				$("#btn_next").show();
	    		$("#btn_prev").show();
	        });
			      
	});
	 
	$("#btn_prev").click(function() {
	
		// Nasconndo pulsanti avanti / indietro
		$("#btn_next").hide();
	    $("#btn_prev").hide();
	    
		var nome = $("#img_webcam img").attr('src');
		var attuale = nome.substr(7,2);
		var prev  = parseInt(attuale,10) - 1;
		
		if (prev == 0)
			prev = num_webcams;
			
		// WEBCAM 10/13 NON ATTIVA
		if (prev == 10)
			prev = 9;
			
		prev = PadDigits(prev,2);
		
		var image1 = $('<img />').attr('src', 'images/indicator.gif').css("padding-top", "170px");
		// Insert preloaded image into the DOM tree
		$('#img_webcam').html(image1);
		
		var timestamp = new Date().getTime();
		
		var immagine = 'images/' + prev + '.jpg';    
			$('<img />')
		    .attr('src', immagine+'?'+timestamp)
		    .height(425).width(985)
	    	.load(function(){
	        	$('#img_webcam').html( $(this));
				$("#btn_next").show();
	    		$("#btn_prev").show();
	        });
		      
	});
});
