// ********************* Funciones Para los menus que siempre te salgan en pantalla con el nombre tabla_desplazar

	function hide() {
	}

	var nombreCookieSelected = "lista_indice_sel";
	var nombreCookieDeselected = "lista_indice_des";

	function toggleNodo(item){
		if (item.checked)
			addNodo(item.name);
		else delNodo(item.name);
		var nodo = getElement("seleccion_cuenta_registros");
		if (nodo!=null) nodo.innerHTML=""+getCuentaSeleccionados();
	}

	function eliminaDelimitadores(valor) {
		while (valor.length>0 && valor.substring(0,1)==",") {
			valor = valor.substring(1);
		}
		while (valor.length>0 && valor.substring(valor.length-1)==",") {
			valor = valor.substring(0,valor.length-1);
		}		
		return valor;
	}

function getString(valor) {
	if (valor==null) res="";
	else res=valor;
	return res;
}
	function addNodo(strId) {
		var listaSel = ","+getString(getCookie(nombreCookieSelected))+",";
		var listaDes = ","+getString(getCookie(nombreCookieDeselected))+",";

		var posSel;
		posSel =listaSel.indexOf(","+strId+",");
		if (posSel!=-1) {

		} else {
			listaSel = strId+listaSel;
			listaSel = eliminaDelimitadores(listaSel);			
			SetCookie( nombreCookieSelected, listaSel);
		}
		var posDes;
		posDes =listaDes.indexOf(","+strId+",");
		if (posDes!=-1) {
			listaDes = replaceSubstring( listaDes, ","+strId+",", "," );
			listaDes = eliminaDelimitadores(listaDes);
			SetCookie( nombreCookieDeselected, listaDes);
		} else {
		}
	}

	function delNodo(strId) {
		var listaSel = ","+getString(getCookie(nombreCookieSelected))+",";
		var listaDes = ","+getString(getCookie(nombreCookieDeselected))+",";
		var posDes;
		posDes =listaDes.indexOf(","+strId+",");
		if (posDes!=-1) {

		} else {
			listaDes = strId+listaDes;
			listaDes = eliminaDelimitadores(listaDes);
			SetCookie( nombreCookieDeselected, listaDes);
		}
		var posSel;
		
		posSel =listaSel.indexOf(","+strId+",");
		if (posSel!=-1) {
			listaSel = replaceSubstring( listaSel, ","+strId+",", "," );
			listaSel = eliminaDelimitadores(listaSel);
			SetCookie( nombreCookieSelected, listaSel);
		} else {
		}
		/*if (pos!=-1) {
			lista = replaceSubstring( lista, ","+strId+",", "," );
			SetCookie( nombreCookieDeselected, lista);
		}*/
	}

function indiceLoad() {
	var i;
	var listaSeleccionados = getString(getCookie(nombreCookieSelected));
	var listaDeseleccionados = getString(getCookie(nombreCookieDeselected));

	var vSel = listaSeleccionados.split(",");
	var vDes = listaDeseleccionados.split(",");
	//alert(listaSeleccionados);
	//alert(listaDeseleccionados);
	for (i=0;i<vSel.length;i++) {
		if (vSel[i]!="") {
			if (document.SeleccionForm[vSel[i]]!=null) document.SeleccionForm[vSel[i]].checked=true;
		}
	}
	for (j=0;j<vDes.length;j++) {
		if (vDes[j]!="") {
			if (document.SeleccionForm[vDes[j]]!=null) document.SeleccionForm[vDes[j]].checked=false;
		}
	}
	var nodo = getElement("seleccion_cuenta_registros");
	cuenta = vSel.length;
	if (listaSeleccionados=="") cuenta=0;
	if (nodo!=null) nodo.innerHTML=cuenta;
}

function getCuentaSeleccionados() {
	var listaSeleccionados = getString(getCookie(nombreCookieSelected));
	var vSel = listaSeleccionados.split(",");
	cuenta = vSel.length;
	if (listaSeleccionados=="") cuenta=0;
	return cuenta;
}


