// validator.js



/************************************************
DESCRIPTION: Validates that a string contains only
    valid dates with 2 digit month, 2 digit day,
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
function validaData(strValue){
	var reg=new RegExp("^([1-9]|0[1-9]|[12][0-9]|3[01])[ /.]([1-9]|0[1-9]|1[012])[ /.](19|20)\\\d\\\d$");
	if(!reg.test(strValue)) return false;

	 var arrayDate=strValue.split("/"); //split date into day,month, year
    
    var intDay=arrayDate[0]*1;
    var intMonth=arrayDate[1]*1;
    var intYear=arrayDate[2]*1;
   
  // alert(intDay+"-"+intMonth+"-"+intYear);
		switch(parseInt(intMonth)){
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				if(intDay<=0 || intDay>31) return false;
				break;
			case 4:
			case 6:
			case 9:
			case 11:
				if(intDay<=0 || intDay>30) return false;
				break;
			case 2:
				if(!(((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28)) && intDay !=0)){
		          return false; 
        		}
				break;
			default: return false;break;
		}
		
   
  	
    return true; //any other values are ok
}

function validaNumero( strValue ) {
  return (!isNaN(strValue));
}

function validaInteger( strValue ) {
  var objRegExp  = new RegExp("^-?\\\d\\\d*$");

  //check for integer characters
  return objRegExp.test(trim(strValue));
}

function validaNoBuit( strValue ) {
   var strTemp = strValue;
   strTemp = trim(strTemp);
   if(strTemp.length > 0){
     return true;
   }
   return false;
}

function validaEmail( strValue) {
	var objRegExp  =new RegExp("^.+\\\@(\\\[?)[a-zA-Z0-9\\\-\\\.]+\\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\\]?)$");
	
	  //check for valid email
	  return objRegExp.test(trim(strValue));
}


function afegirZeros(str,num){
	
	if(str.length<parseInt(num)){
		var strret="";
		var numzeros=parseInt(num)-str.length;
		var i=0;
		while(i<numzeros){
			strret+="0";
			i++;	
		}
		strret+=str;
		return strret;
	}
	return str;
}


function validarCif2(cif){

    if(cif.length!=9) return false;
   // alert(cif);
   // alert(cif.charAt(0)+"-"+cif.substring(1,8)+"-"+cif.charAt(8));
	return validarCIF(cif.charAt(0),cif.substring(1,8),cif.charAt(8));
}


function validarCIF(cif,dni,nif){ 
    
    var dni=afegirZeros(dni,7);
    
    var texto=cif+""+dni+""+nif;
    var pares = 0; 
    var impares = 0; 
    var suma; 
    var ultima; 
    var unumero; 
    var uletra = new Array("J", "A", "B", "C", "D", "E", "F", "G", "H", "I"); 
    var xxx; 
     
    texto = texto.toUpperCase();
     
     
    var regular =/^[ABCDEFGHKLMNPQS]\d\d\d\d\d\d\d[0-9,A-J]$/g; 
     if (!regular.exec(texto)) return false; 
          
     ultima = texto.substr(8,1); 

     for (var cont = 1 ; cont < 7 ; cont ++){ 
         xxx = (2 * parseInt(texto.substr(cont++,1))).toString() + "0"; 
         impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1)); 
         pares += parseInt(texto.substr(cont,1)); 
     } 
     xxx = (2 * parseInt(texto.substr(cont,1))).toString() + "0"; 
     impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1)); 
      
     suma = (pares + impares).toString(); 
     unumero = parseInt(suma.substr(suma.length - 1, 1)); 
     unumero = (10 - unumero).toString(); 
     if(unumero == 10) unumero = 0; 
      
     if ((ultima == unumero) || (ultima == uletra[unumero])) 
         return true; 
     else 
         return false; 

} 

function validarNif2(nif){
	var nif2=afegirZeros(nif,7);
	if(nif2.length>9) return false;
	return validarNif(nif2.substring(0,8),nif2.charAt(8));
}


function validarNif(dni,dc){
	
	//Tabla de caracter de control para NIF
	var tablaNif = new Array("T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E");
	
	r1 = 0;
	posicion = 0;
	dcreal="";
	valit = false;
	
	//dni = dni.toUpperCase();

	r1 = parseInt(dni);

	if(isNaN(r1)){
		return validarNifComunitario(dni,dc);
	}
	
	posicion = r1 % 23;
	dcreal = tablaNif[posicion];
	
	//alert(dcreal);
	return (dc.toUpperCase()==dcreal.toUpperCase());
			
}

function validarNifComunitario(dni,dc){
	var ext=dni.substr(0,1);
	var dnicom=dni.substr(1,dni.length);
	if (ext='X'){
		r1 = parseInt(dnicom);
		if (isNaN(r1)){
			return false;
		}
		// tendriamos que mirar que el dc es una letra
		return true;
	}
	else{
		return false;
	}
}

function validarNif2(nif){
	var dni=nif.substr(0,nif.length-1);
	var dc=nif.substr(nif.length-1,nif.length);
	return validarNif(dni,dc);
	
	
}
function validarEntre(valor,ini,fin){
	if(!validaNumero(valor)) return false;
	if(!validaNumero(ini)) return false;
	if(!validaNumero(fin)) return false;
	
	var t=parseInt(valor);
	return (t>=ini && t<=fin);
}

function validarMayor(valor,ini){
	if(!validaNumero(valor)) return false;
	if(!validaNumero(ini)) return false;
	
	var t=parseInt(valor);
	return (t>=ini);
}

function validarMenor(valor,fin){
	if(!validaNumero(valor)) return false;
	if(!validaNumero(fin)) return false;
	
	var t=parseInt(valor);
	return (t<=fin);
}

function validaRadio(radio){
    var i;
    for (i=0;i<radio.length;i++){
       if (radio[i].checked)
          return true;
    }
    return false;
} 

function validar(obj,lang,alta){
	var oblig="";
	var wrongmail="";
	var wrongdni="";
	var wrongdate="";
	var wrongtel="";
	if(lang==1){
		oblig="Campo Obligatorio";
		wrongmail="Formato del Email no válido";
		wrongdni="Formato del DNI incorrecto. Debe ser un numero de 9 dígitos seguido de una letra válida, sin espacios.";
		wrongdate="Formato de la fecha incorrecto. Debe ser dd/mm/aaaa.";
		wrongtel="Formato del teléfono incorrecto. Debe ser un número, sin espacios.";
		pwdnoeq="No coincide el password en los dos campos.";
	}else{
		oblig="Camp Obligatori";
		wrongmail="Format de l\'email incorrecte";
		wrongdni="Format del DNI incorrecte. Ha de ser un numero de 9 dígits seguit d\'una lletra vàlida, sense espais.";
		wrongdate="Format de la data incorrecte. Ha de ser dd/mm/aaaa.";
		wrongtel="Format del telèfon incorrecte. Ha de ser un numero, sense espais.";
		pwdnoeq="No coincideix el password als dos camps.";
	}
	//alert(obj.name);
	if(!validaNoBuit(obj.rlp_login.value)){
		mensaje=oblig;
		mostrarAjuda(obj.rlp_login,'Error',mensaje,'left');
		obj.rlp_login.focus();
		obj.rlp_login.select();
		return false;
	}else if(!validaEmail(obj.rlp_email.value)){
		mensaje=wrongmail;
		mostrarAjuda(obj.rlp_email,'Error',mensaje,'left');
		obj.rlp_email.focus();
		obj.rlp_email.select();
		return false;
	}else if(alta && !validaNoBuit(obj.rlp_pwd.value)){
		mensaje=oblig;
		mostrarAjuda(obj.rlp_pwd,'Error',mensaje,'left');
		obj.rlp_pwd.focus();
		obj.rlp_pwd.select();
		return false;		
	}else if(alta && !validaNoBuit(obj.rlp_pwd_alt.value)){
		mensaje=oblig;
		mostrarAjuda(obj.rlp_pwd_alt,'Error',mensaje,'left');
		obj.rlp_pwd_alt.focus();
		obj.rlp_pwd_alt.select();
		return false;		
	}else if(obj.rlp_pwd.value!=obj.rlp_pwd_alt.value){
		mensaje=pwdnoeq;
		mostrarAjuda(obj.rlp_pwd_alt,'Error',mensaje,'left');
		obj.rlp_pwd.focus();
		obj.rlp_pwd.select();
		return false;		
	}else if(!validaNoBuit(obj.rlp_nombre.value)){
		mensaje=oblig;
		mostrarAjuda(obj.rlp_nombre,'Error',mensaje,'left');
		obj.rlp_nombre.focus();
		obj.rlp_nombre.select();
		return false;		
	}else if(!validaNoBuit(obj.rlp_apellido1.value)){
		mensaje=oblig;
		mostrarAjuda(obj.rlp_apellido1,'Error',mensaje,'left');
		obj.rlp_apellido1.focus();
		obj.rlp_apellido1.select();
		return false;		
	}else if(!validaNoBuit(obj.rlp_apellido2.value)){
		mensaje=oblig;
		mostrarAjuda(obj.rlp_apellido2,'Error',mensaje,'left');
		obj.rlp_apellido2.focus();
		obj.rlp_apellido2.select();
		return false;		
	}else if(!validaRadio(obj.rlp_sexo)){
		mensaje=oblig;
		mostrarAjuda(obj.rlp_sexo[0],'Error',mensaje,'left');
		return false;		
	}else if(!validaRadio(obj.rlp_sob_por)){
		mensaje=oblig;
		mostrarAjuda(obj.rlp_sob_por[0],'Error',mensaje,'left');
		return false;		
	}else if(!validaRadio(obj.rlp_dis)){
		mensaje=oblig;
		mostrarAjuda(obj.rlp_dis[0],'Error',mensaje,'left');
		return false;		
	}else if(!(obj.rlp_prv.selectedIndex>0)){
		mensaje=oblig;
		mostrarAjuda(obj.rlp_prv,'Error',mensaje,'left');
		obj.rlp_prv.focus();
		//obj.rlp_apellido2.select();
		return false;		
	}else if(!validaNoBuit(obj.rlp_dni.value)){
		mensaje=oblig;
		mostrarAjuda(obj.rlp_dni,'Error',mensaje,'left');
		obj.rlp_dni.focus();
		obj.rlp_dni.select();
		return false;		
	//}else if(!validarNif2(obj.rlp_dni.value)){
		//mensaje=wrongdni;
		//mostrarAjuda(obj.rlp_dni,'Error',mensaje,'left');
		//obj.rlp_dni.focus();
		//obj.rlp_dni.select();
		//return false;		
	}else if(!validaNoBuit(obj.rlp_fechanacimiento.value)){			
		mensaje=oblig;
		mostrarAjuda(obj.rlp_fechanacimiento,'Error',mensaje,'left');
		obj.rlp_fechanacimiento.focus();
		obj.rlp_fechanacimiento.select();
		return false;		
	}else if(!validaData(obj.rlp_fechanacimiento.value)){			
		mensaje=wrongdate;
		mostrarAjuda(obj.rlp_fechanacimiento,'Error',mensaje,'left');
		obj.rlp_fechanacimiento.focus();
		obj.rlp_fechanacimiento.select();
		return false;		
	}else if(!validaNoBuit(obj.rlp_telf.value)){			
		mensaje=oblig;
		mostrarAjuda(obj.rlp_telf,'Error',mensaje,'left');
		obj.rlp_telf.focus();
		obj.rlp_telf.select();
		return false;		
	}else if(alta && !validaNoBuit(obj.rlp_captcha.value)){			
		mensaje=oblig;
		mostrarAjuda(obj.rlp_captcha,'Error',mensaje,'left');
		obj.rlp_captcha.focus();
		obj.rlp_captcha.select();
		return false;		
	}else if(!validaInteger(obj.rlp_telf.value)){			
		mensaje=wrongtel;
		mostrarAjuda(obj.rlp_telf,'Error',mensaje,'left');
		obj.rlp_telf.focus();
		obj.rlp_telf.select();
		return false;		

	}else{
		obj.submit();
	}
	/*rlp_email
	rlp_pwd
	rlp_pwd_alt
	rlp_nombre
	rlp_apellidos
	rlp_dni
	rlp_imagen_file
	rlp_fechanacimiento
	rlp_telf*/
}

