
// lo usamos para ver si hay un proceso activo
var enProceso = false;

// Creamos el objeto XMLHttpRequest
var http = getHTTPObject();

var err = "";

var init=false;

var captchaFuzz = -1;

var captchState = "Loaded";

var captchaImage = 0;

function initRegistro() {
	if(document.getElementById("modoSimpatizante").checked == true)
	{
		modo_simpatizante();
	} else if(getParameter("modoSimpatizante") == "1")
	{
		document.getElementById("modoSimpatizante").checked = true;
		modo_simpatizante();
	}
	
	if(init == false)
	{
		init = true;
		recargaCaptcha();
	}
}

function getParameter(name) {
   var url = window.location.href;
   var paramsStart = url.indexOf("?");

   if(paramsStart != -1){

      var paramString = url.substr(paramsStart + 1);
      var tokenStart = paramString.indexOf(name);

      if(tokenStart != -1){

         paramToEnd = paramString.substr(tokenStart + name.length + 1);
         var delimiterPos = paramToEnd.indexOf("&");

         if(delimiterPos == -1){
            return paramToEnd;
         }
         else {
            return paramToEnd.substr(0, delimiterPos);
         }
      }
   }
}


function modo_afiliado() {
	modificar_campos(['campoNombre', 'campoApellidos', 'grupoDatosAfiliado',
	'campoFechaNacimiento', 'campoSexo', 'campoTelefonos', 'campoDocumentoIdentificacion',
	'campoDireccion', 'campoNacionalidad'] ,'block');
	ocultar('campoApellidos2');
	ocultar('campoNombre2');
	ocultar('campoDireccion2');
	ocultar('campoNacionalidad2');
	mostrar('campoEstatutos');
}

function modo_simpatizante() {
	modificar_campos(['campoNombre', 'campoApellidos', 'grupoDatosAfiliado',
	'campoFechaNacimiento', 'campoSexo', 'campoTelefonos', 'campoDocumentoIdentificacion',
	'campoNacionalidad', 'campoDireccion'] ,'none');
	mostrar('campoApellidos2');
	mostrar('campoNombre2');
	mostrar('campoDireccion2');
	mostrar('campoNacionalidad2');
	ocultar('campoEstatutos');
}

function modificar_campos(campos, display) {
	for(i=0; i < campos.length; i++) {
		document.getElementById(campos[i]).style.display = display;
	}
}

function pais_provincia() {
	if(document.getElementById("pais").value != "esp") {
		mostrar("provinciaText");
		ocultar("provinciaSelect");
		document.getElementById("provinciaText").style.width= "12.5em";
		document.getElementById("provinciaSelect").style.width= "0";
	} else {
		mostrar("provinciaSelect");
		ocultar("provinciaText");
		document.getElementById("provinciaSelect").style.width= "14em";
		document.getElementById("provinciaText").style.width= "0";
	}
}


function pais_provincia2() {
	if(document.getElementById("pais2").value != "esp") {
		mostrar("provinciaText2");
		ocultar("provinciaSelect2");
		document.getElementById("provinciaText2").style.width= "14em";
		document.getElementById("provinciaSelect2").style.width= "0";
	} else {
		mostrar("provinciaSelect2");
		ocultar("provinciaText2");
		document.getElementById("provinciaSelect2").style.width= "14em";
		document.getElementById("provinciaText2").style.width= "0";
	}
}

function mostrar(mostrar) {
	document.getElementById(mostrar).style.visibility = "visible";
	document.getElementById(mostrar).style.display = "inline";
}

function ocultar(ocultar) {
	document.getElementById(ocultar).style.visibility = "hidden";
	document.getElementById(ocultar).style.display = "none";
}

function procesaRegistro() {
	if(document.getElementById("modoAfiliado").checked == true) {
		return procesaAfiliado();
	} else {
		return procesaSimpatizante();
	}
}

