﻿/* 
			REPOSITORIO DE ÚLTILES DE GESTORÍA VIRTUAL 
     (C) 2010, Axesor.es
*/


function EsNumero(cadena)
{
	for (i=0; i < cadena.length; i++)
	{
		if ((cadena.charAt(i) != '0') && (cadena.charAt(i) != '1') && (cadena.charAt(i) != '2') && (cadena.charAt(i) != '3')
			 && (cadena.charAt(i) != '4') && (cadena.charAt(i) != '5') && (cadena.charAt(i) != '6') && (cadena.charAt(i) != '7')
			  && (cadena.charAt(i) != '8') && (cadena.charAt(i) != '9'))
			return false;
	}
	return true;
}


function TrimLeft(str)
{	
	var resultStr = "";	
	var i = len = 0;	
	
	if (str+"" == "undefined" || str == null)	return null;	
	str += "";	
	
	if (str.length == 0) resultStr = "";	
	else {	  		
		len = str.length - 1;		
		len = str.length;		  		
		while ((i <= len) && (str.charAt(i) == " "))			
			i++;   	
		resultStr = str.substring(i, len);  	
	}  	
	return resultStr;
}


function TrimRight(str) 
{	
	var resultStr = "";	
	var i = 0;	
	if (str+"" == "undefined" || str == null)	return null;	
	str += "";		
	
	if (str.length == 0) resultStr = "";	
	else {  		
		i = str.length - 1;  		
		while ((i >= 0) && (str.charAt(i) == " ")) 			
			i--; 			 		
		resultStr = str.substring(0, i + 1);  	
	}  	  	
	return resultStr;  	
}


function Trim(str)
{	
	var resultStr = "";		
	resultStr = TrimLeft(str);	
	resultStr = TrimRight(resultStr);		
	return resultStr;
}


function obtValorSeleccionado(name)
{
	var sValor;
	var idNodeList;
	idNodeList = document.getElementsByName(name);
	
	var i, encontrado;
	
	i = 0;
	encontrado = false;
	
	while (i < idNodeList.length && !encontrado)
	{
		if (idNodeList.item(i).checked)
		{
			sValor = idNodeList.item(i).value;
			encontrado = true;
		}
			
		i = i + 1;
	}
		
	return sValor;
}


//Validador de CIF,NIF, NIE
//Returns: 1 = NIF ok, 2 = CIF ok, 3 = NIE ok, -1 = NIF mal, -2 = CIF mal, -3 = NIE mal, 0 = ??? mal
function valida_nif_cif_nie(cf) 
{
	//Quito todos los CIF del tipo 00000000T
	var c = cf;
	for (var i = 0;i<c.length;i++)
	{
	var t = String(i);
	var exp = new RegExp(t,"ig");
	var cf2 = c.replace(exp, '');
	if(cf2.length<4)
		return 0;
	}

	cf = cf.toUpperCase();
	var num = new Array(9);
	for (var i = 0; i <= 8; i++)
	{
	num[i] = cf.charAt(i);
	}
	  
	var reg1 = new RegExp('((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)');
	//si no tiene un formato valido devuelve error
	if (!reg1.test(cf))
	{
	return 0;
	}
	  
	//comprobacion de NIFs estandar
	var reg2 = new RegExp('(^[0-9]{8}[A-Z]{1}$)');
	var letrasNIF='TRWAGMYFPDXBNJZSQVHLCKE';
	 if (reg2.test(cf))
	 {		
		if (num[8] == letrasNIF.charAt(cf.substring(0, 8) % 23)){
			$('#divPersonaContacto').hide();
			$('#cargo')
			return 1;
		}
		else
		 return -1;
	}
		 
	//algoritmo para comprobacion de codigos tipo CIF
	//Suma de los pares
	var suma = num[2]*1 + num[4]*1 + num[6]*1;
	var tmpsuma;
	//Para cada numero impar
	for (var i = 1; i < 8; i += 2)
	{
	//Calculamos el doble y si tiene 2 cifras las sumamos
	tmpsuma = 2 * num[i];				
	var t1 = String(tmpsuma);
	tmpsuma =  t1.charAt(0)*1 + t1.charAt(1)*1;
	suma += tmpsuma;
	}
	var stsuma = String(suma);
	//Restamos a 10 la última cifra de la suma anterior
	var n = 10 - stsuma.charAt(stsuma.length - 1)*1;

	//comprobacion de NIFs especiales (se calculan como CIFs)
	var reg3 = new RegExp('^[KLM]{1}');
	if (reg3.test(cf))
	{
	if (num[8] == String.fromCharCode(64 + n))
	 return 1;
	else
	 return -1;
	}

	//comprobacion de CIFs
	var reg4 = new RegExp('^[ABCDEFGHJNPQRSUVW]{1}');
	if (reg4.test(cf))
	{
	var t2 = String(n);
	if (num[8] == String.fromCharCode(64 + n) || num[8] == t2.charAt(t2.length-1))
	 return 2;
	else
	 return -2;
	}
		 
	//comprobacion de NIEs
	var reg5 = new RegExp('^[TXYZ]{1}');
	var letrasNIE ='TRWAGMYFPDXBNJZSQVHLCKE';
	var reg6 = new RegExp('^[T]{1}[A-Z0-9]{8}$');

	var cf2 = cf.replace('X', '0');
	cf2 = cf2.replace('Y', '1');
	cf2 = cf2.replace('Z', '2');		

	if (reg5.test(cf))
	{
	if (num[8] == letrasNIE.substr(cf2.substr(0, 8) % 23, 1) || reg6.test(cf))
	 return 3;
	else
	 return -3;
	}
	//si todavia no se ha verificado devuelve error
	return 0;
}