function validarGrupo(obj,lang){
	return true;
}

function validarNuevoMensaje(obj,lang){
	var oblig="";
	if(lang==1){
		oblig="Campo Obligatorio";
	}else{
		oblig="Camp Obligatori";
	}
	
	if(!validaNoBuit(obj.forum_titulo.value)){
		mensaje=oblig;
		mostrarAjuda(obj.forum_titulo,'Error',mensaje,'left');
		obj.forum_titulo.focus();
		obj.forum_titulo.select();
		return false;
	}else if(!validaNoBuit(obj.forum_cuerpo.value)){
		mensaje=oblig;
		mostrarAjuda(obj.forum_cuerpo,'Error',mensaje,'left');
		obj.forum_cuerpo.focus();
		obj.forum_cuerpo.select();
		return false;
	}else{
		obj.submit();
	}
}
function validarNuevaSeccion(obj,lang,numlangs){
	amagarAjuda();
	i=0;
	if(lang==1){
		oblig="Campo Obligatorio";
	}else{
		oblig="Camp Obligatori";
	}
	for(i=0;i<parseInt(numlangs);i++){
		switchTab((i+1));
		//alert("obj.forum_nombre"+(i+1));
		
		var n=eval("obj.forum_nombre"+(i+1));
		if(!validaNoBuit(n.value)){
			mensaje=oblig;
			mostrarAjuda(n,'Error',mensaje,'left');
			n.focus();
			n.select();
			return false;
		}
		
		n=eval("obj.forum_descripcion"+(i+1));
		if(!validaNoBuit(n.value)){
			mensaje=oblig;
			mostrarAjuda(n,'Error',mensaje,'left');
			n.focus();
			n.select();
			return false;
		}
		
	}
	
	obj.submit();
}