function procesaAfiliado() {
	errores=false;
	err="";
	
	reiniciarCampos(["campoNick", "campoPass", "campoPass2", "campoPreguntaSecreta", "campoRespuestaSecreta", "campoEmail", "campoNombre", "campoApellidos", "campoNumeroIdentificacion", "campoFechaNacimiento", "campoDireccion", "campoSexo", "campoCaptcha", "campoAcepta"]);
	limpiarErrores(["nickError", "passError", "pass2Error", "pregsecretaError", "respsecretaError", "emailError", "nombreError", "apellidosError", "numeroIdentificacionError", "nacimientoError", "direccionError", "sexoError", "captchaError", "aceptaError"]);
	
	var regexp = new RegExp('^[0-9A-Z_]+$', 'i');
	if(get("nick").length < 3) {
		errores=true;
		error("campoNick", "nickError", "Nombre de Usuario demasiado corto<br/>\n");
	} else if(!regexp.test(get("nick"))) {
		errores=true;
		error("campoNick", "nickError", "El Nombre de Usuario contiene caracteres inv&aacute;lidos<br/>\n");
	}
	
	if(get("pass").length < 6) {
		errores=true;
		error("campoPass", "passError", "Contrase&ntilde;a demasiado corta<br/>\n");
	}
	
	if(get("pass") != get("pass2")) {
		errores=true;
		error("campoPass2", "pass2Error", "Las contrase&ntilde;as no coinciden<br/>\n");
	}
	
	if (get("pregsecretaSelect") == "null" &&
	    get("pregsecreta").length < 6) {
		errores=true;
		error("campoPreguntaSecreta", "pregsecretaError", "Pregunta secreta demasiado corta<br/>\n");
	}
	
	if (get("respsecreta").length < 6) {
		errores=true;
		error("campoRespuestaSecreta", "respsecretaError", "Respuesta secreta demasiado corta<br/>\n");
	}
	
	
	var regexp = new RegExp('^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$', 'i');
	if(!regexp.test(get("email"))) {
		errores=true;
		error("campoEmail", "emailError", "Direcci&oacute;n de Correo Electr&oacute;nico inv&aacute;lida<br/>\n");
	}
	
	if(get("nombre").length < 3) {
		errores=true;
		error("campoNombre", "nombreError", "Nombre demasiado corto<br/>\n");
	}
	
	if(get("apellidos").length < 3) {
		errores=true;
		error("campoApellidos", "apellidosError", "Apellidos demasiado cortos<br/>\n");
	}
	
	if(get("tipoDocumento") == "dni") {
		var regexp = new RegExp('^[0-9]{8}[ -]?[A-Z]$', 'i');
		
		dni = get("numeroIdentificacion");
		letra = dni.substring(dni.length-1, dni.length).toUpperCase();
		
		if(dni.length < 9 || !regexp.test(dni)) {
			errores=true;
			error("campoNumeroIdentificacion", "numeroIdentificacionError",
			"DNI inv&aacute;lido<br/>\n");
		} else if(letra != letraDNI(dni.substring(0, 8))) {
			errores=true;
			error("campoNumeroIdentificacion", "numeroIdentificacionError",
			"Letra de DNI inv&aacute;lida<br/>\n");
		}
	} else if(get("tipoDocumento") == "nie") {
		var regexp = new RegExp('^(X[ -]?|)?([0-9]{8}[ -]?[A-Z])$', 'i');
		
		dni = get("numeroIdentificacion");
		letra = dni.substring(dni.length-1, dni.length).toUpperCase();
		dni = dni.replace(regexp, "$2");
		alert(dni);
		if(dni.length < 9 || !regexp.test(dni)) {
			errores=true;
			error("campoNumeroIdentificacion", "numeroIdentificacionError",
			"NIE inv&aacute;lido<br/>\n");
		} else if(letra != letraDNI(dni.substring(0, 8))) {
			errores=true;
			error("campoNumeroIdentificacion", "numeroIdentificacionError",
			"Letra de NIE inv&aacute;lida<br/>\n");
		}
	} else if(get("tipoDocumento") == "tarjetaResidencia") {
		var regexp = new RegExp('^[0-9]{8}[ -]?[A-Z]$', 'i');
		
		dni = get("numeroIdentificacion");
		letra = dni.substring(dni.length-1, dni.length).toUpperCase();
		
		if(dni.length < 9 || !regexp.test(dni)) {
			errores=true;
			error("campoNumeroIdentificacion", "numeroIdentificacionError",
			"Tarjeta de Residencia Comunitaria inv&aacute;lida<br/>\n");
		} else if(letra != letraDNI(dni.substring(0, 8))) {
			errores=true;
			error("campoNumeroIdentificacion", "numeroIdentificacionError",
			"Letra de Tarjeta de Residencia Comunitaria inv&aacute;lida<br/>\n");
		}
	}
	if(get("documentoIdentificacion").length < 1) {
		errores=true;
		error("campoDocumentoIdentificacion", "documentoIdentificacionError", "No ha adjuntado el documento<br/>\n");
	}
	
	date = new Date();
	anhoActual = date.getFullYear();
	mesActual = date.getMonth()+1;
	diaActual = date.getDate();
	if(get("diaNacimiento") <= 0
		|| get("mesNacimiento") == 2 && get("diaNacimiento") > 28 
		|| get("mesNacimiento") > 2 && get("mesNacimiento") % 2 == 0 && get("diaNacimiento") > 30)
	{
		errores = true;
		error("campoFechaNacimiento", "nacimientoError", "Fecha inv&aacute;lida<br/>\n");
	} else if((anhoActual - get("anhoNacimiento")) < 18
		|| (anhoActual - get("anhoNacimiento")) == 18 && mesActual < get("mesNacimiento")
		|| (anhoActual - get("anhoNacimiento")) == 18 && mesActual == get("mesNacimiento")
			&& diaActual < get("diaNacimiento")) {
		errores = true;
		error("campoFechaNacimiento", "nacimientoError", "Edad menor a 18 a&ntilde;os<br/>\n");
	}
	
	if(get("direccion") < 5)
	{
		errores = true;
		error("campoDireccion", "direccionError", "Direcci&oacute;n demasiado corta<br/>\n");
	}
	if(get("pais") != "esp" && get("provinciaText").length < 4) {
		errores = true;
		error("campoDireccion", "direccionError", "Provincia demasiado corta<br/>\n");
	} else if(get("pais") == "esp" && get("provinciaSelect") == "null") {
		errores = true;
		error("campoDireccion", "direccionError", "No se ha seleccionado una provincia<br/>\n");
	}
	
	if(get("poblacion").length < 4) {
		errores = true;
		error("campoDireccion", "direccionError", "Poblaci&oacute;n demasiado corta<br/>\n");
	}
	var regexp = new RegExp('^[0-9]{5}$', 'i');
	if(get("cp").length < 5 || !regexp.test(get("cp"))) {
		errores = true;
		error("campoDireccion", "direccionError", "C&oacute;digo postal incorrecto<br/>\n");
	}
	
	if(get("sexo") == "null") {
		errores = true;
		error("campoSexo", "sexoError", "Elija su sexo<br/>\n");
	}
	
	if(!regexp.test(get("captcha"))) {
		errores = true;
		error("campoCaptcha", "captchaError", "Texto del captcha incorrecto<br/>\n");
	}
	
	if(!document.getElementById("lopd").checked) {
		errores = true;
		error("campoAcepta", "aceptaError", "No has autorizado a PIRATA a guardar tus datos<br/>\n");
	}
	
	if(!document.getElementById("estatutos").checked) {
		errores = true;
		error("campoAcepta", "aceptaError", "No has aceptado los estatutos del <em>\"PIRATA\"</em><br/>\n");
	}
	if(errores == false) {
		poststr = "nick=" + encodeURI(get("nick")) +
			"&pass=" + encodeURI(get("pass")) +
			"&nombre=" + encodeURI(get("nombre")) +
			"&apellidos=" + encodeURI(get("apellidos")) +
			"&numeroIdentificacion=" + encodeURI(get("numeroIdentificacion")) +
			"&captcha=" + encodeURI(get("captcha")) +
			"&captchaFuzz=" + encodeURI(captchaFuzz);
		
		ajax("ajax.php?afiliado=true", poststr);
	}
	
	return false;
}

