﻿//////////////// validadores calendarios //////////////////

function comprobarFechaNac(cmp){
	cmp = MM_findObj(cmp).value;
	patron = /^([0][1-9]|[12][0-9]|3[01])(\/|\.|-)(0[1-9]|1[012])\2(\d{4})$/;
	if(cmp=='dd/mm/aaaa' || cmp=='' || !cmp.match(patron)) return false;
	else return true;
}

function comprobarFechaExp(d, m, a, c){
    
    //si la fecha es anterior o igual al dia de hoy
    var hoy = new Date();
    var __hoy = new Date( hoy.getFullYear(),hoy.getMonth(),hoy.getDate() );
    var __fecExp = new Date( Number(a), Number(m)-1, Number(d) );
    if(__fecExp > __hoy ){
        return false;
    }
    else{
	    fExp=new Date(Number(a), Number(m)-1, Number(d)).valueOf();
	    cmp = (c==CH) ? 'fechaNacimientoCH' : 'fechaNacimientoCO';
	    fc = MM_findObj(cmp).value.split('/');
	    if(fc[2]!="" && fc[1]!="" && fc[0]!="")
	        fNac=new Date(Number(fc[2]), Number(fc[1])-1, Number(fc[0])).valueOf();
	    else
	        return false;
    	
	    //bisiestos
	    aNac = Number(fc[2]);
	    aExp = Number(a);
	    diasSuma=0;
	    for(i=aNac; i<=aExp; i++){
		    if (i%4==0 && (i%100!=0 || i%400==0)) diasSuma++;
	    }
	    diasSuma = diasSuma*24*60*60*1000;
    	
	    dif=fExp-fNac-diasSuma;
	    dif=dif/1000/60/60/24/365;
	    return (dif>=18) ? true : false;
    	
	}
}


function generarFechas(camp){
	cmp = camp.toLowerCase();
	tipo = (cmp.indexOf('nacimiento')>=0) ? NAC : EXP;
	cond = (camp.indexOf('CH')>=0) ? CH : CO;

	if(tipo==NAC){
		generarCalendario(camp, tipo, cond);
	}
	else if(tipo==EXP){
		cmp=(cond==CH) ? 'fechaNacimientoCH' : 'fechaNacimientoCO';
		if(comprobarFechaNac(cmp)) generarCalendario(camp, tipo, cond);
		else alert(limpiarCadena(buscarTextoEsp('errorFechaNac'), HToU));
	}
}


/////////////// funciones form final ////////////////////////
function comprobarMail(){
    res=false;
    mail = MM_findObj('email').value;
    patron = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    if(mail!="") res = mail.match(patron);
	else res = true;
	
	if(res){
	   return true;
	}else{
		alert(limpiarCadena(buscarTextoEsp('errorMail'), HToU));
		return false;
	}
}

function validarCodPostal_provincia(){
	MM_findObj('Localidad').value ='';
	val = MM_findObj('CodPostalCirculacion').value;
	
	if(val.length==5){
		if(isNaN(val)){
			MM_findObj('Localidad').value ='';
			txt = buscarTextoEsp('errorNumCodPostal');
			alert(limpiarCadena(txt, HToU));
		}else{
			cod = val.substr(0,2);
			//cod = Math.abs(cod);
			tb='mtprov';
			parametros='cod_postal='+cod;
			parametros+='&css='+MM_findObj('css').value;
            obtenerRequest('consultas/obtenerLista.aspx', parametros, validarMunicipio, tb, 'provincia');
		}
		
	}
}
function validarMunicipio_provincia(){
	
	res=false;
    xmldoc = http_request.responseXML;
    if(xmldoc!=null)
        if( xmldoc.getElementsByTagName('root').item(0).childNodes.length>0) 
			res = true;
	
	if(!res){
		MM_findObj('Localidad').value ='';
		txt = buscarTextoEsp('errorProvCodPostal');
		alert(limpiarCadena(txt, HToU));
	}else{
		MM_findObj('Localidad').value = 
			xmldoc.getElementsByTagName('root').item(0).childNodes.item(0).attributes.getNamedItem('provincia').value;
	}	
}