function TestInputTexto(valor)
{
	var error=false;

	if($('#'+valor+'').val().length < 2 ) {$('#'+valor+'').addClass('error');error=true;}
	else{$('#'+valor+'').removeClass('error');}
	
	return error;
}


function TestInputEntero(valor)
{
	var error=false;

	if($('#'+valor+'').val().length == 0 ){$('#'+valor+'').addClass('error');error=true;}
	else{$('#'+valor+'').removeClass('error');}
	
	return error;
}


function validarEmail(s)
{
    var i = 1;
    var sLength = s.length;

    if (sLength < 5) return false;
   
    while ((i < sLength) && (s.charAt(i) != "@")) i++;

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    while ((i < sLength) && (s.charAt(i) != ".")) i++;

    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}


/**************************************************************************
	JQUERY PARA FORMULARIO DE ALTA DE ÍNDICES
**************************************************************************/

function TestNifIndice(nif, desconozco_nif, titular, ente,tipo)
{
	var error=false;
	
	if (($('#'+ nif +'').val().length < 3 ) &&  ($('[name="'+ desconozco_nif +'"]:checked').val()!="S")){$('#' + nif + '').addClass('error');error=true;}
	else{$('#' + nif+ '').removeClass('error');}
	
	if (($('#'+ nif +'').val().length >= 1 ) &&  ($('[name="'+ desconozco_nif +'"]:checked').val()=="S")){if(tipo==1)AgregaMensajeError("No se puede rellenar el nif del Titular" + titular + " y a la vez indicar su desconocimiento."); error=true;$('#' + nif + '').addClass('error');}
	
	if (!error){
		if(ente=='F')
		{
			switch ($('[name="'+ desconozco_nif +'"]:checked').val())
			{
				case 'Y': //nif
					if (valida_nif_cif_nie(Trim($('#'+ nif +'').val())) != 1){if(tipo==1)AgregaMensajeError("El NIF del Titular " + titular + " introducido no es correcto.");error=true;$('#'+ nif +'').addClass('error');}
					break;
				case 'Z': //nie
					if (valida_nif_cif_nie(Trim($('#'+ nif +'').val())) != 3){if(tipo==1)AgregaMensajeError("El NIE del Titular " + titular + " introducido no es correcto.");error=true;$('#'+ nif +'').addClass('error');}
					break;
				case 'X': //extranjero
					break;
				case 'S': //se desconoce
					break;
			}
		}
		else
		{
			if ($('[name="'+ desconozco_nif +'"]:checked').val()!='S'){
				if (valida_nif_cif_nie(Trim($('#'+ nif +'').val())) != 2){if(tipo==1)AgregaMensajeError("El CIF del Titular " + titular + " introducido no es correcto.");error=true;$('#'+ nif +'').addClass('error');}
			}
		}
	}
	return error;
}