function cambiaDatoAutor(nodo) {
	var f = document.formulario;
	var res=true;
	indice = getIdentificadorPadreIndice(nodo);

	nodoAnonimo = f["campocontributor_"+indice+"_contributoranonimo"];
	nodoYotros = f["campocontributor_"+indice+"_contributoryotros"];
	nodoVariosautores = f["campocontributor_"+indice+"_contributorvariosautores"];
	nodoNombre = f["campocontributor_"+indice+"_personnameinvertednombre"];
	nodoApellidos = f["campocontributor_"+indice+"_personnameinvertedapellidos"];
	nodoWebsite = f["campocontributor_"+indice+"_websitelink"];
	nodoDesconocido = f["campocontributor_"+indice+"_contributordesconocido"];

	if (nodoNombre.value=="" && nodoApellidos.value=="" && nodoWebsite.value=="") {
		nodoAnonimo.disabled=false;
		nodoYotros.disabled=false;	
		nodoVariosautores.disabled=false;	
		nodoDesconocido.disabled=false;
	} else {
		nodoAnonimo.checked=false;
		nodoAnonimo.disabled=true;
		nodoYotros.checked=false;
		nodoYotros.disabled=true;	
		nodoVariosautores.checked=false;
		nodoVariosautores.disabled=true;	
		nodoDesconocido.checked=false;
		nodoDesconocido.disabled=true;
		res=false;
	}
	if (nodo.checked) {
		if (nodo==nodoYotros) {
			nodoAnonimo.checked=false;
			nodoVariosautores.checked=false;
			nodoDesconocido.checked=false;
		}
		if (nodo==nodoAnonimo) {
			nodoYotros.checked=false;
			nodoVariosautores.checked=false;
			nodoDesconocido.checked=false;
		}
		if (nodo==nodoVariosautores) {
			nodoYotros.checked=false;
			nodoAnonimo.checked=false;
			nodoDesconocido.checked=false;
		}
		if (nodo==nodoDesconocido) {
			nodoYotros.checked=false;
			nodoAnonimo.checked=false;
			nodoVariosautores.checked=false;
		}
	}
	if (nodoAnonimo.checked || nodoYotros.checked || nodoVariosautores.checked || nodoDesconocido.checked) {
		nodoNombre.disabled=true;
		nodoApellidos.disabled=true;
		nodoWebsite.disabled=true;
		nodoNombre.value="";
		nodoApellidos.value="";
		nodoWebsite.value="";
	} else {
		nodoNombre.disabled=false;
		nodoApellidos.disabled=false;		
		nodoWebsite.disabled=false;		
	}
	return res;
}

function cambiaDatoLibroTexto(nodo) {
	var b;
	var	f = document.formulario;

	b = true;
	f.nivel_educativo.disabled=b;
	f.comunidad_autonoma.disabled=b;		
	f.asignatura.disabled=b;		

	f.material.disabled=false;

	if (getValor(f.material)=="") {
		//Deshabilito el resto
	} else {
		b=false;
		if (nodo==null) {
			/*str = "" + f.codigo_ncc.value + f.asignatura.value;
			if (str=="") {
				setValor(f.EsLibroTexto, "NO");
			} else {
				setValor(f.EsLibroTexto, "SI");
			}*/
		} else {
			if (nodo.name=="material") {
				if (getValor(f.material)=="") {
					f.nivel_educativo.value="";
					f.comunidad_autonoma.value="";		
					f.asignatura.value="";		
					f.codigo_ncc.value="";
				}
			}
		}

		if (getValor(f.material)=="") {
		} else {		
			f.nivel_educativo.disabled=b;
			f.comunidad_autonoma.disabled=b;		
			f.asignatura.disabled=b;		
		}
	}
}

function nuevoRol(nombreCampo, nvalor) {
	var valor = nvalor;
	//alert(nombreCampo);
	//alert(getElement(nombreCampo));
	indice = getIdentificadorPadreIndice(getElement(nombreCampo));
	nombreNodo = "campocontributor_"+indice+"_contributorrole";
	var nodo = document.formulario[nombreNodo+"_0"];
	//alert(nombreNodo+"_0");
	//alert(nodo);

	var subindice = idCampos++; 
	var nombre="campocontributor_"+ indice +"_contributorrolediv";
	var nododiv = getElement(nombre);
	res = nodo.outerHTML;

	re = new RegExp('<([^>]*='+nombreNodo+'_)([0-9]*)','g'); 
	res = res.replace(re, '<$1'+subindice);
	re = new RegExp('<([^>]*="'+nombreNodo+'_)([0-9]*)','g'); 
	res = res.replace(re, '<$1'+subindice);
	//alert(5);

	nododiv.innerHTML=nododiv.innerHTML+"<div id='"+nombreNodo+"_"+subindice+"'>"+res+"<span class='accion'>[ <A HREF='#' class='botonaccion' onclick='eliminarAutorRol(getIdentificadorPadre(this));return false;'>Borrar</A> ]</span>";
	//alert(nododiv.innerHTML);
	//alert(6);
	if (valor==null) valor="A01";
	if (valor!=null) {
		nuevoNodo = nombreNodo + "_" + subindice;
		//alert(nuevoNodo);
		document.formulario[nuevoNodo].value=valor;
		//alert(8);
	}
}