function validarCodPostal()
{
	MM_findObj('Localidad').value ='';
	MM_findObj('LocalidadCirculacion').value ='';
	val = MM_findObj('CodPostalCirculacion').value;
	
	if(val.length==5){
		if(isNaN(val)){
			MM_findObj('Localidad').value ='';
			txt = buscarTextoEsp('errorNumCodPostal');
			alert(limpiarCadena(txt, HToU));
		}else{
			cod = val;
			tb='mtprov';
			parametros='cod_postal='+cod;
			parametros+='&css='+MM_findObj('css').value;
            obtenerRequest('consultas/obtenerLista.aspx', parametros, validarMunicipio, tb, 'poblacion');
		}
	}
	else
	    MM_findObj('LocalidadCirculacion').options.length=0; 
	
}
function validarMunicipio()
{
    var elSel = MM_findObj('LocalidadCirculacion');
	elSel.options.length=0;
    
    xmldoc = http_request.responseXML;

	var res=false;
	var countMuni = xmldoc.getElementsByTagName('root').item(0).childNodes.length;
    if(xmldoc!=null)
        if( countMuni > 0) 
			res = true;
	
	if(!res)
	{
		MM_findObj('Localidad').value ='';
	    MM_findObj('LocalidadCirculacion').value ='';
		txt = buscarTextoEsp('errorProvCodPostal');
		alert(limpiarCadena(txt, HToU));
	}
	else
	{
	    var opcion;
	    var texto;
	    
//	    if(countMuni>1)
//	    {
//	        opcion = document.createElement('option');
//            texto = buscarTextoEsp("seleccione"); 
//            opcion.text = limpiarCadena(texto, HToU);
//            opcion.value = -1;
//        }
      
        //if(browser.isIE &&  browser.version=="7")
        {
            var size = (countMuni>3)?"3":countMuni;
            elSel.setAttribute("size",size);
        }
        
        MM_findObj('Localidad').value = xmldoc.getElementsByTagName('root').item(0).childNodes.item(0).attributes.getNamedItem('Provincia').value;
	    for(var c=0;c<countMuni;c++)
        {
	        var opcion = document.createElement('option');
            var texto = xmldoc.getElementsByTagName('root').item(0).childNodes.item(c).attributes.getNamedItem('Nombre').value;
            opcion.text = limpiarCadena(texto, HToU);
            opcion.value = texto;
            if(texto!=""){
                try{
                    elSel.add(opcion, null); //Mozilla, etc
                }catch(e){
                    elSel.add(opcion); //IE
                }   
                //xmldoc.getElementsByTagName('root').item(0).childNodes.item(0).attributes.getNamedItem('Provincia').value;
            }
        }
        
        if(elSel.options.length==0)
        {
            var txt = buscarTextoEsp('errorProvCodPostal');
            alert(limpiarCadena(txt, HToU));
        }
            
	}	
}

function comprobarFormulario(){

    var valid = true;
    var lopd = false;
    if(MM_findObj('Localidad').value != '')
	{
	    //Si se introducen datos poloza
		if(document.getElementById("rdPolizaSi").checked)
		{
		    lopd = true;
		    
		    var numPoliza = trim(document.getElementById("numPoliza").value);
            var dni = trim(document.getElementById("dni").value);
        	
	        valid = comprobarPoliza(numPoliza,dni); 
	        txt = (valid) ? "" : buscarTextoEsp('errorObligPoliza');
		}
		
		var validContacto = true;
		if(DatosContacto())
		{
		    if(ValidarDatosContacto() )
		        lopd = true;
		    else
		    {
		        validContacto = false;
                txt = "Los datos introducidos no son correctos.";
		    }
		}
		
		
		if(valid && validContacto)
		{
		    //se debe aceptar la política de privacidad
            if(lopd && !document.getElementById("chkLOPD").checked)
		    {
		        txt = "Debe aceptar la Política de Privacidad.";
		        alert(limpiarCadena(txt, HToU));
		    }
		    else
		    {
		        // INICIO::GoogleAnalitics
                var label = document.getElementById('css').value; //instalacion
                var action = "CodPostal"; 
                EventoGoogle(label,"Tarificar_"+ action);
                // FIN::GoogleAnalitics
		        document.forms[0].submit();		
		    }
		}
		else
		{
		    alert(limpiarCadena(txt, HToU));
	    }
		
	}
	else
	{
		txt = buscarTextoEsp('errorObligCodPostal');
		alert(limpiarCadena(txt, HToU));
	}
}