function TestNif(tipo)
{
	var error=false;

	if (($('#nif_solicitante').val().length < 3 ) &&  !($('#desconozco_nif').attr('checked'))){$('#nif_solicitante').addClass('error');error=true;}
	else{$('#nif_solicitante').removeClass('error');
	
	    if (($('#nif_solicitante').val().length >= 1 ) &&  ($('#desconozco_nif').attr('checked'))){
	        if (tipo==1)
	            AgregaMensajeError("No se puede rellenar el nif del Solicitante y a la vez indicar su desconocimiento");
	        error=true;
	    }

	    if(($('#nif_solicitante').val().length >= 3 ) && (valida_nif_cif_nie(Trim($('#nif_solicitante').val())) < 1)){
	        if (tipo==1)
	            AgregaMensajeError("El nif del Solicitante introducido no es correcto.");
	        error=true;
	        $('#nif_solicitante').addClass('error');
	    }
	    else{$('#nif_solicitante').removeClass('error');}
	}
		
	return error;
}


function TestConyuge(conyuge)
{
	var error=false;
	
	if($('[name="t_titularidades_conyuge'+ conyuge +'"]:checked').val()=="S"){
		if(TestInputTexto('t_conyuge'+conyuge)){error=true;}
		if(TestInputTexto('t_nif_conyuge'+conyuge)){error=true;}
	}
	
	return error;
}


function TestCausa()
{
	var error=false;

	if (($('#otra_causa').val().length < 3 ) &&  ($('#causa').val()=='5')){$('#otra_causa').addClass('error');error=true;}
	else{$('#otra_causa').removeClass('error');}
	
	return error;
}

function TestEmail(tipo)
{
    var error=false;
    if(TestInputTexto('correo_electronico')){
        error=true;
    }
	else{
	    if (!validarEmail($('#correo_electronico').val())){
	        if (tipo==1)
	            AgregaMensajeError("La dirección de correo introducida no es válida.");
	        error=true;
	        $('#correo_electronico').addClass('error');
	     }
	     else
	         $('#correo_electronico').removeClass('error');
	}
	return error;      
}


function TestFormaSocial(titular)
{
	var error=false;

	if (($('#beneficiario_fsocial'+titular).val().length < 3 ) &&  ($('#forma_social_alternativa'+titular).val().length < 3)){$('#beneficiario_fsocial'+titular).addClass('error_combo');$('#forma_social_alternativa'+titular).addClass('error');error=true;}
	else{$('#beneficiario_fsocial'+titular).removeClass('error_combo');$('#forma_social_alternativa'+titular).removeClass('error');}
	
	return error;
}


function TestIndices()
{
	var nIndices;
	var i=1;
	var valor;
	var error=false;
	
	nIndices=$('#num_altas').val();
	
	while(i<=nIndices)
	{
		valor = obtValorSeleccionado('TIPO_BENEFICIARIO' + i.toString());
		
		if(valor == 'F'){ //Persona Física
				if(TestInputTexto('beneficiario'+i)){error=true;}
				if(TestInputTexto('beneficiario_apellido1'+i)){error=true;}
				
				if(TestNifIndice('nif'+i,'desconozco_nif'+i,i,'F',1)){error=true;}
				
				if(TestConyuge(i)){error=true;}
		}else{ 
			if(valor == 'J'){ //Persona Jurídica
				if(TestInputTexto('beneficiario_sociedad'+i)){error=true;}
				if(TestFormaSocial(i)){error=true;}
				if(TestNifIndice('nif2'+i,'desconozco_nif2'+i,i,'J',1)){error=true;}
			}
			else{AgregaMensajeError("Debe introducir los datos del Titular " + i + " <br>");error=true} //No se ha seleccionado ninguna
			}
		i++;
	}
	return error;
}

function TestCombo(valor)
{
	var error=false;
	if($('#'+valor+'').val().length == 0) {$('#'+valor+'').addClass('error_combo');error=true;}
	else{$('#'+valor+'').removeClass('error_combo');}
	
	return error;
}