function procesaSimpatizante() {
	errores=false;
	err="";
	
	reiniciarCampos(["campoNick", "campoPass", "campoPass2", "campoPreguntaSecreta", "campoRespuestaSecreta", "campoEmail", "campoNombre", "campoApellidos", "campoNumeroIdentificacion", "campoFechaNacimiento", "campoDireccion", "campoSexo", "campoCaptcha", "campoAcepta"]);
	limpiarErrores(["nickError", "passError", "pass2Error", "pregsecretaError", "respsecretaError", "emailError", "nombreError", "apellidosError", "numeroIdentificacionError", "nacimientoError", "direccionError", "sexoError", "captchaError", "aceptaError"]);
	
	var regexp = new RegExp('^[0-9A-Z_]+$', 'i');
	if(get("nick").length < 3) {
		errores=true;
		error("campoNick", "nickError", "Nombre de Usuario demasiado corto<br/>\n");
	} else if(!regexp.test(get("nick"))) {
		errores=true;
		error("campoNick", "nickError", "El Nombre de Usuario contiene caracteres inv&aacute;lidos<br/>\n");
	}
	
	if(get("pass").length < 6) {
		errores=true;
		error("campoPass", "passError", "Contrase&ntilde;a demasiado corta<br/>\n");
	}
	
	if(get("pass") != get("pass2")) {
		errores=true;
		error("campoPass2", "pass2Error", "Las contrase&ntilde;as no coinciden<br/>\n");
	}
	
	if (get("pregsecretaSelect") == "null" &&
	    get("pregsecreta").length < 6) {
		errores=true;
		error("campoPreguntaSecreta", "pregsecretaError", "Pregunta secreta demasiado corta<br/>\n");
	}
	
	if (get("respsecreta").length < 6) {
		errores=true;
		error("campoRespuestaSecreta", "respsecretaError", "Respuesta secreta demasiado corta<br/>\n");
	}
	
	var regexp = new RegExp('^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$', 'i');
	if(!regexp.test(get("email"))) {
		errores=true;
		error("campoEmail", "emailError", "Direcci&oacute;n de Correo Electr&oacute;nico inv&aacute;lida<br/>\n");
	}
	
	var regexp = new RegExp('^[A-Z0-9]+$', 'i');
	if(!regexp.test(get("captcha"))) {
		errores = true;
		error("campoCaptcha", "captchaError", "Texto del captcha incorrecto<br/>\n");
	}
	
	if(!document.getElementById("lopd").checked) {
		errores = true;
		error("campoAcepta", "aceptaError", "No has autorizado a PIRATA a guardar tus datos<br/>\n");
	}
	
	if(errores == false) {
		poststr = "nick=" + encodeURI(get("nick")) +
			"&pass=" + encodeURI(get("pass")) +
			"&captcha=" + encodeURI(get("captcha")) +
			"&captchaFuzz=" + encodeURI(captchaFuzz);
		
		ajax("ajax.php?simpatizante=true", poststr);
	}
	
	return false;
}

