/**********************************************************************************
****** Funciones JavaScript utilizadas en las páginas de la sección QUIÉN ES QUIÉN
***********************************************************************************/

var objXML = false;
var personId;
var isInProcess = false;
var zIndexCounter = 100;
var DELAY_IN_MILLISECONDS = 600;

var lastPression = 0;
function searching(event)
{
	// 8 = backspace    13 = return
	keynum = (window.event) ? event.keyCode : event.which;

	lastPression = (lastPression == 0) ? (new Date()).getTime() : lastPression;
	timeGap = (new Date()).getTime() - lastPression;

	text = document.forms[0].elements["query"].value;
	query = (keynum == 8) ? trim(text.substring(0,text.length - 1)) : trim(text);
	len = query.length;

	if (len > 2)
	{
		document.getElementById("resultados").style.display = "none";
		document.getElementById("buscando").style.display = getDisplayProperty();
		search(query);
	}
	else if (keynum == 13) // return
	{
		alert("Por favor, escribe al menos tres caracteres.");
	}
}

function search(initial)
{
	if (!isInProcess)
	{
		try
		{
			objXML = new ActiveXObject('Microsoft.XMLHTTP');
		}
		catch (e2)
		{
			objXML = false;
		}

		if (window.XMLHttpRequest)
			objXML = new XMLHttpRequest();

		if (!objXML && typeof XMLHttpRequest != 'undefined')
			objXML = new XMLHttpRequest();

		var URL = "quien/query07.asp?pattern=" + initial;
		if (objXML)
		{
			isInProcess = true;
			objXML.open('GET', URL, true);
			objXML.onreadystatechange = processResults;
			objXML.send(null);
		}
	}
}

function processResults()
{
	isInProcess = false;
	lastPression = 0;
	if (objXML.readyState == 4)
	{
		var rowsJSON = eval("(" + objXML.responseText + ")");
		var numberOfRows = rowsJSON.data.length;

		var theTable = (document.all) ? document.all.socios : document.getElementById("socios");
		var theTableBody = theTable.tBodies[0];
		resetTable(theTableBody);

		var newRow, newCell;
		for (var i = 0; i < numberOfRows; i++)
		{
			newRow = theTableBody.insertRow(i + 1);
			newRow.height = (isInternetExplorer()) ? 20 : "20px";
			newRow.className = (i % 2 == 0) ? "comunes_filaimpar" : "comunes_filapar";
			newCell = newRow.insertCell(0);
			newCell.className = "quien_nombre";
			newCell.innerHTML = "<a href=\"quien/datos_personales07.asp?codigo=" + rowsJSON.data[i].id + "\">" + rowsJSON.data[i].nombre + "&nbsp;" + rowsJSON.data[i].apellidos + "</a>";
		}

		if (numberOfRows == 0)
		{
			newRow = theTableBody.insertRow(1);
			newRow.height = 25;
			newRow.className = "comunes_filapar";
			newCell = newRow.insertCell(0);
			newCell.className = "comunes_formulario_valor";
			newCell.innerHTML = "No se ha encontrado a nadie que coincida con el criterio de b&uacute;squeda";
		}
		document.getElementById("buscando").style.display = "none";
		document.getElementById("resultados").style.display = getDisplayProperty();
		document.forms[0].elements["query"].value = "";
	}
}

function resetTable(table)
{
	var numberOfRows = table.rows.length;
	for (var i = numberOfRows - 1; i > 0; i--)
		table.deleteRow(i);
}

function mainSearch()
{
	var initialPosition = document.forms[0].inicial.selectedIndex;
	var initial = document.forms[0].inicial.options[initialPosition].value;
	document.forms[0].elements["query"].value = "";
	if (initialPosition > 0)
		mainCommonSearch(initial);
}

