errorColor="#ffcccc";
$(document).ready(function(){
	
	if($('#popBuoniShellOverlayContainer')){
		setTimeout(function(){$('#popBuoniShellOverlayContainer').fadeIn('fast'); setTimeout(function(){$('#popBuoniShellOverlayContainer').fadeOut('fast');}, 10000);}, 2000);
		$('#popBuoniShellClose').click(function(){
			$('#popBuoniShellOverlayContainer').fadeOut('fast');
		});
	}
	
	if($('#popScioperoTirOverlayContainer')){
		setTimeout(function(){$('#popScioperoTirOverlayContainer').fadeIn('fast'); setTimeout(function(){$('#popScioperoTirOverlayContainer').fadeOut('fast');}, 10000);}, 2000);
		$('#popScioperoTirClose').click(function(){
			$('#popScioperoTirOverlayContainer').fadeOut('fast');
		});
	}
	
	speseDiSpedizione= 0;
	errore1="Non puoi utilizzare questo codice promozionale, poich&egrave; l'hai gi&agrave; usato in un ordine precedente.";
	errore2= "Il codice promozionale inserito non &egrave; valido o non &egrave; pi&ugrave; attivo.";
	jQuery.fn.ForceNumericOnly =
	function()
	{
	    return this.each(function()
	    {
	        $(this).keydown(function(e)
	        {
	            var key = e.charCode || e.keyCode || 0;
	            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
	            return (
	                key == 8 || 
	                key == 9 ||
	                key == 46 ||
	                (key >= 37 && key <= 40) ||
	                (key >= 48 && key <= 57) ||
	                (key >= 96 && key <= 105));
	        })
	    })
	};
//SLIDES
    $('#mostraButton').click(function(){
        if($(this).hasClass('selectedMOSTRA'))
        {
            $(this).removeClass('selectedMOSTRA')
            $('#mostraContainer').fadeOut('fast');
            
        }
        else
        {
            $(this).addClass('selectedMOSTRA')
            $('#mostraContainer').fadeIn('fast');
        }
        
    });
    
    $('#closeMostra button').click(function(){
        
        $('#mostraButton').removeClass('selectedMOSTRA')
        $('#mostraContainer').fadeOut('fast');
        
    });
    
    verificaIndex = function(){
        if( indexMostra > 0)
        {
            $('#mostraPrevious').fadeIn('fast');   
        }
        if(indexMostra == 0)
        {
            $('#mostraPrevious').hide();
			document.title = "Acquisto buoni pasto online | Day Shop";
        }
        if( indexMostra < mostraMax)
        {
            $('#mostraNext').fadeIn('fast');   
        }
        else
        {
            $('#mostraNext').hide();
        }
		if(indexMostra == 1)
		{
			calcoloSpeseDiSpedizione();
			document.title = "Inserisci il numero della tua partita IVA | Day Shop";
		}
		if(indexMostra == 2)
		{
			
			document.title = "Inserisci i tuoi dati | Day Shop";
		}
		if(indexMostra == 3)
		{
			
			document.title = "Scegli il sistema di pagamento | Day Shop";
		}
                
    }
    
    coloraTratto = function(indexMostra){
        $('.trattoMostra').removeClass('actual');
        $('.trattoMostra[rel='+indexMostra+']').addClass('actual');
     // console.log("indexMostra"+indexMostra);
        //per i link in alto
        $('.mostraTabs').removeClass('selectedTabs');
        //coloriamoli   
        $('.mostraTabs').each(function()
        {
            var rels= $(this).attr('rel').split(',');
            var minRel= parseInt(rels[0]);
            var maxRel= parseInt(rels[1]);
         // console.log("minRel"+minRel);
        //  console.log("maxRel"+maxRel);
            if ( minRel <= indexMostra && maxRel >= indexMostra)
            {
                $(this).addClass('selectedTabs');  
            }
        }
        
        );
    }
    aggiornaSlide = function(indexMostra){
        marginLeftVar=-(indexMostra*900);
        $('.stripeMostra').animate({
            marginLeft: marginLeftVar
			},
            {duration : 400});     
    }
    
    var indexMostra = 0;
    var mostraMax = 5;
    
    coloraTratto(0);

    $('#mostraPrevious').hide();
    //mostra
    
    $('.nextMostra').click(function(){
		if(!$(this).hasClass('disabled'))
		{
			indexMostra++;
			$('ul#roundAbout').roundabout_animateToChild(indexMostra);
			if($(this).attr('rel')=='3')
			{
				//salvaNelDb();
			}		
		}
        aggiornaSlide(indexMostra);
        verificaIndex();
        coloraTratto(indexMostra);
        
    });
	$('.prevMostra').click(function(){
        indexMostra--;
        aggiornaSlide(indexMostra);
        verificaIndex();
        coloraTratto(indexMostra);
        
    });
    $('#mostraNext').click(function(){
        indexMostra++;
        aggiornaSlide(indexMostra);
        verificaIndex();
        coloraTratto(indexMostra);
        
    });
    $('#mostraPrevious').click(function(){
        indexMostra--;
        aggiornaSlide(indexMostra);
        verificaIndex();
        coloraTratto(indexMostra);
        
    });
    $('.trattoMostra').click(function(){
        indexMostra=parseInt($(this).attr('rel'));
        aggiornaSlide(indexMostra);
        verificaIndex();
        coloraTratto(indexMostra);
        
    });
    $('.mostraTabs').click(function(){
        indexMostra=parseInt($(this).attr('rel').split(',')[0]);
        aggiornaSlide(indexMostra);
        verificaIndex();
        coloraTratto(indexMostra);
        
    });

//SCROLL

	$('.stripeMostraVertical').jScrollPane({
		showArrows: true,
		horizontalGutter: 100
	});
//roundabout
$('ul#roundAbout').roundabout({
        tilt: -8.0,
		clickToFocus: false,
		reflect:true,
		minOpacity:0.4,
		btnPrev:'.prevMostra',
		duration: 400,
		minScale:0.6
      });	
	
/**
SLIDE 1
**/
 //freccette
var aggiornaTotale = function(){
	//ciclo tutti gli input e moltiplico
	var i = 0 ;
	var totale=0;
	speseDiSpedizione=0;
	var valori =Array(3.0,5.0,5.29,7.00,10.0);
	$('input.blocchetto').each(function(){
		if($(this).val()!='')
		{
			totale += parseInt($(this).val()) * valori[i]*20; 
		}
		i++;
	});
	if(totale<=8000)
	{
		$('#valoreTotale').text(totale.toFixed(2).replace(".",","));
		$('#valoreTotale2').text(totale.toFixed(2).replace(".",","));
	}
	
	//pesco l'iva
	var tipoIva=$('input[name=tipo_iva]:checked').val();
	var percIva=  0.1;
	if(tipoIva=="aziendale")
	{
		percIva= 0.04;
	}
	
	

//attiviamo o meno il tasto per andare avanti
	if(totale > 0 )
		{
			$('.nextMostra[rel=1]').removeClass('disabled');
		}
		else
		{
			$('.nextMostra[rel=1]').addClass('disabled');
		}
	return totale;
};
var calcoloSpeseDiSpedizione =function(){
		//pesco l'iva
		var tipoIva=$('input[name=tipo_iva]:checked').val();
		var percIva=  0.1;
		if(tipoIva=="aziendale")
		{
			percIva= 0.04;
		}
	    var totaleString=$('#valoreTotale').text().replace(",",".");
	//alert(totaleString);
		var totale= parseFloat(totaleString);
		//aggiorno anche le spese di spedizione
		$.get('ajaxRequests.php?totale_buoni_spese_spedizione='+totale,function(data){
			speseDiSpedizione=parseInt(data);
			//alert(speseDiSpedizione);
			if(speseDiSpedizione > 0)
			{
				$('#speseSpedizione').text(speseDiSpedizione+ " €");
			}
			else
			{
				$('#speseSpedizione').text("gratuite");
				speseDiSpedizione=0;
			}
			//alert(tipoIva);
			$('#totaleIva').text((speseDiSpedizione+totale+((totale+speseDiSpedizione)*percIva)).toFixed(2).replace(".",","));
			$('#totaleIva2').text((speseDiSpedizione+totale+((totale+speseDiSpedizione)*percIva)).toFixed(2).replace(".",","));



		});	
};
var aggiornaBlocchetto =  function(elemString,value){
	$('.totaleBuono').find('span[rel="'+elemString+'"]').text(""+(value*20));
};
var attivaPulsanti =  function(elem,value){
	if(value > 0)
	{
		elem.find('.freccettaGiu').removeClass('disabled');
		elem.find('.cestinoBuoni').removeClass('disabled');
	}
	if(value == 0)
	{
		elem.find('.freccettaGiu').addClass('disabled');
		elem.find('.cestinoBuoni').addClass('disabled');
	}
	if(value >= 99)
	{
		elem.find('.freccettaSu').addClass('disabled');
	}
	else
	{
		elem.find('.freccettaSu').removeClass('disabled');	
	}
	
};
$('.freccettaSu').click(function(){
	if(!$(this).hasClass('disabled'))
	{
		var bloccoPulsanti=$(this).parents('.tabellaFive');
		var name=$(this).parents('.tabellaFive').find('input').attr('name');
		var actualString=$(this).parents('.tabellaFive').find('input').val()
		var actual=parseInt(actualString);
		if(actualString!='')
		{
			actual++;
		}
		else
		{
			actual=1;
		}
		
		$(this).parents('.tabellaFive').find('input').val(actual);
		aggiornaBlocchetto(name,actual);
		if(aggiornaTotale() > 8000)
		{
				actual--;
				$(this).parents('.tabellaFive').find('input').val(actual);
				aggiornaBlocchetto(name,actual);
				maxPrice();
		}
		attivaPulsanti(bloccoPulsanti,actual);
	}
	
});

$('.imageBlocchetto').click(function(){
		var name=$(this).attr('rel');
        var bloccoPulsanti=$('input[name='+name+']').parents('.tabellaFive');
		var actualString=$('input[name='+name+']').val();
		var actual=parseInt(actualString);
		if(actualString!='')
		{
			actual++;
		}
		else
		{
			actual=1;
		}
		
		$('input[name='+name+']').val(actual);
		aggiornaBlocchetto(name,actual);
		if(aggiornaTotale() > 8000)
		{
				actual--;
				$('input[name='+name+']').val(actual);
				aggiornaBlocchetto(name,actual);
				maxPrice();
		}
		attivaPulsanti(bloccoPulsanti,actual);
});
$('.cestinoBuoni').click(function(){
	if(!$(this).hasClass('disabled'))
	{
		var bloccoPulsanti=$(this).parents('.tabellaFive');
		var name=$(this).parents('.tabellaFive').find('input').attr('name');
		var actual=0
		$(this).parents('.tabellaFive').find('input').val(actual);
		aggiornaBlocchetto(name,actual);
		aggiornaTotale();
		attivaPulsanti(bloccoPulsanti,actual);
	}
	
});
$('.freccettaGiu').click(function(){
	if(!$(this).hasClass('disabled'))
	{
		var bloccoPulsanti=$(this).parents('.tabellaFive');
		var name=$(this).parents('.tabellaFive').find('input').attr('name');
		var actualString=$(this).parents('.tabellaFive').find('input').val()
		var actual=parseInt(actualString);
		if(actualString!='')
		{
			actual--;
		}
		else
		{
			actual=0;
		}
		
		$(this).parents('.tabellaFive').find('input').val(actual);
		aggiornaBlocchetto(name,actual);
		aggiornaTotale();
		attivaPulsanti(bloccoPulsanti,actual);
	}
});
//input
$('input.blocchetto').keyup(function(){
	//console.log($(this).attr('name'));
	var actual=parseInt($(this).val());
	if ($(this).val()=="")
	{
		actual=0;
	}
	aggiornaBlocchetto($(this).attr('name'),actual);
	while(aggiornaTotale() > 8000)
	{
			actual--;
			$(this).val(actual);
			aggiornaBlocchetto($(this).attr('name'),actual);
			maxPrice();
	}
	
	var bloccoPulsanti=$(this).parents('.tabellaFive');
	attivaPulsanti(bloccoPulsanti,actual);
});
$('input.blocchetto').ForceNumericOnly();


/***
Slide 2
**/
//popup

$('.popIva').click(function(){
	$('#popIvaOverlayContainer').fadeIn('slow');
});

$('#popIvaClose').click(function(){
	$('#popIvaOverlayContainer').fadeOut('fast');
});

//cambio dell'iva
$('input[name=tipo_iva]').change(function(){
	/*totale=parseFloat($('#valoreTotale').text());
	//if($)
	var tipoIva=$('input[name=tipo_iva]:checked').val();
	var percIva=  0.1;
	if(tipoIva=="aziendale")
	{
		percIva= 0.04;
	}
	//alert(tipoIva);
	$('#totaleIva').text((speseDiSpedizione+totale+((totale+speseDiSpedizione)*percIva)).toFixed(2).replace(".",","));
	$('#totaleIva2').text((speseDiSpedizione+totale+((totale+speseDiSpedizione)*percIva)).toFixed(2).replace(".",","));
	*/
	calcoloSpeseDiSpedizione();
});
var okPartitaIva =false;
//partita iva numerica
//$('#p_iva').ForceNumericOnly();
//controllo validità piva
$('#p_iva').keyup(function(){
	var PivaEl=$('#p_iva');
	if($(this).val().length < 11)
	{
		$('.nextMostra[rel=2]').addClass('disabled');
		PivaEl.css('background-color','white');
	}
	else
	{
		$('.nextMostraSpinner[rel=2]').removeClass('disabled');
		$.get('ajaxRequests.php?partita_iva='+$(this).val(),function(data){
			var promozione=$('input[name=promozionale]:checked').val();
			data =$.parseJSON(data);
			
			if(data.result == "OK"  )
			{ 
				$('input[name=partita_iva_last]').val(PivaEl.val());
				$.each(data,function(index, value) { 
					if(index != 'result')
					{
						$('input[name='+index+']').val(value);
					}
				});
				PivaEl.css('background-color','white');
				if(promozione!="si")
				{
					$('.nextMostraSpinner[rel=2]').addClass('disabled');
					$('.nextMostra[rel=2]').removeClass('disabled');
				}
				else
				{
					
					$.get('ajaxRequests.php?codice_prom='+$('#codice_prom').val()+'&p_iva='+$('#p_iva').val(),function(data)
					{
						$('.nextMostraSpinner[rel=2]').addClass('disabled');
						calcoloSpeseDiSpedizione();
						if(data != errore1 && data != errore2 )
						{
							$('.nextMostra[rel=2]').removeClass('disabled');
							$('#codice_prom').css('background-color','#FFFFFF');
						}
						else
						{
							$('#codice_prom').css('background-color',errorColor);
							$('.nextMostra[rel=2]').addClass('disabled');
						}
					});			
				}		
			}
			else
			{
				$('.nextMostraSpinner[rel=2]').addClass('disabled');
				PivaEl.css('background-color',errorColor);
			}
		});
	
	}
});
//inizializzo nascondibile
$('.nascondibile').fadeOut('fast');
$('input[name=promozionale]').change(function(){
	var PivaEl=$('#p_iva');
	var promozione=$('input[name=promozionale]:checked').val();
	if(promozione=="si")
	{
		$('.nascondibile').fadeIn('fast');
		
		if($('#codice_prom').val().length > 1)
		{
			$('.nextMostraSpinner[rel=2]').removeClass('disabled');
			$.get('ajaxRequests.php?codice_prom='+$('#codice_prom').val()+'&p_iva='+PivaEl.val(),function(data){
				$('.nextMostraSpinner[rel=2]').addClass('disabled');
				if(data != errore1 && data != errore2 )
				{
					
						
							//$('#speseSpedizione').text("gratuite");
							calcoloSpeseDiSpedizione();
						
						$('.nextMostra[rel=2]').removeClass('disabled');
						

				}
				else
				{
					$('.nextMostra[rel=2]').addClass('disabled');
					calcoloSpeseDiSpedizione();
					//PivaEl.css('background-color',errorColor);
				}
			}
			);
		}
	}
	else
	{
		$('.nascondibile').fadeOut('fast');
		$('.nextMostraSpinner[rel=2]').removeClass('disabled');
		$.get('ajaxRequests.php?partita_iva='+$('#p_iva').val(),function(data){
			$('.nextMostraSpinner[rel=2]').addClass('disabled');
			var promozione=$('input[name=promozionale]:checked').val();
			data =$.parseJSON(data);
			if(data.result == "OK"  )
			{	
				$('input[name=partita_iva_last]').val(PivaEl.val());
				$.each(data,function(index, value) { 
					if(index != 'result')
					{
						$('input[name='+index+']').val(value);
					}
				});
				if(promozione!="si")
				{
					$('.nextMostra[rel=2]').removeClass('disabled');
				}
				
			}
			else
			{
				$('.nextMostra[rel=2]').addClass('disabled');
				PivaEl.css('background-color',errorColor);
			}
		});
	}
});
//verifico codice promozionale
$('#codice_prom').keyup(function(){
	var PivaVal=$('#p_iva').val();
	if($(this).val().length > 1)
	{
		$('.nextMostraSpinner[rel=2]').removeClass('disabled');
		$.get('ajaxRequests.php?codice_prom='+$(this).val()+'&p_iva='+PivaVal,function(data){
			if(data != errore1 && data != errore2)
			{
					
						//$('#speseSpedizione').text("gratuite");
						calcoloSpeseDiSpedizione();
					
					$('#codice_prom').css('background-color','#FFFFFF');
					
						var PivaEl=$('#p_iva');
						if($('#p_iva').val().length < 11)
						{
							$('.nextMostraSpinner[rel=2]').addClass('disabled');
							$('.nextMostra[rel=2]').addClass('disabled');
							PivaEl.css('background-color','white');
						}
						else
						{
							$.get('ajaxRequests.php?partita_iva='+$('#p_iva').val(),function(data){
								$('.nextMostraSpinner[rel=2]').addClass('disabled');
								var promozione=$('input[name=promozionale]:checked').val();
								data =$.parseJSON(data);

								if(data.result == "OK"  )
								{ 
									$('input[name=partita_iva_last]').val(PivaEl.val());
									$.each(data,function(index, value) { 
										if(index != 'result')
										{
											$('input[name='+index+']').val(value);
										}
									});
									
										$('.nextMostra[rel=2]').removeClass('disabled');
											
								}
								else
								{
									PivaEl.css('background-color',errorColor);
								}
							});

						}
					
				/*	$.get('ajaxRequests.php?ricava_codice_prom='+$(this).val(),function(data){
						
					});*/
			}
			else
			{
				$('.nextMostraSpinner[rel=2]').addClass('disabled');
				calcoloSpeseDiSpedizione();
				$('.nextMostra[rel=2]').addClass('disabled');
				//PivaEl.css('background-color',errorColor);
				$('#codice_prom').css('background-color',errorColor);
			}
		}
		);
	}
	
	
});
/*SLIDE 3*/

//popup

$('#visioneImg').click(function(){
	$('#popVisioneOverlayContainer').fadeIn('slow').jScrollPane();
	$('#popVisioneOverlayContainer').find('.stripeMostraVertical').jScrollPane({
		showArrows: true,
		horizontalGutter: 100
	});
});

$('#popVisioneClose').click(function(){
	$('#popVisioneOverlayContainer').fadeOut('fast');
});

$('#lettoImg').click(function(){
	$('#popLettoOverlayContainer').fadeIn('slow');
	$('#popLettoOverlayContainer').find('.stripeMostraVertical').jScrollPane({
		showArrows: true,
		horizontalGutter: 100
	});
});

$('#popLettoClose').click(function(){
	$('#popLettoOverlayContainer').fadeOut('fast');
});


$('input[name=visione]').change(function(){
	OkObbligatori();
});
$('input[name=letto]').change(function(){
	OkObbligatori();
});
$('.obbligatorio').keyup(function(){
	OkObbligatori(this);
});
$('input[name=cap_f]').ForceNumericOnly();
$('input[name=cap_c]').ForceNumericOnly();
$('input[name=partita_iva_last]').ForceNumericOnly();
$('input[name=telefono]').ForceNumericOnly();

//Slide 4
$('.cliccaEpaga').click(function(){
	salvaNelDb(this);
	
});

var checkPIva = null;
var checkCF = null;
var checkEmail = null;

function checkPIvaInit(){//SINCRONO!
	var ok = false;
	var PivaEl=$('input[name=partita_iva_last]');
	if(PivaEl.val().length >= 11){
		$.ajax({
	         url: 'ajaxRequests.php?partita_iva='+PivaEl.val(),
	         success: function(data){
				//var promozione=$('input[name=promozionale]:checked').val();
				data =$.parseJSON(data);
				if(data.result == "OK"  ){ 
					ok = true;
				}
			},
	        async: false
	    });
	}
	return ok;
}

function checkCFInit(){//SINCRONO!
	var ok = false;
	var CodiceFiscEl=$('input[name=cf]');
	if(CodiceFiscEl.val().length >= 11){
		$.ajax({
	         url: 'ajaxRequests.php?controllaCF='+CodiceFiscEl.val(),
	         success: function(data){
				//var promozione=$('input[name=promozionale]:checked').val();
				//data =$.parseJSON(data);
				if(data == "ok"  ){ 
					ok = true;
				}
			},
	        async: false
	    });
	}
	return ok;
}

function checkEmailInit(){//SINCRONO!
	var ok = false;
	var EmailEl=$('input[name=email]');
	if(EmailEl.val().length >= 5){
		$.ajax({
	         url: 'ajaxRequests.php?controllaEmail='+EmailEl.val(),
	         success: function(data){
				//var promozione=$('input[name=promozionale]:checked').val();
				//data =$.parseJSON(data);
				if(data == "ok"  ){ 
					ok = true;
				}
			},
	        async: false
	    });
	}
	return ok;
}

function checkObbligatori(){
	var ok = true;
	
	$('.obbligatorio').each(function(){
		var length=2;
		if ($(this).attr('name')== "cap_f" || $(this).attr('name')== "cap_c"){
			length = 5;
		}
		if($(this).val().length < length ){
			if($(this).val().length > 0){
				$(this).css('background-color',errorColor);
			}
			ok = false;
		}else{
			$(this).css('background-color','white');
		}
	});
	
	if($('input[name=letto]:checked').val()!="si" || $('input[name=visione]:checked').val()!="si" ){
		ok = false;
	} 
	
	if(checkPIva==null){
		checkPIva = checkPIvaInit();
	}
	if(!checkPIva){
		ok = false;		
		if($('input[name=partita_iva_last]').val().length > 2){
			$('input[name=partita_iva_last]').css('background-color',errorColor);
		}
	}
	
	if(checkCF==null){
		checkCF = checkCFInit();
	}
	if(!checkCF){
		ok = false;		
		if($('input[name=cf]').val().length > 2){
			$('input[name=cf]').css('background-color',errorColor);
		}
	}
	
	if(checkEmail==null){
		checkEmail = checkEmailInit();
	}
	if(!checkEmail){
		ok = false;		
		if($('input[name=email]').val().length > 2){
			$('input[name=email]').css('background-color',errorColor);
		}
	}
	
	return ok;
}

function OkObbligatori(elem){
	$('.nextMostraSpinner[rel=3]').removeClass('disabled');
	elemClicked=$(elem);
	var avanti = true;
	var ajaxInAction = false;
	
	avanti = checkObbligatori();
	
	//Caso speciale Partita IVA
	if(elemClicked.attr('name')== 'partita_iva_last'){
		avanti = false;
		var PivaEl=elemClicked;
		if(PivaEl.val().length < 11){
			PivaEl.css('background-color',errorColor);
		}else{
			ajaxInAction = true;
			$.get('ajaxRequests.php?partita_iva='+PivaEl.val(),function(data){ //ASINCRONO!!!!
				//var promozione=$('input[name=promozionale]:checked').val();
				data =$.parseJSON(data);
				if(data.result == "OK"  ){ 
					avanti = true;
					checkPIva = true;
					PivaEl.css('background-color','white');	
				}else{
					avanti = false;
					PivaEl.css('background-color',errorColor);
				}
				if(avanti && checkObbligatori()){
					$('.nextMostra[rel=3]').removeClass('disabled');
				}else{
					$('.nextMostra[rel=3]').addClass('disabled');
				}
				$('.nextMostraSpinner[rel=3]').addClass('disabled');
			});
		}
	}
	
	//Caso speciale codiceFiscale
	if(elemClicked.attr('name')== 'cf'){
		avanti = false;
		var CodiceFiscEl=elemClicked;
		if(CodiceFiscEl.val().length < 11){
			CodiceFiscEl.css('background-color',errorColor);
		}else{
			ajaxInAction = true;
			$.get('ajaxRequests.php?controllaCF='+CodiceFiscEl.val(),function(data){ //ASINCRONO!!!!
				//var promozione=$('input[name=promozionale]:checked').val();
				//data =$.parseJSON(data);
				if(data == "ok"  ){ 
					avanti = true;
					checkCF = true;
					CodiceFiscEl.css('background-color','white');	
				}else{
					avanti = false;
					//$('.nextMostra[rel=3]').addClass('disabled');
					CodiceFiscEl.css('background-color',errorColor);
				}
				if(avanti && checkObbligatori()){
					$('.nextMostra[rel=3]').removeClass('disabled');
				}else{
					$('.nextMostra[rel=3]').addClass('disabled');
				}
				$('.nextMostraSpinner[rel=3]').addClass('disabled');
			});
		}
	}
	
	//Caso speciale email
	if(elemClicked.attr('name')== 'email'){
		avanti = false;
		var EmailEl=elemClicked;
		if(EmailEl.val().length < 5){
			EmailEl.css('background-color',errorColor);
		}else{
			ajaxInAction = true;
			$.get('ajaxRequests.php?controllaEmail='+EmailEl.val(),function(data){ //ASINCRONO!!!!
				//var promozione=$('input[name=promozionale]:checked').val();
				//data =$.parseJSON(data);
				if(data == "ok"  ){ 
					avanti = true;
					checkEmail = true;
					EmailEl.css('background-color','white');	
				}else{
					avanti = false;
					//$('.nextMostra[rel=3]').addClass('disabled');
					EmailEl.css('background-color',errorColor);
				}
				if(avanti && checkObbligatori()){
					$('.nextMostra[rel=3]').removeClass('disabled');
				}else{
					$('.nextMostra[rel=3]').addClass('disabled');
				}
				$('.nextMostraSpinner[rel=3]').addClass('disabled');
			});
		}
	}
	
	if(avanti){
		$('.nextMostra[rel=3]').removeClass('disabled');
	}else{
		$('.nextMostra[rel=3]').addClass('disabled');
	}
	
	if(!ajaxInAction){
		$('.nextMostraSpinner[rel=3]').addClass('disabled');
	}
	
	return avanti; 
}

function salvaNelDb(tasto)
{   
	$('#popWaitOverlayContainer').fadeIn('fast');
	var requestString = "ajaxRequestsPost.php";
	//alert('1');
	var datiDaInviare = "{";
	datiDaInviare+='"nelDB": "yes",';
	//alert(datiDaInviare['nelDB']);
	$('.nelDb').each(function(){
		datiDaInviare+='"'+$(this).attr('name')+'": "'+$(this).val().replace(/\"/g,'\\"').replace(/(\r\n|\n|\r)/gm, ' ')+'",';
		//alert(datiDaInviare[$(this).attr('name')]);
	});
	//alert('3');
	datiDaInviare+='"totale_buoni": "'+$('#valoreTotale2').text().replace(",",".")+'",';
	if (isNaN(parseInt($('#speseSpedizione').text())))
	{
		datiDaInviare+='"spese_spedizione": "0",';
	}
	else
	{
		datiDaInviare+='"spese_spedizione": "'+''+parseInt($('#speseSpedizione').text())+'",';
	}

	datiDaInviare+='"totale_ordine": "'+''+parseFloat($('#totaleIva').text().replace(",","."))+'",';
	datiDaInviare+='"iva": "'+$('input[name=tipo_iva]:checked').attr('rel')+'",';
	//alert('4');
	
	
	//alert('5');
	

	if($(tasto).attr('id')=='bonificoClick')
	{
		//datiDaInviare['iva=";
	}
	if($(tasto).attr('id')=='myBankClick')
	{
		datiDaInviare+='"tasto_mybank": '+'"1",';
	}
	if($(tasto).attr('id')=='paypalClick')
	{
		datiDaInviare+='"tasto_paypal": '+'"1",';
	}
	//alert('prima');
/*	$(datiDaInviare).each(function(val){
		alert(val);
	});*/
	//cattura anche i blocchetti
	datiDaInviare+='"blocchetto1": "'+$('#blocchetto1').val()+'",';
	datiDaInviare+='"blocchetto2": "'+$('#blocchetto2').val()+'",';
	datiDaInviare+='"blocchetto3": "'+$('#blocchetto3').val()+'",';
	datiDaInviare+='"blocchetto4": "'+$('#blocchetto4').val()+'",';
	datiDaInviare+='"blocchetto5": "'+$('#blocchetto5').val()+'"}';
	
	//da eliminare
	//datiDaInviare='{"nelDB": "yes"}';
	
	$.post(requestString,datiDaInviare,function(data){
		//alert(datiDaInviare);
	   	data =$.parseJSON(data);
		
		if(data.result == "OK"  )
		{
			gestisciPagamenti(tasto,data);
		}
		else
		{
			somethingGoesWrong(data.error_type);
		}
		
	});
	
}
function maxPrice()
{
	$('#maxPrice').css({borderWidth: "3px"});
	$('#maxPrice').fadeIn('fast',function(){
		$('#maxPrice').animate({borderWidth: "0"},2000);
		setTimeout(function(){
			$('#maxPrice').fadeOut('slow');
		},3000);
	});
}
function somethingGoesWrong(error_type)
{
	alert('Non è possibile completare l\'ordine perchè i dati inviati non sono corretti ('+error_type+'). Riprova!');
	window.location.reload();
}

function gestisciPagamenti(tasto,data)
{
	if($(tasto).attr('id')=='bonificoClick')
	{
		
		location.href=  location.href.substring(0,location.href.indexOf('acquista.php'))+'acquistoCompletatoBonifico.php?ordine='+data.id;
	}
	if($(tasto).attr('id')=='myBankClick')
	{
		$('#namePerMybank').val("Ordine n."+data.id);
		$('#idPerMybank').val(data.id);
		$('#emailPerMybank').val(data.email);
		$('#b64PerMybank').val(data.b64);
		$('#totalePerMybank').val(data.totale);
		$('#form_mybank').submit();
		
	}
	if($(tasto).attr('id')=='paypalClick')
	{
		$paypal_url="www.paypal.com";
		$paypal_account="info@day.it";
		$paypal_causale="Ordine DAYshop.it n. ";
		$paypal_currency="EUR";
		$paypal_returnok="http://"+top.location.host+"/acquistoCompletatoPaypal.php";
		$paypal_returnno="http://"+top.location.host+"/pagamento_no.php";
		$id=data.id;
		$totale=data.totale;
		//alert("https://"+$paypal_url+"/cgi-bin/webscr?cmd=_xclick&business="+$paypal_account+"&item_name="+$paypal_causale+$id+"&currency_code="+$paypal_currency+"&amount="+$totale+"&return="+$paypal_returnok+"&cancel_return="+$paypal_returnno+"&no_shipping=1&no_note=1&item_number="+$id);
		location.href="https://"+$paypal_url+"/cgi-bin/webscr?cmd=_xclick&business="+$paypal_account+"&item_name="+$paypal_causale+$id+"&currency_code="+$paypal_currency+"&amount="+$totale+"&return="+$paypal_returnok+"&cancel_return="+$paypal_returnno+"&no_shipping=1&no_note=1&item_number="+$id;
	}
	
}

});