function changeValoresPrecio(item) {
	var f = document.formulario;
	var iva;
	var precio_siniva = f["precio_siniva"].value;
	var pvp_final=f["pvp_final"].value;

	nameItem="";
	if (item!=null) {
		nameItem = item.name;
	}

	if (nameItem=="pvp_final") {
		if (!esVacio(pvp_final)) {
			pvp_final = parseFloat( str2double(pvp_final) );

			iva = f["iva"].value;
			if (iva=="") {
				f["iva"].value="4";
				iva="4";
			}
			if (!esVacio(iva)) {
				iva = parseFloat( str2double(iva) );
				precio_siniva = pvp_final/((100+iva)/100);
				
				f.precio_siniva.value = FormatNumber(precio_siniva,4,true,false,false) ;				
			}
		} else {
			f.precio_siniva.value = "";
		}
	} else {
		if (!esVacio(precio_siniva)) {
			precio_siniva = parseFloat( str2double(precio_siniva) );

			iva = f["iva"].value;
			if (iva=="") {
				f["iva"].value="4";
				iva="4";
			}
			if (!esVacio(iva)) {
				iva = parseFloat( str2double(iva) );
				total = precio_siniva*(100+iva)/100;
				
				f.pvp_final.value = FormatNumber(total,2,true,false,false) ;				
			}
		} else {
			f.pvp_final.value = "";
		}
	}

	var base = f["base"].value;
	var pvp_final_canarias = f["pvp_final_canarias"].value;	
	if (nameItem=="pvp_final_canarias") {
		if (!esVacio(pvp_final_canarias)) {
			pvp_final_canarias = parseFloat( str2double(pvp_final_canarias) );

			igic = f["igic"].value;
			if (igic=="") {
				f["igic"].value="0";
				igic="0";
			}
			if (!esVacio(igic)) {
				igic = parseFloat( str2double(igic) );
				aiem = f["aiem"].value;
				if (aiem=="") {
					f["aiem"].value="4"; 
					aiem="4";
				}
				if (!esVacio(aiem)) {
					aiem = parseFloat( str2double(aiem) );
					base = pvp_final_canarias / ((100+igic+aiem) /100);
					f.base.value = FormatNumber(base,4,true,false,false) ;
				}
			}
		} else {
			f.base.value = "";
		}
	} else {
		if (!esVacio(base)) {
			base = parseFloat( str2double(base) );

			igic = f["igic"].value;
			if (igic=="") {
				f["igic"].value="0";
				igic="0";
			}
			if (!esVacio(igic)) {
				igic = parseFloat( str2double(igic) );
				aiem = f["aiem"].value;
				if (aiem=="") {
					f["aiem"].value="4";
					aiem="4";
				}
				if (!esVacio(aiem)) {
					aiem = parseFloat( str2double(aiem) );
					total = base* (100+igic+aiem) /100;
					f.pvp_final_canarias.value = FormatNumber(total,2,true,false,false) ;
				}
			}
		} else {
			f.pvp_final_canarias.value = "";
		}
	}

}

function findScrollTop() {
	if (window.pageYOffset != null)
		return window.pageYOffset;
	if (document.body.scrollWidth != null)
		return document.body.scrollTop;
	return null;
}
var offsetTablaInicial = null;

function miOnScroll() {
	var top;
	//alert("scroll");
	if ( offsetTablaInicial==null) {
		offsetTablaInicial = document.all["tabla_desplazar"].offsetTop;
	} else {
		top = findScrollTop();
		if (top!=null) {
			if (top>offsetTablaInicial) {
				document.all["tabla_desplazar"].style.top = top;				
			} else {
				document.all["tabla_desplazar"].style.top = offsetTablaInicial;
			}
		}				
	}
}

function getValor(item) {
	var res=null;
	if (item!=null) {
		if (item.value==null) {
			for (i=0;i<item.length;i++) {
				if (item[i].checked==true) {
					res=item[i].value;
				}
			}
		} else {
			res = item.value;
		}
	}
	return res;
}

function setValor(item, valor) {
	var res="";
	if (item.value==null) {
		for (i=0;i<item.length;i++) {
			if (item[i].value==valor) {
				item[i].checked=true;
			} else {
				item[i].checked=false;
			}
		}
	} else {
		item.value = valor;
	}
	return;
}

function getRadioValue( radio ) {
	var i, res;
	res="";
	for (i=0;i<radio.length;i++) {
		if (radio[i].checked) res=radio[i].value;
	}
	return res;
}

function eliminarEntradaAsiento(numero) {
	if (confirm("¿Seguro que desea borrar esta linea?")) {
		eval("document.formulario.importe_"+numero+".value='';");
		eval("document.formulario.cuenta_"+numero+".value='';");
	}
	return;
}

function changeDisplay(id) {
	//Permite ocultar o ver un elemento:
	var nodo=document.all[id];
	if (nodo.style.display=="none") {
		nodo.style.display="block";
	} else {
		nodo.style.display="none";
	}
}

function openWindow(url, ancho, alto) {
	strancho=ancho;
	stralto=alto;
	if (ancho==null) strancho = 600;
	if (alto==null) stralto = 360;
	window.open(url,"","resizable=yes,status=1,scrollbars=1,width="+strancho+",height="+stralto,false);
}

function openWindowPos(url, ancho, alto, top, left) {
	strancho=ancho;
	stralto=alto;
	strtop=top;
	strleft=left;
	if (ancho==null) strancho = 600;
	if (alto==null) stralto = 360;
	if (strtop==null) strtop = 200;
	if (strleft==null) strleft = 200;
	window.open(url,"","resizable=yes,status=1,scrollbars=1,width="+strancho+",height="+stralto,top="+strtop+",left="+strleft",false);
}

function openWindowTitle(titulo, url, ancho, alto) {
	strancho=ancho;
	stralto=alto;
	if (ancho==null) strancho = 600;
	if (alto==null) stralto = 360;
	window.open(url,titulo,"resizable=yes,status=1,scrollbars=1,width="+strancho+",height="+stralto,false);
}

function esVacio(cadena) {
	if (cadena==null) res=true;
	else if (trim(cadena)=="") return true;
	else return false;
}

	function esVacio(s) {
		var res=false;
		if (s==null) res=true;
		else {
			if (s=="") res=true;
		}
		return res;
	}