function mainSearching(event)
{
	// 8 = backspace    13 = return
	keynum = (window.event) ? event.keyCode : event.which;
	if ( (keynum > 0 && keynum < 13) || (keynum > 13 && keynum < 65) || (keynum > 90 && keynum < 97) || (keynum > 122 && keynum < 192))
		return;

	lastPression = (lastPression == 0) ? (new Date()).getTime() : lastPression;
	timeGap = (new Date()).getTime() - lastPression;

	text = document.forms[0].elements["query"].value;
	query = (keynum == 8) ? trim(text.substring(0, text.length - 1)) : trim(text);
	len = query.length;

	if (len > 2)
	{
		setTimeout("searchInProgress('" + query + "','" + keynum + "')", DELAY_IN_MILLISECONDS);
	}
	else if (keynum == 13) // return
	{
		//alert("Por favor, escribe al menos tres caracteres.");
	}
}

function searchInProgress(query, letter)
{
	text = document.forms[0].elements["query"].value;
	currentQuery = trim(text);

	if (currentQuery == query && currentQuery.length == query.length && query.length > 2)
	{
		document.getElementById("paginacion-cell").innerHTML = "&nbsp;";
		resetListTable();
		document.getElementById("buscando").style.display = getDisplayProperty();
		document.forms[0].inicial.selectedIndex = 0;
		mainCommonSearch(query);
	}
}

function resetListTable()
{
	var theTable = (document.all) ? document.all.table_content : document.getElementById("table_content");
	var theTableBody = theTable.tBodies[0];
	resetTable(theTableBody);
}


function mainSubmit()
{
	var text = document.forms[0].elements["query"].value;
	var query = trim(text);

	var initialPosition = document.forms[0].inicial.selectedIndex;
	var initial = document.forms[0].inicial.options[initialPosition].value;

	if (query != '' && query.length > 2)
		mainCommonSearch(query);
	else if (initialPosition > 0)
		mainCommonSearch(initial);
	else
	{
		alert("Por favor, escribe al menos tres caracteres.");
		document.forms[0].elements["query"].focus();
		return false;
	}
}

function mainCommonSearch(pattern)
{
	if (!isInProcess)
	{
		try
		{
			objXML = new ActiveXObject('Microsoft.XMLHTTP');
		}
		catch (e2)
		{
			objXML = false;
		}

		if (window.XMLHttpRequest)
			objXML = new XMLHttpRequest();

		if (!objXML && typeof XMLHttpRequest != 'undefined')
			objXML = new XMLHttpRequest();

		var URL = "quien/query07.asp?pattern=" + pattern + "&all=True";
		if (objXML)
		{
			isInProcess = true;
			objXML.open('GET', URL, true);
			objXML.onreadystatechange = mainProcessResults;
			objXML.send(null);
		}
	}
}

