function trim(str){ 
  return str.replace(/^\s+|\s+$/g, '');
};

$(document).ready(function() {
	$('#pulsanteInvio').click(function() {
		var errors = 'Correggi i seguenti errori:\n';
		var errorsFound = false;
		
		var nome = $('#nome').val();
		var cognome = $('#cognome').val();
		var email = $('#email').val();
		var citta = $('#citta').val();
		var sezione = $('#sezione').attr('value');
		var professione = $('input[name=professione]:checked').val();
		var privacy = $('input[name=privacy]:checked').val();
		var contact = $('input[name=contact]:checked').val();
		contact = (contact=="yes")?1:0;
		
		if (nome == '') {
			errors += '  - Non hai specificato il tuo nome\n';
			errorsFound = true;
		}
		
		if (cognome == '') {
			errors += '  - Non hai specificato il tuo cognome\n';
			errorsFound = true;
		}
		
		var email = trim(email);  // value of field with whitespace trimmed off
		var re = /^[^@]+@[^@.]+\.[^@]*\w\w$/
		if (!re.test(email)) {
			errors += '  - L\'e-mail non è corretta\n';
			errorsFound = true;
		}
		
		if (privacy != 'yes') {
			errors += '  - Devi accettare le condizioni e l\'informativa sulla privacy\n';
			errorsFound = true;
		}
		
		if (errorsFound) {
			alert(errors);
		} else {
			$.ajax({
				type: 'POST',
				url: '/aggiornamenti/save/',
				data: {
					nome: nome,
					cognome: cognome,
					email: email,
					citta: citta,
					professione: professione,
					sezione: sezione,
					contact: contact
				},
				dataType: 'text',
				success: function(text) {
					if (text == 'ok') {
						$('#form-aggiornamenti').html('<strong>La tua iscrizione è andata a buon fine. Riceverai aggiornamenti al più presto.</strong>');
						
					} else {
						alert('Siamo spiacenti, ma si è verificato un errore di invio. Ritenta.\n(' + text + ')');
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert('Siamo spiacenti, ma si è verificato un errore di invio. Ritenta.\n(' + errorThrown + " - " + textStatus + ')');
				}
			});
		}
	});
});