function openLogin() {
	var url="popup_login.php";
	window.open(url,"","resizable=0,status=0,scrollbars=0,width=200,height=140",false);
	//window.open(url,"","",false);
}

function openBigWindow(url) {
	window.open(url,"","resizable=yes,status=1,scrollbars=1,width=540,height=480",false);
}


 
function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

function resaltarGuardar() {
	var element = document.getElementById("boton_guardar");
	if (element!=null) {
		element.innerHTML ="* Guardar *";
	}
}

function abrirMail() {
	if (event.ctrlKey) {
		event.returnValue=false;
		window.open('http://www.varaderoweb.com/cgi-bin/sqwebmail');
		return false;
	}
}

function getElement( id, ndoc ) {
	var element;
	doc=ndoc;
	if (doc==null) doc=document;
	if (doc.getElementById==null) {
		element = doc.all[id];
	} else {
		element =doc.getElementById(id);
	}
	return element;
}

function toggleOcultacion(partner) {
	var table = getElement(partner);
	if (table!=null) {
		if (table.style.display=="none") table.style.display="block";
		else table.style.display="none";
	}
}

function toggleOcultacionLibro(partner) {
	var table = getElement(partner);
	if (table!=null) {
		var nodo = getElement("img_"+partner);
		if (table.style.display=="none") {
			table.style.display="block";
			if (nodo!=null) nodo.src="img/bullet_cab_ficha_abierto.gif";	
		} else {
			table.style.display="none";
			if (nodo!=null) nodo.src="img/bullet_cab_ficha_cerrado.gif";	
		}
	}
}

function toggleOpcionesAbiertas(campo) {
	var opcionesAbiertas = document.formulario.opciones_abiertas.value;

	//Si no esta ya
	if((-1) == opcionesAbiertas.indexOf(campo)){
		opcionesAbiertas = opcionesAbiertas + campo + ";"; 
	} else {
	//Si no eliminar
		var campoAux = campo + ";";
		opcionesAbiertas = replaceSubstring(opcionesAbiertas,campoAux,"");
	}

	document.formulario.opciones_abiertas.value = opcionesAbiertas;
}

function abreOpcionesAbiertas(opcionesAbiertas) {
	var opciones = opcionesAbiertas.split(";");
	var lon = opciones.length; 
	for(i = 0; i<lon; i++){
		if(!esVacio(opciones[i])){
			var aux = 'campo_' + opciones[i];
			var nodo = getElement(aux);
			if (nodo!=null) nodo.style.display="block";

			var nodo = getElement("img_"+aux);
			if (nodo!=null) nodo.src="img/bullet_cab_ficha_abierto.gif";
		}
	}
}

function mostrarOcultacion(partner) {
	var table = getElement(partner);
	table.style.display="block";	
}

function ocultarOcultacion(partner) {
	var table = getElement(partner);
	table.style.display="none";	
}

function getElementDoc( ndoc, id) {
	var doc;
	doc = ndoc;
	if (doc==null) doc = document;
	var element;
	if (doc.getElementById==null) {
		element = doc.all[id];
	} else {
		element =doc.getElementById(id);
	}
	return element;
}


function set(nombre, valor) {
	var mivalor = valor;
	var strEval = "window.top."+nombre+"=valor;"
	eval(strEval);
}

function get(variable) {
	var strEval, res;
	strEval = "window.top."+variable;
	res = eval(strEval);
	if (res==undefined) res="";
    return res;
}

function setRadio(nombre, valor) {
	var res,item ;
	item = document.formulario[nombre];
	if (item!=null) {
		if (item.length!=null) {
			for (i=0;i<item.length;i++) {
				if (item[i].value==valor) {
					item[i].checked=true;
				}
			}
		}
	}
	return res;
}

function setInputRadio(arrRadio, valor) {
	var res,item ;
	item = arrRadio;
	if (item!=null) {
		if (item.length!=null) {
			for (i=0;i<item.length;i++) {
				if (item[i].value==valor) {
					item[i].checked=true;
				}
			}
		}
	}
	return res;
}


function eliminarAutorRol(strid) {
	var strOculto;
	var nodo = getElement(strid);
	nodo.outerHTML="";
	strOculto = getLeftToLast(strid,"_",2) + "_contributorrole";
	valor = getRightToLast(strid,"_",1);
	var valorPrevio = document.formulario[strOculto].value;
	res = eliminaDeLista2(valor , valorPrevio) 
	document.formulario[strOculto].value = res;
}



function eliminaDeLista2(valor,lista) {
	var posSel;
	var listaSel = ";"+lista+";";
	posSel =listaSel.indexOf(";"+valor+";");
	if (posSel!=-1) {
		listaSel = replaceSubstring( listaSel, ";"+valor+";", ";" );
	} else {
	}
	if (listaSel.indexOf(";")==0) listaSel=listaSel.substring(1);
	if (listaSel.lastIndexOf(";")==listaSel.length-1) listaSel=listaSel.substring(0,listaSel.length-1);
	return listaSel;
}



function perteneceLista2(valor,lista) {
	var res=false;
	pos =(";"+lista+";").indexOf(";"+valor+";");
	if (pos!=-1) {
		res=true;
	}
	return res;
}

