window.addEvent('domready',function(){Validacion()});

var Validacion=function(){ 
    
  var validaciones={
    obligatorio: " es obligatorio",
    hora: " debe tener el formato hh:mm, por ejemplo: 11:30",
    nif: " no es un NIF o NIE válido",
    nie: " no es un NIE válido",
    cif: " no es un CIF válido" ,
    nif_cif: " no es un NIF, CIF o NIE válido",
    email : " no es un email válido",
    numero: " debe ser un número entero, sin puntos ni comas",
    decimal: " debe ser un número con hasta dos decimales, utlizando el punto como separador",
    fecha : " debe tener el formato dd/mm/aaaa, por ejemplo 18/10/2007",
    color: " debe ser un color en hexadecimal, por ejemplo CC0000",
    aceptar: "debe estar marcado"    
  }    

  function nombreCampo(em){
    var nombre=em.title;
    if(!nombre && $(em.parentNode).getTag()=='label'){
        nombre=em.parentNode.firstChild.nodeValue;
    }
    if(!nombre && em.getPrevious() && ($(em.getPrevious()).getTag()=='label' || $(em.getPrevious()).getTag()=='span')){
        nombre=$(em.getPrevious()).firstChild.nodeValue;
    }
    if(!nombre) nombre=em.name;
    if(!nombre) nombre=em.id;  
    nombre=nombre.replace(":","");
    return nombre;
  }
    
	$$('form').each(function(el){
	     el.validar=function(event){
		   $$('.texto_por_defecto').each(function(em){
           if(em.value==em.title) em.value='';
           });  	    
           el.getElements('*').each(function(em){
           	em.removeClass("campo_incorrecto");
           }); 
	         var mensaje="";       
	         for (valor in validaciones){
              $$('.'+valor).each(function(em){ 
                    if((em.getTag()=="input") || (em.getTag()=="textarea") || (em.getTag()=="select")){
                      if(esAncestro(el,em)){
                      	switch(em.type){
                      		case "file": var valor_campo=em.value;
                      			break;
                      		case "checkbox":  var valor_campo  = em.checked;
                      			break;
                      		default:
                      			var valor_campo=em.getValue();
                      	}
                      	
                        if(!this[valor+"Validar"](valor_campo)){
                              mensaje+="- El campo <em>" + nombreCampo(em) + "</em> "+validaciones[valor]+"<br/>";
                              em.addClass("campo_incorrecto");
                        }
                      }
                    }
                });
	       	 }
                    
	         if(mensaje){
	            alerta('<strong>Por favor, corrija los siguientes errores:</strong><br/> '+mensaje);  
	            try{
								cancelarRespuesta(event);	          
	            }catch(ex){}
              return false;           
	         }
	         return true;
	     }
	     
	    if(el.hasClass('ajax')){
	    	el.addEvent('submit',function(event){
	    		cancelarRespuesta(event);	 
	    		if(this.validar()){
		    		this.send({onComplete: function(res){
	          	alerta(res);
	          }});
	    		}
	    	});
	    }else{  
	    // Clase para que no se valide automáticamente.  
	    	if(!el.hasClass('sin_alerta')){
	    		el.addEvent('submit',el.validar);  
	    	}
	    }
	       
	});
}


function nifValidar(nif){   
    if(nif=="") return true;
    cadena="TRWAGMYFPDXBNJZSQVHLCKE";
    numeros="0123456789";
    if (nif.length!=9){
        return false;
    }
    for (i=0;i<8;i++) {
    numero = nif.charAt(i);
    if ( numeros.lastIndexOf(numero) == -1)
        return false; 
    }
    
    letra=nif.charAt(8).toUpperCase();
    if ( cadena.lastIndexOf(letra) == -1) {
        return false;
    }
    
    letra_calculada = cadena.charAt((nif.substr(0,8) % 23));
    if( letra_calculada != letra){
        //return false;
        return nieValidar(nif); //compruebo si es un nie
    }
    return true;
}


