$(document).ready(function(){
 	
	$("form").validate({
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? ' Hai inserito 1 campo errato. Gli errori sono evidenziati in rosso'
					: ' Hai inserito ' + errors + ' campi errati. Gli errori sono evidenziati in rosso';
				$("div.error span").html(message);
				$("div.error").show();
			} else {
				$("div.error").hide();
			}
		},
		onkeyup: false,
		submitHandler: function() {
			$("div.error").hide();
			alert("submit! use link below to go to the other step");
		},
		messages: {
			password2: {
				required: " ",
				equalTo: "Please enter the same password as above"	
			},
			email: {
				required: " ",
				email: "Please enter a valid email address, example: you@yourdomain.com",
				remote: jQuery.validator.format("{0} is already taken, please enter a different address.")	
			}
		},
		debug:true
	});
	
	// ----------------- Maschere di INPUT ------------------
	$("input.zipcode").mask("99999");
	$("input.dateITA").mask("99/99/9999");
	// ------------------------------------------------------

	// *********** .button  *********
	$(".button").mouseover(function (){
		var src = $(this).attr('src');
		var parti2 = src.split(".");
		var est = parti2[1];
		var parti = parti2[0].split("/");
		var nome = parti[parti.length - 1];
		parti = nome.split("_");
		var originale = parti[0];
		if(src.indexOf('_over') != -1){
			$(this).attr('src', 'images/' + originale + '.' + est);
		}else{
			$(this).attr('src', 'images/' + originale + '_over.' + est);
		}
	});
	$(".button").mouseout(function (){
		var src = $(this).attr('src');
		var parti2 = src.split(".");
		var est = parti2[1];
		var parti = parti2[0].split("/");
		var nome = parti[parti.length - 1];
		parti = nome.split("_");
		var originale = parti[0];
		if(src.indexOf('_over') != -1){
			$(this).attr('src', 'images/' + originale + '.' + est);
		}else{
			$(this).attr('src', 'images/' + originale + '_over.' + est);
		}
	});
	// *****************************
});


// ----------------- Traduzioni Standard ------------------
jQuery.extend(jQuery.validator.messages, {
       required: "Campo obbligatorio.",
       remote: "Controlla questo campo.",
       email: "Inserisci un indirizzo email valido.",
       url: "Inserisci un indirizzo web valido (es: http://www.miosito.it).",
       date: "Inserisci una data valida.",
       dateISO: "Inserisci una data valida (ISO).",
       dateITA: "Inserisci una data valida.",
       number: "Inserisci un numero valido.",
       numberDE: "Inserisci un numero valido.",
       digits: "Inserisci solo numeri.",
       creditcard: "Inserisci un numero di carta di credito valido.",
       equalTo: "Il valore non corrisponde.",
       accept: "Inserisci un valore con un&apos;estensione valida.",
       maxlength: jQuery.validator.format("Non inserire pi&ugrave; di {0} caratteri."),
       minlength: jQuery.validator.format("Inserisci almeno {0} caratteri."),
       rangelength: jQuery.validator.format("Inserisci un valore compreso tra {0} e {1} caratteri."),
       range: jQuery.validator.format("Inserisci un valore compreso tra {0} e {1}."),
       max: jQuery.validator.format("Inserisci un valore minore o uguale a {0}."),
       min: jQuery.validator.format("Inserisci un valore maggiore o uguale a {0}.")
});
// ------------------------------------------------------

function codfiscale(cf){
	// vedi http://www.icosaedro.it/cf-pi/cf-js.txt
	var validi, i, s, set1, set2, setpari, setdisp;
	if(cf == '') return true;
	cf = cf.toUpperCase();
	if(cf.length != 16) return false;
	validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	for( i = 0; i < 16; i++ ){
		if(validi.indexOf( cf.charAt(i) ) == -1) return false;
	}
	set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
	s = 0;
	for(i = 1; i <= 13; i += 2)
		s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	for(i = 0; i <= 14; i += 2)
		s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	if(s % 26 != cf.charCodeAt(15) - 'A'.charCodeAt(0)) return false;
	return true;
}
// ----------------- Metodi Specifici -------------------
jQuery.validator.addMethod("codfiscale", function(value){ 
	return codfiscale(value);
}, "Formato Codice Fiscale errato");