function perteneceLista(valor,lista) {
	var res=false;
	pos =(","+lista+",").indexOf(","+valor+",");
	if (pos!=-1) {
		res=true;
	}
	return res;
}

/*
*Dada una cadena como campo_1_idcampo_personalizado un delimitador _ y numero=1 obtendría campo
*/
function getLeftNumber(cadena, delim, num) {
	var pos;
	var res="";
	var tmp=cadena;
	for(i=0;i<num;i++) {
		pos = tmp.indexOf(delim);
		if (pos!=-1) {
			res = res + tmp.substring(0,pos);
			tmp = tmp.substring(pos);
		} else {
			res = res + tmp;
		}
	}
	if (res.length>=delim.length) {
		if (res.substring(0,delim.length)==delim) {
			res = res.substring(delim.length);
		}
	}
	return res;
}

/* dado campo_1_idcampopersonalizado te obtiene el 1 */
function getIdcampo(str) {
	var res;
	res=str;
	res = getLeftToLast(res,"_",1);
	res = getRightToLast(res,"_",1);
	return res;
}

function getRightToLast(cadena, delim, num) {
	var pos;
	var res="";
	var tmp=cadena;
	for(i=0;i<num;i++) {
		pos = tmp.lastIndexOf(delim);
		if (pos!=-1) {
			res = tmp.substring(pos) + res;
			tmp = tmp.substring(0,pos);
		} else {
			res = tmp + res;
			tmp = "";
		}
	}
	if (res.length>=delim.length) {
		if (res.substring(0,delim.length)==delim) {
			res = res.substring(delim.length);
		}
	}
	return res;
}

function getLeftToLast(cadena, delim, num) {
	var pos;
	var res=cadena;
	for(i=0;i<num;i++) {
		pos = res.lastIndexOf(delim);
		if (pos!=-1) {
			res = res.substring(0,pos);
		}
	}
	return res;
}


function seleccionar(atributo,valor,campo, doc) {
	var nombre="campocontributor_"+ campo +"_contributorrolediv";
	var res = doc.formulario['campocontributor_'+ campo + '_contributorrole'].value;

	if (!perteneceLista2(atributo,res)) {
		var nodo = getElement(nombre,doc);
		nodo.outerHTML=nodo.outerHTML+"<div id='"+nombre+"_"+atributo+"'><a href='#' onclick='eliminarAutorRol(getIdentificadorPadre(this));return false;'>X</a> "+valor+"</div>";

		res = res + ";"+atributo;
		if (res.substring(0,1)==";") res = res.substring(1);
		// estoy quitando la coima.

		doc.formulario['campocontributor_'+ campo + '_contributorrole'].value = res;
	}
	if (window.opener!=null) {
		window.close();
	}
}

function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function



function str2double(str) {
	var dvalue;
	dvalue = parseFloat(replaceSubstring( replaceSubstring(str,".",""),",",".") );
	return dvalue;

}

//Pasa un valor real a cadena con 2 decimales y separador de miles.
function double2moneda (numero) {
	//1. Redondeo a 2 decimales
	var cadena = Math.round( numero * 100)+"";
	if (cadena.length==1) {
		cadena = "0"+cadena+"0";
	} else if (cadena.length==2) {
		cadena = "0"+cadena;
	}
	//alert(numero+" ::: "+cadena+" :: "+cadena.length);
	var res = cadena.substring( 0, cadena.length-2) + "," + cadena.substring( cadena.length-2, cadena.length);
	//alert("Cadena="+cadena+"; res="+res+"; numero="+numero+"; otro="+cadena.substring( cadena.length-2, cadena.length));

	var parteEntera = res.substring( 0, res.length-3);
	var num = "";
	var lon = parteEntera.length;
	for (j = 0; j < lon; j++){
		if ((j % 3 == 0) && (j > 0))
			num = "." + num;
		num = parteEntera.charAt(lon - j - 1) + num;
	}
	res = num + res.substring( res.length-3, res.length);
	return res;
}

function aniadirQuery(url, resto) {
	var res;
	if (url.indexOf('?')==-1) {
		res = url +'?'+resto;
	} else {
		res = url +'&'+resto;
	}
	return res;
}


function construyeUrlMenosMas(url,lista,itemsMas) {
	var res,urlBase,resto,w,x,i,atributo,valor,nresto;
	var v = url.split("?");
	if (v.length==1) {
		res = url+"?"+itemsMas;
	} else {
		nresto="";
		urlBase = v[0];
		resto = v[1];
		w = resto.split("&");
		for (i=0;i<w.length;i++) {
			if (w[i]!=""){
				x = w[i].split("=");
				atributo = x[0];
				valor="";
				if (x.length>0) valor = x[1];
				if (valor!="") {
					if (!perteneceLista(atributo,lista)) {
						nresto = nresto + "&" + atributo + "=" + valor;
					}
				}
			}
		}
		nresto += "&" + itemsMas;
		if (nresto!="") nresto=nresto.substring(1);
		res = urlBase + "?" + nresto;
	}
	return res;
}


