// JavaScript Document

// expandir/contraer capas
function expandir(valor) {
	elemento = document.getElementById('exp_'+valor);
	estado = elemento.style.display;
	if(estado != 'none') {
		elemento.style.display = 'none';
	} else {
		elemento.style.display = 'block';	
	}
}

// Popup window code
function newWindow(url, alto, ancho, left, top) {
	popupWindow = window.open(url,'','height='+alto+',width='+ancho+',left='+left+',top='+top+',resizable=0,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=yes');
}

function mailAbogado(idAbogado){

	newWindow('/paginas/ab_mail.php?id='+idAbogado,690,655,100,50);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// FUNCION QUE VALIDA

function validar(campo,expresion,titulo,maximo,obligatorio) {
	// variables principales
	var entrada = document.getElementById(campo);
	
	// variables de validación
	var patron;
	var patron_obligatorio = /\w/;

	// variables de mensaje
	var tit_msj;
	var texto;
	var ver;
	entrada.onblur = function() {
		if(campo == "nombre") {
			obligatorio = validar_abogado();
		}
		if(campo == "bufete") {
			obligatorio = validar_bufete();
		}
		if(obligatorio && entrada.value == "") {
			tit_msj = titulo;
			texto = "El campo no puede ser vacío";
			ver = true;
		} else {
			if(entrada.value != "") {
				switch (expresion) {
					case "num":
						patron = /^[0-9 ]*$/;
						texto = "No pueden contener ningún caracter distinto de números";
					break;
					case "x_num":
						patron = /^[0-9 \.\_\-\"\'\´\`\¨\&\/\\\(\)\+\*\?\¿\!\¡]*$/;
						texto = "Sólo pueden contener números y algunos caracteres especiales: (.-_/\\\"\'`´*+/!¡?¿).";
					break;
					case "alfa":
						patron = /^[A-Za-z0-9ñÑzáéíóúàèìòùäëïöüâêîôûçÇ \"\'\´\`\¨]*$/;
						texto = "Sólo pueden contener letras, tilde, números y comillas.";
					break;
					case "x_alfa":
						patron = /^[A-Za-z0-9ñÑzáéíóúàèìòùäëïöüâêîôûçÇ \.\_\-\"\'\´\`\¨\&\/\\\(\)\+\*\?\¿\!\¡]*$/;
						texto = "Sólo puede contener letras, tilde, números, comillas y algunos caracteres especiales: (.-_/\\\"\'`´*+/!¡?¿).";
					break;
					case "abc":
						patron = /^[A-Za-zñÑzáéíóúàèìòùäëïöüâêîôûçÇ \'\"\`\´]*$/;
						texto = "Sólo puede contener caracteres alfabéticos, tildes y comillas.";
					break;
					case "x_abc":
						patron = /^[A-Za-zñÑáéíóúàèìòùäëïöüâêîôûçÇ \.\_\-\"\'\´\`\¨\&\/\\\(\)\+\*\?\¿\!\¡]*$/;
						texto = "Sólo puede contener caracteres alfabéticos, tildes, comillas y algunos caracteres especiales: (.-_/\\\"\'`´*+/!¡?¿).";
					break;
					case "mail":
						patron = /^[A-Za-z0-9._-]+@(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,4}$/;
						texto = "El e-mail debe tener el formato correcto, no puede contener caracteres especiales ni ñ.";
					break;
					case "web":
						patron = /^(www.)?(\w|-)+(\.(\w|-)+)*((\.[a-zA-Z]{2,3})|\.(aero|coop|info|museum|name))+(\/)?$/;
						texto = "La dirección web debe tener el formato correcto, no puede contener caracteres especiales, ñ ni espacios.";
					break;
					case "nifcif":
						patron = /^([a-zA-Z]{1}-[0-9]{9}|[0-9]{8}-[a-zA-Z]{1})$/;
						texto = "El Nif/Cif debe tener el formato correcto.";
					break;
					default:
						patron = /\w/;
						texto = "El campo no puede ser vacío";
					break;
				}
				if(!patron.test(entrada.value)) {
					tit_msj = titulo;
					//texto;
					ver = true;
				} else {
					if(entrada.value.length > maximo) {
						tit_msj = titulo
						texto = "No puede superar los "+maximo+" caracteres en el campo. Hay "+(entrada.value.length - maximo)+" caracteres de más.";
						ver = true;
					} else {	
						tit_msj = "";
						texto = "";
						ver = false;
						entrada.style.border = "1px solid #7F9DB7";
					}
				}
			}
		}
		crearMensaje(campo,tit_msj,texto,ver,"mal",true);
	}
}

function crearMensaje(campo,titulo,texto,ver,img,mostrar_mensaje) {
	var entrada = document.getElementById(campo);
	// obtengo el elemento padre y el elemento siguiente al campo
	var padre = entrada.parentNode;
	var siguiente = entrada.nextSibling.nextSibling;
	// creo la capa que contendrá a la imagen y al mensaje
	var marca = document.createElement("div");
		marca.setAttribute("class","marca");
		marca.setAttribute("className","marca");
	if(ver) {
		// creo la imagen	
		var imagen = document.createElement("img");
			imagen.setAttribute("src","./img/iconos/"+img+".png");
			imagen.setAttribute("alt","Datos Incorrectos");
			imagen.setAttribute("title","Datos Incorrectos");
			imagen.setAttribute("class","icono");
			imagen.setAttribute("className","icono");
		// introduzco la imagen en la capa
		marca.appendChild(imagen);
		if(img != "mal") {
			entrada.style.border = "1px solid #7F9DB7";
		} else {
			entrada.style.border = "1px solid #990000";	
		}
		if(mostrar_mensaje) {
			marca.onmouseover = function() { mostrar(campo,1); }
			marca.onmouseout = function() { mostrar(campo,0); }
		}
	}
	// creo el mensaje;
	var mensaje = document.createElement("div");
		mensaje.setAttribute("class","mensaje");
		mensaje.setAttribute("className","mensaje");
		mensaje.setAttribute("id",campo+"_b");
		
	var encabezado = document.createElement("h3");
	var titulo = document.createTextNode(titulo);
		encabezado.appendChild(titulo);
	var datos = document.createElement("p");
	var info = document.createTextNode(texto);
		datos.appendChild(info);
	var boton = document.createElement("input");
		boton.setAttribute("type","button");
		boton.setAttribute("class","cerrar");
		boton.setAttribute("className","cerrar");
		boton.onclick = function() { mostrar(campo,0); }
	var boton2 = document.createElement("input");
		boton2.setAttribute("type","button");
		boton2.setAttribute("class","x");
		boton2.setAttribute("className","x");
		boton2.onclick = function() { mostrar(campo,0); }

		mensaje.appendChild(encabezado);
		mensaje.appendChild(datos);
		mensaje.appendChild(boton);
		mensaje.appendChild(boton2);
	// introduzco el mensaje en la capa
	marca.appendChild(mensaje);
	//padre.replaceChild(marca,siguiente.previousSibling)
}

function mostrar(nombre,ver) {
	var objeto = document.getElementById(nombre+"_b");
	if(ver == 1) objeto.style.display = "block";
	if(ver == 0) objeto.style.display = "none";
}

function validar_abogado() {
	if(document.getElementById('radio_abogado').checked) return true;
	else return false;
}

function validar_bufete() {
	if(document.getElementById('radio_bufete').checked) return true;
	else return false;
}

function tabular(formulario,campo) {
	elementos_form = eval('document.'+formulario+'.elements');
	objeto = document.getElementById(campo);
	objeto.onkeypress = function(elEvento) {
		var evento = window.event || elEvento;
		if(evento.keyCode == 13) {
			// recorro los elelentos del formulario...
			for(i=0; i<elementos_form.length; i++) {
				// ...y si es el que estoy parado
				if(campo == elementos_form[i].id) {
					if(elementos_form[i+1].disabled || elementos_form[i+1].style.display == "none" || elementos_form[i+1].style.visibility == "hidden") {
						if(!elementos_form[i+2].disabled || elementos_form[i+2].style.display == "none" || elementos_form[i+2].style.visibility == "hidden") {
							elementos_form[i+2].focus();
						}
					} else {
						elementos_form[i+1].focus();
					}
				}
			}
			return false;
		}
	}
}

function inicializarTabular() {
	tabular('frm_alta','nombre');
	tabular('frm_alta','bufete');
	tabular('frm_alta','radio_abogado');
	tabular('frm_alta','radio_bufete');
	tabular('frm_alta','selProvincia');
	tabular('frm_alta','mail');
	tabular('frm_alta','nifcif');
	tabular('frm_alta','descripcion_breve');
	tabular('frm_alta','web');
	tabular('frm_alta','telefono1');
	tabular('frm_alta','telefono2');
	tabular('frm_alta','telefono3');
	tabular('frm_alta','fax');
	tabular('frm_alta','direccion');
	tabular('frm_alta','ambito');
	tabular('frm_alta','informacion');
	tabular('frm_alta','informacion___Config');
	tabular('frm_alta','lista');
	tabular('frm_alta','selected');
	tabular('frm_alta','aceptar_terminos');
	tabular('frm_alta','codigo');
	tabular('frm_alta','fderecha');
	tabular('frm_alta','fizquierda');
	tabular('frm_alta','buscaPoblacion');
	tabular('frm_alta','btnBuscarPoblacion');
	tabular('frm_alta','id_poblaciones');
}

function inicializarCheck() {
	// OBLIGATORIOS
	validar("nombre","abc","Nombre",80);
	validar("bufete","x_alfa","Bufete",80);
	validar("mail","mail","e-Mail",80,true);
	validar("nifcif","nifcif","Nif-Cif",12,true);
	validar("descripcion_breve","","Descripción",255,true);
	// OPCIONALES
	validar("web","web","Sitio Web",100);
	validar("telefono1","num","Teléfono",17);
	validar("telefono2","num","Teléfono",17);
	validar("telefono3","num","Teléfono",17);
	validar("fax","num","Fax",20);
	validar("direccion","x_alfa","Dirección",100);
	validar("ambito","alfa","Ámbito",100);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

arregloEspecialidades = new Array();
empezar = 1;


function createElementWithName(tipo, nombre) {
	var elemento;
	// First try the IE way; if this fails then use the standard way
	if (document.all) {
		elemento = document.createElement('<'+tipo+' name="'+nombre+'" />');
	} else {
		elemento = document.createElement(tipo);
		elemento.setAttribute('name', nombre);
	}
	return elemento;
}

function nuevas_especialidades(elObjeto) {
	viejasEspecialidades = new Array();
	objeto = document.getElementById(elObjeto);
	campo = objeto.previousSibling.previousSibling;
	// si el campo es vacío no inserto nada
	if(campo.value == "") alert('El campo está vacío');
	else {
		existe_enCaja = indice(arregloEspecialidades,campo.value);
		opciones = document.getElementById('lista').options;
		for(e=0; e<opciones.length; e++) {
			viejasEspecialidades[e] = opciones[e].text;
		}
		existe_enSelect = indice(viejasEspecialidades,campo.value);
		if(!isNaN(existe_enCaja)) {
			alert('La especialiad ya está en la caja, entre una nueva');
		}
		else {// si empezar es 1 debo crear la tabla, de lo contrario significa que la tabla ya está creada

			if(!isNaN(existe_enSelect)) {
				alert('La especialidad ya existe en la base de datos, verifique en la lista superior!');
			}
			else {
				if(empezar == 1) {
					// creo la tabla
					var tabla = document.createElement("table");
						tabla.setAttribute("class","tabEspecialidades");
						tabla.setAttribute("className","tabEspecialidades");
						tabla.setAttribute("align","center");
					
					// creo la cabecera de la tabla con su titulo
					var tablaHead = document.createElement("thead");
					var filaTitulo = document.createElement("tr");
					var titulo = document.createElement("td");
					var textoTitulo = document.createTextNode("Nuevas Especialidades");
						titulo.appendChild(textoTitulo);
						titulo.setAttribute("colSpan","2");
						filaTitulo.appendChild(titulo);
						tablaHead.appendChild(filaTitulo);
						tabla.appendChild(tablaHead);
					
					// creo el cuerpo de la tabla vacio
					var tablaBody = document.createElement("tbody");
						tabla.appendChild(tablaBody);
					
					// obtengo el lugar donde quiero incertar la tabla
					siguiente = objeto.nextSibling;
					contenedor = objeto.parentNode;
					contenedor.insertBefore(tabla,siguiente);
					empezar = 0;
				}
				else {
					// si la tabla ya esta creada obtengo el cuerpo
					tablaBody = objeto.nextSibling.firstChild.nextSibling;
				}
				// creo la fila con la celda que contendrá la especialidad y la que contendrá las acciones
				var fila = document.createElement("tr");
				var celda = document.createElement("td");
				var celda2 = document.createElement("td");
					fila.appendChild(celda);
					fila.appendChild(celda2);
				
				// creo el parrafo para la especialidad
				var parrafoEspecialidad = document.createElement("p");
				var especialidad = document.createTextNode(campo.value);
					// pongo el nuevo valor de especialidad en el array contenedor
					arregloEspecialidades.push(campo.value);
		
					parrafoEspecialidad.appendChild(especialidad);
				
				// creo el campo de edición de la especiliadad
				var inputEspecialidad = document.createElement("input");
					inputEspecialidad.setAttribute("value",parrafoEspecialidad.innerHTML);
					inputEspecialidad.setAttribute("type","text");
					inputEspecialidad.setAttribute("name","espNuevas['"+parrafoEspecialidad.innerHTML+"']");
					inputEspecialidad.style.display = "none";
					//inputEspecialidad.onblur = terminarModificarEspecialidad;
				
				// creo las acciones quitar y modificar
				var quitar = createElementWithName("a","quitar");
					quitar.setAttribute("href","javascript:void(0)");
					
				var modificar = createElementWithName("a","modificar");
					modificar.setAttribute("href","javascript:void(0)");
					
				var vinculoQuitar = document.createTextNode("Quitar");
				var separador = document.createTextNode(" | ");
				var vinculoModificar = document.createTextNode("Modificar");
					quitar.appendChild(vinculoQuitar);
					modificar.appendChild(vinculoModificar);
					
					fila.lastChild.appendChild(quitar);
					fila.lastChild.appendChild(separador);
					fila.lastChild.appendChild(modificar);
						fila.lastChild.style.width = "40%";
						fila.lastChild.style.textAlign = "right";
					fila.firstChild.appendChild(parrafoEspecialidad);
					fila.firstChild.appendChild(inputEspecialidad);
				tablaBody.insertBefore(fila,tablaBody.firstChild);
				objeto.previousSibling.previousSibling.value = "";
				objeto.previousSibling.previousSibling.focus();
			}
		}
	}
	manejarTabla();
}

function indice(array,valor) {
	// debe recorrer el array comparando todos sus elementos con valor, cuando encuentra coincidencia devuelve el indice
	elementos = array.length;
	//alert(elementos);
	for(i=0; i<elementos; i++) {
		if(array[i].toLowerCase() == valor.toLowerCase()) {
			//alert('El indice del valor '+array[i]+' es '+i);
			return i;
		}
	}
}

function borrarEspecialidad(objeto) {
	cantidadElementos = arregloEspecialidades.length;

	// obtengo el elemento a eliminar que es toda la fila
	if(cantidadElementos == 1) {
		eliminar = this.parentNode.parentNode.parentNode.parentNode;
		this.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(eliminar);
		empezar = 1;
	}
	else {
		eliminar = this.parentNode.parentNode;		
		this.parentNode.parentNode.parentNode.removeChild(eliminar);
	}
	parrafo = eliminar.firstChild.firstChild.innerHTML;

	elIndice = indice("arregloEspecialidades",parrafo)

	arregloEspecialidades.splice(elIndice,1);

}

function modificarEspecialidad() {
	elTexto = this.parentNode.parentNode.firstChild.firstChild;
	elCampo = this.parentNode.parentNode.firstChild.lastChild;
	elTexto.style.display = "none";
	elCampo.style.display = "block";
	elCampo.focus();
}

function terminarModificarEspecialidad() {
	elTexto = this.previousSibling;
	elCampo = this;
	elTexto.innerHTML = elCampo.value;
	this.name = "espNuevas['"+elCampo.value+"']";
	elTexto.style.display = "block";
	elCampo.style.display = "none";
}

function inicializar_ingreso() {
	// boton "Agregar Especialidad"
	var agregar = document.getElementById('agregar');
	// campo "Nueva Especialidad"
	var campoAgregar = document.getElementById('campo_agregar');
	// formulario en si
	var formulario = document.getElementById('frm_alta');
	// boton submit del formulario
	var boton_submit = document.getElementById('btn_submit');
	
	// si hago click en el boton "Agregar Especialidad" Agrega la especialidad a la tabla
	agregar.onclick = function() { nuevas_especialidades("agregar"); }

	campoAgregar.onkeypress = function(elEvento) {
		var evento = window.event || elEvento;
		if(evento.keyCode == 13) {
			nuevas_especialidades("agregar");
			return false;
		}
	}
}

function manejarTabla() {
	vinculos = document.getElementsByTagName('a');
	nomQuitar = "quitar";
	nomModificar = "modificar";
	
	for(k=0; k<vinculos.length; k++) {
		if(vinculos[k].name == nomQuitar) {
			vinculos[k].onclick = borrarEspecialidad;
		}
		else {
			if(vinculos[k].name == nomModificar) {
				vinculos[k].onclick = modificarEspecialidad;
			}
		}
	}

	campos = document.getElementsByTagName('input');
	nombre = new RegExp("^espNuevas","i");
	//alert(campos.length);
	for(j=0; j<campos.length; j++) {
		if(nombre.test(campos[j].name)) {
			campos[j].onblur = terminarModificarEspecialidad;
		}
	}
}

window.onload = function() {
	try {
		inicializar_ingreso();
		inicializarCheck();
		inicializarTabular();
		enviar_form = document.getElementById('btn_submit');
		//alert(enviar_form);
	}
	catch(e) {}
}

function mailbustbot(nm,dm){
	var mailurl = "mailto:" + nm + "@" + dm;window.location = mailurl;
}