function trim(cadena)
{
	var str = cadena.replace(/^\s*|\s*$/g,"");
	return str;
}

function comprobarPoliza(numPoliza,dni)
{
    var val = true;
    
    //si ha marcado que se va a informar del nº de poliza, es obligatorio tanto dni como poliza
    if(numPoliza != "" && numPoliza.length > 4)
    {
        val = true;    
        document.getElementById("numPoliza").className = "cabeceraVersion";
        
        // INICIO::GoogleAnalitics
        var label = document.getElementById('css').value; //instalacion
        var action = "NumPoliza"; 
        EventoGoogle(label, "Tarificar_"+action);
        // FIN::GoogleAnalitics
    }
    else
    {
        val = false;
        document.getElementById("numPoliza").className = "error";
    }
    
    if(val)
    {
        if( dni != "" && ValidarNifCif(dni.toUpperCase()) )
        {
            val = true;    
            document.getElementById("dni").className = "cabeceraVersion"; 
            
            // INICIO::GoogleAnalitics
            var label = document.getElementById('css').value; //instalacion
            var action = "Nif"; 
            EventoGoogle(label,"Tarificar_"+ action);
            // FIN::GoogleAnalitics
        }
        else
        {
            val = false;
            document.getElementById("dni").className = "error";
        }
    } 
    
    if( document.getElementById("matricula").value != "" )
    {
        // INICIO::GoogleAnalitics
        var label = document.getElementById('css').value; //instalacion
        var action = "Matricula"; 
        EventoGoogle(label,"Tarificar_"+ action);
        // FIN::GoogleAnalitics
    }
        
    return val;
}

function DatosContacto()
{
    var nombre = trim(document.getElementById("txtNombreContacto").value);
    var email = trim(document.getElementById("txtEmail").value);
    var tfno = trim(document.getElementById("txtTelefono").value);
    
    if(nombre !="" || email!="" || tfno!=""){
        return true;
    }
    return false;
}