function mainProcessResults()
{
	isInProcess = false;
	lastPression = 0;
	if (objXML.readyState == 4)
	{
		document.getElementById("cabecera0").innerHTML = "&nbsp;&nbsp;NOMBRE&nbsp;";
		document.getElementById("cabecera1").innerHTML = "LOCALIDAD&nbsp;";

		var rowsJSON = eval("(" + objXML.responseText + ")");
		var numberOfRows = rowsJSON.data.length;
		document.getElementById("buscando").style.display = "none";
		var message = (numberOfRows == 1) ? "<b>1</b> coincidencia." : "<b>" + numberOfRows + "</b> coincidencias.";
		document.getElementById("paginacion-cell").innerHTML = "Encontradas " + message;

		document.getElementById("volver-cell").innerHTML = "";
		if (numberOfRows > 0)
		{
			document.getElementById("volver-cell").innerHTML = "";
			document.getElementById("volver-cell").className = "quien_buscador_resultados";
			document.getElementById("volver-cell").innerHTML = "<img src=\"imagenes/transparent.gif\" width=\"270\"  height=\"1\" /><a href=\"quien/lista07.asp\"><img src=\"imagenes/volver07.gif\" border=\"0\" alt=\"Volver a la lista completa\" /></a>";
		}

		var theTable = (document.all) ? document.all.table_content : document.getElementById("table_content");
		var theTableBody = theTable.tBodies[0];
		resetTable(theTableBody);
		var newRow, newCell;
		for (var i = 0; i < numberOfRows; i++)
		{
			newRow = theTableBody.insertRow(i*3 + 1);
			//newRow.className = (i % 2 == 0) ? "comunes_filaimpar" : "comunes_filapar";
			newCell = newRow.insertCell(0);
			newCell.colSpan = 6;
			newCell.innerHTML = "<img src=\"imagenes/transparent.gif\" width=\"1\" height=\"2\" alt=\"\" />";

			newRow = theTableBody.insertRow(i*3 + 2);
			newRow.className = (i % 2 == 0) ? "comunes_filaimpar" : "comunes_filapar";

			newCell = newRow.insertCell(0);
			newCell.innerHTML = "&nbsp;";

			newCell = newRow.insertCell(1);
			newCell.className = "quien_nombre";
			newCell.innerHTML = "<a href=\"quien/datos_personales07.asp?codigo=" + rowsJSON.data[i].id  + "\" title=\"Pulsa para ver la ficha personal\">" + rowsJSON.data[i].nombre + "&nbsp;" + rowsJSON.data[i].apellidos + "</a>";

			newCell = newRow.insertCell(2);
			newCell.innerHTML = "<img src=\"imagenes/transparent.gif\" width=\"20\" alt=\"\" />";

			newCell = newRow.insertCell(3);
			newCell.className = "quien_localidad";
			newCell.innerHTML = rowsJSON.data[i].localidad;

			newCell = newRow.insertCell(4);
			newCell.innerHTML = "<img src=\"imagenes/transparent.gif\" width=\"20\" alt=\"\" />";

			newCell = newRow.insertCell(5);
			newCell.className = "quien_correo";
			newCell.innerHTML = "<a href=\"mailto:" + rowsJSON.data[i].mail + "\" class=\"quien_correo\">" + rowsJSON.data[i].mail + "</a>";

			newRow = theTableBody.insertRow(i*3 + 3);
			//newRow.className = (i % 2 == 0) ? "comunes_filaimpar" : "comunes_filapar";
			newCell = newRow.insertCell(0);
			newCell.colSpan = 6;
			newCell.innerHTML = "<img src=\"imagenes/transparent.gif\" width=\"1\" height=\"2\" alt=\"\" />";
		}

		if (numberOfRows == 0)
		{
			newRow = theTableBody.insertRow(1);
			newRow.height = (isInternetExplorer()) ? 50 : "50px";
			newRow.className = "comunes_filapar";
			newCell = newRow.insertCell(0);
			newCell.colSpan = 6;
			newCell.className = "comunes_formulario_valor";
			newCell.align = "center";
			message = "No se ha encontrado a nadie que coincida con el criterio de b&uacute;squeda<br />";
			message += "<a href=\"quien/lista07.asp\" class=\"comunes_enlaces\">Volver a la lista completa</a>."
			newCell.innerHTML = message;
		}
		//document.forms[0].elements["query"].value = "";
	}
}

function sendDNI(mailAdmin)
{
	var nombre = '<%= nombrecompleto %>';
	if (confirm("El Administrador va a enviarte tu contraseña a la dirección de correo que figura\nen tus datos personales. Comprueba antes que es correcta. Si no es correcta\n o tienes algún problema, pulsa Cancelar y manda un e-mail al Administrador\n(" + mailAdmin +"). ¿Estás seguro de que deseas continuar?"))
	{
		var identificador = document.forms[0].elements["codigo"].value;
		var parametros = "scrollbars=no,status=no,width=300,height=240";
		var posH = (screen.width-300)/2;
		var posV = (screen.height-240-100)/2;
		if (posH < 0) posH = 0;
			if (posV <0 ) posV = 0;
		parametros += ",left=" + posH;
		parametros += ",top=" + posV;
		var ventana = window.open('../envioEmail.asp?id=' + identificador + '&listaSocios=false','envioEmail',parametros);
	}
}

