$(document).ready(function(){
	// mostrar / ocultar combo hijos
	$('#rvip_children_si,#rvip_children_no').click(function(){
		if ( $(this).val() == 'S' )
		{
			$('#children_container').show();
		}
		else
		{
			$('#children_container').hide();
		}
	});
	// mostrar / ocultar fichas hijos
	$('#num_hijos').change(function(){
		$('#children-fichas-container .hijo').slice(0,$(this).val()).show();
		$('#children-fichas-container .hijo').slice($(this).val()).hide();
	});
});

function visibilidades_paso1() {
	
	compruebaEdad()
	
	if ( $('#rvip_children_si').attr('checked') ) {
		$('#children_container').show();
	} else {
		$('#children_container').hide();
	}
	$('#children-fichas-container .hijo').slice(0,$('#num_hijos').val()).show();
	$('#children-fichas-container .hijo').slice($('#num_hijos').val()).hide();
}

function visibilidades_paso2() {
	var f = document.registrovip;
	
	visibilidadPreguntaProductos()
	
	// Miramos si hay que comprobar más visibilidades
	if ( typeof visibilidades_paso2_extra == "function" ) {
		// Existe la función para comprobar visibilidades
		if ( ! visibilidades_paso2_extra(f) ) {
			return;
		}
	}	
}

// Se mostrará si el usuario contesta afirmativamente a las pérdidas de orina
function visibilidadPreguntaProductos() {
	var f = document.registrovip;
	
	if ( f['pregunta9[]'] && f['pregunta10[]'] ) {
		var valPP = valorSeleccionado(f['pregunta9[]']);
		var valPC = valorSeleccionado(f['pregunta10[]']);
		
		if ( (valPP != false && valPP != '5') || (valPC != false && valPC != '5') ) {
			document.getElementById('dvPregProductos').style.display = "block"
		} else {
			document.getElementById('dvPregProductos').style.display = "none"
		}
	}
}

function cambioFechaNac(cal) {
	compruebaEdad()
	cal.hide();
	return true;
}

function login() {
	var f = document.acceso;
	
	if ( f.email.value == '' ) {
		alert('Escribe tu email');
		f.email.focus();
		return;
	}

	if ( f.contrasenya.value == '' ) {
		alert('Escribe tu contraseña');
		f.contrasenya.focus();
		return;
	}
	
	f.submit();
}