function validarTelefono(tfno)
{
    var val = false; 
    var primerNum = tfno.value.substring(0,1);
    if ( tfno.value =="" || (tfno.value.length == 9 && (primerNum == "" || primerNum == "9" || primerNum == "6" || primerNum == "8") ) )
    {
        val = true; 
        tfno.className="cabeceraVersion"; 
        tfno.title=""; 
        
        // INICIO::GoogleAnalitics
        var label = document.getElementById('css').value; //instalacion
        var action = "Telefono"; 
        EventoGoogle(label,"Tarificar_"+ action);
        // FIN::GoogleAnalitics
        
    }
    else
    {
        tfno.className = "error";  
        tfno.title="No valido";
    }
    
    return val;

}
function validarEmail(elem){ //function isEmailAddress(theElement, nombre_del_elemento )
    
    var s = elem.value;
    var filter=/^[0-9A-Za-z][A-Za-z0-9_.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
    //var filter = /(^[0-9a-zA-Z]+(?:[.|_|\\-|0-9a-zA-Z]+)*)@([0-9a-zA-Z]+(?:[._-][0-9a-zA-Z]+)*\\.[0-9a-zA-Z]{2,3})$/;

    if (elem.value.length==0 || filter.test(s))
    {
        elem.className = "cabeceraVersion";
        elem.title=""; 
        
        // INICIO::GoogleAnalitics
        var label = document.getElementById('css').value; //instalacion
        var action = "Email"; 
        EventoGoogle(label,"Tarificar_"+ action);
        // FIN::GoogleAnalitics
        
        
        return true;
    }
    else
    {
        elem.className = "error"; //style.border="1px solid Red"; 
        elem.title="No valido";
        return false;
    }

}

function ValidarDatosContacto()
{
    var val = false;
    //Si se introducen datos de contacto tienen q ser validos
    if(document.getElementById("hddnValTelefono").value != "false" 
        && document.getElementById("hddnValEmail").value != "false" )
        val=true;
    
    if(trim(document.getElementById("txtNombreContacto").value) != "")
    {
        // INICIO::GoogleAnalitics
        var label = document.getElementById('css').value; //instalacion
        var action = "Nombre"; 
        EventoGoogle(label,"Tarificar_"+ action);
        // FIN::GoogleAnalitics
    }
    
    return val;
}
	    
// ************************************************************** 
// Validación de los elementos de la página principal
//
function ValidarNifCif(NIF)
{
	// alert(NIF);
    var Letras, DigitoControl, Numero, SumaParcial, Digito, ResFinal, LetraNIF, NumeroNIF, Resto, LetraCorrecta;
    var Par1, Par2, Par3, ResPares;
    var Impar1, Impar2, Impar3, Impar4, ResImpar1, ResImpar2, ResImpar3, ResImpar4, ResImpares;
    
    //alert("El primer carácter es: "+NIF.charAt(0));
    if (isNaN(NIF.charAt(0))) 
    {
		if (NIF.substring(0, 1)=="X" || NIF.substring(0, 1)=="Y") 
		{
			// alert("NIE");
			NIF = NIF.substr(1);
			// A partir de aquí comprobamos en NIF
    		Letras        = "TRWAGMYFPDXBNJZSQVHLCKE";
	    	LetraNIF      = NIF.charAt(NIF.length-1);
			NumeroNIF     = NIF.substring(0, NIF.length-1);
			Resto         = NumeroNIF%23;
    		LetraCorrecta = Letras.charAt(Resto);
		    // alert(LetraCorrecta+LetraNIF);
		    if (LetraNIF==LetraCorrecta) return true;
		} 
		else 
		{
			// alert("CIF");
			// Desde aquí comprobamos el CIF
    		Letras        = "JABCDEFGHI";
			DigitoControl = NIF.charAt(NIF.length-1);
    		Numero        = NIF.substr(1, NIF.length-2);
			Par1=Numero.charAt(1); Par2=Numero.charAt(3); Par3=Numero.charAt(5);
    		ResPares      = Par1-(-Par2)-(-Par3);
    		if(!isNaN(ResPares))
    		{
	    	    //alert(par1+"+"+par2+"+"+par3+"="+ResPares);
		        Impar1=(Numero.charAt(0)*2).toString(); ResImpar1=Impar1.charAt(0)-(-Impar1.charAt(1));
		        Impar2=(Numero.charAt(2)*2).toString(); ResImpar2=Impar2.charAt(0)-(-Impar2.charAt(1));
		        Impar3=(Numero.charAt(4)*2).toString(); ResImpar3=Impar3.charAt(0)-(-Impar3.charAt(1));
		        Impar4=(Numero.charAt(6)*2).toString(); ResImpar4=Impar4.charAt(0)-(-Impar4.charAt(1));
		        ResImpares=ResImpar1-(-ResImpar2)-(-ResImpar3)-(-ResImpar4);
		        //alert(ResImpares);
		        SumaParcial=(ResPares-(-ResImpares)).toString();
		        //alert("Suma parcial: "+SumaParcial);
		        if (SumaParcial.length==1) 
		        {
			        Digito=SumaParcial.charAt(0);
		        } 
		        else 
		        {
			        Digito=SumaParcial.charAt(1);
		        }
		        //alert("Dígito: "+Digito);
		        ResFinal=10-eval(Digito);
		        if (ResFinal==10) ResFinal=0;
		        //alert("Resultado final: "+ResFinal);
		        if (isNaN(DigitoControl)) 
		        {
			        //alert(Letras.charAt(ResFinal)+" "+DigitoControl);
			        if (Letras.charAt(ResFinal)==DigitoControl) return true;
		        } 
		        else 
		        {
			        if (ResFinal==DigitoControl) return true;
		        }
		    }
		    else    return false;
	    }
    } 
    else 
    {
		// alert("NIF");
		// A partir de aquí comprobamos en NIF
    	Letras        = "TRWAGMYFPDXBNJZSQVHLCKE";
		LetraNIF      = NIF.charAt(NIF.length-1);
    	NumeroNIF     = NIF.substring(0, NIF.length-1);
    	Resto         = NumeroNIF%23;
	    LetraCorrecta = Letras.charAt(Resto);
	    // alert(LetraCorrecta+LetraNIF);
	    if (LetraNIF==LetraCorrecta) return true;
    }
}
