var cont=true;
var msg='';

function validate(validator, validator_class){
	ret_msg='';
	cont=true;
	msg='';
	if (validator == undefined){
		var validator = new Object();
	}

	if (validator_class == undefined){
		var validator_class = new Object();
	}
	for (classe in validator_class){
		$$('.'+classe).each(function(el){
			validator[el.id] = new Object();
			validator[el.id]['msg'] = validator_class[classe]['msg'];
			validator[el.id]['format'] = validator_class[classe]['format'];
			validator[el.id]['level'] = validator_class[classe]['level'];
			validator[el.id]['query'] = validator_class[classe]['query'];
			validator[el.id]['force'] = validator_class[classe]['force'];
			validator[el.id]['if_clausule'] = validator_class[classe]['if_clausule'];
		});
	}
	for (id in validator){
		if ($(id) != undefined){
			//Gestisco la validazione condizionale (se presente)
			if ((!visibleField($(id))) && (id!='spec_count') && (validator[id].force!=1)){
				console.log(id);
				var if_cl = false;
			}else{
				if (validator[id].if_clausule!=undefined){
					var if_cl = eval(validator[id].if_clausule.replace(/&amp;/g,'&').replace(/&gt;/g,'>').replace(/&lt;/g,'<'));
				}else{
					var if_cl = true;
				}
			}
			
			if (if_cl){
				if (validator[id].format=='FILL'){
					if ($(id).value==''){
						cont = false;
						msg+=" * "+validator[id].msg+"\n";
					}
				}
				if (validator[id].format=='GT0'){
					if ($(id).value==0){
						cont = false;
						msg+=" * "+validator[id].msg+"\n";
					}
				}
				if (validator[id].format=='CK'){
					if ($(id).checked == false){
						cont = false;
						msg+=" * "+validator[id].msg+"\n";
					}
				}
				if (validator[id].format=='PIVA'){
					var tipo = $('tipo_azienda');
					if (tipo!=undefined){
						if ((tipo.value=='G') || (tipo.value=='D')){
							ret_msg = ControllaPIVA($(id).value);
						}
					}
					if (ret_msg!=''){
						cont = false;
						msg+=" * PI: "+ret_msg+"\n";
					}
				}
				if (validator[id].format=='CF'){
					var tipo = $('tipo_azienda');
					if (tipo!=undefined){
						if ((tipo.value=='G') || (tipo.value=='N')){
							ret_msg = ControllaPIVA($(id).value);
						}else if (tipo.value!='E'){	
							ret_msg = ControllaCF($(id).value);
						}
					}else{
						ret_msg = ControllaCF($(id).value);
					}
					if (ret_msg!=''){
						cont = false;
						msg+=" * CF: "+ret_msg+"\n";
					}
				}
			}
			//Inserire qui altre forme di validazione
		}
	}
	if (msg!='') alert(msg);
	return cont;
}

function visibleField (elem) {
   while (elem) {
       if (elem == document.body) break;
       if (!elem.visible()) return false;
       if (elem.getStyle('display') == 'none') return false;
       if (elem.readOnly) return false;
       elem = elem.up();
   }
   return true;
}

function checkquery(id){
	try{
		var id_value = $(id).value;
				
		var match = validator[id].query.match(/#[^#]+#/g);
		var query = validator[id].query;
		match.each(function(m){
		    if ($(m.gsub('#',''))!=undefined){
		    	query = query.replace(m, $(m.gsub('#','')).value)
		    }
		});
		var ansmsg = validator[id].msg;
		new Ajax.Request('ajax.php?op=query&query='+query, {
			onSuccess: function(transport){
				eval(transport.responseText);
				if (result['1']['ans']=='NO'){
					msg = ansmsg;
					alert(msg);
				}else{
					cont = true;
				}
			}
		});
	} catch (e) {
		return;
	}
}

function unique(element,id,value,field,table,ansmsg){
	if (value!=''){
		var query = "select IF(count("+field+")>0,'NO','OK') as ans from "+table+" where "+field+"='"+value+"' and "+id+"!="+element+" and status=1";
		new Ajax.Request('ajax.php?op=query&query='+query, {
			onSuccess: function(transport){
				eval(transport.responseText);
				if (result['1']['ans']=='NO'){
					cont = false;
					msg = ansmsg;
					alert(msg);
				}else{
					cont = true;
				}
			}
		});
	}else{
		cont = true;
	}
}

function ControllaCF(cf){
	var validi, i, s, set1, set2, setpari, setdisp;
	//if( cf == '' )  return '';
	cf = cf.toUpperCase();
	if( cf.length != 16 )
		return "Il codice fiscale dovrebbe essere lungo esattamente 16 caratteri.";
	validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	for( i = 0; i < 16; i++ ){
		if( validi.indexOf( cf.charAt(i) ) == -1 )
			return "Il codice fiscale contiene un carattere non valido `" + cf.charAt(i) + "'";
	}
	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 "Il codice di controllo del codice fiscale non corrisponde.";
	return "";
}

function ControllaPIVA(pi){
	//if( pi == '' )  return '';
	if( pi.length != 11 )
		return "la partita IVA dovrebbe essere lunga esattamente 11 caratteri.";
	validi = "0123456789";
	for( i = 0; i < 11; i++ ){
		if( validi.indexOf( pi.charAt(i) ) == -1 )
			return "La partita IVA contiene un carattere non valido `" + pi.charAt(i) + "'";
	}
	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 "Il codice di controllo della partita iva non corrisponde.\n";
	return '';
}