function registro1() {
	var f = document.registrovip;

	if ( f.Email.value == '' ) {
		alert('El email es obligatorio.');
		f.Email.focus();
		return;
	}

	if( !validamail(f.Email.value) ) {
		alert("El e-mail parece incorrecto.");
	    f.Email.focus();
		return;
    }

	if ( f.Password.value.length < 6 ) {
		alert('La contraseña tiene que ser de almenos 6 caracteres.');
		f.Password.focus();
		return;
	}

	if ( contieneCaracteres(f.Password.value,';:[](){}=+<>\/&*¿?¡!%$#|`´", ñçàèìòùáéíóúâêîôûäëïöüÑÇÀÈÌÒÙÁÉÍÓÚÂÊÎÔÛÄËÏÖÜ\'') ) {
		alert('La contraseña no puede contener caracteres extraños.');
		f.Password.focus();
		return;
	}

	if ( f.Password.value != f.Password_replay.value ) {
		alert('Las contraseñas escritas no coinciden.');
		f.Password.focus();
		return;
	}

	if ( f.nick.value == '' ) {
		alert('Tu nombre en la web (nick) es obligatorio.');
		f.nick.focus();
		return;
	}

	if ( contieneCaracteres(f.nick.value,';:[](){}=+<>\/&*¿?¡!%$#|`´", ñçàèìòùáéíóúâêîôûäëïöüÑÇÀÈÌÒÙÁÉÍÓÚÂÊÎÔÛÄËÏÖÜ\'') ) {
		alert('Tu nombre en la web (nick) no puede contener caracteres extraños.');
		f.nick.focus();
		return;
	}
	
	if ( f.Nombre.value == '' ) {
		alert('Tu nombre es obligatorio');
		f.Nombre.focus();
		return;
	}

	if ( contieneCaracteres(f.Nombre.value,'0123456789;:[]{}=+<>\/&*¿?¡!%$#|') ) {
		alert('Tu nombre no puede contener los caracteres: 0123456789;:[]{}=+<>\/&*¿?¡!%$#|');
		f.Nombre.focus();
		return;
	}
	
	if ( f.ApellidoPrincipal.value == '' ) {
		alert('Tu primer apellido es obligatorio');
		f.ApellidoPrincipal.focus();
		return;
	}

	if ( contieneCaracteres(f.ApellidoPrincipal.value,'0123456789;:[]{}=+<>\/&*¿?¡!%$#|') ) {
		alert('Tu primer apellido no puede contener los caracteres: 0123456789;:[]{}=+<>\/&*¿?¡!%$#|');
		f.ApellidoPrincipal.focus();
		return;
	}
	
	if ( f.ApellidoSecundario.value != '' && contieneCaracteres(f.ApellidoSecundario.value,'0123456789;:[]{}=+<>\/&*¿?¡!%$#|') ) {
		alert('Tu segundo apellido no puede contener los caracteres: 0123456789;:[]{}=+<>\/&*¿?¡!%$#|');
		f.ApellidoSecundario.focus();
		return;
	}

	if ( f.FechaNacimiento.value == "" || f.FechaNacimiento.value == "dd/mm/aaaa" ) {
		alert("La fecha de nacimiento es obligatoria.")
		f.FechaNacimiento.focus()
		return;
	}

	if ( !es_fecha(f.FechaNacimiento.value) ) {
		alert("La fecha de nacimiento no es correcta.")
		f.FechaNacimiento.focus()
		return;
	}

	var edadUsr = edad(f.FechaNacimiento.value)

	if ( edadUsr > 100 || edadUsr < 14) {
		alert("La fecha de nacimiento no puede ser menor de 14 o de más de 100 años.")
		f.FechaNacimiento.focus()
		return;
	}
	
	// Si es menor de 18, comprobamos que nos hayan puesto el nif del progenitor
	if ( edadUsr < 18 ) {
	
		/*if ( f.NIFProgenitor.value == '' ) {
			alert('Si eres menor de 18 años, el NIF de tu padre, madre o tutor es obligatorio');
			f.NIFProgenitor.focus();
			return;
		}
		
		if ( !valida_nif(f.NIFProgenitor.value.substr(0,f.NIFProgenitor.value.length-1), f.NIFProgenitor.value.substr(f.NIFProgenitor.value.length-1,1)) ) {
			alert('El NIF de tu padre, madre o tutor es incorrecto');
			f.NIFProgenitor.focus();
			return;
		}*/		
	}

	if ( f.TipoVia.value == "" ) {
		alert("Selecciona un tipo de vía.")
		f.TipoVia.focus()
		return;
	}
	
	if( f.Calle.value == "" ) {
	 	alert("La vía es obligatoria.")
		f.Calle.focus()
		return;
	}	

	if ( contieneCaracteres(f.Calle.value,';:[]{}=+<>\/&*¿?¡!%$#|') ) {
		alert('La vía no puede contener los caracteres: ;:[]{}=+<>\/&*¿?¡!%$#|');
		f.Calle.focus();
		return;
	}

	if ( f.Numero.value == "" ) {
		alert("El número es obligatorio.")
		f.Numero.focus()
		return;
	}

	if ( contieneCaracteres(f.Numero.value,'*¿?¡!%$#|') ) {
		alert('El número no puede contener los caracteres: *¿?¡!%$#|');
		f.Numero.focus();
		return;
	}
	
	if ( f.Poblacion.value == "" ) {
		alert("La población es obligatoria.")
		f.Poblacion.focus()
		return;
	}

	if ( contieneCaracteres(f.Poblacion.value,'0123456789;:[]{}=+<>\/&*¿?¡!%$#|') ) {
		alert('La población no puede contener los caracteres: 0123456789;:[]{}=+<>\/&*¿?¡!%$#|');
		f.Poblacion.focus();
		return;
	}

  	if (f.Provincia.selectedIndex==0) {
  		alert("Selecciona una provincia.");
  		f.Provincia.focus();
  		return;
  	}
    
	if ( f.CodigoPostal.value == "" || isNaN(f.CodigoPostal.value) ) {
		alert("El código postal es obligatorio y de 5 dígitos.")
		f.CodigoPostal.focus()
		return;
	} else {
		if ( f.CodigoPostal.value.length < 5 || isNaN(f.CodigoPostal.value) || 
	     	 f.CodigoPostal.value.substring(0,2) < 1 || f.CodigoPostal.value.substring(0,2) > 52 ) {
			alert("El código postal no es correcto.")
			f.CodigoPostal.focus()
			return;
		}	 
	}

  	// Capturamos los dos primeros digitos del cp, que nos indican la provincia
  	var idProvincia = f.CodigoPostal.value.substring(0,2)
  	
  	// Y comprobamos que el cp coincida con la provincia
  	if ( Number(f.Provincia.value) != Number(idProvincia) ) {
  		alert('El Código postal no coincide con la provincia seleccionada')
  		f.CodigoPostal.focus()
  		return;
  	}

	//Comprueba que se introduzca uno de los dos los telefonos
	if(f.Telefono1.value == "" && f.Telefono2.value == "") {
		alert("Escribe uno de los dos teléfonos.")
		f.Telefono1.focus()
		return;
	}

	if(f.Telefono1.value != "" && ( f.Telefono1.value.length != 9 || isNaN(f.Telefono1.value) || f.Telefono1.value.match(/^(6|8|9)/) == null) ) {
		alert("El teléfono tiene que ser númerico de 9 dígitos y empezar por 6,8 o 9.")
		f.Telefono1.focus()
		return;
	}

	if(f.Telefono2.value != "" && ( f.Telefono2.value.length != 9 || isNaN(f.Telefono2.value) || f.Telefono2.value.match(/^6/) == null) ) {
		alert("El móvil tiene que ser númerico de 9 dígitos y empezar por 6.")
		f.Telefono2.focus()
		return;
	}

	if ( f.pais_nacimiento.value == "" ) {
		alert("El país de nacimiento es obligatorio.")
		f.pais_nacimiento.focus()
		return;
	}

	// Si la usuaria tiene 24 años o más, validamos los hijos.
	if ( edadUsr >= 24 ) {

		var tieneHijos = valorSeleccionado(f.hijos)
		/*if ( tieneHijos == false ) {
			alert("Tienes que responder si tienes hijos o no.")
			f.hijos[0].focus()
			return;	
		}*/
		
		// Si ha contestado que tiene hijos, comprobamos los datos de los hijos
		if ( tieneHijos == "S" ) {
		
			// Miramos si nos ha indicado el nº de hijos
			if ( f.num_hijos.value == 0 ) {
				alert("Dinos el número de hijos.")
				f.num_hijos.focus()
				return;
			}	
		
			// Para cada hijo, comprobamos sexo y fecha de nacimiento
			var edadHijo = 0;
			for(h = 1; h <= f.num_hijos.value; h++) {
				
				if ( valorSeleccionado(f['sexo_hijo' + h]) == false ) {
					alert("Selecciona el sexo de hijo " + h + ".")
					f['sexo_hijo' + h][0].focus()
					return;	
				}
	
				if ( f['fnac_hijo' + h].value == "" || f['fnac_hijo' + h].value == "dd/mm/aaaa"  ) {
					alert("La fecha de nacimiento del hijo " + h + " es obligatoria.")
					f['fnac_hijo' + h].focus()
					return;
				}
			
				if ( !es_fecha(f['fnac_hijo' + h].value) ) {
					alert("La fecha de nacimiento del hijo " + h + " no es correcta.")
					f['fnac_hijo' + h].focus()
					return;
				}
				
				edadHijo = edad(f['fnac_hijo' + h].value)
				if ( edadHijo > 100 || edadHijo < 0 ) {
					alert("La fecha de nacimiento no puede ser futura o de más de 100 años.")
					f.fnac.focus()
					return;
				}
			}
		}
	}
	
	if (f.responsable_compras) {
		var personaHogar = valorSeleccionado(f.responsable_compras)
		if ( personaHogar == false ) {
			alert("Tienes que responder si eres la persona responsable de las compras del hogar.")
			f.responsable_compras[0].focus()
			return;	
		}
	}
		
	f.submit();
}

