var TIMEOUT = 7000
var inscripcionVisitanteHecha = false

function cambioProvinciaVisitantes()
{
	showLoading('Cargando poblaciones...')
    var url = '/eventos/rrhh/traerPoblaciones.aspx?id=' + $('#provincia').val();	
	$.getJSON(url, function (data) 
	{
		provinciasDescargadasVisitantes(data);
	});
}

function provinciasDescargadasVisitantes(data)                                                      
{
	$('#fVisitante #poblacion').empty()
	$('#fVisitante #poblacion').append('<option value="000000">Seleccione una poblaci&oacute;n</option>')
	for(var i = 0; i < data.data.Id_poblacion.length; i++)
	{
		$('#fVisitante #poblacion').append('<option value="' + data.data.Id_poblacion[i] + '">' + data.data.nombre[i] + '</option>')
	}
	hideLoading()
}

function comprobarFormularioVisitantes()
{
	if (!inscripcionVisitanteHecha)
	{
		var form = document.fVisitante
		var mensajes = new Array();
		var mensaje = ''
		var s = ''
		var altoFila = 20;
		var altoCapa = 300
		var tipo = $('input[name=tipo_visitante]:checked').val()
		var long
		
		// Comprobación de partes comunes. 1 y 2
		// Parte 1
		if (form.empresa.value == textoObligatorio)
			mensajes[mensajes.length] = 'Es obligatorio rellenar el <b>nombre de la empresa</b>.'
		if (form.direccion.value == textoObligatorio)
			mensajes[mensajes.length] = 'Es obligatorio rellenar el <b>direcci&oacute;n de la empresa</b>.'
		if (form.cp.value == textoObligatorio)
			mensajes[mensajes.length] = 'Es obligatorio rellenar el <b>CP. de la empresa</b>.'
		if (form.poblacion.selectedIndex == 0)
			mensajes[mensajes.length] = 'La <b>provincia y la poblaci&oacute;n de la empresa</b> son obligatorias.'
		s = form.telefono.value.replace(/ /g, '')
		if (isNaN(s) || s.length < 9)
			mensajes[mensajes.length] = 'El <b>tel&eacute;fono de la empresa</b> es obligatorio.'	
		if (form.cif.value == textoObligatorio)
			mensajes[mensajes.length] = 'El <b>CIF de la empresa</b> es obligatorio.'
		
		// Parte 2
		if (form.nombre_participante.value == textoObligatorio)
			mensajes[mensajes.length] = 'Es obligatorio rellenar el <b>nombre del participante</b>.'
		if (form.apellidos_participante.value == textoObligatorio)
			mensajes[mensajes.length] = 'Es obligatorio rellenar los <b>apellidos del participante</b>.'
		if (form.cargo_participante.value == textoObligatorio)
			mensajes[mensajes.length] = 'Es obligatorio rellenar el <b>cargo del participante</b>.'
		if (!$CEmail(form.email_participante.value))
			mensajes[mensajes.length] = 'Es obligatorio rellenar el <b>email del participante</b>.'
		s = form.telefono_directo_participante.value.replace(/ /g, '')
		if (isNaN(s) || s.length < 9)
			mensajes[mensajes.length] = 'El <b>tel&eacute;fono directo del participante</b> es obligatorio.'
		s = form.movil_participante.value.replace(/ /g, '')
		if (isNaN(s) || s.length < 9)
			mensajes[mensajes.length] = 'El <b>tel&eacute;fono m&oacute;vil del participante</b> es obligatorio.'
		
		long = $('[name*=participacion]:checked').length;
			if (long == 0)
				mensajes[mensajes.length] = 'Hay que elegir <b>cuantos d&iacute;as de participaci&oacute;n</b>.'
			
		if (tipo == 'A')
		{
			// Parte 3
			if (form.actividad.value == textoObligatorio)
				mensajes[mensajes.length] = 'La <b>actividad de la empresa</b> es obligatoria.'
			// Parte 7. Alojamiento
			long = $('[name*=alojamiento]:checked').length;
			if (long == 0)
				mensajes[mensajes.length] = 'Hay que elegir al menos <b>1 alojamiento</b>.'
			// Parte 5
			/*long = $('[name*=producto_]:checked').length;
			if (long == 0)
				mensajes[mensajes.length] = 'Hay que elegir al menos <b>1 producto</b>.'*/
		}
		
		/*if ((tipo == 'A') || (tipo == 'B'))
		{
			// Parte 6
			long = $('[name*=foros_]:checked').length;
			if (long == 0)
				mensajes[mensajes.length] = 'Hay que elegir al menos <b>1 actividad</b>.'
		}*/
		
		if (
            (form.nombre_sustituto.value == '') || 
            (!$CEmail(form.email_sustituto.value)) || 
            (form.cargo_sustituto.value == '') ||
			(form.dni_sustituto.value == '')  
            )
            mensajes[mensajes.length] = 'Hay que rellenar el <b>nombre</b>, <b>email</b>, <b>cargo</b> y <b>DNI</b> del sustituto.'
		
		if (!form.reglamento.checked)
			mensajes[mensajes.length] = 'Debe aceptar el <b>reglamento</b>.'	
		if (mensajes.length != 0)
		{
			for (i = 0; i < mensajes.length; i++)
			{
				mensaje += '<div style="float: left;margin: 5px 0px; width: 100%; text-align: left">- ' + mensajes[i] + '</div>'
			}
			divMensajes.dialog({ title: 'Error' });
			divMensajes.html(mensaje)
			divMensajes.dialog('open');			
			return false;
		}
		else 
		{
			var url = '/eventos/rrhh/includes/inscribirVisitanteV2010.aspx?'
			var datos = $("#fVisitante").serialize()
			//window.open(url + datos)		
			$.ajax({
				url: url,
				type: 'POST',
				dataType: 'js',
				cache : true,
				data: datos,
				timeout: TIMEOUT,
				error: function(){
					hideLoading()
					alert('Error guardando la suscripci&oacute;n');
				},
				success: function(texto){
					suscrito(texto)
					hideLoading()
					
				},
				beforeSend: function(){
					showLoading('GUARDANDO LA INSCRIPCI&Oacute;N');
				}
				});
			return false;
		}
	}
	else
	{
		alert('Ya has realizado la inscripción en el evento.')
		return false;	
	}
}