function get(nombre) {
	return document.getElementById(nombre).value;
}

function set(nombre, valor) {
	document.getElementById(nombre).value = valor;
}

function error(campo, campoError, error) {
	document.getElementById(campo).className = "campo error";
	document.getElementById(campoError).innerHTML += error;
	
	if(err == "") {
		err = document.location = "#" + campo;
	}
}

function reiniciarCampos(campos) {
	for(i=0; i < campos.length; i++) {
		document.getElementById(campos[i]).className = "campo";
	}
}

function limpiarErrores(campos) {
	for(i=0; i < campos.length; i++) {
		document.getElementById(campos[i]).innerHTML = "";
	}
}

function resaltar(campos, clases) {

	for(i=0; i < campos.length; i++) {
		document.getElementById(campos[i]).className = clases;
	}
}

function letraDNI(dni) 
{ 
	cadena="TRWAGMYFPDXBNJZSQVHLCKET";
	posicion = dni % 23;
	return cadena.substring(posicion,posicion+1);
} 


function preguntaSecreta() {
	sel = document.getElementById('pregsecretaSelect');
	if (sel.options[sel.selectedIndex].value == 'null') {
		document.getElementById('pregsecreta').style.display = 'block';
		document.getElementById('pregsecreta').focus();
		document.getElementById('labelForpregsecretaSelect').setAttribute('for', 'pregsecreta');
	} else {
		document.getElementById('pregsecreta').style.display = 'none';
		document.getElementById('labelForpregsecretaSelect').setAttribute('for', 'pregsecretaSelect');
	}
}

function ajax(url, parameters) {
	if (!enProceso && http) {
		http.open("POST", url, true);
		http.onreadystatechange = handleHttpResponse;
		enProceso = true;
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.setRequestHeader("Content-length", parameters.length);
		http.setRequestHeader("Connection", "close");
		http.send(parameters);
		
	}
}

function getHTTPObject() {
	var xmlhttp;
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
		xmlhttp = new XMLHttpRequest();
		} catch (e) { xmlhttp = false; }
	}
	return xmlhttp;
}

function recargaCaptcha() {
// 	alert("function recargaCaptcha()");
	if(captchState == "Loaded") {
		if(captchaImage == 0)
			captchaImage = new Image();
		
		captchaFuzz = Math.random();
		captchState = "Loading";
		document.getElementById('captchaFuzz').value = captchaFuzz;
// 		alert("loading captcha.." + captchState);
		captchaImage.src = 'misc/captcha/button.php?v=' + captchaFuzz;
		captchaImage.onload =  function(){captchaLoaded(captchaImage)};
	} else {
// 		alert("captcha loading already.." + captchState);
	}
}