function volver_paso1() {
	var f = document.registrovip;
	f.action = "registro_paso1.php"
	f.submit();
}

function registro2() {
	var f = document.registrovip;

	if ( f['pregunta1[]'] && valorSeleccionado(f['pregunta1[]']) == false ) {
			alert("Contesta a todas las preguntas.")
			f['pregunta1[]'][0].focus()
			return;
	}

	if ( f['pregunta2[]'] && valorSeleccionado(f['pregunta2[]']) == false ) {
			alert("Contesta a todas las preguntas.")
			f['pregunta2[]'][0].focus()
			return;
	}

	if ( f['pregunta3[]'] && valorSeleccionado(f['pregunta3[]']) == false ) {
			alert("Contesta a todas las preguntas.")
			f['pregunta3[]'][0].focus()
			return;
	}
	
	if ( f['pregunta4[]'] && valorSeleccionado(f['pregunta4[]']) == false ) {
			alert("Contesta a todas las preguntas.")
			f['pregunta4[]'][0].focus()
			return;
	}
	
	// Miramos si hay que validar más preguntas
	if ( typeof valida_preguntas_extra == "function" ) {
		// Existe la función para validar las preguntas extra
		if ( ! valida_preguntas_extra(f) ) {
			return;
		}
	}

	if ( valorSeleccionado(f.condiciones) == false ) {
		alert("Tienes que aceptar las condiciones legales.")
		f.condiciones.focus()
		return;
	}

	f.submit()
}

