var eventoEscogido=0;
var categoriaEscogida=0;
var categoriasPlazas = new Array();
var inscripciones=1;
var inscripcionActual=1;
var inscritos = new Array();
var descuentos = new Array();
var idFactura = 0;
var inscripcionesTOPE = 0;
var otraInscripcion = true;

function insP1EventoEscogido(mostrarPlazas){	
	eventoEscogido = $('input[name=eventos]:checked');
	
	if(eventoEscogido.length > 0){
		mZona('pas2',true);
		insP2categoriasCargar("false");
	}else{alert("Debes escoger un evento para continuar");}
}
$("div span:last-child")

function insP2categoriasCargar(mostrarPlazas){
	
	//$('#p2eventoEscogido').html($('input[name=eventos]:checked').next().html());
	$.ajax({
			type: "POST",
			url: "AJ_p2categoriasCargar.php",
			data: "evento="+eventoEscogido[0].value+"&mostrar="+mostrarPlazas,
			success: function(msg){
				$('#p2listadoCategorias').empty();
				$('#p2listadoCategorias').html(msg);
				hideLoading();
		}
 	});
}

function insP2CategoriaEscogida(){
	categoriaEscogida = $('input[name=categorias]:checked').val();
		
	if(categoriaEscogida > 0){
			//insP2comprovarPlazas(true);
			insP3iniciar(true);			
	}else{alert("Debes escoger una categoria del evento para continuar");}
}
function insP2comprovarPlazas(varr){//tmbien se crea la factura en blanco si no existe!
	$.ajax({
			type: "POST",
			url: "AJ_p2comprovarPlazas.php",
			data: "categoria="+categoriaEscogida+"&factura="+idFactura,
			success: function(response){
				if(response != 'false'){
					idFactura = response;
					$('#p3eventoEscogido').html($('input[name=eventos]:checked').next().html());
					
					if(varr){						
						$('#p3categoriaEscogida').html($('input[name=categorias]:checked').next().html());
					}else{
						$('#p3categoriaEscogida').html($('input[name=categoriasp3]:checked').next().html());
					}
					insP3iniciar(varr);					
				}else{alert('No quedan mas plazas para eset evento');}
		}
 	});	
}
function insP3iniciar(){
	$('#p3detalleDescuento').html(" ");
	$('#numeroInscripcionActual').html(inscripcionActual);
	$('#pas3formDatos').hide();
	$('#loadingPiloto').hide();
	$('#pas3formDatos').reset();
	$('#bdni').val('');
	$('#bcd').val('');
	$('#fdescuento').val('');
	$('#fcodigodescuento').val('');
	mZona('pas3',true);
	hideLoading();	
}
function insCargarPlazasDisponibles(response){
	
		var categorias = response.firstChild;
		categoriasPlazas = false;
		categoriasPlazas = new Array();
		var tmp;
		for(var i=0;i<categorias.childNodes.length;i++){
			tmp = new Array;
			tmp.push(categorias.childNodes[i].childNodes[0].firstChild.nodeValue);	
			tmp.push(categorias.childNodes[i].childNodes[1].firstChild.nodeValue);	
			
			categoriasPlazas.push(tmp);
		}
}
function insRestarPlazasInscripcion(){
		var cat;
		for(var i=0;i<categoriasPlazas.length;i++){
			cat = categoriasPlazas[i][0];
			
			for(var u=0;u<inscritos.length;u++){if(inscritos[u][0] == cat){categoriasPlazas[i][1]--;}}			
		}
}
function insComprovarDisponibilidad(){
		var disponible = false;		
		for(var i=0;i<categoriasPlazas.length;i++){
			if((categoriasPlazas[i][0] == categoriaEscogida)&&(categoriasPlazas[i][1] > 0)){disponible=true;}
		}
		return disponible;
}
function insP3categoriasMostrar(){
	$('#p3listadoCategorias').show('fast');
}
function insP3categoriasCargar(){
	$.ajax({
			type: "POST",
			url: "AJ_p3categoriasCargar.php",
			data: "evento="+eventoEscogido,
			success: function(msg){
				$('#p3listadoCategoriasDiv').html(msg);
				
		}
 	});
}
function insP3categoriaCambiar(){
	var tmp = $('#p3categoriaEscogida').html(); 
	$('#p3listadoCategorias').hide();
	$('#p3categoriaEscogida').html('Cargando...');
	categoriaEscogida = $('input[name=categoriasp3]:checked').val();

	if(categoriaEscogida > 0){
			insP2comprovarPlazas(false);			
	}else{$('#p3categoriaEscogida').html(tmp);alert("Debes escoger una categoria del evento para continuar");}
}
function insp3mostrarDivCodigoDescuento(){
	$('#insp3linkCodigoDescuento').toggle();	
	$('#insp3inputCodigoDescuento').toggle();	
}
function pas3OcultarForm(){
	$('#pas3formDatos').hide();
}
function insP3buscaDatosPiloto(){
	$('#pas3formDatos').hide();
	$('#pas3formDatos').reset();
	
	var dniUsado = false;
	
	for(var i=0;i<inscritos.length;i++){//comprobamos si en la misma insripcion ya se uso ese DNI
		if(inscritos[i][1] == $('#bdni').val().toUpperCase()){dniUsado=true;}}
		
		
	if(dniUsado){alert("Este dni ya esta usado para este Evento")}
	else{
		
		$('#loadingPiloto').show('fast');
		$.ajax({
			type: "POST",
			url: "AJ_p3comprovarDniYdescuento.php",
			data: "categoria="+categoriaEscogida+"&dni="+$('#bdni').val(),
			success: function(response){
				if(response == 'descuentoUsado'){
					alert("Descuento utilizado");
					$('#loadingPiloto').hide();
				}
				else if(response == 'descuentoInvalido'){
					alert("Descuento invalido");
					$('#loadingPiloto').hide();
				}
				else if(response == 'dniOK'){
					//p3cargarDetalleDescuento();
					$('#p3botonContinuar').hide();
					
					$('#fdni').val($('#bdni').val())		
						$.ajax({
						type: "POST",
						url: "AJ_p3buscaDatosPiloto.php",
						data: "dni="+$('#bdni').val(),
						success: function(response){
							if(response.firstChild.hasChildNodes()){//EL INSCRITO YA EXISTE
								var datos = response.firstChild;
								var campos = datos.childNodes.length;
								
								$('#finscrito').val('inscrito');
								
								$(datos).children().each(function(){
									
									if($(this)[0].nodeName.substr(0,3) == 'dn_'){
										var tmp = $('#'+$(this)[0].nodeName+' > option');
										var sel = $('#'+$(this)[0].nodeName);
										for (var opc=0;opc < tmp.length;opc++){
											if(parseFloat(tmp[opc].value)==parseFloat($(this).text())){
												sel[0].selectedIndex=opc;
											}
										} 
									}else{
										$('#f'+$(this)[0].nodeName).val($(this).text());					
									}
								});					
							}
							else{$('#finscrito').val('nuevo');}//EL INSCRITO NO EXISTE
							$('#loadingPiloto').hide();
							$('#pas3formDatos').show('fast');
						}
					});	
				}else{$('#loadingPiloto').hide();alert('Este dni ya esta usado para este Evento y categoria');}
			}
 		});	//ajax
	}//if dniUsado
}
function p3cargarDetalleDescuento(){
	$.ajax({
			type: "POST",
			url: "AJ_p3detalleDescuento.php",
			data: "descuento="+$('#bcd').val(),
			success: function(response){
				if(response != "0::0"){
				var datos = response.split("::");
					$('#p3detalleDescuento').html(datos[0]+" ("+datos[1]+" de Descuento)");
					$('#fdescuento').val(datos[1]);
					$('#fcodigodescuento').val($('#bcd').val());
				}
		}
 	});
}
function insP3DatosInscripcion(){	
	$('#pas3formDatos').hide();
	$('#bdni').val('');
	$('#bcd').val('');
	$('#p3detalleDescuento').html("");
	var inputs = $('#pas3formDatos :input');
	var variables = "categoria="+categoriaEscogida+"&factura="+idFactura;
	for(var i=0;i<(inputs.length-1);i++){
		if(inputs[i].value == ""){inputs[i].value = "0"}
		variables += "&"+inputs[i].name+"="+inputs[i].value;
	}
	$.ajax({
			type: "POST",
			url: "AJ_p3inscripcionDatos.php",
			data: variables,
			success: function(response){
				inscripcionActual++;
				inscritos.push(new Array(categoriaEscogida,$('#fdni').val().toUpperCase()));
				if($('#fcodigodescuento').val() != 0){descuentos.push($('#fcodigodescuento').val());}
				$('#p3botonContinuar').show('fast');
				
				if(otraInscripcion){inscripciones++;}
				if(inscripciones == inscripcionesTOPE){otraInscripcion = false;}
				
				if(inscripcionActual <= inscripciones){//siguiente inscripcion
					insP3iniciar();
				}else{//continuamos el proceso de inscripcion
					insP4cargarDatos();
				}
		}
 	});
}
function insP4cargarDatos(){
mZona('pas4',true);	
	$.ajax({
			type: "POST",
			url: "AJ_p4cargarDatos.php",
			data: "factura="+idFactura,
			success: function(response){
				
				var conceptos = response.firstChild;
				var precioTotal = 0;
				var tmpXml;
				var tmpEvento;
				var tmpCategoria;
				var tmpNombre;
				var tmpDni;
				var tmpPrecio;
				var tmpDesc;
				var tmpHtml;
				
				for(var i=0;i<conceptos.childNodes.length;i++){
					if(conceptos.childNodes[i].nodeType == 1){
						tmpXml = conceptos.childNodes[i];
						//alert(tmpXml.childNodes[0].nodeValue);
						tmpEvento = tmpXml.childNodes[0].firstChild.nodeValue;
						tmpCategoria = tmpXml.childNodes[1].firstChild.nodeValue;
						tmpNombre = tmpXml.childNodes[2].firstChild.nodeValue;
						tmpDni = tmpXml.childNodes[3].firstChild.nodeValue;
						tmpPrecio = tmpXml.childNodes[4].firstChild.nodeValue;
						tmpDesc = tmpXml.childNodes[5].firstChild.nodeValue.replace(/€/g,'&euro;');	
						
						tmpHtml = "<tr>";
						tmpHtml += "<td>"+tmpEvento+" ("+tmpCategoria+")</td>";
						tmpHtml += "<td>"+tmpNombre+"</td>";
						tmpHtml += "<td>"+tmpDni+"</td>";
						tmpHtml += "<td style=\"text-align:right\">"+tmpPrecio+" &euro;</td>";
						tmpHtml += "<td style=\"text-align:right\">"+tmpDesc+"</td>";
						tmpHtml += "</tr>";
		
						precioTotal += parseFloat(tmpPrecio);
						$('#p4conceptosTabla tr:last').after(tmpHtml);
					
					}
				}
				tmpHtml = "<tr>";
				tmpHtml += "<td colspan=\"3\" style=\"text-align:right\">TOTAL</td>";
				tmpHtml += "<td style=\"text-align:right\">"+precioTotal+" &euro;</td>";
				tmpHtml += "<td></td>";
				tmpHtml += "</tr>";
				$('#p4conceptosTabla tr:last').after(tmpHtml);
				$("#p4inscripcionPago").val(precioTotal);
				$("#p4inscripcionFactura").val(idFactura);
				hideLoading();
				
		}
 	});	
}
function insP4FinalizarInscripcion(){
	var metodo = $('input[name=metodoPago]:checked').val();
	$.ajax({
			type: "POST",
			url: "AJ_p4formalizarInscripcion.php",
			data: "tipopago="+metodo+"&factura="+idFactura,
			success: function(response){
				
		}
 	});
	
	if(metodo == '2'){//TPV
		if(confirm('Va a pasar a la pasarela de pago por TPV y finalizar asi su inscripcion. Desea continuar?')){
			$("#insFinalizarInscripcion").submit();
		}	
	}else{//TRANSFERENCIA
		mZona('pas5',false);
		$.ajax({
			type: "POST",
			url: "AJ_p5enviarMailTransfer.php",
			data: "factura="+idFactura,
			success: function(response){		
			}
 	});
	}
}