function captchaLoaded(img) {
// 	alert("function captchaLoaded(img)");
	if(captchState == "Loading")
	{
		document.getElementById('imagenCaptcha').src = captchaImage.src;
// 		alert("Loaded, was " + captchState);
	} else if(img != captchaImage || img.src == "http://none") {
// 		alert("ignoring");
	} else {
// 		alert("Loaded, error. was " + captchState + ", " + img.src);
	}
	captchState = "Loaded";
}

function expiraCaptcha() {
	recargaCaptcha();
	document.getElementById("campoCaptcha").className = "campo error";
	document.getElementById("captchaError").innerHTML = "El captcha ha expirado, escríbalo de nuevo";
}


function handleHttpResponse() {
	/*&& http.responseText.indexOf('invalid') == -1*/
	if (http.readyState == 4 && http.status == 200) {
		// Armamos un array, usando la coma para separar elementos
		if(http.responseText == "todo correcto") {
			document.formulario.submit();
// 			alert("todo correcto, pero estamos de testing");
// 			limpiarErrores(["passError"]);
// 			enProceso=false;
			return;
		}
		
		// Si no está todo correcto, el captcha ha expirado, así que lo
		// cambiamos por otro
		expiraCaptcha();
		
		array = http.responseText.split(";");
		
		i2=-1;
		for(i = 0; i< array.length; i++) {
			results = array[i].split(", ");
			if(i2 == i)
				break;
			i2 = i;
			
			if(results[0] == "nick invalido") {
				limpiarErrores(["nickError"]);
				error("campoNick", "nickError", results[1]);
			} else if(results[0] == "pass invalido") {
				limpiarErrores(["passError"]);
				error("campoPass", "passError", results[1]);
			} else if(results[0] == "nombre invalido") {
				limpiarErrores(["nombreError"]);
				error("campoNombre", "nombreError", results[1]);
				error("campoApellidos", "apellidosError", results[1]);
			} else if(results[0] == "carnet invalido") {
				limpiarErrores(["numeroIdentificacionError"]);
				expiraCaptcha();
				error("campoNumeroIdentificacion", "numeroIdentificacionError", results[1]);
			} else if(results[0] == "captcha invalido") {
				limpiarErrores(["captchaError"]);
				error("campoCaptcha", "captchaError", results[1]);
			} else if(results[0] == "nombre y apellidos existentes") {
				limpiarErrores(["nombreError"]);
				error("campoNombre", "nombreError", results[1]);
			} else if(results[0] == "pass invalido") {
				limpiarErrores(["passError"]);
				error("campoPass", "passError", results[1]);
			}
		}
		enProceso=false;
	}
}

function get2(nombre) {
	return document.getElementsByName(nombre)[0].value;
}


function procesaVoto() {
	num = get("numVotos");
	var votos = new Array();
	var votosSet = new Array();
	var repe = false;
	
	for(i=0; i < num; i++) {
		votos[i] = "<nada>";
		document.getElementById("campoError" + i).innerHTML = "";
	}
	
	var count=0;
	
	for(i=0; i < num; i++) {
		if(votosSet[get2("cand" + i)-1] == true) {
			repe = true;
			error("campo" + i, "campoError" + i, "Opción repetida");
		}
		if(get2("cand" + i) >= 0) {
			votos[get2("cand" + i)-1] = get("hid" + i);
			votosSet[get2("cand" + i)-1] = true;
			count++;
		}
	}
	
	if(repe)
		return false;
	
	var pregunta = "Has elegido:\n";
	
	var comenzado = (count==0) ? true : false;
	var terminado = false;
	var ultima = null;
	for(i=0; i < num; i++) {
		if(!votosSet[i] && !comenzado) {
			alert("Falta por votar la " + (i+1) + "º opción");
			return false;
		} else if (votosSet[i] && terminado) {
			alert("Falta por votar la " + (ultima+1) + "º opción");
			return false;
		}
		
		if(!comenzado && votosSet[i]) {
			comenzado = true;
		} else if(comenzado && !votosSet[i]) {
			terminado = true;
			ultima = i;
		}
		pregunta += "Opción " + (i+1) + ": " + votos[i] + "\n";
	}
	
	
	pregunta += "¿Estás seguro de emitir tu voto?";
	
	return confirm(pregunta);
}