function compruebaEdad() {
	var f = document.registrovip
	
	if ( es_fecha(f.FechaNacimiento.value) ) {

		var edadUsr = edad(f.FechaNacimiento.value)
		
		if ( edadUsr < 18 ) {
            if (edadUsr >= 14) {
			// No mostramos el nif del progenitor
			// document.getElementById('campo_nif_progenitor').style.display = "block";
			 document.getElementById('campo_nif_progenitor2').style.display = "none"
            }else{
                f.FechaNacimiento.value = '';
				
				  document.getElementById('campo_nif_progenitor2').style.display = "block"
                document.getElementById('campo_nif_progenitor').style.display = "none"
                return
            }

		} else {
			
			document.getElementById('campo_nif_progenitor').style.display = "none"
			 document.getElementById('campo_nif_progenitor2').style.display = "none"
			
			if ( edadUsr >= 24 ) {	
				// mostramos las preguntas de hijos
				document.getElementById('preguntas_hijos').style.display = "block"
				return
			}
		}
	}
	
	document.getElementById('preguntas_hijos').style.display = "none"
}

function nota_legal() {
    var w = 740;
    var h = 600;
    
    var x = screen.availWidth/2-w/2;
    var y = screen.availHeight/2-h/2;
    
    var opcionesPopup= "height=" + h + ",innerHeight=" + h + ",width=" + w + ",innerWidth=" + w;
    opcionesPopup += ",left=" + x + ",screenX=" + x + ",top=" + y + ",screenY=" + y;
    opcionesPopup += ",status=yes,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes";

    window.open("aviso-legal-pop.php","avisolegal",opcionesPopup)
}

function revisaChecks(chk) {
	var f = chk.form
	
	if ( chk.id.substr(0,3) == 'nu_' && chk.checked ) {
		// Han seleccionado un "No uso". Deschequeamos los otros
		for(i=0;i<f[chk.name].length;i++) {
			
			// Nos saltamos el actual
			if ( f[chk.name][i].value == chk.value ) continue;
		
			f[chk.name][i].checked = false;
		}
		return
		
	} else if ( chk.id.substr(0,3) != 'nu_' && chk.checked ) {
		// Seleccionan otro que no es "No uso". Si hay un "No uso", lo deschequeamos
		for(i=0;i<f[chk.name].length;i++) {
			if ( f[chk.name][i].id.substr(0,3) == 'nu_' ) {
				f[chk.name][i].checked = false;
				break;
			}
		}
	}

	if ( chk.id.match(/^pregunta12_[0-9]$/) && chk.checked ) {
		if(chk.id.match(/^pregunta12_2$/)){
			$('#pregunta13Cont').show();
		}	
		if(chk.id.match(/^pregunta12_3$/)){
			$('#pregunta13Cont').find('input[type=checkbox]:checked').removeAttr('checked');
			$('#pregunta13Cont').hide();
			$('#pregunta14Cont').find('input[type=text]').val('');
			$('#pregunta14Cont').hide();
			$('#pregunta12Cont').find('input[type=checkbox]').not('#pregunta12_3').removeAttr('checked');
		}else{
			$('#pregunta12_3').removeAttr('checked');
		}
	}
	if ( chk.id.match(/^pregunta12_[0-9]$/) && !chk.checked ) {
		if(chk.id.match(/^pregunta12_2$/)){
			$('#pregunta13Cont').find('input[type=checkbox]:checked').removeAttr('checked');
			$('#pregunta13Cont').hide();
			$('#pregunta14Cont').find('input[type=text]').val('');
			$('#pregunta14Cont').hide();
		}	
	}
	if ( chk.id.match(/^pregunta13_3$/) && chk.checked ) {
			$('#pregunta14Cont').show();
	}
	if ( chk.id.match(/^pregunta13_3$/) && !chk.checked ) {
			$('#pregunta14Cont').hide();
			$('input[name=pregunta14]').val('');
	}

}