function cifValidar(cif){
	numeros="0123456789";
	cadena="ABCDEFGHPQSKLMX";
	cif=cif.toUpperCase();
	if (cif.length!=9) return false;
	for (i=1;i<8;i++) {    //comprueba si cif(i) no es un numero
        	   numero = cif.charAt(i);
        	   if ( numeros.lastIndexOf(numero) == -1 ) return false;
	}
	letra1=cif.charAt(0);
	letra9=cif.charAt(8);
	numero=cif.substr(1,8);
	if (letra1=="X") return false;
	if (cadena.indexOf(letra1) == -1) return false;
	control=0;
	for (i=0;i<7;i+=2){
		aux=parseInt(numero.charAt(i))*2;
		control+=aux%10+(aux-aux%10)/10;
	}
	control=10-(control+parseInt(numero.charAt(1))+parseInt(numero.charAt(3))+parseInt(numero.charAt(5)))%10;
	if (control==10) control=0;
	if (( control==letra9 ) || ( letra9==String.fromCharCode(control+64) ) ) return true;
		else return false;
}

function nieValidar(nie){
	if (nie.length!=9) return false;
	nie=nie.toUpperCase();
	letra1=nie.charAt(0);
	letra9=nie.charAt(8);
	numero=nie.substr(1,8);
	if (letra1=="X"){
                nif = "0"+""+numero;
	     return nifValidar(nif);
	}else return false;
}

function nif_cifValidar(numero){
  return (nifValidar(numero) ||  cifValidar(numero)); 
}


function horaValidar(hora){
    if ( hora == "" ) return true;
    var exp=new RegExp("(^([0-9]{2}):([0-9]{2})$)");    
    partes=hora.split(':');
    if ( exp.test(hora) == false || partes[0]<0 || partes[0]>23 || partes[1]>59 || partes[1]<0 ){
    	return false;
    }else{
       return true;
    }
}

function emailValidar(email){
    if (email!='' && (email.indexOf("@")==-1 || email.indexOf(".")==-1 ) ){
       return false;
    }
    return true;	
}

function obligatorioValidar(valor){
    if(valor==""){
        return false;
    }
    return true;
}

function numeroValidar(valor){
    if(Math.ceil(valor)==valor) return true;
    return false;
}

function decimalValidar(valor){
		partes=valor.split('.');
		if(partes.length>2) return false;
		if(partes[1] && partes[1].length>2) return false;
    if(Number(valor)==valor) return true;
    return false;
}

function fechaValidar(fecha){
	if ( fecha == "" ){
		return true;
	}
	var exp=new RegExp("(^([0-9]{2})/([0-9]{2})/([0-9]{4})$)");	
	partes=fecha.split('/');
	partes[1]=parseInt(partes[1],10);
	switch (partes[1])
	{
	case 1 : limite_dias= 31;
		break;
	case 3 : limite_dias= 31;
		break;
	case 5 : limite_dias= 31;
		break;
	case 7 : limite_dias= 31;
		break;
	case 8 : limite_dias= 31;
		break;
	case 10 : limite_dias= 31;
		break;
	case 12 : limite_dias= 31;
		break;
	case 4 : limite_dias= 30;
		break;
	case 6 : limite_dias= 30;
		break;
	case 9 : limite_dias= 30;
		break;
	case 11 : limite_dias= 30;
		break;
	case 2: if (partes[2]%400==0) limite_dias=29
					else if (partes[2]%100==0) limite_dias=28
							else if (partes[2]%4==0) limite_dias=29
									else limite_dias=28;
		break;
	default : limite_dias=0;
	}
	if (exp.test(fecha) == false || partes[0]>limite_dias || partes[0]<1 || partes[1]<1 || partes[1]>12){
		return false;
	}
	return true;
}

function colorValidar(color){
	if ( color == "" ) return true;
	var exp=new RegExp("^[0-9a-fA-F]{6}$");
	return exp.test(color);
}

function aceptarValidar(valor){
    return valor;
}