function TestNotas(tipo)
{
	var error=false;
	
	if (tipo==1){
	    if(obtValorSeleccionado('SOLICITAR_NOTAS')!= "S" && obtValorSeleccionado('SOLICITAR_NOTAS')!="N"){AgregaMensajeError("Debe indicar si desea solicitar las Notas Simples al registro");error=true;}
        
	    if(obtValorSeleccionado('SOLICITAR_NOTAS')=="S"){
		    if(TestInputEntero('MAX_NOTAS') && !($('#PEDIR_TODAS').attr('checked'))){$('#MAX_NOTAS').addClass('error');error=true;}
		    else{$('#MAX_NOTAS').removeClass('error');}
    	
		    if(!(TestInputEntero('MAX_NOTAS')) && ($('#PEDIR_TODAS').attr('checked'))){AgregaMensajeError("No puede indicar el máximo número de notas que desea y marcar la opción de seleccionar todas");error=true;$('#MAX_NOTAS').addClass('error');}
		    if(!EsNumero($('#MAX_NOTAS').val())){AgregaMensajeError("El número máximo de notas introducido es incorrecto");error=true;$('#MAX_NOTAS').addClass('error');}
		    if($('#MAX_NOTAS').val().length>0 && $('#MAX_NOTAS').val()==0){AgregaMensajeError("El número máximo de notas no puede ser cero");error=true;$('#MAX_NOTAS').addClass('error');}
		    if($('#PEDIR_TODAS').attr('checked')){$('#MAX_NOTAS').removeClass('error');}
	    }
	}
	else{
	   if(obtValorSeleccionado('SOLICITAR_NOTAS')!= "S" && obtValorSeleccionado('SOLICITAR_NOTAS')!="N")
	        error=true;
	   
        
	    if(obtValorSeleccionado('SOLICITAR_NOTAS')=="S"){
		    if(TestInputEntero('MAX_NOTAS') && !($('#PEDIR_TODAS').attr('checked'))){
		        $('#MAX_NOTAS').addClass('error');
		        error=true;
		    }
		    else
		        $('#MAX_NOTAS').removeClass('error');
    	
		    if(!(TestInputEntero('MAX_NOTAS')) && ($('#PEDIR_TODAS').attr('checked'))){
		        error=true;
		        $('#MAX_NOTAS').addClass('error');
		    }
		    if(!EsNumero($('#MAX_NOTAS').val())){
		        error=true;
		        $('#MAX_NOTAS').addClass('error');
		    }
		    if($('#MAX_NOTAS').val().length>0 && $('#MAX_NOTAS').val()==0){
		        error=true;
		        $('#MAX_NOTAS').addClass('error');
		    }
		    if($('#PEDIR_TODAS').attr('checked')){
		        $('#MAX_NOTAS').removeClass('error');
		    } 
		}
	}
	
	return error;
}


//Limpiamos ventana de errores para hacer un nuevo test.
function LimpiarErrores()
{
	$('#errores > p').remove();

	//Borramos las clases de error
	$('input.error').removeClass('error');
	$('select.error_combo').removeClass('error_combo');
	$('div.error').removeClass('error');
}

//Agregamos nuevo error a la ventana de errores
function AgregaMensajeError(texto)
{
	$('#errores').append("<p><img src=\"img\\flecha_red.gif\"><b>" + texto + "</b></p>");
}

//Mueve ventana al principio
function MoverAlPrincipio(){window.scrollTo(0,0);}

//Función para realizar el test de campos de todo el formulario 
//antes de realizar un alta de una solicitud.
function TestFormularioIndices()
{
	var error=false;
    
	LimpiarErrores();
	
	//Dtos del solicitante
	if(TestInputTexto('solicitante')){error=true;}
	if(TestNif(1)){error=true;}
	if(TestCausa()){error=true;}
	
	//Datos de la solicitud
	if(TestIndices()){error=true};
	
	//Solicitud notas simples
	if(TestNotas(1)){error=true;}
	
	//Datos de envío
	if (TestEmail(1)){error=true;}
	
	if(error)
	{
		if (($('input.error').length)>0 ||($('select.error_combo').length)>0){AgregaMensajeError("Rellene los campos marcados en rojo para completar la solicitud");}
		mostrarDiv('smsAlertas',1);
		MoverAlPrincipio();
	}
	else{mostrarDiv('smsAlertas',0);dcSendFormDispatcher();}
}	