function mostrarTodos(id)
{
	$('[name=' + id + ']').each(function(){
		$(this).show()
	});	
}

function ocultarTodos(id)
{
	$('[name=' + id + ']').each(function(){
		$(this).hide()
	});	
}
	
function mostrarOcultar()
{
	var tipo = $('input[name=tipo_visitante]:checked').val() 
	if (tipo == 'A')
	{
		for (i = 3; i <= 7; i++)
			mostrarTodos('parte_' + i)
	}
	else if (tipo == 'B')
	{
		ocultarTodos('parte_3')
		ocultarTodos('parte_4')
		ocultarTodos('parte_5')
		mostrarTodos('parte_6')
		ocultarTodos('parte_7')
	}
	else if (tipo == 'C')
	{
		ocultarTodos('parte_3')
		ocultarTodos('parte_4')
		ocultarTodos('parte_5')
		ocultarTodos('parte_6')
		ocultarTodos('parte_7')
	}
}

function suscrito(texto)
{
	var a = texto.split('|')
	hideLoading()
	if (a[0] == 'ok')
	{
		mensaje = 'Su solicitud de inscripci&oacute;n a BusinessEvent™ Salón Capital Humano ha sido registrada.<br>'
		mensaje += 'Un asesor de eventos se pondr&aacute; en contacto con Ud. en breve.<br>'
		mensaje += 'Puede ponerse en contacto con nosotros para resolver cualquier duda en el 902 93 18 18.<br>'		
		mensaje += '&iexcl;Gracias por su confianza!'
        
        //	inscripcionVisitanteHecha = true
        divMensajes.dialog({ title: 'Suscripci&oacute;n realizada' });
		divMensajes.html(mensaje)
		divMensajes.dialog('open');	
	}
	else
    {
        mensaje = "Ha habido un error realizando su inscripci&oacute;n.<br> Int&eacute;ntelo m&aacute;s tarde por favor o póngase en contacto con el 902 93 18 18."
        alert(mensaje)
    }
}