function deleteUser(userId)
{
	if (confirm("¿Realmente quieres darte de baja?"))
	{
		document.location.href = "quien/deleteUser.asp?id=" + userId;
	}
}

/*
	Funciones que se utilizan en los formularios de Quién es Quién
*/
function validaDNI()
{
	dni = document.forms[0].elements["dni"].value;
	tienePunto = (dni.indexOf(".") != -1) ? true : false ;
	tieneBlancos = (dni.indexOf(" ") != -1) ? true : false ;
	if (	(dni=="")  || tienePunto || tieneBlancos || isNaN(dni) )
	{
		alert("Por favor, escribe tu D.N.I. o contraseña sin letra");
		document.forms[0].elements["dni"].select();
		document.forms[0].elements["dni"].focus();
		return false;
	}
	return true;
}


function valida()
{
	//updateRTE('rte');
	//document.forms[0].elements["texto"].value = document.forms[0].elements["rte"].value;

	dia  = document.forms[0].elements["dia"].value;
	mes  = document.forms[0].elements["mes"].value;
	anio = document.forms[0].elements["anio"].value;

	document.forms[0].elements["nombre"].value    = LTrim(document.forms[0].elements["nombre"].value);
	document.forms[0].elements["apellidos"].value = LTrim(document.forms[0].elements["apellidos"].value);

	if (document.forms[0].elements["nombre"].value == "")
	{
		alert("El nombre y los apellidos son obligatorios");
		document.forms[0].elements["nombre"].focus();
		return false;
	}

	if (document.forms[0].elements["apellidos"].value == "")
	{
		alert("El nombre y los apellidos son obligatorios");
		document.forms[0].elements["apellidos"].focus();
		return false;
	}
	if (document.forms[0].elements["lugar"].value == "")
	{
		alert("El Lugar de residencia es obligatorio");
		document.forms[0].elements["lugar"].focus();
		return false;
	}

	if (document.forms[0].elements["mail"].value == "")
	{
		alert("El E-mail es obligatorio");
		document.forms[0].elements["mail"].focus();
		return false;
	}
	else
	{
		primero = document.forms[0].elements["mail"].value.indexOf("@");
		ultimo  = document.forms[0].elements["mail"].value.lastIndexOf("@");
		var dominio = document.forms[0].elements["mail"].value.substr(ultimo+1,document.forms[0].elements["mail"].value.length);
		if (dominio.indexOf(".")<0)
		{
			alert("Has introducido una dirección de correo inválida.");
			document.forms[0].elements["mail"].select();
			document.forms[0].elements["mail"].focus();
			return false;
		}
	}

	if ((dia != "") || (mes != "") || (anio != ""))
	{
		if (!ValidaFecha(dia,mes,anio))
		{
			alert("La fecha no es correcta");
			document.forms[0].elements["dia"].focus();
			return false;
		}
	}

	archivo = document.forms[0].elements["foto"].value.toUpperCase();
	posicion = archivo.lastIndexOf(".JPG");
	if ((archivo!="") && (posicion==-1))
	{
		alert("La foto debe tener extensión .jpg");
		return false;
	}

	dni = document.forms[0].elements["dni"].value;
	tienePunto = (dni.indexOf(".") != -1) ? true : false ;
	tieneBlancos = (dni.indexOf(" ") != -1) ? true : false ;
	if ((dni=="")  || tienePunto || tieneBlancos || isNaN(dni))
	{
		alert("Por favor, escribe tu D.N.I. sin letra");
		document.forms[0].elements["dni"].select();
		document.forms[0].elements["dni"].focus();
		return false;
	}

	return true;
}