function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 **********************************************************************/
{ 
        if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign


	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0) {
			iStart = tmpNumStr.length;
		}

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}	
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	var pos = tmpNumStr.indexOf(".");
	if (pos<0) {
		tmpNumStr = tmpNumStr+".";
		for (i=0;i<decimalNum;i++) {
			tmpNumStr+="0";
		}
	} else {
		//alert(tmpNumStr + "===" + decimalNum + "*" + tmpNumStr.length + "*" + pos );
		for (;tmpNumStr.length-pos<decimalNum+1;i++) {
			tmpNumStr+="0";
		}
	}
	res = replaceSubstring(tmpNumStr,".",",");
	if (decimalNum==0) {
		alert( res.substring(res.length-1) );
		if (res.substring(tmpNumStr.length-1)==",") {
			res = res.substring(0,res.length-1);
		}
	}
	return res	// Return our formatted string!
}

	//Indica si una cadena tiene algún espacio en su nombre
	function tieneEspacios(str){
		if (str==null) str="";
		var res = (str.indexOf(" ")!=-1);
		return res;
	}
	
	//Detecta si la cadena str contiene algún caracter no aceptable
  	function nombreIncorrecto(str){
  		if (str==null) str="";
    	//var forbidden = "áéíóíñÁÉÍÓÚÑ;,:-+*^`'ºª!|@~%&¬()=?¿¡[]{}<>\" ";
		var forbidden = "áéíóíñÁÉÍÓÚÑ;,:+*^`'ºª!|@~%&¬()=?¿¡[]{}<>\" ";
    	for (i=0;i<str.length;i++) {
       		if (forbidden.indexOf(str.substring(i,i+1))!=-1) return true;  // Si hay uno malo, ya no vale...
    	}
    	return false;
	 }

	//function to check valid email address
	function isValidMail(str){
		if (str==null) str="";
		var res = (str.indexOf(".") > 0) && (str.indexOf("@") > 0);
		if (res) {
			//pos = str.indexOf("@");
			//dominio = str.substring(pos);
		}
		// comprobar que no tenga acentos
		var forbidden = "áéíóúÁÉÍÓÚ";
    	for (i=0;i<str.length && res;i++)
       		res = res && forbidden.indexOf(str.substring(i,i+1))==-1;
		return res;
	}

	//function to check valid email address
	function isValidDigit(str){
		var validRegExp = /^[0-9]+$/i;
		res=true;
		// search email text for regular exp matches
		if (str.search(validRegExp) == -1) {
			res=false;
		} 
		return res; 
	}

function esNumericoDecimal(str){
	var validRegExp = /^[0-9]+(\,[0-9]+)?$/i;
	res=true;
	// search email text for regular exp matches
	if (str.search(validRegExp) == -1) {
		res=false;
	} 
	return res; 
}

function esNumericoRomanos(str){
	var validRegExp = /^[IVXLCDM]+$/i;
	res=true;
	// search email text for regular exp matches
	if (str.search(validRegExp) == -1) {
		res=false;
	} 
	return res; 
}

function esLoginValido(str){
	var validRegExp = /^[A-Za-z0-9]+$/i;
	res=true;
	// search email text for regular exp matches
	if (str.search(validRegExp) == -1) {
		res=false;
	} 
	return res; 
}

function esShortnameValido(str){
	var validRegExp = /^[A-Za-z0-9_]+$/i;
	res=true;
	// search email text for regular exp matches
	if (str.search(validRegExp) == -1) {
		res=false;
	} 
	return res; 
}

function esDilveIdValido(str){
	var validRegExp = /^[A-Za-z0-9][A-Za-z0-9]?[A-Za-z0-9]?[A-Za-z0-9]?[A-Za-z0-9]?[A-Za-z0-9]?[A-Za-z0-9]?[A-Za-z0-9]?$/i;
	res=true;
	// search email text for regular exp matches
	if (str.search(validRegExp) == -1) {
		res=false;
	} 
	return res; 
}

function esDilveIdValido2(str){
	var validRegExp = /^........[A-Za-z0-9][A-Za-z0-9]?[A-Za-z0-9]?[A-Za-z0-9]?[A-Za-z0-9]?[A-Za-z0-9]?[A-Za-z0-9]?[A-Za-z0-9]?$/i;
	res=true;
	// search email text for regular exp matches
	if (str.search(validRegExp) == -1) {
		res=false;
	} 
	return res; 
}

function esNombreFicheroValido(strIn){
	str = getNombreFile(strIn);
	var validRegExp = /^[A-Za-z0-9_\-]+$/i;
	res=true;
	
	if (str.search(validRegExp) == -1) {
		res=false;
	} 
	return res; 
}

function getNombreFile(str) {
	var res="";
	var strfile = "";
	var pos = -1;
	
	strfile = str.replace( '/','\\');
	pos = strfile.lastIndexOf("\\");
	res = strfile.substring(pos+1);
	res = res.toLowerCase();
	
	return res;
}

function esNombreDescargaErroneo(str){
	var validRegExp = /^[A-Za-z0-9]+$/i;
	res=true;
	// search email text for regular exp matches
	if (str.search(validRegExp) == -1) {
		res=false;
	} 
	return res; 
}

function esNumerico(str){
	var validRegExp = /^[0-9]+$/i;
	res=true;
	// search email text for regular exp matches
	if (str.search(validRegExp) == -1) {
		res=false;
	} 
	return res; 
}