/**************************************************************************
	JQUERY PARA FORMULARIO DE ALTA DE NOTAS
**************************************************************************/

function TestFormularioNotas()
{
	var error=false;
	LimpiarErrores();
	
	//Datos de la solicitud
	if (TestNotasSimples()){error=true;}
	
	if(TestCombo('provincia')){error=true;}
	if(TestCombo('registro')){error=true;}

	if(TestInputTexto('correo_electronico')){error=true;}
	else{if (!validarEmail($('#correo_electronico').val())){AgregaMensajeError("La dirección de correo eléctronico introducida no es válida.");error=true;$('#correo_electronico').addClass('error');}}
    
    
    if($('#motivo').val()== "") {$('#motivo').addClass('error_combo');error=true;AgregaMensajeError("Debe seleccionar un motivo.")}
	else{$('#motivo').removeClass('error_combo');}
    
    
	if(error)
	{
		if (($('input.error').length)>0 ||($('select.error_combo').length)>0){AgregaMensajeError("Rellene los campos marcados en rojo para completar la solicitud");}
		mostrarDiv1('smsAlertas',1);
		MoverAlPrincipio();
	}
	else{mostrarDiv1('smsAlertas',0);dcSendFormDispatcher();}
}	

function TestMaxNotas()
{
	var error=false;
	if ($('#t_pedir_todas').attr('checked')==false){error=TestInputEntero("t_num_max_notas");}

	return error;
}

function TestConyuge()
{
	var error=false;
	
	if($('[name="t_titularidades_conyuge"]:checked').val()=="S"){
		if(TestInputTexto('t_conyuge')){error=true;}
		if(TestInputTexto('t_nif_conyuge')){error=true;}
	}
	
	return error;
}


function TestNotasSimples()
{
	var error=false;
	var valor=obtValorSeleccionado('tip_solicitud');
	
	if (valor=='F')
	{
		if(TestInputTexto('f_municipio')){error=true;}
		
		if ($('#f_numero_finca').val()== 0) 
		{
			if(($('#f_calle').val()==0) || ($('#f_numero').val()==0) || ($('#f_titular').val()==0))				
				{error=true; AgregaMensajeError("Indique el número de la finca o bien, la calle el número y el titular de la finca");}
		}
	}
	else
	{ 
		if (valor=='T')
		{
			
			
			var todasPedidas=false;
			var titular=obtValorSeleccionado('t_tip_titular');
			
			if ($('#t_pedir_todas').attr('checked')==true)
			    todasPedidas=true;
			
			if(TestMaxNotas())
			    error=true;
			    
			if(!error){
			    if (!todasPedidas && !EsNumero(Trim($('#t_num_max_notas').val()))){
			        AgregaMensajeError("El número máximo de notas es incorrecto");
			        error=true;$('#t_num_max_notas').addClass('error');
			    }
			    else
			        if(!todasPedidas && Trim($('#t_num_max_notas').val())<0){
			            AgregaMensajeError("El número máximo de notas es incorrecto");
			            error=true;$('#t_num_max_notas').addClass('error');
			        }
			        else
			            if(!todasPedidas && Trim($('#t_num_max_notas').val())==0){
			                AgregaMensajeError("El número máximo de notas no puede ser cero");
			                error=true;$('#t_num_max_notas').addClass('error');
			            }
			}
			
			if(TestConyuge())
			    error=true;
			    
			if(titular=="F"){
				if (TestInputTexto('t_nombre')){error=true;}
				if (TestInputTexto('t_apellidos')){error=true;}
			}
			if(titular=="J"){
				if (TestInputTexto('t_denominacion')){error=true;}
			}
			
			
			
			
			
			
			
			
			
			
		}
		else{error=1;AgregaMensajeError("Debe seleccionar el tipo de solicitud.");}
	}
		
	return error;
}
