$(document).ready(function(){
	
	$("#requestForm .quantita input").val("0");
	ricalcolaQuantitaPrezzo();
	
	var validator = $("#formId").validate({
		rules: {
			name: {
				required: true
			},
			surname:{
				required: true
			},
			city:{
				required: true
			},
			address:{
				required: true
			},
			tel:{
				required: true
			},
			email:{
				required: true,
				email: true
			}
		}
	});
	
	
	
    $("#requestForm .quantita input").change(function () {
    	if(!IsNumeric($(this).val()))
    		$(this).val("0");
    	
    	ricalcolaQuantitaPrezzo();

    });
    
    
    

  });

function ricalcolaQuantitaPrezzo(){
	var totQta=0;
	var totPrezzo=0;
	$("#requestForm .quantita input").each(function () {
        totQta += $(this).val()*1;
        totPrezzo += ricalcolaPrezzoRiga($(this));
      });
	totPrezzo=Math.round(totPrezzo*100)/100;
	$("#requestForm #totQta").html(totQta);
	if (totPrezzo.toString().lastIndexOf('.')>0){
		var y = totPrezzo.toString().split(".");

		if((totPrezzo*100%10)!=0)
			totPrezzo = y[0]+","+y[1];
		else
			totPrezzo = y[0]+","+y[1]+"0";
		
	} else {
		totPrezzo = totPrezzo+",00";
	}
		$("#requestForm #totPrezzo").html('<span>&euro;&nbsp;</span>'+totPrezzo);
	
	
}

function ricalcolaPrezzoRiga(e){
	
	var prezzoSingolo = e.parent().next("td").find("span").html();
	prezzoSingolo = prezzoSingolo.replace(',','.');
	prezzoSingolo = prezzoSingolo.substring(2);
	var prezzoRiga = e.val()* prezzoSingolo;

	return 	prezzoRiga;
	
}

function IsNumeric(expression) {

	var nums = "0123456789";
	if (expression.length==0)return(false);
	for (var n=0; n < expression.length; n++){
		if(nums.indexOf(expression.charAt(n))==-1)return(false);
	}
	return(true);
}