function esAnnio(str){
	var validRegExp = /^[0-9][0-9][0-9][0-9]$/i;
	res=true;
	// search email text for regular exp matches
	if (str.search(validRegExp) == -1) {
		res=false;
	} 
	return res; 
}

function numDigitos(numero, numDigitos) {
	var res=""+numero;
	while (res.length<numDigitos) {
		res = "0"+res;
	}
	return res;
}

function compruebaFecha(strFecha) {
	var res=false;
	var mmddaaaa = strFecha.substring(4,6) +"/"+ strFecha.substring(6,8) +"/"+ strFecha.substring(0,4);	
	if (isDate(mmddaaaa)) {
		res=true;
	} else {

	}
	return res;
}



/*** FUNCIONES DE FECHA ***/
/*** FUNCIONES DE FECHA ***/
/*** FUNCIONES DE FECHA ***/

var dtCh= "/";
var minYear=1000;
var maxYear=3000;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}

function ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }
/*** FIN FUNCIONES DE FECHA ***/
/*** FIN FUNCIONES DE FECHA ***/
/*** FIN FUNCIONES DE FECHA ***/

function clickMenu(item) {
	var nodo, i;
	/*var strMenus="editorial,busquedas,cargas,descargas,seleccion,principal,default";
	var v=strMenus.split(",");
	nombre = (item.id).substring(2);
	for (i=0;i<v.length;i++) {
		nodo = getElement("t_"+v[i]);
		if (nodo!=null) nodo.style.display="none";
		nodo = getElement("a_"+v[i]);
		if (nodo!=null) nodo.className="menu1";
		nodo = getElement("td_"+v[i]);
		if (nodo!=null) nodo.className="menunivel1";
	}
	nodo = getElement("t_"+nombre);
	if (nodo!=null) nodo.style.display="block";
	nodo = getElement("a_"+nombre);
	if (nodo!=null) nodo.className="menu1act";
	nodo = getElement("td_"+nombre);
	if (nodo!=null) nodo.className="menunivel1act";*/
	return true;
}

function eliminaDeLista(strId, lista) {
	var listaSel = ","+lista+",";
	var posSel;
	posSel = listaSel.indexOf(","+strId+",");
	if (posSel!=-1) {
		listaSel = replaceSubstring( listaSel,","+strId+",", "," );
	}
			
	if (listaSel.charAt(0)==",") {
		listaSel = listaSel.substring(1,listaSel.length);
	} 	

	if (listaSel.charAt(listaSel.length-1)==",") {
		listaSel = listaSel.substring(0,listaSel.length-1);
	} 	

	return listaSel;
}

function enviarMiSeleccion() {
	document.formCookies.cookie_sel.value=getCookie('lista_indice_sel'); 
	document.formCookies.cookie_des.value=getCookie('lista_indice_des');  
	document.formCookies.redirect.value='verseleccion';
	document.formCookies.submit();
	return false;
}

function enviarMiSeleccionRedirect(redirect) {
	document.formCookies.cookie_sel.value=getCookie('lista_indice_sel'); 
	document.formCookies.cookie_des.value=getCookie('lista_indice_des');  
	document.formCookies.redirect.value=redirect;
	document.formCookies.submit();
	return false;
}

function eliminarDeListaMultiple(nombreCampo, codigo){
	var campo = "mostrar_" + nombreCampo + "_"+codigo;
	var oDiv = getElement(campo);
	oDiv.style.display = "none";
	var nodo = getElement(nombreCampo);
	var lista=nodo.value;
	lista = eliminaDeLista(codigo, lista);
	nodo.value=lista;
	return lista.length==0;
}

function funcionLibrosPropios() {										
	if (document.formtopbusqueda.opc_busq.value=='') {
		document.formtopbusqueda.campo.value='';
		document.formtopbusqueda.q.value=document.formtopbusqueda.search.value;
	}
	if (document.formtopbusqueda.opc_busq.value=='AUTOR') {
		document.formtopbusqueda.campo.value='AUTOR';
	}
	if (document.formtopbusqueda.opc_busq.value=='TITULO') {
		document.formtopbusqueda.campo.value='TITULO';
	}
	if (document.formtopbusqueda.opc_busq.value=='ISBN') {
		document.formtopbusqueda.action='view_libro.jsp';
		document.formtopbusqueda.isbn.value=document.formtopbusqueda.search.value;
	}
	if (document.formtopbusqueda.opc_busq.value=='EAN') {
		document.formtopbusqueda.action='view_libro.jsp';
		document.formtopbusqueda.ean.value=document.formtopbusqueda.search.value;
	}
	if (document.formtopbusqueda.librospropios2.checked) {
		document.formtopbusqueda.librospropios.value='S';
	} else {
		document.formtopbusqueda.librospropios.value='N';
	}
}

	function nuevoCampo(nodo,strTitle,nuevoTexto ) {
		if (strTitle=="othertext") {
			if (numeroResumen>=3) {
				alert("No se pueden introducir más de 3 resúmenes");
				return;
			}			
			numeroResumen++;
		}					
		var res = nuevoTexto;
		var re;
		re = new RegExp('<([^>]*=campo'+strTitle+'_)([0-9]*)','g'); 
		res = res.replace(re, '<$1'+idCampos);
		re = new RegExp('<([^>]*="campo'+strTitle+'_)([0-9]*)','g'); 
		res = res.replace(re, '<$1'+idCampos);
		re = new RegExp('<([^>]*id=campo'+strTitle+'_)([0-9]*)','g'); 
		res = res.replace(re, '<$1'+idCampos);
		re = new RegExp('<([^>]*id="campo'+strTitle+'_)([0-9]*)','g'); 
		res = res.replace(re, '<$1'+idCampos);

		re = new RegExp('Campo ([0-9]*):','g'); 
		res = res.replace(re, 'Campo '+idCampos);
		//alert(res);
		var strSpan = nodo.id.substring(0, nodo.id.length-4 ) + "span";
		var span = getElement( strSpan );
		elem = document.createElement("div");
		elem.id = "campo"+strTitle+"_" + idCampos+ "_span"
		idCampos++; 
		elem.innerHTML = res;
		span.parentNode.appendChild( elem );
		return idCampos-1;
	}


	function getPadreConId(nodo) {
		var res=null;
		//alert(nodo);
		if (nodo.id!=null) {
			if (nodo.id!="") {
				res = nodo;
			}
		}
		if (res==null) res = getPadreConId(nodo.parentNode);
		return res;
	}


	function getIdentificadorPadre(nodo) {
		var nodoPadre = getPadreConId(nodo);
		var res=nodoPadre.id;
		return res;
	}

	function getIdentificadorPadreIndice(nodo) {
		var nodoPadre = getPadreConId(nodo);
		var v = nodoPadre.id.split("_");
		var res="";
		res = v[1];
		return res;
	}