function piva(pi){
	// vedi http://www.icosaedro.it/cf-pi/pi-js.txt
	var i, validi, s, c;
	if(pi == '') return true;
	if(pi.length != 11) return false;
	validi = "0123456789";
	for(i = 0; i < 11; i++){
		if(validi.indexOf(pi.charAt(i)) == -1) return false;
	}
	s = 0;
	for(i = 0; i <= 9; i += 2)
		s += pi.charCodeAt(i) - '0'.charCodeAt(0);
	for(i = 1; i <= 9; i += 2){
		c = 2 * (pi.charCodeAt(i) - '0'.charCodeAt(0));
		if(c > 9) c = c - 9;
		s += c;
	}
	if((10 - s % 10) % 10 != pi.charCodeAt(10) - '0'.charCodeAt(0)) return false;
	return true;
}
jQuery.validator.addMethod("piva", function(value){ 
	return piva(value);
}, "Formato Partita IVA errato");

jQuery.validator.addMethod("codfiscale_piva", function(value){ 
	return codfiscale(value) || piva(value);
}, "Formato Codice fiscale / partita IVA errato");

jQuery.validator.addMethod("codfiscale_azienda", function(value){ 
	return codfiscale(value) || piva(value);
}, "Formato Codice Fiscale errato");

jQuery.validator.addMethod("zipcode", function(value, element){ 
	var regex = /[\d]{5}/;
	if(value == "") return true;
	else if(value == "_____") return true;
	else return value.match(regex);
}, "Formato CAP errato");

jQuery.validator.addMethod("dateITA", function(value, element){
		if(value == "__/__/____") return true;
		var check = false;
		var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
		if( re.test(value)){
			var adata = value.split('/');
			var gg = parseInt(adata[0],10);
			var mm = parseInt(adata[1],10);
			var aaaa = parseInt(adata[2],10);
			var xdata = new Date(aaaa,mm-1,gg);
			if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) )
				check = true;
			else
				check = false;
		} else
			check = false;
		return this.optional(element) || check;
	}, "Formato data errato");

jQuery.validator.addMethod("almeno", function(value, element, params){ 
	if(value == "") return true;
	if(value.length >= params*1) return true;
	else return false;
}, "Troppi pochi caratteri");

jQuery.validator.addMethod("somma100", function(value, element, params){ 
	if((params*1 + value*1) <= 100) return true;
	else return false;
}, "Si prega di specificare un valore che sommato non superi il 100%");

jQuery.validator.addMethod("data_successiva", function(value, element, params){ 
	if(value == "") return true;
	else if(value == "__/__/____") return true;

	var arr1 = value.split("/");
	var arr2 = params.split("/");
	var d1 = new Date(arr1[2], arr1[1]-1, arr1[0]);
	var d2 = new Date(arr2[2], arr2[1]-1, arr2[0]);
	var r1 = d1.getTime();
	var r2 = d2.getTime();

	if(r1>=r2) return true;
	else return false;

}, "Si prega di specificare una data successiva alla compilazione");
jQuery.validator.addMethod("data_precedente", function(value, element, params){ 
	if(value == "") return true;
	else if(value == "__/__/____") return true;

	var arr1 = value.split("/");
	var arr2 = params.split("/");
	var d1 = new Date(arr1[2], arr1[1]-1, arr1[0]);
	var d2 = new Date(arr2[2], arr2[1]-1, arr2[0]);
	var r1 = d1.getTime();
	var r2 = d2.getTime();

	if(r1<r2) return true;
	else return false;

}, "Si prega di specificare una data precedente alla compilazione");
jQuery.validator.addMethod("anno_uguale", function(value, element, params){ 
	if(value == "") return true;
	else if(value == "__/__/____") return true;

	var a1 = value.split('/')[2];
	var a2 = params;
	return a1 == a2;
}, "Anno sbagliato.");

jQuery.validator.addMethod("required_if", function(value, element, params){
	var el = jQuery('input[name=' + params + ']:first').get()[0];
	if (jQuery(el).is(':checked')){
		return element.value != '';
	};
	return true;
}, 'Il dato è obbligatorio');
// ------------------------------------------------------

function scambia_occhietto(campo){
	str = "document.form." + campo;
	if(eval(str).value == "ON"){
		eval(str).value = "";
		document.getElementById("Occhietto_" + campo).src = "images/visnot.gif";
	}else{
		eval(str).value = "ON";
		document.getElementById("Occhietto_" + campo).src = "images/vis.gif";
	}
}