/*
	function eliminarCampo(strId,strTitle) {
		if (confirm("¿Seguro que desea eliminar este dato?")) {
			if (strId!="campo"+strTitle+"_1_span") { 
				var nodo = getElement(strId);
				nodo.parentNode.removeChild( nodo );	
			}
		}
	}*/

	function eliminarCampo(nodo,strTitle) {
		var nodoPadre = getPadreConId(nodo);
		if (confirm('¿Seguro que desea borrar este elemento?')) {
			if(strTitle=="othertext") numeroResumen--;
			var nodo = nodoPadre;
			nodo.parentNode.removeChild( nodo );		
		}
		return false;
	}

// Dado un nodo que tiene un nobre tal que "camposubject_1_href" elimina el nodo que tiene como base "subject"
function eliminarCampoBase(item) {
	var name = ""+item.id;
	name = name.substr(5);
	name = getLeftNumber(name,"_",1);

	return eliminarCampo(item.parentNode.parentNode,name);
}

function comprobarEstado() {
	var b = confirm("Va a abrir un archivo de más de 250 KB. ¿Desea continuar?");
	return b;
}

function esUnicamenteDilveIdFromCodigo(codigo)  {
	var ean = trim(codigo);

	//Miro si es EAN
	var validRegExp = /^[0-9].*$/i;
	esEan=true;
	// search email text for regular exp matches
	if (str.search(validRegExp) == -1) {
		esEan=false;
	} 
	return !esEan; 
}

function selectAll(valor) {
	var f = document.SeleccionForm;	
	res="";
	patron="_";
	var elements = f.elements;
	for(i=0;i<elements.length;i++) {		
		var campo = elements[i];
		if (campo!=null) {
			var nombreCampo = campo.name;
			if (nombreCampo.substring(0, patron.length)==patron) {
				campo.checked = valor;
				if (valor) {
					addNodo(nombreCampo);
				} else {
					delNodo(nombreCampo);
				}
				//else delNodo(nombreCampo);
			}
		}
	}
}

function selectInverted() {
	var f = document.SeleccionForm;
	res="";
	patron="_";
	var elements = f.elements;
	for(i=0;i<elements.length;i++) {	
		var campo = elements[i];
		if (campo!=null) {
			var nombreCampo = campo.name;
			if (nombreCampo.substring(0, patron.length)==patron) {
				campo.checked = !campo.checked;
				if(campo.checked){
					addNodo(nombreCampo);
				} else {
					delNodo(nombreCampo);
				}
			}
		}
	}
}


 function eliminaFiltro(){
	document.SeleccionForm.search.value="";
	document.SeleccionForm.submit();
 }


function addSeleccionesCampana() {
	var id="";
	var n;
	var f = document.SeleccionForm;
	patron="_";
	var elements = f.elements;
	for(i=0;i<elements.length;i++) {
		var campo = elements[i];
		if (campo!=null) {
			var nombreCampo = campo.name;
			if (campo.checked == true) {
				id +=nombreCampo.substring(patron.length,nombreCampo.length)+ ",";
				
			}
		}
	}
	idsSelecciones=id.substring(0,id.length-1);
	f.selecciones.value=idsSelecciones;
}

function camposSeleccionados() {
	var f = document.SeleccionForm;
	for(i=0;i<f.all.length;i++) {	
		var campo = f[i];
		if (campo!=null) {
			if( campo.checked == true){
				return true;
				break;
			}
		}
	}
}

//Si el valor de _contributorunnamedpersons es "", 02 o 03, la autoría es visible. Si no es no visible
function esAutoriaVisible(valor) {
	var res=false;
	if (valor=="" || valor=="2" || valor=="3" ) res=true;
	return res;
}
